diff --git a/tasks/mansini2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/mansini2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mansini2020/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/mansini2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/mansini2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mansini2020/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/mansini2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/mansini2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mansini2020/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/mansini2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/mansini2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mansini2020/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/mansini2020/gurobi_solution/large_solution_1.json b/tasks/mansini2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d068368a7d830bc574a95a77cbf89309719119f0 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d05dedc083374878ca23d9ec7eb1857a317baacac3fdd01e6e55c83a743872e2 +size 8569644 diff --git a/tasks/mansini2020/gurobi_solution/large_solution_2.json b/tasks/mansini2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d3c9ecd8e031e0da3c5c08b0a9d51ef26d5aaa11 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e72e790c1a4bfcd89cfc31b0229067a7c5975ebfb5f180f82762167633e84b9 +size 8547809 diff --git a/tasks/mansini2020/gurobi_solution/large_solution_3.json b/tasks/mansini2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..74718eb9ecd121d7906605f672ffa2b73c6a06f5 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0447759795d7b45dca72e5db7d11eee987803ec5782f0aa6430e6958da5ec1a +size 8569657 diff --git a/tasks/mansini2020/gurobi_solution/large_solution_4.json b/tasks/mansini2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..911f2cc9b50ec1a6bdde34fa5496a3a611201c22 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:371d1d5565f71eee09d2a58067fcf94bad317b7f143cabc580da07631a63f5f5 +size 8508149 diff --git a/tasks/mansini2020/gurobi_solution/large_solution_5.json b/tasks/mansini2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e3805d41ec048f189ffa10837c19c03f19006343 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afe599c1451937803404f5d762b2bf48b140f50ab6c49452236a0160e0c9137f +size 8568147 diff --git a/tasks/mansini2020/gurobi_solution/tiny_solution.json b/tasks/mansini2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..f71168962f85dfe64c1f3e78a2aecd2eaee0737b --- /dev/null +++ b/tasks/mansini2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2558a9fd26d6a9c8b6f211218b382ba542e89fda9b88aeb9d7ad34ff75b38bd1 +size 11161 diff --git a/tasks/mansini2020/gurobi_solution_log/large_log_1.jsonl b/tasks/mansini2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..491298a66ec7dfff8bfb6145c33100a2f99bd222 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:23e2aa9ff84af840609086d6f681ee422b0733173254687f0f35139e7949eb0c +size 47 diff --git a/tasks/mansini2020/gurobi_solution_log/large_log_2.jsonl b/tasks/mansini2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ba8398e153e76e3472850b121dd67c9af5b964b8 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aef55475a513ae597eb5ae13256b28653e7ae1fd7dff1a111aeaefd27b718831 +size 45 diff --git a/tasks/mansini2020/gurobi_solution_log/large_log_3.jsonl b/tasks/mansini2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..44da48d93d507ba463517bb2183f4495864540f1 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2ad79952cccd9d2e698b12c9d2772fadb08776c911e28783048d3b5c5d8708b +size 46 diff --git a/tasks/mansini2020/gurobi_solution_log/large_log_4.jsonl b/tasks/mansini2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6dfc2897ffe3a063a2c2772c1cc9d59d0831e025 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7bb98b13be52ad9ce10fa3f1c758df99edc189a561fe08d5d27414c2c94a1b2 +size 46 diff --git a/tasks/mansini2020/gurobi_solution_log/large_log_5.jsonl b/tasks/mansini2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2bc6936c5e7e3e9b165243caa967d9351bf0d2ce --- /dev/null +++ b/tasks/mansini2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:748e934f423bf37ce19aa3dc3bb9dbfc7e76ddc82ff232a6f33927b430d7b607 +size 46 diff --git a/tasks/mansini2020/gurobi_solution_log/tiny_log.jsonl b/tasks/mansini2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d4422d72ff291f273f6c6281059e1e25c01fed48 --- /dev/null +++ b/tasks/mansini2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79386943474b72d1052d12237d34a605052e30c38ea1febe87652e77bd946c96 +size 43 diff --git a/tasks/mansini2020/instance/large_instance_1.json b/tasks/mansini2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6bf621c4567d0fd6931233f527699a5a61e05be5 --- /dev/null +++ b/tasks/mansini2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48636ff73d6abbfadecfbaf139fb1efe7ed7bb4cc26b0d567c06bc8239367189 +size 561182775 diff --git a/tasks/mansini2020/instance/large_instance_2.json b/tasks/mansini2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c628e10fbea645e6fedc995dd026a6243435a0ac --- /dev/null +++ b/tasks/mansini2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50d2f7bd54d359b21bd95ba786f9b8e2df8ee83b7d70036862ba65096f6084fb +size 561111750 diff --git a/tasks/mansini2020/instance/large_instance_3.json b/tasks/mansini2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..eb12da2961b6546b6e9f61f8c760003fffca2fc2 --- /dev/null +++ b/tasks/mansini2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:21b65d8394089ff854e473f8ff05bde41e7acd515aebd7c1dd35189aedc7707a +size 561156593 diff --git a/tasks/mansini2020/instance/large_instance_4.json b/tasks/mansini2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..101acc5b58b9f8bc4a833ecbf04f7bd79cb2911f --- /dev/null +++ b/tasks/mansini2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19e854a39212c5493cd498958c311904eeb55f3e0d74a6e8cb18d6ecf4c6fb86 +size 561156106 diff --git a/tasks/mansini2020/instance/large_instance_5.json b/tasks/mansini2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..4a26571227d15323d006f7123fc726c6de933d6b --- /dev/null +++ b/tasks/mansini2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb246dbe15d50007549a40a6dfacde94426572cb2e9dccaa83a68febd7efefd2 +size 561155680 diff --git a/tasks/mansini2020/instance/tiny_instance.json b/tasks/mansini2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..8b4cda534eac1bb87f0795afc297346b98221413 --- /dev/null +++ b/tasks/mansini2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db2322e7c2ec25f81d5d0f0aaa2a3d14cd495bafea0cb3d0a353934d6f00e69d +size 134638 diff --git a/tasks/mansini2020/instance_schema.json b/tasks/mansini2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..0ef4c32f4a0a3cb55b27526622f4dd87d99e229b --- /dev/null +++ b/tasks/mansini2020/instance_schema.json @@ -0,0 +1,21 @@ +{ + "parameters": { + "n_groups": " Number of disjoint groups from which exactly one item must be selected.", + "m_resources": " Number of shared resources, each with a limited capacity.", + "n_items_per_group": " Number of candidate items available within each group.", + "n_bar_total_items": " Total number of candidate items across all groups." + }, + "capacities": " Maximum available amount of each shared resource.", + "groups": [ + { + "group_id": " Zero-based identifier of this group.", + "items": [ + { + "item_id": " Zero-based identifier of this item within its group.", + "profit": " Reward earned when this item is selected.", + "weights": " Amount of each shared resource consumed by this item." + } + ] + } + ] +} diff --git a/tasks/mansini2020/mathematical_formulation.md b/tasks/mansini2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..fd0e9b70a102e57e5fb92b0223ec84afc1eadd81 --- /dev/null +++ b/tasks/mansini2020/mathematical_formulation.md @@ -0,0 +1,36 @@ +# Original Formulation (Eqs. 1–4) + +## Sets and Indices + +- $\{G_1, G_2, \ldots, G_n\}$: a collection of $n$ disjoint groups (classes) of items, with $G_q \cap G_l = \emptyset$ for all $q \neq l$. + +- Each group $G_i$ has $n_i = |G_i|$ items, denoted by ordered pairs $(i, j)$, $i = 1,\ldots,n$, $j = 1,\ldots,n_i$. + +- $\tilde{N}$: set of all items, $|\tilde{N}| = \tilde{n} = \sum_{i=1}^{n} n_i$. + +- $k = 1,\ldots,m$: index for the $m$ resources. + +## Parameters + +- $p_{ij} \geq 0$: profit of item $(i,j) \in \tilde{N}$. + +- $w_{ij}^{k} \geq 0$: amount of resource $k$ required by item $(i,j)$. + +- $c_k \geq 0$: capacity of resource $k$, for $k=1,\ldots,m$. + +## Decision Variables + +- $x_{ij} \in \{0,1\}$ for each $(i,j) \in \tilde{N}$: 1 if item $(i,j)$ is selected, 0 otherwise. + +## Objective and Constraints + +$$\begin{align} +\max \quad & z = \sum_{i=1}^{n} \sum_{j=1}^{n_i} p_{ij}\, x_{ij} + \tag{1} \\ +\text{s.t.}\quad & \sum_{i=1}^{n} \sum_{j=1}^{n_i} w_{ij}^{k}\, x_{ij} \leq c_k + && k = 1,\ldots,m, \tag{2} \\ +& \sum_{j=1}^{n_i} x_{ij} = 1 + && i = 1,\ldots,n, \tag{3} \\ +& x_{ij} \in \{0,1\} + && (i,j) \in \tilde{N}. \tag{4} +\end{align}$$ diff --git a/tasks/mansini2020/problem_description.txt b/tasks/mansini2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..c67bf3ea74bf186288dd7b7b84e04cb5cec29c20 --- /dev/null +++ b/tasks/mansini2020/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +A collection of items is partitioned into a number of disjoint groups. Each group contains a specified number of items, and every item belongs to exactly one group. There are also several shared resources, each with a given capacity. For every item, the input data specifies a profit and, for each resource, the amount of that resource the item consumes. All profits and resource consumptions are nonnegative, and every resource capacity is nonnegative. + +The task is to select exactly one item from each group so as to maximize the total profit of the selected items. The selection must respect all resource limits: for each resource, the sum of the consumptions of the selected items across all groups must not exceed that resource's capacity. Because exactly one item must be chosen per group, omitting a group entirely or picking more than one item from any single group is not allowed. diff --git a/tasks/mansini2020/solution_logger.py b/tasks/mansini2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/mansini2020/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/mansini2020/solution_schema.json b/tasks/mansini2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..0b16a3ab268c8154c8a19e8ff8309cf1d5b3d167 --- /dev/null +++ b/tasks/mansini2020/solution_schema.json @@ -0,0 +1,11 @@ +{ + "objective_value": " Total profit obtained from the chosen items across all groups.", + "selected_items": [ + { + "group_id": " Identifier of the group from which an item has been picked.", + "item_id": " Identifier of the item chosen from the corresponding group.", + "profit": " Profit contributed by the chosen item.", + "weights": " Amount of each resource consumed by the chosen item." + } + ] +} diff --git a/tasks/martello1999/feasibility_check.py b/tasks/martello1999/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e72bae7c230b44c3be530df861c6e0b5f14e3aad --- /dev/null +++ b/tasks/martello1999/feasibility_check.py @@ -0,0 +1,335 @@ +""" +Feasibility checker for the 0-1 Knapsack Problem (KP). +Based on: Martello, Pisinger, and Toth (1999) + +Hard constraints (from formulation section, top to bottom): + Constraint 1 (1b): sum_{j=1}^{n} w_j x_j <= c + Constraint 2 (1c): x_j in {0, 1}, j = 1, ..., n + Constraint 3 (obj): reported objective_value must equal + sum_{j=1}^{n} p_j x_j (Tier-C anti-exploit check) +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'selected_items') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def check_feasibility(instance, solution): + n = instance["n"] + capacity = instance["capacity"] + items = instance["items"] + + # Build lookup from item id to item data + item_map = {item["id"]: item for item in items} + valid_ids = set(item_map.keys()) + + selected = solution.get("selected_items", []) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ------------------------------------------------------------------------- + # Constraint 2 (1c): x_j in {0, 1} — each selected item must be a valid + # item id, appear at most once, and be within {1, ..., n}. + # ------------------------------------------------------------------------- + seen = set() + invalid_items = [] + duplicate_items = [] + for item_id in selected: + if item_id not in valid_ids: + invalid_items.append(item_id) + if item_id in seen: + duplicate_items.append(item_id) + seen.add(item_id) + + if invalid_items: + violated_constraints.add(2) + violations.append( + f"Selected items not in instance: {invalid_items}" + ) + for item_id in invalid_items: + # violation_amount = 1 per invalid item (binary domain violation) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(item_id), + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": max(abs(0.0), EPS), + "ratio": 1.0 / max(abs(0.0), EPS), + }) + + if duplicate_items: + violated_constraints.add(2) + violations.append( + f"Duplicate items in selection: {duplicate_items}" + ) + for item_id in duplicate_items: + violation_magnitudes.append({ + "constraint": 2, + "lhs": 2.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": max(abs(1.0), EPS), + "ratio": 1.0 / max(abs(1.0), EPS), + }) + + # ------------------------------------------------------------------------- + # Constraint 1 (1b): sum_{j=1}^{n} w_j x_j <= c + # ------------------------------------------------------------------------- + total_weight = 0.0 + for item_id in seen: + if item_id in item_map: + total_weight += item_map[item_id]["weight"] + + lhs = total_weight + rhs = float(capacity) + violation_amount = lhs - rhs # for <= constraint: how much LHS exceeds RHS + + if violation_amount > TOL: + violated_constraints.add(1) + violations.append( + f"Capacity exceeded: total weight {lhs} > capacity {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 3 (obj): reported objective_value must equal + # sum_{j=1}^{n} p_j x_j. Tier-C defense against LLM exploits that lie + # about the objective value while passing the constraint checks. + # ------------------------------------------------------------------------- + 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: + # Recompute over unique, valid selected items (matches weight sum) + true_obj = 0.0 + for item_id in seen: + if item_id in item_map: + true_obj += float(item_map[item_id]["profit"]) + abs_diff = abs(reported - true_obj) + # Profits are positive integers; an integer mismatch by >=1 fires. + # Add a tiny relative slack for large magnitudes (true_obj can be + # ~1e10), so float round-trips never cause false positives. + tol = max(0.5, 1e-9 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(3) + violations.append( + f"Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum_j(p_j*x_j)={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, + }) + + # ------------------------------------------------------------------------- + # 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 0-1 Knapsack Problem " + "(Martello, Pisinger, Toth 1999)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path for the output 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) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"Result: {status}") + 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/martello1999/gurobi_code.py b/tasks/martello1999/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..3d418ff5b44cb4960099a57a442bd3eab029ccae --- /dev/null +++ b/tasks/martello1999/gurobi_code.py @@ -0,0 +1,104 @@ +""" +Gurobi implementation of the 0-1 Knapsack Problem (KP). +Based on: Martello, Pisinger, and Toth (1999) +"Dynamic Programming and Strong Bounds for the 0-1 Knapsack Problem" +Management Science 45(3): 414-424 + +Formulation (1): + maximize z = sum_{j=1}^{n} p_j x_j + subject to sum_{j=1}^{n} w_j x_j <= c + x_j in {0, 1}, j = 1, ..., n +""" + +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_knapsack(instance_path, solution_path, time_limit): + # Load instance + with open(instance_path, "r") as f: + data = json.load(f) + + n = data["n"] + capacity = data["capacity"] + items = data["items"] + + profits = [item["profit"] for item in items] + weights = [item["weight"] for item in items] + + # Build model + model = gp.Model("knapsack_01") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables: x_j in {0, 1} + x = model.addVars(n, vtype=GRB.BINARY, name="x") + + # Objective: maximize sum p_j * x_j + model.setObjective( + gp.quicksum(profits[j] * x[j] for j in range(n)), + GRB.MAXIMIZE + ) + + # Constraint: sum w_j * x_j <= c + model.addConstr( + gp.quicksum(weights[j] * x[j] for j in range(n)) <= capacity, + name="capacity" + ) + + # Solve + model.optimize() + + # Extract solution + result = {"objective_value": None, "selected_items": []} + + if model.SolCount > 0: + result["objective_value"] = round(model.ObjVal) + result["selected_items"] = [ + items[j]["id"] for j in range(n) if x[j].X > 0.5 + ] + else: + result["objective_value"] = 0 + result["selected_items"] = [] + + # 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"Objective value: {result['objective_value']}") + print(f"Solution written to: {solution_path}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Solve 0-1 Knapsack Problem 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 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_knapsack(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/martello1999/gurobi_feasi_result/large_feasi_result_1.json b/tasks/martello1999/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martello1999/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/martello1999/gurobi_feasi_result/large_feasi_result_2.json b/tasks/martello1999/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martello1999/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/martello1999/gurobi_feasi_result/large_feasi_result_3.json b/tasks/martello1999/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martello1999/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/martello1999/gurobi_feasi_result/large_feasi_result_4.json b/tasks/martello1999/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martello1999/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/martello1999/gurobi_feasi_result/large_feasi_result_5.json b/tasks/martello1999/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martello1999/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/martello1999/gurobi_feasi_result/tiny_feasi_result.json b/tasks/martello1999/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martello1999/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/martello1999/gurobi_solution/large_solution_1.json b/tasks/martello1999/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..836032d962ca6e4a4b6da30ae159a5437bcec106 --- /dev/null +++ b/tasks/martello1999/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1296c00ed28e79f1671725129476eebb007c74a8193f004970c90c4297a402d6 +size 63806716 diff --git a/tasks/martello1999/gurobi_solution/large_solution_2.json b/tasks/martello1999/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..24ef12057b191360db3447caa61ef347d4df9886 --- /dev/null +++ b/tasks/martello1999/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:518a647e46fe180aa933561a2a59dd3b931530ba22e7f0a5e68c4baa4f391d22 +size 80079975 diff --git a/tasks/martello1999/gurobi_solution/large_solution_3.json b/tasks/martello1999/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..006fa51cdc7af5b35cdd1d6823a5c57bd1b8a3e3 --- /dev/null +++ b/tasks/martello1999/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a8c26ece18b9a696284ff68659ce90cc252a8682443695a540395b447ae7693 +size 66330793 diff --git a/tasks/martello1999/gurobi_solution/large_solution_4.json b/tasks/martello1999/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..286805947bc581ff8bf8317e3df1a8eaaf123d5c --- /dev/null +++ b/tasks/martello1999/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b877be81dd7d3bf81ae1b9444408674bf20bd9cd7faf86aac74f8e38463f2002 +size 90683375 diff --git a/tasks/martello1999/gurobi_solution/large_solution_5.json b/tasks/martello1999/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..fe80d8657c3fc23eadea98cb751b8519c1680b1a --- /dev/null +++ b/tasks/martello1999/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81fccb416ccfebfec47eb2df9a43b07764a2cc9309db91193e50fcaee598c0fe +size 90693970 diff --git a/tasks/martello1999/gurobi_solution/tiny_solution.json b/tasks/martello1999/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..b77dcde8ab0a7d5297b103222bfcd7c49f6af3d9 --- /dev/null +++ b/tasks/martello1999/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c71515c0d9635751f49c2b4963c21b66f9b3b022136725f86c3f15be6273e3a9 +size 335 diff --git a/tasks/martello1999/gurobi_solution_log/large_log_1.jsonl b/tasks/martello1999/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6cfd9335a3fd0f8fe0412395e263358d27828b94 --- /dev/null +++ b/tasks/martello1999/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99e82e84bae1a7306917bb59ee5722ffe12328509ecf5dd0b49ab57c1af0a9ea +size 51 diff --git a/tasks/martello1999/gurobi_solution_log/large_log_2.jsonl b/tasks/martello1999/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..82a91d39f54d004563a117120ddc1446c4b188d6 --- /dev/null +++ b/tasks/martello1999/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:243420c0f21c2cdb7bab2f6f5dba1543985d2695825d058e6592b74ff47b1ad3 +size 52 diff --git a/tasks/martello1999/gurobi_solution_log/large_log_3.jsonl b/tasks/martello1999/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7e82f45aee86628ea56b4f62cc9a54e38edb8c44 --- /dev/null +++ b/tasks/martello1999/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb1c6065a53036dd0fe1d4e7c65d6845756f4d60747a24910652d66f77dc1bd0 +size 52 diff --git a/tasks/martello1999/gurobi_solution_log/large_log_4.jsonl b/tasks/martello1999/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f8a9eb25460e73a60996f217fa5c90206d54bfce --- /dev/null +++ b/tasks/martello1999/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dafbea693415f1af3eab45342d228359c1358e9383adedde9729c4a393437939 +size 52 diff --git a/tasks/martello1999/gurobi_solution_log/large_log_5.jsonl b/tasks/martello1999/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3d3d7ae164514ec6dd2a2461dc7920529aa7c3ab --- /dev/null +++ b/tasks/martello1999/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:458cfbf573fb5d6847239dcfaf41d0b1b8e8f5c40493da8f0a2a53c4eb140b1c +size 51 diff --git a/tasks/martello1999/gurobi_solution_log/tiny_log.jsonl b/tasks/martello1999/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dc442ea11c0823623e675a51d798fdd6e3113ce3 --- /dev/null +++ b/tasks/martello1999/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24cf240d348bbc12d7a457028e07073652903340cf6596b024231e8d22565d42 +size 44 diff --git a/tasks/martello1999/instance/large_instance_1.json b/tasks/martello1999/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d999979864cac81e3413bee293bc6086afa2b907 --- /dev/null +++ b/tasks/martello1999/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e09cc29b5c2514960d9746f8e6d7afb4d1949a0fba08b10c7f00507bf60c3c87 +size 777820124 diff --git a/tasks/martello1999/instance/large_instance_2.json b/tasks/martello1999/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..daac90af6b252c5314c91d4b1d1becdfffab784f --- /dev/null +++ b/tasks/martello1999/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:981732aed63a47c23ebba870b384c19774dc5a3d1875a29d1e7ecdff0f12666e +size 786670683 diff --git a/tasks/martello1999/instance/large_instance_3.json b/tasks/martello1999/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..0ea85e7d82044b68a14ff3f42391ccdbfabe274d --- /dev/null +++ b/tasks/martello1999/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ef33692340bf5cee1738fa430f31eb245406ee186a0d74ba5aa93072b01841c +size 787005356 diff --git a/tasks/martello1999/instance/large_instance_4.json b/tasks/martello1999/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c9d700258f15e39384be2101cc0c6318529cf398 --- /dev/null +++ b/tasks/martello1999/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7420944679be146bb68b2f97915b0f0820e3ae7e13eca523d1475a696f930eee +size 788778685 diff --git a/tasks/martello1999/instance/large_instance_5.json b/tasks/martello1999/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..1682e95e149775c31518029cb37fc69e34643d9f --- /dev/null +++ b/tasks/martello1999/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f175dc52790c08c3f85787d477aba3808666a73ab7456152a898d4a96caf92de +size 786665836 diff --git a/tasks/martello1999/instance/tiny_instance.json b/tasks/martello1999/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..e01754e34f30681b43205b5aae7a260b947eefde --- /dev/null +++ b/tasks/martello1999/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54b2a681e007323fea0074de6018a48a7262e97289e4cafedd1f51194900e148 +size 3679 diff --git a/tasks/martello1999/instance_schema.json b/tasks/martello1999/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..ac635b56910ee98aafae33ea8c1185e5b373f56b --- /dev/null +++ b/tasks/martello1999/instance_schema.json @@ -0,0 +1,11 @@ +{ + "n": " Number of items available for packing.", + "capacity": " Maximum total weight the knapsack can hold.", + "items": [ + { + "id": " Unique identifier of the item.", + "profit": " Profit earned by packing this item into the knapsack.", + "weight": " Weight consumed in the knapsack when this item is packed." + } + ] +} diff --git a/tasks/martello1999/mathematical_formulation.md b/tasks/martello1999/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..0a4a5e692bf69b53dd58931ea048d61c8619cc45 --- /dev/null +++ b/tasks/martello1999/mathematical_formulation.md @@ -0,0 +1,29 @@ +# Original Formulation (Eqs. 1a–1c) + +## Sets and Indices + +- $J = \{1, 2, \ldots, n\}$: set of items, indexed by $j \in J$. + +## Parameters + +- $n$: number of items (positive integer). + +- $p_j$: profit of item $j$ (positive integer), for all $j \in J$. + +- $w_j$: weight of item $j$ (positive integer), for all $j \in J$. + +- $c$: knapsack capacity (positive integer). + +Standard assumptions: $w_j \leq c$ for all $j$, and $\sum_{j=1}^{n} w_j > c$. + +## Decision Variables + +- $x_j \in \{0,1\}$: 1 if item $j$ is packed, 0 otherwise. + +## Objective and Constraints + +$$\begin{align} +\max \quad & z = \sum_{j=1}^{n} p_j\, x_j \tag{1a} \\ +\text{s.t.}\quad & \sum_{j=1}^{n} w_j\, x_j \leq c \tag{1b} \\ +& x_j \in \{0,1\}, \quad j \in \{1, \ldots, n\} \tag{1c} +\end{align}$$ diff --git a/tasks/martello1999/problem_description.txt b/tasks/martello1999/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..ade399edc1685f37ceb02e8dc1655ac420805712 --- /dev/null +++ b/tasks/martello1999/problem_description.txt @@ -0,0 +1,3 @@ +# Problem Description + +A collection of items is available, each with a known profit and a known weight, both of which are positive integers. A single knapsack is available with a given capacity that is also a positive integer. The total weight of all items exceeds the knapsack capacity, so not every item can be packed. Each individual item's weight does not exceed the capacity, meaning every item could in principle fit on its own. For each item, the decision is whether to pack it into the knapsack or leave it out; partial inclusion of an item is not allowed. The total weight of all packed items must not exceed the knapsack capacity. The goal is to select a subset of items to pack so as to maximize the total profit of the packed items. diff --git a/tasks/martello1999/solution_logger.py b/tasks/martello1999/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/martello1999/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/martello1999/solution_schema.json b/tasks/martello1999/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1e2821d595ad174331a60b4ababf7640c03b1f64 --- /dev/null +++ b/tasks/martello1999/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total profit of the selected items.", + "selected_items": " Identifiers of the items chosen to be placed in the knapsack." +} diff --git a/tasks/martin-iradi2024/feasibility_check.py b/tasks/martin-iradi2024/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..2d883d239952f1a40df5c8f63fdbef1b91c9f203 --- /dev/null +++ b/tasks/martin-iradi2024/feasibility_check.py @@ -0,0 +1,799 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Multi-Port Continuous Berth Allocation Problem (MCBAP). + +Checks all hard constraints from the MIP formulation (paper Equations 3-19), +numbered as Constraint 1-17 counting from top to bottom in the formulation, +plus an additional Constraint 18 that recomputes the objective from solution +variables and rejects when the reported objective_value disagrees (Tier C +defense against LLM score-gaming exploits). + +Constraint mapping: + 1 (Eq 3): Quay space limits: x_i^c + l_i <= L^p + 2 (Eq 4): Left-right positioning: x_i^c + l_i <= x_j^{c'} + L^p(1 - sigma) + 3 (Eq 5): Time ordering: y_i^c + h_i^c <= y_j^{c'} + M(1 - delta) + 4 (Eq 6): Non-overlapping: sigma+sigma+delta+delta >= 1 + 5 (Eq 7): Arrival time linking: y_i^c + h_i^c + travel = a_i^{c+1} + 6 (Eq 8): Berthing after arrival: a_i^c <= y_i^c + 7 (Eq 9): Earliest start time: EST_i^c <= y_i^c + 8 (Eq 10): Delay over EFT: y_i^c + h_i^c - EFT <= d_i^c + 9 (Eq 11): Delay over LFT: y_i^c + h_i^c - LFT <= u_i^c + 10 (Eq 12): Handling time: (1 + beta*r)*h0 = h + 11 (Eq 13): Position deviation right: x - x0 <= r + 12 (Eq 14): Position deviation left: x0 - x <= r + 13 (Eq 15): One speed per leg: sum_s v_{i,s}^c = 1 + 14 (Eq 16): Non-negativity x, y: x, y >= 0 + 15 (Eq 17): Non-negativity a,h,d,u,r: a,h,d,u,r >= 0 + 16 (Eq 18): Binary speed domain: v_{i,s}^c in {0,1} + 17 (Eq 19): Binary sigma/delta: sigma, delta in {0,1} + 18 (Obj): Objective envelope: reported objective_value must lie + between a tight lower bound recomputed + from solution variables and a loose + per-instance worst-case upper bound +""" + +import argparse +import json +import math +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'ships') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('objective_value', 'ships') +_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 main(): + parser = argparse.ArgumentParser(description="MCBAP feasibility checker") + parser.add_argument("--instance_path", required=True, help="Path to instance JSON") + parser.add_argument("--solution_path", required=True, help="Path to solution JSON") + parser.add_argument("--result_path", required=True, help="Path to write 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 + + tol = 1e-5 + eps = 1e-5 + + violations = [] + violation_magnitudes = [] + violated_constraints = set() + + # --- Extract instance data --- + beta = instance["handling_time_deviation_factor_beta_per_meter"] + ports = {p["id"]: p for p in instance["ports"]} + distances = instance["distances_nautical_miles"] + travel_times = instance["travel_time_hours_per_nm_by_speed"] + speeds = instance["speeds_knots"] + + # ------------------------------------------------------------------------- + # Empty solution guard: if solver returned no incumbent (objective_value + # is None and ships list empty/missing), do NOT vacuously return feasible + # — solution structure REQUIRES ships routing every port_visit. Mark + # feasi=False with a "no candidate" violation. (Earlier versions returned + # feasi=True because subsequent loops iterated over an empty ships list.) + # ------------------------------------------------------------------------- + if solution.get("objective_value") is None and not solution.get("ships"): + result = { + "feasible": False, + "violated_constraints": [1], + "violations": [ + "Empty solution (objective_value is None and ships list empty)" + " — no candidate routing to verify; constraint 1 (every " + "instance ship/port_visit must have a route) cannot be " + "satisfied." + ], + "violation_magnitudes": [{ + "constraint": 1, "lhs": 0.0, "rhs": 1.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }], + } + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + print("INFEASIBLE: Empty solution") + return + + # --- Build solution lookups --- + sol_ships = {s["ship_id"]: s for s in solution["ships"]} + sol_visits = {} + for s in solution["ships"]: + for pv in s["port_visits"]: + sol_visits[(s["ship_id"], pv["port_call_index"])] = pv + + inst_ships = {s["id"]: s for s in instance["ships"]} + inst_visits = {} + for s in instance["ships"]: + for pv in s["port_visits"]: + inst_visits[(s["id"], pv["port_call_index"])] = pv + + def add_violation(constraint_idx, msg, lhs, rhs, operator="<="): + if operator == "<=": + violation_amount = lhs - rhs + elif operator == ">=": + violation_amount = rhs - lhs + elif operator == "=": + violation_amount = abs(lhs - rhs) + else: + violation_amount = 0.0 + + if violation_amount > tol: + violated_constraints.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # A dictionary comprehension would otherwise hide duplicate ship/call + # entries, while all subsequent loops silently skip missing entries. Make + # the serialized witness an exact representation of the instance before + # checking any of its numerical constraints. + expected_ship_ids = [s["id"] for s in instance["ships"]] + reported_ship_ids = [s["ship_id"] for s in solution["ships"]] + if (len(reported_ship_ids) != len(set(reported_ship_ids)) + or set(reported_ship_ids) != set(expected_ship_ids)): + missing = sorted(set(expected_ship_ids) - set(reported_ship_ids)) + extra = sorted(set(reported_ship_ids) - set(expected_ship_ids)) + add_violation( + 1, + f"Ship witness mismatch: missing={missing}, extra={extra}, " + f"reported_entries={len(reported_ship_ids)}, " + f"unique_entries={len(set(reported_ship_ids))}", + 0.0, + 1.0, + "=", + ) + + expected_visit_keys = set(inst_visits) + reported_visit_keys = [] + for sol_ship in solution["ships"]: + sid = sol_ship["ship_id"] + reported_visit_keys.extend( + (sid, pv["port_call_index"]) + for pv in sol_ship.get("port_visits", []) + ) + if (len(reported_visit_keys) != len(set(reported_visit_keys)) + or set(reported_visit_keys) != expected_visit_keys): + missing = sorted(expected_visit_keys - set(reported_visit_keys)) + extra = sorted(set(reported_visit_keys) - expected_visit_keys) + add_violation( + 1, + f"Port-call witness mismatch: missing={missing[:20]}, " + f"extra={extra[:20]}, reported_entries={len(reported_visit_keys)}, " + f"expected_entries={len(expected_visit_keys)}", + 0.0, + 1.0, + "=", + ) + + # --- Gather all berth occupations per port (for non-overlapping checks) --- + port_occupations = defaultdict(list) + + for s in instance["ships"]: + ship_id = s["id"] + if ship_id not in sol_ships: + continue + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + port_id = pv_inst["port_id"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + port_occupations[port_id].append({ + "label": f"Ship {ship_id}", + "ship_id": ship_id, + "call_idx": c, + "x": sol_pv["berthing_position"], + "length": s["length_meters"], + "y_start": sol_pv["start_time"], + "y_end": sol_pv["start_time"] + sol_pv["handling_time"], + "is_external": False, + }) + + for ext_port in instance["external_ships"]: + port_id = ext_port["port_id"] + for ext_s in ext_port["ships"]: + port_occupations[port_id].append({ + "label": f"External {ext_s['id']} at {port_id}", + "ship_id": f"ext_{port_id}_{ext_s['id']}", + "call_idx": 0, + "x": ext_s["berthing_position"], + "length": ext_s["length_meters"], + "y_start": ext_s["start_time_hours"], + "y_end": ext_s["start_time_hours"] + ext_s["handling_time_hours"], + "is_external": True, + }) + + # ========================================================================= + # Constraint 1 (Eq 3): x_i^c + l_i <= L^p + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + port_id = pv_inst["port_id"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + x = sol_pv["berthing_position"] + l = s["length_meters"] + L_p = ports[port_id]["quay_length_meters"] + add_violation( + 1, + f"Ship {ship_id} call {c} at {port_id}: x({x})+l({l})={x+l} > L_p({L_p})", + x + l, L_p, "<=" + ) + + # Also check external ships + for ext_port in instance["external_ships"]: + port_id = ext_port["port_id"] + L_p = ports[port_id]["quay_length_meters"] + for ext_s in ext_port["ships"]: + x = ext_s["berthing_position"] + l = ext_s["length_meters"] + add_violation( + 1, + f"External ship {ext_s['id']} at {port_id}: x({x})+l({l})={x+l} > L_p({L_p})", + x + l, L_p, "<=" + ) + + # ========================================================================= + # Constraints 2-4 (Eqs 4-6): Non-overlapping + # Constraints 2 & 3 define sigma/delta via big-M (always satisfiable). + # Constraint 4 requires at least one ordering to hold. + # We derive sigma/delta from the solution and check constraint 4. + # ========================================================================= + for port_id, occs in port_occupations.items(): + L_p = ports[port_id]["quay_length_meters"] + for i_idx in range(len(occs)): + for j_idx in range(i_idx + 1, len(occs)): + oi = occs[i_idx] + oj = occs[j_idx] + + # Derive binary ordering variables + sigma_ij = 1 if oi["x"] + oi["length"] <= oj["x"] + tol else 0 + sigma_ji = 1 if oj["x"] + oj["length"] <= oi["x"] + tol else 0 + delta_ij = 1 if oi["y_end"] <= oj["y_start"] + tol else 0 + delta_ji = 1 if oj["y_end"] <= oi["y_start"] + tol else 0 + + lhs_sum = sigma_ij + sigma_ji + delta_ij + delta_ji + if lhs_sum < 1: + add_violation( + 4, + f"{oi['label']} call {oi['call_idx']} and {oj['label']} call {oj['call_idx']} " + f"overlap at {port_id} " + f"(space: [{oi['x']:.1f},{oi['x']+oi['length']:.1f}] vs " + f"[{oj['x']:.1f},{oj['x']+oj['length']:.1f}], " + f"time: [{oi['y_start']:.1f},{oi['y_end']:.1f}] vs " + f"[{oj['y_start']:.1f},{oj['y_end']:.1f}])", + float(lhs_sum), 1.0, ">=" + ) + + # ========================================================================= + # Constraint 5 (Eq 7): Arrival time linking + # y_i^c + h_i^c + sum_s v_{i,s}^c * Theta_s * Delta^{rho_c, rho_{c+1}} = a_i^{c+1} + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + sol_ship = sol_ships.get(ship_id) + if sol_ship is None: + continue + pvs = sorted(s["port_visits"], key=lambda pv: pv["port_call_index"]) + for idx in range(len(pvs) - 1): + pv_curr = pvs[idx] + pv_next = pvs[idx + 1] + c = pv_curr["port_call_index"] + c_next = pv_next["port_call_index"] + + sol_curr = sol_visits.get((ship_id, c)) + sol_next = sol_visits.get((ship_id, c_next)) + if sol_curr is None or sol_next is None: + continue + + # Find speed selection for this leg + speed_knots = None + for ss in sol_ship["speed_selections"]: + if ss["from_call"] == c and ss["to_call"] == c_next: + speed_knots = ss["speed_knots"] + break + + if speed_knots is None: + add_violation( + 13, f"Ship {ship_id}: no speed selection from call {c} to {c_next}", + 0.0, 1.0, ">=" + ) + continue + + from_port = pv_curr["port_id"] + to_port = pv_next["port_id"] + dist_key = f"{from_port}_{to_port}" + distance = distances.get(dist_key, 0) + theta_s = travel_times.get(str(speed_knots), 0) + travel_time = theta_s * distance + + lhs = sol_curr["start_time"] + sol_curr["handling_time"] + travel_time + rhs = sol_next["arrival_time"] + add_violation( + 5, + f"Ship {ship_id}: y({sol_curr['start_time']})+h({sol_curr['handling_time']})" + f"+travel({travel_time:.4f})={lhs:.4f} != arrival({rhs})", + lhs, rhs, "=" + ) + + # ========================================================================= + # Constraint 6 (Eq 8): a_i^c <= y_i^c + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + a = sol_pv["arrival_time"] + y = sol_pv["start_time"] + add_violation( + 6, f"Ship {ship_id} call {c}: arrival({a}) > start_time({y})", + a, y, "<=" + ) + + # ========================================================================= + # Constraint 7 (Eq 9): EST_i^c <= y_i^c + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + est = pv_inst["earliest_start_time_hours"] + y = sol_pv["start_time"] + add_violation( + 7, f"Ship {ship_id} call {c}: EST({est}) > start_time({y})", + est, y, "<=" + ) + + # ========================================================================= + # Constraint 8 (Eq 10): y_i^c + h_i^c - EFT_i^c <= d_i^c + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + y = sol_pv["start_time"] + h = sol_pv["handling_time"] + eft = pv_inst["expected_finish_time_hours"] + d = sol_pv["delay"] + lhs = y + h - eft + add_violation( + 8, f"Ship {ship_id} call {c}: y+h-EFT={lhs:.6f} > delay({d})", + lhs, d, "<=" + ) + + # ========================================================================= + # Constraint 9 (Eq 11): y_i^c + h_i^c - LFT_i^c <= u_i^c + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + y = sol_pv["start_time"] + h = sol_pv["handling_time"] + lft = pv_inst["latest_finish_time_hours"] + u = sol_pv["lft_violation"] + lhs = y + h - lft + add_violation( + 9, f"Ship {ship_id} call {c}: y+h-LFT={lhs:.6f} > lft_violation({u})", + lhs, u, "<=" + ) + + # ========================================================================= + # Constraint 10 (Eq 12): (1 + beta * r) * h0 = h + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + h0 = pv_inst["min_handling_time_hours"] + r = sol_pv["position_deviation"] + h = sol_pv["handling_time"] + lhs = (1 + beta * r) * h0 + add_violation( + 10, + f"Ship {ship_id} call {c}: (1+{beta}*{r})*{h0}={lhs:.6f} != h({h})", + lhs, h, "=" + ) + + # ========================================================================= + # Constraint 11 (Eq 13): x - x0 <= r + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + x = sol_pv["berthing_position"] + x0 = pv_inst["ideal_berthing_position"] + r = sol_pv["position_deviation"] + add_violation( + 11, + f"Ship {ship_id} call {c}: x({x})-x0({x0})={x-x0:.6f} > r({r})", + x - x0, r, "<=" + ) + + # ========================================================================= + # Constraint 12 (Eq 14): x0 - x <= r + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + x = sol_pv["berthing_position"] + x0 = pv_inst["ideal_berthing_position"] + r = sol_pv["position_deviation"] + add_violation( + 12, + f"Ship {ship_id} call {c}: x0({x0})-x({x})={x0-x:.6f} > r({r})", + x0 - x, r, "<=" + ) + + # ========================================================================= + # Constraint 13 (Eq 15): Exactly one speed per sailing leg + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + sol_ship = sol_ships.get(ship_id) + if sol_ship is None: + continue + pvs = sorted(s["port_visits"], key=lambda pv: pv["port_call_index"]) + for idx in range(len(pvs) - 1): + c = pvs[idx]["port_call_index"] + c_next = pvs[idx + 1]["port_call_index"] + count = sum( + 1 for ss in sol_ship["speed_selections"] + if ss["from_call"] == c and ss["to_call"] == c_next + ) + if count != 1: + add_violation( + 13, + f"Ship {ship_id}: {count} speed selections from call {c} to {c_next} (expected 1)", + float(count), 1.0, "=" + ) + + # ========================================================================= + # Constraint 14 (Eq 16): x_i^c >= 0, y_i^c >= 0 + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + x = sol_pv["berthing_position"] + y = sol_pv["start_time"] + if x < -tol: + add_violation( + 14, f"Ship {ship_id} call {c}: x({x}) < 0", + 0.0, x, "<=" + ) + if y < -tol: + add_violation( + 14, f"Ship {ship_id} call {c}: y({y}) < 0", + 0.0, y, "<=" + ) + + # ========================================================================= + # Constraint 15 (Eq 17): a, h, d, u, r >= 0 + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + for pv_inst in s["port_visits"]: + c = pv_inst["port_call_index"] + sol_pv = sol_visits.get((ship_id, c)) + if sol_pv is None: + continue + var_checks = [ + ("arrival_time", sol_pv["arrival_time"]), + ("handling_time", sol_pv["handling_time"]), + ("delay", sol_pv["delay"]), + ("lft_violation", sol_pv["lft_violation"]), + ("position_deviation", sol_pv["position_deviation"]), + ] + for var_name, val in var_checks: + if val < -tol: + add_violation( + 15, f"Ship {ship_id} call {c}: {var_name}({val}) < 0", + 0.0, val, "<=" + ) + + # ========================================================================= + # Constraint 16 (Eq 18): Speed variables are binary (valid speed chosen) + # ========================================================================= + for s in instance["ships"]: + ship_id = s["id"] + sol_ship = sol_ships.get(ship_id) + if sol_ship is None: + continue + for ss in sol_ship["speed_selections"]: + spd = ss["speed_knots"] + if spd not in speeds: + add_violation( + 16, + f"Ship {ship_id}: speed {spd} from call {ss['from_call']} " + f"to {ss['to_call']} not in allowed speeds {speeds}", + 0.0, 1.0, ">=" + ) + + # ========================================================================= + # Constraint 17 (Eq 19): sigma/delta binary - trivially satisfied + # (Derived from solution; always binary by construction) + # ========================================================================= + # No check needed - sigma/delta are not decision variables in the solution. + + # ========================================================================= + # Constraint 18 (Obj): exact objective consistency. + # Every cost-bearing variable is serialized: call timing/slack values and + # one speed for every sailing leg. With the exact ship/call coverage check + # above, the objective is therefore a value, not an envelope. + # ========================================================================= + reported_raw = solution.get("objective_value") + reported_obj = None + if reported_raw is not None: + try: + reported_obj = float(reported_raw) + except (TypeError, ValueError): + reported_obj = None + + if reported_obj is not None: + cp = instance.get("cost_parameters", {}) + I_c = cp.get("waiting_cost_usd_per_hour", 0) + H_c = cp.get("handling_cost_usd_per_hour", 0) + D_c = cp.get("delay_cost_usd_per_hour", 0) + U_c = cp.get("lft_penalty_usd", 0) + F_c = cp.get("fuel_price_usd_per_tonne", 0) + true_obj = 0.0 + for inst_s in instance["ships"]: + ship_id = inst_s["id"] + sol_ship = sol_ships.get(ship_id) + if sol_ship is None: + continue + inst_pvs_by_call = {pv["port_call_index"]: pv for pv in inst_s["port_visits"]} + fuel_by_speed = inst_s.get("fuel_consumption_per_nm_by_speed", {}) + + for pv in sol_ship.get("port_visits", []): + a = pv.get("arrival_time", 0.0) + y = pv.get("start_time", 0.0) + h = pv.get("handling_time", 0.0) + d = pv.get("delay", 0.0) + u = pv.get("lft_violation", 0.0) + true_obj += I_c * (y - a) + H_c * h + D_c * d + U_c * u + + for ss in sol_ship.get("speed_selections", []): + spd = ss.get("speed_knots") + c = ss.get("from_call") + c_next = ss.get("to_call") + if spd is None or c is None or c_next is None: + continue + pv_from = inst_pvs_by_call.get(c) + pv_to = inst_pvs_by_call.get(c_next) + if pv_from is None or pv_to is None: + continue + dist_key = f"{pv_from['port_id']}_{pv_to['port_id']}" + distance = distances.get(dist_key, 0) + gamma = fuel_by_speed.get(str(spd)) + if gamma is None: + try: + gamma = fuel_by_speed.get(f"{float(spd):.1f}") + except (TypeError, ValueError): + gamma = None + if gamma is None: + continue + true_obj += F_c * gamma * distance + + obj_tol = max(1e-3, 1e-8 * max(abs(true_obj), 1.0)) + if not math.isfinite(reported_obj) or abs(reported_obj - true_obj) > obj_tol: + add_violation( + 18, + f"Objective consistency violated: reported objective_value=" + f"{reported_obj} differs from the fully recomputed cost " + f"{true_obj} (absolute difference=" + f"{abs(reported_obj - true_obj):.6g}, tol={obj_tol:.6g})", + reported_obj, true_obj, "=" + ) + + # --- Build output --- + unique_violated = sorted(violated_constraints) + + result = { + "feasible": len(violated_constraints) == 0, + "violated_constraints": unique_violated, + "violations": violations, + "violation_magnitudes": violation_magnitudes + if violation_magnitudes + else [], + } + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"{status}: {len(unique_violated)} constraint(s) violated, " + f"{len(violation_magnitudes)} violation instance(s)") + + +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/martin-iradi2024/gurobi_code.py b/tasks/martin-iradi2024/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..b274fb98cff2073f6d15100fa337d235dabce756 --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_code.py @@ -0,0 +1,494 @@ +#!/usr/bin/env python3 +""" +Gurobi MIP formulation for the Multi-Port Continuous Berth Allocation Problem (MCBAP). + +Based on: Martin-Iradi, Pacino, Ropke (2023) - "An adaptive large neighborhood search +heuristic for the multi-port continuous berth allocation problem" + +Implements the MIP formulation from Section 3.1 (Equations 2-19). +""" + +import argparse +import json +import sys +import math +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(path): + """Load a problem instance from a JSON file.""" + with open(path, 'r') as f: + return json.load(f) + + +def build_and_solve(instance, time_limit): + """Build and solve the MCBAP MIP model using Gurobi.""" + + # ------------------------------------------------------------------------- + # Extract instance data + # ------------------------------------------------------------------------- + cost_params = instance["cost_parameters"] + F_cost = cost_params["fuel_price_usd_per_tonne"] + H_cost = cost_params["handling_cost_usd_per_hour"] + D_cost = cost_params["delay_cost_usd_per_hour"] + I_cost = cost_params["waiting_cost_usd_per_hour"] + U_cost = cost_params["lft_penalty_usd"] + + beta = instance["handling_time_deviation_factor_beta_per_meter"] + + # Ports + ports = {p["id"]: p for p in instance["ports"]} + port_ids = [p["id"] for p in instance["ports"]] + quay_lengths = {p["id"]: p["quay_length_meters"] for p in instance["ports"]} + + # Distances between ports + distances = {} + for key, val in instance["distances_nautical_miles"].items(): + parts = key.split("_") + p1, p2 = parts[0], parts[1] + distances[(p1, p2)] = val + + # Speeds + speeds = instance["speeds_knots"] + speed_strs = [str(s) for s in speeds] + travel_time_per_nm = instance["travel_time_hours_per_nm_by_speed"] + + # Ships to optimize (N*) + ships = instance["ships"] + + # External ships (N_bar) - fixed + external_ships_by_port = {} + for ext_group in instance["external_ships"]: + pid = ext_group["port_id"] + external_ships_by_port[pid] = ext_group["ships"] + + # ------------------------------------------------------------------------- + # Build index structures + # ------------------------------------------------------------------------- + + # For each optimized ship i, build its port visits + # ship_visits[(i, c)] = dict with port_id, ideal_pos, h0, EST, EFT, LFT, etc. + ship_visits = {} + ship_data = {} + for ship in ships: + sid = ship["id"] + ship_data[sid] = ship + for pv in ship["port_visits"]: + c = pv["port_call_index"] + ship_visits[(sid, c)] = { + "port_id": pv["port_id"], + "ideal_pos": pv["ideal_berthing_position"], + "h0": pv["min_handling_time_hours"], + "h_max": pv["max_handling_time_hours"], + "EST": pv["earliest_start_time_hours"], + "EFT": pv["expected_finish_time_hours"], + "LFT": pv["latest_finish_time_hours"], + } + + # N_p: set of (ship_id, call_index) visiting port p (optimized ships) + # Also build external ship visits at each port + opt_visits_at_port = {pid: [] for pid in port_ids} + for (sid, c), info in ship_visits.items(): + opt_visits_at_port[info["port_id"]].append((sid, c)) + + ext_visits_at_port = {pid: [] for pid in port_ids} + for pid in port_ids: + if pid in external_ships_by_port: + for es in external_ships_by_port[pid]: + ext_visits_at_port[pid].append(es) + + # All visits at port (for non-overlap constraints): combine optimized and external + # External ships are identified by ("ext", port_id, ext_id) + # Optimized ships by (ship_id, call_index) + + # For each optimized ship, get max call index + ship_max_call = {} + for ship in ships: + sid = ship["id"] + ship_max_call[sid] = max(pv["port_call_index"] for pv in ship["port_visits"]) + + # ------------------------------------------------------------------------- + # Create Gurobi model + # ------------------------------------------------------------------------- + model = gp.Model("MCBAP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # ------------------------------------------------------------------------- + # Decision variables for optimized ships + # ------------------------------------------------------------------------- + # x[i,c]: leftmost berthing position + x = {} + # y[i,c]: start time of berthing + y = {} + # h[i,c]: handling time + h = {} + # a[i,c]: arrival time + a = {} + # d[i,c]: delay over EFT + d = {} + # u[i,c]: delay over LFT + u = {} + # r[i,c]: distance from ideal position + r = {} + + for (sid, c), info in ship_visits.items(): + L_p = quay_lengths[info["port_id"]] + l_i = ship_data[sid]["length_meters"] + + x[sid, c] = model.addVar(lb=0, ub=L_p - l_i, name=f"x_{sid}_{c}") + y[sid, c] = model.addVar(lb=info["EST"], name=f"y_{sid}_{c}") + h[sid, c] = model.addVar(lb=info["h0"], name=f"h_{sid}_{c}") + a[sid, c] = model.addVar(lb=0, name=f"a_{sid}_{c}") + d[sid, c] = model.addVar(lb=0, name=f"d_{sid}_{c}") + u[sid, c] = model.addVar(lb=0, name=f"u_{sid}_{c}") + r[sid, c] = model.addVar(lb=0, name=f"r_{sid}_{c}") + + # v[i,s,c]: speed selection binary (for non-last calls) + v = {} + for ship in ships: + sid = ship["id"] + max_c = ship_max_call[sid] + fuel_per_nm = ship["fuel_consumption_per_nm_by_speed"] + for c_idx in range(1, max_c): # c in C_i \ {c_i} + for s_str in speed_strs: + v[sid, s_str, c_idx] = model.addVar( + vtype=GRB.BINARY, name=f"v_{sid}_{s_str}_{c_idx}" + ) + + # sigma[i,c,j,c']: ship i left of ship j at port p + # delta[i,c,j,c']: ship i finishes before ship j starts at port p + sigma = {} + delta_var = {} + + for pid in port_ids: + # Collect all visits at this port (optimized + external) + all_visits = [] + for (sid, c) in opt_visits_at_port[pid]: + all_visits.append(("opt", sid, c)) + for es in ext_visits_at_port[pid]: + all_visits.append(("ext", pid, es["id"])) + + # For each pair (i != j), create sigma and delta variables + for idx_a in range(len(all_visits)): + for idx_b in range(len(all_visits)): + if idx_a == idx_b: + continue + va = all_visits[idx_a] + vb = all_visits[idx_b] + key = (va, vb, pid) + sigma[key] = model.addVar(vtype=GRB.BINARY, name=f"sigma_{va}_{vb}_{pid}") + delta_var[key] = model.addVar(vtype=GRB.BINARY, name=f"delta_{va}_{vb}_{pid}") + + model.update() + + # ------------------------------------------------------------------------- + # Helper: get position, start time, handling time, length for any visit + # ------------------------------------------------------------------------- + def get_visit_vars(visit_tuple): + """Return (x_var_or_val, y_var_or_val, h_var_or_val, length) for a visit.""" + if visit_tuple[0] == "opt": + sid, c = visit_tuple[1], visit_tuple[2] + return x[sid, c], y[sid, c], h[sid, c], ship_data[sid]["length_meters"] + else: + # External ship + pid_ext = visit_tuple[1] + eid = visit_tuple[2] + for es in external_ships_by_port[pid_ext]: + if es["id"] == eid: + return (es["berthing_position"], es["start_time_hours"], + es["handling_time_hours"], es["length_meters"]) + raise ValueError(f"External ship not found: {visit_tuple}") + + # ------------------------------------------------------------------------- + # Constraints + # ------------------------------------------------------------------------- + + # Constraint (3): Ships berth within available quay space + for (sid, c), info in ship_visits.items(): + l_i = ship_data[sid]["length_meters"] + L_p = quay_lengths[info["port_id"]] + model.addConstr(x[sid, c] + l_i <= L_p, name=f"quay_{sid}_{c}") + + # Constraints (4), (5), (6): Non-overlapping for each port + for pid in port_ids: + all_visits = [] + for (sid, c) in opt_visits_at_port[pid]: + all_visits.append(("opt", sid, c)) + for es in ext_visits_at_port[pid]: + all_visits.append(("ext", pid, es["id"])) + + L_p = quay_lengths[pid] + + for idx_a in range(len(all_visits)): + for idx_b in range(len(all_visits)): + if idx_a == idx_b: + continue + va = all_visits[idx_a] + vb = all_visits[idx_b] + key_ab = (va, vb, pid) + + x_a, y_a, h_a, l_a = get_visit_vars(va) + x_b, y_b, h_b, l_b = get_visit_vars(vb) + + # Constraint (4): x_i^c + l_i <= x_j^{c'} + L_p*(1 - sigma) + model.addConstr( + x_a + l_a <= x_b + L_p * (1 - sigma[key_ab]), + name=f"space_{va}_{vb}_{pid}" + ) + + # Constraint (5): y_i^c + h_i^c <= y_j^{c'} + M*(1 - delta) + # Big-M: use a large value based on planning horizon + # INFERRED ASSUMPTION: M is set to the planning horizon in hours, + # as the paper states "M can be limited to the latest finish time + # of the pair of ships". We use planning_horizon_hours as a safe upper bound. + M_val = instance.get("planning_horizon_hours", 10000) + model.addConstr( + y_a + h_a <= y_b + M_val * (1 - delta_var[key_ab]), + name=f"time_{va}_{vb}_{pid}" + ) + + # Constraint (6): sigma_ij + sigma_ji + delta_ij + delta_ji >= 1 + # Only for i < j (to avoid redundant constraints) + for idx_a in range(len(all_visits)): + for idx_b in range(idx_a + 1, len(all_visits)): + va = all_visits[idx_a] + vb = all_visits[idx_b] + key_ab = (va, vb, pid) + key_ba = (vb, va, pid) + model.addConstr( + sigma[key_ab] + sigma[key_ba] + + delta_var[key_ab] + delta_var[key_ba] >= 1, + name=f"nonoverlap_{va}_{vb}_{pid}" + ) + + # Constraint (7): Arrival time linking via sailing speed + for ship in ships: + sid = ship["id"] + max_c = ship_max_call[sid] + fuel_per_nm = ship["fuel_consumption_per_nm_by_speed"] + route = ship["route"] + + for c_idx in range(1, max_c): # c in C_i \ {c_i} + next_c = c_idx + 1 + port_from = ship_visits[(sid, c_idx)]["port_id"] + port_to = ship_visits[(sid, next_c)]["port_id"] + dist = distances[(port_from, port_to)] + + travel_expr = gp.LinExpr() + for s_str in speed_strs: + theta_s = travel_time_per_nm[s_str] + travel_expr += v[sid, s_str, c_idx] * theta_s * dist + + # y_i^c + h_i^c + travel_time = a_i^{c+1} + model.addConstr( + y[sid, c_idx] + h[sid, c_idx] + travel_expr == a[sid, next_c], + name=f"arrival_{sid}_{c_idx}" + ) + + # Constraint (8): Berthing starts after arrival + for (sid, c), info in ship_visits.items(): + model.addConstr(a[sid, c] <= y[sid, c], name=f"arr_before_berth_{sid}_{c}") + + # For the first port call, arrival time = EST (or could be earlier) + # INFERRED ASSUMPTION: For the first port call (c=1), arrival time a_i^1 + # is not linked by constraint (7). We set a_i^1 <= y_i^1 via constraint (8) + # and a_i^1 >= 0 via non-negativity. The waiting cost will push a_i^1 close to y_i^1. + # Actually, for the first call, a_i^1 is the ship's arrival time at the first port. + # The paper doesn't explicitly define it; we assume a_i^1 = EST_i^1 as the earliest + # the ship could arrive, so waiting cost = y_i^1 - EST_i^1. + for ship in ships: + sid = ship["id"] + first_c = 1 + est = ship_visits[(sid, first_c)]["EST"] + # INFERRED ASSUMPTION: a_i^1 = EST_i^1 for the first port call. + # This means the ship arrives exactly at the earliest start time. + # The paper doesn't provide a separate arrival time for the first visit. + model.addConstr(a[sid, first_c] == est, name=f"first_arrival_{sid}") + + # Constraint (9): Berthing starts after earliest start time + # (Already enforced by lb on y variables) + + # Constraint (10): Delay over expected finish time + for (sid, c), info in ship_visits.items(): + model.addConstr( + y[sid, c] + h[sid, c] - info["EFT"] <= d[sid, c], + name=f"delay_{sid}_{c}" + ) + + # Constraint (11): Delay over latest finish time + for (sid, c), info in ship_visits.items(): + model.addConstr( + y[sid, c] + h[sid, c] - info["LFT"] <= u[sid, c], + name=f"lft_delay_{sid}_{c}" + ) + + # Constraint (12): Handling time depends on deviation from ideal position + # h_i^c = (1 + beta * r^{i,c}) * h_0^{i,c} + # => h_i^c = h_0 + beta * h_0 * r^{i,c} (linear since h_0 is a parameter) + for (sid, c), info in ship_visits.items(): + h0 = info["h0"] + model.addConstr( + h[sid, c] == h0 + beta * h0 * r[sid, c], + name=f"handling_{sid}_{c}" + ) + + # Constraints (13), (14): Position deviation + for (sid, c), info in ship_visits.items(): + x0 = info["ideal_pos"] + model.addConstr(x[sid, c] - x0 <= r[sid, c], name=f"dev_right_{sid}_{c}") + model.addConstr(x0 - x[sid, c] <= r[sid, c], name=f"dev_left_{sid}_{c}") + + # Constraint (15): Exactly one speed chosen per sailing leg + for ship in ships: + sid = ship["id"] + max_c = ship_max_call[sid] + for c_idx in range(1, max_c): + model.addConstr( + gp.quicksum(v[sid, s_str, c_idx] for s_str in speed_strs) == 1, + name=f"one_speed_{sid}_{c_idx}" + ) + + # ------------------------------------------------------------------------- + # Objective function (Equation 2) + # ------------------------------------------------------------------------- + obj = gp.LinExpr() + + for ship in ships: + sid = ship["id"] + max_c = ship_max_call[sid] + fuel_per_nm = ship["fuel_consumption_per_nm_by_speed"] + route = ship["route"] + + for pv in ship["port_visits"]: + c = pv["port_call_index"] + # Waiting cost: I * (y_i^c - a_i^c) + obj += I_cost * (y[sid, c] - a[sid, c]) + # Handling cost: H * h_i^c + obj += H_cost * h[sid, c] + # Delay cost: D * d_i^c + obj += D_cost * d[sid, c] + # LFT penalty: U * u_i^c + obj += U_cost * u[sid, c] + + # Fuel cost for sailing legs + for c_idx in range(1, max_c): + next_c = c_idx + 1 + port_from = ship_visits[(sid, c_idx)]["port_id"] + port_to = ship_visits[(sid, next_c)]["port_id"] + dist = distances[(port_from, port_to)] + + for s_str in speed_strs: + gamma_s = fuel_per_nm[s_str] + # Fuel cost = F * gamma_s * distance * v_{i,s}^c + obj += F_cost * gamma_s * dist * v[sid, s_str, c_idx] + + model.setObjective(obj, GRB.MINIMIZE) + + # ------------------------------------------------------------------------- + # 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 + + ship_solutions = [] + for ship in ships: + sid = ship["id"] + max_c = ship_max_call[sid] + ship_sol = {"ship_id": sid, "port_visits": []} + + for pv in ship["port_visits"]: + c = pv["port_call_index"] + pv_sol = { + "port_call_index": c, + "port_id": pv["port_id"], + "berthing_position": x[sid, c].X, + "start_time": y[sid, c].X, + "handling_time": h[sid, c].X, + "arrival_time": a[sid, c].X, + "delay": d[sid, c].X, + "lft_violation": u[sid, c].X, + "position_deviation": r[sid, c].X, + } + ship_sol["port_visits"].append(pv_sol) + + # Speed selections + speed_selections = [] + for c_idx in range(1, max_c): + for s_str in speed_strs: + if v[sid, s_str, c_idx].X > 0.5: + speed_selections.append({ + "from_call": c_idx, + "to_call": c_idx + 1, + "speed_knots": float(s_str) + }) + break + ship_sol["speed_selections"] = speed_selections + ship_solutions.append(ship_sol) + + solution["ships"] = ship_solutions + else: + solution["objective_value"] = None + solution["status"] = model.Status + solution["ships"] = [] + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi MIP solver for the Multi-Port Continuous Berth Allocation 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) + + 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) + + print(f"Solution written to {args.solution_path}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']:.2f}") + else: + print("No feasible solution found within time limit.") + + +if __name__ == "__main__": + main() diff --git a/tasks/martin-iradi2024/gurobi_feasi_result/large_feasi_result_1.json b/tasks/martin-iradi2024/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martin-iradi2024/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/martin-iradi2024/gurobi_feasi_result/large_feasi_result_2.json b/tasks/martin-iradi2024/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martin-iradi2024/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/martin-iradi2024/gurobi_feasi_result/large_feasi_result_3.json b/tasks/martin-iradi2024/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martin-iradi2024/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/martin-iradi2024/gurobi_feasi_result/large_feasi_result_4.json b/tasks/martin-iradi2024/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martin-iradi2024/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/martin-iradi2024/gurobi_feasi_result/large_feasi_result_5.json b/tasks/martin-iradi2024/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martin-iradi2024/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/martin-iradi2024/gurobi_feasi_result/tiny_feasi_result.json b/tasks/martin-iradi2024/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/martin-iradi2024/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/martin-iradi2024/gurobi_solution/large_solution_1.json b/tasks/martin-iradi2024/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..cee9763034a90749641b1120a381b6d2cb8cad4d --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44de8d6304b253f590cde4a81537b55df9c69f32676b0d68e561cf4d5ec9d7d9 +size 36757 diff --git a/tasks/martin-iradi2024/gurobi_solution/large_solution_2.json b/tasks/martin-iradi2024/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..706cee1bdd41ced530f59362489566c029ddb826 --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e3182bfe55c7c0f9c35b2f4aa8b190c2c24feea8688154ef7ac33ef70d9e323e +size 36018 diff --git a/tasks/martin-iradi2024/gurobi_solution/large_solution_3.json b/tasks/martin-iradi2024/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..de5f4e25d0ec1d9d4c6faac15908c24bffefa890 --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e58fcc706cb223c691376523822277abd24d439c92d2951e45d78ae368ed5694 +size 35689 diff --git a/tasks/martin-iradi2024/gurobi_solution/large_solution_4.json b/tasks/martin-iradi2024/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..d1bf3e1578032b81083530b1206b79a54d1f9556 --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc6fbda4d8c5b2d81b5cc09010551ff87c79646a503dcdc908f8b914aeec29ed +size 36036 diff --git a/tasks/martin-iradi2024/gurobi_solution/large_solution_5.json b/tasks/martin-iradi2024/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8884f0203ddb7a0b336cccbe2a56576b2b94944d --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81e1fecc11b2dd2acafdbfba77093949bfa8f97ae507b36b73ed014879359e5d +size 38372 diff --git a/tasks/martin-iradi2024/gurobi_solution/tiny_solution.json b/tasks/martin-iradi2024/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..98595963fc23e0533da15153fddd1f6aeb450837 --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01dd38aa9dfa098809fccf12334acf637ef3bfb25cc339134a9ebd50b4527c01 +size 3871 diff --git a/tasks/martin-iradi2024/gurobi_solution_log/large_log_1.jsonl b/tasks/martin-iradi2024/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f3219f8f74c89983772608d212fe779acb392f63 --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb6138476900388a333c5f133b3afc941cb807c7ce206a626132aa2f78c99d47 +size 4629 diff --git a/tasks/martin-iradi2024/gurobi_solution_log/large_log_2.jsonl b/tasks/martin-iradi2024/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1193e5296cdef17afa265fb4bee3bb0d682dd07b --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c18aec45b4050e9d8efa3b74f77eca2c1924fc62945f593679e64dd109dc8cb2 +size 4640 diff --git a/tasks/martin-iradi2024/gurobi_solution_log/large_log_3.jsonl b/tasks/martin-iradi2024/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5b51534c50a987dc704875421e82974d9ab4e95b --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46ef082810aba736f4c2bb6dc5496d15cc79293e877efc35c247b862c5e71266 +size 5832 diff --git a/tasks/martin-iradi2024/gurobi_solution_log/large_log_4.jsonl b/tasks/martin-iradi2024/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dfcda34c43cc652ed66b9770f989a523e10be092 --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3953227d23953fa74e3a5f0a9132c09cc75ab65ccf99cb376c8c105a21da5ca +size 6662 diff --git a/tasks/martin-iradi2024/gurobi_solution_log/large_log_5.jsonl b/tasks/martin-iradi2024/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..644e1246f46efbbc8cc79ebdf12a4db9d3858896 --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fb4c35d289484cd708ed63995d9b7f9957789c4cf1991849e0e2e44ba4b6ba9 +size 5028 diff --git a/tasks/martin-iradi2024/gurobi_solution_log/tiny_log.jsonl b/tasks/martin-iradi2024/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0a5d159b4a7036428b55728240f83a771765a990 --- /dev/null +++ b/tasks/martin-iradi2024/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75fe969907b9eb99540cf94f7b2cf729b6d1a744543d0177085a0d376204d301 +size 55 diff --git a/tasks/martin-iradi2024/instance/large_instance_1.json b/tasks/martin-iradi2024/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..495194c1626f62343a891b1e10135f3c131e48ce --- /dev/null +++ b/tasks/martin-iradi2024/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04b86a2b8ea90f70b8e7ad9cba796879d72499994ab391f02100bd89c019b2ca +size 55836 diff --git a/tasks/martin-iradi2024/instance/large_instance_2.json b/tasks/martin-iradi2024/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4ac8e5c3956b52d9f3907957437b946fbb9a7da9 --- /dev/null +++ b/tasks/martin-iradi2024/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:414e546e99e21aee723df661ddc6be689349367bbf02c9f7f9455682f268699e +size 55826 diff --git a/tasks/martin-iradi2024/instance/large_instance_3.json b/tasks/martin-iradi2024/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..fa39beba8773746efb6c6a6abdb6dae095e33bce --- /dev/null +++ b/tasks/martin-iradi2024/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4edbb6fd8fada5fd1990d2c3deafaed9525fdfcde85ca340bc57cc587ae7907 +size 54695 diff --git a/tasks/martin-iradi2024/instance/large_instance_4.json b/tasks/martin-iradi2024/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..7e10bdb0051c832d927eac9719b928376430a80d --- /dev/null +++ b/tasks/martin-iradi2024/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d935eefcf2d4a99ceee6deeaee8d0b99f7b5685e963258bc5db1d516a5b7824b +size 55422 diff --git a/tasks/martin-iradi2024/instance/large_instance_5.json b/tasks/martin-iradi2024/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..cb6792216cad7d78c8feb57ee1f963589daaa7ad --- /dev/null +++ b/tasks/martin-iradi2024/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:626049904c721732e51c98eb5aa06e533830dc733dac4666e2f4f75f14ba0373 +size 56933 diff --git a/tasks/martin-iradi2024/instance/tiny_instance.json b/tasks/martin-iradi2024/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..fbd43c358dc34e32b146445c84d46633d7c6e8bd --- /dev/null +++ b/tasks/martin-iradi2024/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:733afd244bf250b00ad4792063704d651349377c3c3c371da477af86ee637cdc +size 9014 diff --git a/tasks/martin-iradi2024/instance_schema.json b/tasks/martin-iradi2024/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..83fb146df85bbb677156793717e7cf83e7f7de2d --- /dev/null +++ b/tasks/martin-iradi2024/instance_schema.json @@ -0,0 +1,58 @@ +{ + "planning_horizon_hours": " Total length of the scheduling period in hours.", + "cost_parameters": { + "fuel_price_usd_per_tonne": " Price of bunker fuel per metric tonne in US dollars.", + "handling_cost_usd_per_hour": " Cost per hour of cargo handling at berth in US dollars.", + "delay_cost_usd_per_hour": " Cost per hour of finishing after the expected finish time in US dollars.", + "waiting_cost_usd_per_hour": " Cost per hour a ship waits at anchorage before berthing in US dollars.", + "lft_penalty_usd": " Penalty in US dollars for each hour of finishing after the latest finish time." + }, + "handling_time_deviation_factor_beta_per_meter": " Rate at which handling time increases per meter of deviation from the ideal berthing position.", + "ports": [ + { + "id": " Unique port identifier code.", + "quay_length_meters": " Total usable quay length at the port in meters." + } + ], + "distances_nautical_miles": " Sailing distance in nautical miles between each ordered pair of ports.", + "speeds_knots": " Set of discrete sailing speeds available to all ships in knots.", + "travel_time_hours_per_nm_by_speed": " Hours required to sail one nautical mile at each available speed.", + "ships": [ + { + "id": " Unique ship identifier.", + "type": " Ship size category (feeder, medium, or large).", + "length_meters": " Overall length of the ship in meters.", + "design_speed_knots": " Nominal cruising speed of the ship in knots.", + "fuel_consumption_at_design_speed_tonnes_per_day": " Daily fuel consumption when sailing at design speed in metric tonnes.", + "fuel_consumption_per_nm_by_speed": " Fuel consumed per nautical mile at each available sailing speed in metric tonnes.", + "route": " Ordered sequence of port identifiers the ship must visit.", + "port_visits": [ + { + "port_call_index": " Position of this visit in the ship's route sequence, starting from 1.", + "port_id": " Identifier of the port being visited.", + "ideal_berthing_position": " Preferred leftmost quay coordinate in meters where the ship should berth.", + "min_handling_time_hours": " Minimum cargo handling duration in hours when berthed at the ideal position.", + "max_handling_time_hours": " Maximum possible cargo handling duration in hours when berthed at the worst position.", + "earliest_start_time_hours": " Earliest hour at which berthing may begin.", + "expected_finish_time_hours": " Target departure hour equal to earliest start time plus minimum handling time.", + "latest_finish_time_hours": " Latest acceptable departure hour before penalty costs apply." + } + ] + } + ], + "external_ships": [ + { + "port_id": " Identifier of the port where these external ships are berthed.", + "ships": [ + { + "id": " Unique identifier of the external ship within this port.", + "berthing_position": " Fixed leftmost quay coordinate in meters where the external ship is berthed.", + "length_meters": " Overall length of the external ship in meters.", + "start_time_hours": " Hour at which the external ship begins occupying the berth.", + "handling_time_hours": " Duration in hours the external ship occupies the berth.", + "end_time_hours": " Hour at which the external ship departs the berth." + } + ] + } + ] +} diff --git a/tasks/martin-iradi2024/mathematical_formulation.md b/tasks/martin-iradi2024/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..73ca1579aef2d42f2ecdd60d84ff5d2ceb84b5fb --- /dev/null +++ b/tasks/martin-iradi2024/mathematical_formulation.md @@ -0,0 +1,107 @@ +# Original Formulation (Eqs. 2–19) + +## Sets and Indices + +- $N$: set of all ships berthing at any of the ports; $N^* \subseteq N$ are ships being optimized; $\bar{N} \subseteq N$ are external (fixed) ships. + +- $P$: set of ports; $L_p$: length of quay in port $p \in P$. + +- $S$: set of (discretized) sailing speeds. + +- $P_i \subseteq P$: ports planned to be visited by ship $i \in N^*$, in visiting order. + +- $C_i = \{1, \ldots, c_i\}$: port calls for ship $i \in N$; $c_i$ is the last port visit. + +- $\rho_i^c \in P$: port corresponding to port visit $c \in C_i$ for ship $i \in N$. + +- $N_p \subseteq N$: ships visiting port $p \in P$. + +- $C_i^p \subseteq C_i$: port call positions of ship $i$ visiting port $p$. + +## Parameters + +- $x_0^{i,c}$: ideal berthing position (leftmost) for ship $i \in N^*$, visit $c \in C_i$. + +- $EST_i^c,\ EFT_i^c,\ LFT_i^c$: earliest start, expected finish, latest finish times. + +- $\beta$: relative increase in handling time per unit distance from the ideal position. + +- $\Delta^{p,p'}$: distance between ports $p, p'$; $\Theta_s$: travel time per unit distance at speed $s$. + +- $\Gamma_s^i$: fuel consumption per unit distance at speed $s$ for ship $i$. + +- $l_i$: length of ship $i$; $h_0^{i,c}$: minimum handling time at the preferred berthing position. + +- Cost coefficients: $F$ (fuel, USD/tonne), $H$ (handling, USD/h), $D$ (delay, USD/h), $I$ (waiting, USD/h), $U$ (LFT-exceeding penalty, USD). + +- $M$: a sufficiently large constant (big-M). + +## Decision Variables + +Primary: + +- $x_i^c \in \mathbb{R}_+$: leftmost berthing position of ship $i \in N$ at port visit $c$. + +- $y_i^c \in \mathbb{R}_+$: start time of berthing of ship $i \in N$ at port visit $c$. + +- $v_{i,s}^c \in \{0,1\}$: 1 if ship $i \in N^*$ sails from visit $c$ to $c+1$ at speed $s$. + +- $d_i^c \in \mathbb{R}_+$: delay over $EFT_i^c$ for ship $i \in N^*$ at port visit $c$. + +- $u_i^c \in \mathbb{R}_+$: delay over $LFT_i^c$ for ship $i \in N^*$ at port visit $c$. + +Auxiliary: + +- $\sigma_{i,j}^{c,c'} \in \{0,1\}$: 1 if ship $i$ is positioned left of vessel $j$ at port $p$. + +- $\delta_{i,j}^{c,c'} \in \{0,1\}$: 1 if ship $i$ finishes berthing before vessel $j$ starts at port $p$. + +- $r^{i,c} \in \mathbb{R}_+$: distance between ideal and actual berthing position. + +Dependent: + +- $a_i^c \in \mathbb{R}_+$: arrival time of ship $i \in N^*$ at port visit $c$. + +- $h_i^c \in \mathbb{R}_+$: handling time of ship $i \in N^*$ at port visit $c$. + +## Objective and Constraints + +$$\begin{align} +\min \quad & \sum_{i \in N^*} \Bigg( \sum_{c \in C_i} \Big( I(y_i^c - a_i^c) + H(h_i^c) + D(d_i^c) + U(u_i^c) \Big) + + \sum_{c \in C_i \setminus \{c_i\}} F\Big( \textstyle\sum_{s \in S} v_{i,s}^c\, \Gamma_s^i\, \Delta^{\rho_i^c, \rho_i^{c+1}} \Big) \Bigg) + \tag{2} \\ +\text{s.t.}\quad & x_i^c + l_i \leq L_p, + && \forall\, p \in P,\ i \in N_p,\ c \in C_i^p \tag{3} \\ +& x_i^c + l_i \leq x_j^{c'} + L_p\,(1 - \sigma_{i,j}^{c,c'}), + && \forall\, p \in P,\ i,j \in N_p,\ i \neq j,\ c \in C_i^p,\ c' \in C_j^p \tag{4} \\ +& y_i^c + h_i^c \leq y_j^{c'} + M\,(1 - \delta_{i,j}^{c,c'}), + && \forall\, p \in P,\ i,j \in N_p,\ i \neq j,\ c \in C_i^p,\ c' \in C_j^p \tag{5} \\ +& \sigma_{i,j}^{c,c'} + \sigma_{j,i}^{c',c} + \delta_{i,j}^{c,c'} + \delta_{j,i}^{c',c} \geq 1, + && \forall\, p \in P,\ i,j \in N_p,\ i < j,\ c \in C_i^p,\ c' \in C_j^p,\ c < c' \tag{6} \\ +& y_i^c + h_i^c + \sum_{s \in S} v_{i,s}^c\, \Theta_s\, \Delta^{\rho_i^c, \rho_i^{c+1}} = a_i^{c+1}, + && \forall\, i \in N^*,\ c \in C_i \setminus \{c_i\} \tag{7} \\ +& a_i^c \leq y_i^c, + && \forall\, i \in N^*,\ c \in C_i \tag{8} \\ +& EST_i^c \leq y_i^c, + && \forall\, i \in N^*,\ c \in C_i \tag{9} \\ +& y_i^c + h_i^c - EFT_i^c \leq d_i^c, + && \forall\, i \in N^*,\ c \in C_i \tag{10} \\ +& y_i^c + h_i^c - LFT_i^c \leq u_i^c, + && \forall\, i \in N^*,\ c \in C_i \tag{11} \\ +& (1 + \beta\, r^{i,c})\, h_0^{i,c} = h_i^c, + && \forall\, i \in N^*,\ c \in C_i \tag{12} \\ +& x_i^c - x_0^{i,c} \leq r^{i,c}, + && \forall\, i \in N^*,\ c \in C_i \tag{13} \\ +& x_0^{i,c} - x_i^c \leq r^{i,c}, + && \forall\, i \in N^*,\ c \in C_i \tag{14} \\ +& \sum_{s \in S} v_{i,s}^c = 1, + && \forall\, i \in N^*,\ c \in C_i \setminus \{c_i\} \tag{15} \\ +& y_i^c,\ x_i^c \geq 0, + && \forall\, i \in N,\ c \in C_i \tag{16} \\ +& a_i^c,\ h_i^c,\ d_i^c,\ u_i^c,\ r^{i,c} \geq 0, + && \forall\, i \in N^*,\ c \in C_i \tag{17} \\ +& v_{i,s}^c \in \{0,1\}, + && \forall\, i \in N^*,\ c \in C_i \setminus \{c_i\},\ s \in S \tag{18} \\ +& \sigma_{i,j}^{c,c'},\ \delta_{i,j}^{c,c'} \in \{0,1\}, + && \forall\, p \in P,\ i,j \in N_p,\ i \neq j,\ c \in C_i^p,\ c' \in C_j^p \tag{19} +\end{align}$$ diff --git a/tasks/martin-iradi2024/problem_description.txt b/tasks/martin-iradi2024/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..b4ba635ddcff852e6e8990d9b35808d708b1b9e8 --- /dev/null +++ b/tasks/martin-iradi2024/problem_description.txt @@ -0,0 +1,13 @@ +# Problem Description + +A shipping line operates a fleet of container ships, each following a predetermined route through a subset of ports. Each port has a single continuous quay of a given length in meters. The ships fall into different types (feeder, medium, large), each with a known length in meters, a design speed, and a cubic speed-fuel consumption relationship. The problem simultaneously determines, for every ship being optimized, the exact berthing position along the quay at each port visit, the berthing start time at each port visit, and the sailing speed chosen for each voyage leg between consecutive ports on its route. + +The input data specifies the following. For each port: an identifier and the total quay length. For each pair of ports: the sailing distance in nautical miles. A discrete set of feasible sailing speeds is given (for example, ten speeds ranging from 17.0 to 21.5 knots), and for each speed the travel time per nautical mile is precomputed as the reciprocal of the speed. For each ship being optimized: its length, its type, its ordered sequence of port visits (the route), and for each speed the fuel consumption in tonnes per nautical mile, which follows a cubic relationship with speed relative to the ship's design speed and design-speed fuel consumption. For each port visit of each optimized ship: an ideal berthing position (the preferred leftmost quay coordinate), a minimum handling time in hours (the service duration when berthed at the ideal position), a maximum handling time, an earliest start time before which berthing cannot begin, an expected finish time equal to the earliest start time plus the minimum handling time, and a latest finish time equal to the expected finish time plus half the difference between the maximum and minimum handling times. Five cost rates are given globally: a fuel price in USD per tonne, a handling cost in USD per hour, a delay cost in USD per hour, a waiting cost in USD per hour, and a penalty rate in USD per hour for exceeding the latest finish time. A deviation factor (beta, per meter) governs how handling time increases with distance from the ideal position. In addition, a set of external ships is given at each port; each external ship has a fixed berthing position, length, start time, and handling time and occupies quay space that optimized ships must avoid. + +Each optimized ship must be assigned a quay position (measured as the leftmost point of the ship along the quay) and a berthing start time at each port it visits, and exactly one sailing speed for each leg between consecutive port visits. The berthing position plus the ship's length must not exceed the quay length at the corresponding port. The handling time at each port visit equals the minimum handling time multiplied by one plus the deviation factor times the absolute distance between the chosen berthing position and the ideal berthing position. The arrival time at each port visit after the first equals the berthing start time at the previous port visit plus the handling time there plus the travel time for the inter-port distance at the chosen speed. At the first port visit, there is no preceding voyage, and the arrival time is required only to be no later than the berthing start time at that port. Berthing may not begin before the ship arrives, and it may not begin before the earliest start time. + +No two ships (whether optimized or external) may overlap in both quay space and time at the same port. For every pair of ships visiting the same port, at least one of the following must hold: one ship is positioned entirely to the left of the other along the quay, or one ship finishes its berthing period entirely before the other begins. External ships are treated identically to optimized ships for the purpose of these non-overlap requirements, but their positions, start times, and handling times are fixed inputs rather than decisions. + +The delay at each port visit is the amount by which the berthing end time (start time plus handling time) exceeds the expected finish time, taken as zero if the end time is earlier. The overshoot beyond the latest finish time at each port visit is the amount by which the berthing end time exceeds the latest finish time, again taken as zero if there is no excess. The waiting time at each port visit is the difference between the berthing start time and the arrival time. + +The goal is to minimize the total operational cost across all optimized ships. This total is the sum, over every port visit of every optimized ship, of the waiting cost rate times the waiting time, plus the handling cost rate times the handling time, plus the delay cost rate times the delay, plus the latest-finish-time penalty rate times the overshoot, plus, for each sailing leg between consecutive port visits, the fuel price times the fuel consumption per nautical mile at the chosen speed times the inter-port distance. diff --git a/tasks/martin-iradi2024/solution_logger.py b/tasks/martin-iradi2024/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/martin-iradi2024/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/martin-iradi2024/solution_schema.json b/tasks/martin-iradi2024/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..ec80f1e0e9a976ed3f9968d72d1a3f94e49de60d --- /dev/null +++ b/tasks/martin-iradi2024/solution_schema.json @@ -0,0 +1,28 @@ +{ + "objective_value": " Total operational cost across all optimized ships including waiting, handling, delay, latest-finish-time penalty, and fuel costs in US dollars.", + "ships": [ + { + "ship_id": " Identifier of the optimized ship matching the input data.", + "port_visits": [ + { + "port_call_index": " Position of this visit in the ship's route sequence, starting from 1.", + "port_id": " Identifier of the port being visited at this port call.", + "berthing_position": " Assigned leftmost quay coordinate in meters where the ship berths at this port call.", + "start_time": " Hour at which the ship begins berthing at this port call.", + "handling_time": " Actual cargo handling duration in hours at this port call, inflated by the deviation from the ideal berthing position.", + "arrival_time": " Hour at which the ship arrives at the port and becomes ready to berth for this port call.", + "delay": " Hours by which the berthing end time exceeds the expected finish time, zero if on time.", + "lft_violation": " Hours by which the berthing end time exceeds the latest finish time, zero if within the limit.", + "position_deviation": " Absolute distance in meters between the assigned berthing position and the ideal berthing position." + } + ], + "speed_selections": [ + { + "from_call": " Port call index of the departure port for this sailing leg.", + "to_call": " Port call index of the arrival port for this sailing leg.", + "speed_knots": " Sailing speed chosen in knots for this sailing leg between consecutive port visits." + } + ] + } + ] +} diff --git a/tasks/mehrotra1996/feasibility_check.py b/tasks/mehrotra1996/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..38681925f1c39f20cfcabdda69c46ea8e0df6794 --- /dev/null +++ b/tasks/mehrotra1996/feasibility_check.py @@ -0,0 +1,380 @@ +""" +Feasibility checker for the Graph Coloring problem. + +Mathematical formulation from: +Mehrotra & Trick (1996), "A Column Generation Approach for Graph Coloring", +INFORMS Journal on Computing 8(4):344-354. + +Constraints are numbered top-to-bottom from the formulation in math_model.txt: + Constraint 1 (VC adjacency): x_{ik} + x_{jk} <= 1 for all (i,j) in E, k=1,...,K + => No two adjacent vertices share the same color. + Constraint 2 (VC assignment): sum_k x_{ik} = 1 for all i in V + => Every vertex is assigned exactly one color. + Constraint 3 (VC binary): x_{ik} in {0,1} for all i in V, k=1,...,K + => Binary variable domain (inherently satisfied by integer solution format). + Constraint 6 (obj consistency): reported_obj == |{ vc[i] : i in V }| + => Reported objective_value must equal the number of distinct color + labels actually used in `vertex_colors`. Tier-C defense against + LLM exploits that fabricate the objective_value. + +Only the original vertex-coloring (VC) constraints 1-3 are checked. The IS +set-covering reformulation constraints (Constraint 4: sum_{s: i in s} x_s >= 1; +Constraint 5: x_s in {0,1}) require `color_classes` (pattern variables) that +a generated algorithm operating on the VC solution structure may not produce. +The LP relaxation (Section 3), MWIS subproblem (Section 4), and the set +covering example (Section 5) are also not constraints on the final coloring. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('color_classes', 'objective_value', 'vertex_colors') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('color_classes',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(instance, solution): + """ + Check feasibility of a candidate graph coloring solution. + + Returns a dict with: + - feasible (bool) + - violated_constraints (list of int) + - violations (list of str) + - violation_magnitudes (list of dict) + """ + tol = 1e-5 + eps = 1e-5 + + nodes = instance["graph"]["nodes"] + edges = [tuple(e) for e in instance["graph"]["edges"]] + node_set = set(nodes) + + vertex_colors = solution.get("vertex_colors", {}) + + # Convert vertex_colors keys to int (JSON keys are strings) + vc = {} + for k, v in vertex_colors.items(): + vc[int(k)] = int(v) + + # Build edge set for quick lookup + edge_set = set() + for u, v in edges: + edge_set.add((min(u, v), max(u, v))) + + violated_constraints_set = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint 1 (VC adjacency): x_{ik} + x_{jk} <= 1 for all (i,j) in E, k + # Meaning: No two adjacent vertices may share the same color. + # For each edge (i,j), if both i and j are colored the same, this is violated. + # LHS = x_{ik} + x_{jk} (= 2 if same color k), RHS = 1 + # violation_amount = LHS - RHS (for <= constraint) + # ========================================================================= + for u, v in edges: + if u in vc and v in vc and vc[u] == vc[v]: + lhs = 2.0 + rhs = 1.0 + violation_amount = lhs - rhs # = 1.0 + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(1) + violations.append( + f"Constraint 1 violated: adjacent vertices {u} and {v} " + f"share color {vc[u]}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ========================================================================= + # Constraint 2 (VC assignment): sum_k x_{ik} = 1 for all i in V + # Meaning: Every vertex must be assigned exactly one color. + # Checked directly against the `vertex_colors` dict (primary VC structure). + # LHS = number of colors assigned to vertex i (0 or 1 from vertex_colors), + # RHS = 1 + # ========================================================================= + for node in nodes: + if node not in vc: + lhs = 0.0 + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(2) + violations.append( + f"Constraint 2 violated: vertex {node} is not assigned any color" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ========================================================================= + # Constraint 3 (VC binary): x_{ik} in {0, 1} for all i in V, k = 1,...,K + # Inherently satisfied by the integer solution format (vertex_colors maps + # each vertex to one color index). No check needed. + # ========================================================================= + + # ========================================================================= + # Constraint 4 (IS-1 coverage) and Constraint 5 (IS-2 binary) SKIPPED: + # These belong to the IS set-covering reformulation (Section 2 of the + # paper, used for column generation). A generated algorithm operating + # on the VC solution structure produces `vertex_colors` (not pattern + # variables `x_s` / `color_classes`), so these reformulation-only + # constraints are not checked here. + # ========================================================================= + + # ========================================================================= + # Constraint 6 (objective consistency): + # reported_obj == |{ vc[i] : i in V, i in vc }| + # Tier-C defense: the eval pipeline trusts solution["objective_value"]; + # LLM-evolved candidates have learned to lie about it. For graph + # coloring the objective equals the number of distinct color labels + # actually used in `vertex_colors`, so we can fully recompute it. + # Tolerance is 0.5 because the objective is an integer color count, so + # any off-by-one or larger mismatch fires. + # ========================================================================= + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(len(set(vc.values()))) + abs_diff = abs(reported - true_obj) + obj_tol = 0.5 + if abs_diff > obj_tol: + lhs = reported + rhs = true_obj + normalizer = max(abs(true_obj), eps) + ratio = abs_diff / normalizer + violated_constraints_set.add(6) + violations.append( + f"Constraint 6 violated: reported objective_value={reported} " + f"differs from recomputed |distinct(vertex_colors)|={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs, + "rhs": rhs, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": ratio, + }) + + feasible = len(violated_constraints_set) == 0 + + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Graph Coloring (Mehrotra & Trick, 1996)" + ) + 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 found.") + else: + print(f"INFEASIBLE: {len(result['violated_constraints'])} constraint(s) violated.") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/mehrotra1996/gurobi_code.py b/tasks/mehrotra1996/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..a278f59dff69b75dde6e9343fdfb6f8a0028d20d --- /dev/null +++ b/tasks/mehrotra1996/gurobi_code.py @@ -0,0 +1,410 @@ +""" +Gurobi implementation of the Independent Set (IS) formulation for Minimum Graph Coloring. + +Based on: Mehrotra & Trick (1996), "A Column Generation Approach for Graph Coloring", +INFORMS Journal on Computing 8(4):344-354. + +The IS formulation: + Minimize sum_{s in S} x_s + Subject to sum_{s: i in s} x_s >= 1 for all i in V + x_s in {0, 1} for all s in S + +Since S (all maximal independent sets) can be exponentially large, we use +column generation: solve the LP relaxation iteratively, generating new columns +by solving the Maximum Weighted Independent Set (MWIS) pricing subproblem. + +The released entry point uses an exact compact assignment model. The legacy +column-generation routines remain below for comparison, but their restricted +integer master is not used as a global certificate. +""" + +import argparse +import json +import math +import time +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load a graph coloring instance from JSON.""" + with open(path, 'r') as f: + data = json.load(f) + nodes = data["graph"]["nodes"] + edges = data["graph"]["edges"] + # Build adjacency set for each node + n = len(nodes) + adj = {v: set() for v in nodes} + edge_set = set() + for u, v in edges: + adj[u].add(v) + adj[v].add(u) + edge_set.add((min(u, v), max(u, v))) + return nodes, edges, adj, edge_set + + +def greedy_mwis_heuristic(candidates, adj, weights): + """ + Greedy MWIS heuristic from the paper (Section 7.3): + Order vertices by nonincreasing sqrt(degree) * weight. + Add vertices greedily, skipping those adjacent to already-selected vertices. + Returns a maximal independent set as a list of vertices. + """ + # Compute ordering value for each candidate + scored = [] + for v in candidates: + deg = len(adj[v]) + w = weights.get(v, 1.0) + score = math.sqrt(max(deg, 1)) * w + scored.append((score, v)) + scored.sort(reverse=True) + + indep_set = [] + in_set = set() + blocked = set() + for _, v in scored: + if v not in blocked: + indep_set.append(v) + in_set.add(v) + for u in adj[v]: + if u in candidates: + blocked.add(u) + return indep_set + + +def solve_mwis_exact(candidates, adj, weights): + """ + Solve MWIS exactly using Gurobi for the pricing subproblem. + Maximize sum_i pi_i * z_i + s.t. z_i + z_j <= 1 for all (i,j) in E restricted to candidates + z_i in {0, 1} + """ + cand_set = set(candidates) + model = gp.Model("MWIS") + model.setParam("Threads", 1) + model.setParam("OutputFlag", 0) + model.setParam("TimeLimit", 60) # subproblem time limit + + z = {} + for v in candidates: + z[v] = model.addVar(vtype=GRB.BINARY, obj=weights.get(v, 0.0), name=f"z_{v}") + + model.setAttr("ModelSense", GRB.MAXIMIZE) + + for v in candidates: + for u in adj[v]: + if u in cand_set and u > v: + model.addConstr(z[v] + z[u] <= 1) + + model.optimize() + + if model.Status in (GRB.OPTIMAL, GRB.TIME_LIMIT) and model.SolCount > 0: + result = [v for v in candidates if z[v].X > 0.5] + obj_val = model.ObjVal + return result, obj_val + return [], 0.0 + + +def greedy_coloring(nodes, adj): + """ + Generate initial coloring using greedy MWIS heuristic with unit weights. + Returns list of independent sets (one per color class) and the number of colors. + """ + remaining = set(nodes) + color_classes = [] + # Restricted adjacency for remaining nodes + while remaining: + weights = {v: 1.0 for v in remaining} + # Build restricted adjacency + restricted_adj = {v: adj[v] & remaining for v in remaining} + indep = greedy_mwis_heuristic(remaining, restricted_adj, weights) + color_classes.append(list(indep)) + remaining -= set(indep) + return color_classes + + +def column_generation_coloring(nodes, edges, adj, edge_set, time_limit): + """ + Solve graph coloring using the IS formulation with column generation in Gurobi. + + Phase 1: Generate initial columns via greedy coloring. + Phase 2: Column generation loop - solve LP relaxation, generate improving columns. + Phase 3: Solve restricted IP over all generated columns. + """ + start_time = time.time() + n = len(nodes) + + # Phase 1: Initial columns from greedy coloring + columns = greedy_coloring(nodes, adj) + best_ub = len(columns) # initial upper bound + best_coloring = columns[:] + + print(f"Initial greedy coloring uses {best_ub} colors") + + # Phase 2: Column generation + iteration = 0 + while True: + elapsed = time.time() - start_time + if elapsed > time_limit: + print("Time limit reached during column generation") + break + + # Solve restricted LP relaxation + lp_model = gp.Model("LP_relaxation") + lp_model.setParam("Threads", 1) + lp_model.setParam("OutputFlag", 0) + lp_model.setParam("TimeLimit", max(1, time_limit - (time.time() - start_time))) + + x = {} + for s_idx, col in enumerate(columns): + x[s_idx] = lp_model.addVar(lb=0.0, ub=GRB.INFINITY, obj=1.0, name=f"x_{s_idx}") + + lp_model.setAttr("ModelSense", GRB.MINIMIZE) + lp_model.update() + + # Coverage constraints: each vertex must be covered + cover_constrs = {} + for v in nodes: + expr = gp.LinExpr() + for s_idx, col in enumerate(columns): + if v in col: + expr.add(x[s_idx], 1.0) + cover_constrs[v] = lp_model.addConstr(expr >= 1.0, name=f"cover_{v}") + + lp_model.optimize() + + if lp_model.Status != GRB.OPTIMAL: + print("LP relaxation not optimal, stopping column generation") + break + + lp_value = lp_model.ObjVal + print(f"Iteration {iteration}: LP value = {lp_value:.4f}, columns = {len(columns)}") + + # Get dual values + dual_values = {} + for v in nodes: + dual_values[v] = cover_constrs[v].Pi + + # Solve MWIS pricing subproblem + # First try greedy heuristic + heuristic_set = greedy_mwis_heuristic(nodes, adj, dual_values) + heuristic_weight = sum(dual_values.get(v, 0.0) for v in heuristic_set) + + if heuristic_weight > 1.0 + 1e-6: + # Heuristic found an improving column + new_col = heuristic_set + print(f" Heuristic found improving column with weight {heuristic_weight:.4f}") + else: + # Solve MWIS exactly + exact_set, exact_weight = solve_mwis_exact(nodes, adj, dual_values) + if exact_weight > 1.0 + 1e-6: + new_col = exact_set + print(f" Exact MWIS found improving column with weight {exact_weight:.4f}") + else: + print(f" No improving column found (MWIS value = {exact_weight:.4f}). LP optimal.") + break + + # Check if this column already exists + new_col_set = set(new_col) + duplicate = False + for existing_col in columns: + if set(existing_col) == new_col_set: + duplicate = True + break + if duplicate: + print(" Duplicate column detected, stopping.") + break + + columns.append(new_col) + iteration += 1 + + lp_bound = math.ceil(lp_value - 1e-6) if 'lp_value' in dir() else 1 + + # Phase 3: Solve restricted IP over all generated columns + elapsed = time.time() - start_time + remaining_time = max(1, time_limit - elapsed) + + ip_model = gp.Model("IP_coloring") + ip_model.setParam("Threads", 1) + ip_model.setParam("OutputFlag", 1) + ip_model.setParam("TimeLimit", remaining_time) + + x_ip = {} + for s_idx, col in enumerate(columns): + x_ip[s_idx] = ip_model.addVar(vtype=GRB.BINARY, obj=1.0, name=f"x_{s_idx}") + + ip_model.setAttr("ModelSense", GRB.MINIMIZE) + ip_model.update() + + for v in nodes: + expr = gp.LinExpr() + for s_idx, col in enumerate(columns): + if v in col: + expr.add(x_ip[s_idx], 1.0) + ip_model.addConstr(expr >= 1.0, name=f"cover_{v}") + + ip_model.optimize() + + if ip_model.SolCount > 0: + ip_value = ip_model.ObjVal + selected_sets = [columns[s_idx] for s_idx in range(len(columns)) if x_ip[s_idx].X > 0.5] + if ip_value < best_ub: + best_ub = int(round(ip_value)) + best_coloring = selected_sets + print(f"IP solution: {int(round(ip_value))} colors") + else: + print("No IP solution found, using greedy coloring") + + # Build vertex-to-color mapping + vertex_color = {} + for color_idx, color_class in enumerate(best_coloring): + for v in color_class: + if v not in vertex_color: + vertex_color[v] = color_idx + + # Ensure all vertices are colored + used_colors = set(vertex_color.values()) + next_color = max(used_colors) + 1 if used_colors else 0 + for v in nodes: + if v not in vertex_color: + vertex_color[v] = next_color + next_color += 1 + + return best_ub, vertex_color, best_coloring + + +def verify_coloring(nodes, edges, vertex_color): + """Verify that the coloring is valid (no two adjacent vertices share a color).""" + for u, v in edges: + if vertex_color.get(u) == vertex_color.get(v): + return False + return True + + +def solve_exact_coloring(nodes, edges, adj, time_limit): + """Solve the full coloring problem and return an honest bound/gap.""" + greedy_classes = greedy_coloring(nodes, adj) + n = len(nodes) + position = {node: i for i, node in enumerate(nodes)} + greedy_classes.sort(key=lambda color_class: min(position[node] for node in color_class)) + color_limit = len(greedy_classes) + + model = gp.Model("exact_graph_coloring") + model.Params.Threads = 1 + model.Params.TimeLimit = max(1.0, float(time_limit)) + x = model.addVars(n, color_limit, vtype=GRB.BINARY, name="x") + used = model.addVars(color_limit, vtype=GRB.BINARY, name="used") + + for i in range(n): + model.addConstr(gp.quicksum(x[i, k] for k in range(color_limit)) == 1) + for k in range(color_limit): + model.addConstr(x[i, k] <= used[k]) + # Color labels can be ordered by first use without loss of generality. + for k in range(i + 1, color_limit): + model.addConstr(x[i, k] == 0) + for k in range(color_limit - 1): + model.addConstr(used[k] >= used[k + 1]) + for u, v in edges: + i, j = position[u], position[v] + for k in range(color_limit): + model.addConstr(x[i, k] + x[j, k] <= 1) + + for k, color_class in enumerate(greedy_classes): + used[k].Start = 1.0 + members = {position[node] for node in color_class} + for i in range(n): + x[i, k].Start = 1.0 if i in members else 0.0 + + model.setObjective(gp.quicksum(used), GRB.MINIMIZE) + model.optimize() + if model.SolCount: + vertex_color = { + node: next(k for k in range(color_limit) if x[i, k].X > 0.5) + for i, node in enumerate(nodes) + } + remap = { + old: new for new, old in enumerate(sorted(set(vertex_color.values()))) + } + vertex_color = {node: remap[color] for node, color in vertex_color.items()} + num_colors = len(remap) + else: + vertex_color = { + node: k for k, color_class in enumerate(greedy_classes) + for node in color_class + } + num_colors = color_limit + classes = [[] for _ in range(num_colors)] + for node in nodes: + classes[vertex_color[node]].append(node) + return { + "num_colors": num_colors, + "vertex_colors": vertex_color, + "color_classes": classes, + "solver_status": int(model.Status), + "best_bound": float(model.ObjBound) if model.SolCount else None, + "mip_gap": float(model.MIPGap) if model.SolCount else None, + "greedy_upper_bound": color_limit, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Exact compact Gurobi graph coloring model" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + print(f"Loading instance from: {args.instance_path}") + nodes, edges, adj, edge_set = load_instance(args.instance_path) + print(f"Graph: {len(nodes)} nodes, {len(edges)} edges") + + exact = solve_exact_coloring(nodes, edges, adj, args.time_limit) + num_colors = exact["num_colors"] + vertex_color = exact["vertex_colors"] + color_classes = exact["color_classes"] + + valid = verify_coloring(nodes, edges, vertex_color) + print(f"\nResult: {num_colors} colors, valid = {valid}") + + # Build solution + solution = { + "objective_value": num_colors, + "num_colors": num_colors, + "valid": valid, + "vertex_colors": {str(v): c for v, c in vertex_color.items()}, + "color_classes": [[v for v in cc] for cc in color_classes], + "optimization_method": "exact_compact_assignment", + "solver_status": exact["solver_status"], + "best_bound": exact["best_bound"], + "mip_gap": exact["mip_gap"], + "greedy_upper_bound": exact["greedy_upper_bound"], + } + + 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/mehrotra1996/gurobi_feasi_result/large_feasi_result_1.json b/tasks/mehrotra1996/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mehrotra1996/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/mehrotra1996/gurobi_feasi_result/large_feasi_result_2.json b/tasks/mehrotra1996/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mehrotra1996/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/mehrotra1996/gurobi_feasi_result/large_feasi_result_3.json b/tasks/mehrotra1996/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mehrotra1996/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/mehrotra1996/gurobi_feasi_result/large_feasi_result_4.json b/tasks/mehrotra1996/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mehrotra1996/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/mehrotra1996/gurobi_feasi_result/large_feasi_result_5.json b/tasks/mehrotra1996/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mehrotra1996/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/mehrotra1996/gurobi_feasi_result/tiny_feasi_result.json b/tasks/mehrotra1996/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mehrotra1996/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/mehrotra1996/gurobi_solution/large_solution_1.json b/tasks/mehrotra1996/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..67097222885b1fbedd54ed36c9a760efef5b0c81 --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6068599446f3d566d7c1bf82f47e7fc68e15efea713fb2e09a8e6779d20a28d6 +size 7735 diff --git a/tasks/mehrotra1996/gurobi_solution/large_solution_2.json b/tasks/mehrotra1996/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..fcf7739401c8eb3bb24eb73f9c2b49b6e7866293 --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:872f74c2cefd153fd586661a694024a929788314b62afa5e855e1dfd5368f36f +size 8702 diff --git a/tasks/mehrotra1996/gurobi_solution/large_solution_3.json b/tasks/mehrotra1996/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8289b0e63e76da3affd08176ecbaf4477729064d --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22798c8c46f6563b0f512a260096d9a11a04d878e91a6641e9b968f76e54acfb +size 6980 diff --git a/tasks/mehrotra1996/gurobi_solution/large_solution_4.json b/tasks/mehrotra1996/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..0ceea1d4e5c8e99712339a58a487577ed310693f --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83f288698e657c6857a244a8b1c5e4d572186c4bfbd451dca14f477650e112b2 +size 7945 diff --git a/tasks/mehrotra1996/gurobi_solution/large_solution_5.json b/tasks/mehrotra1996/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..80a5a710dfb7425e0fa6fc840e5ab7ec07e253c9 --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b53bab82829f1cafcf67fa75e09c70e88b8372a66fc9feefeddef820219fcdf +size 7746 diff --git a/tasks/mehrotra1996/gurobi_solution/tiny_solution.json b/tasks/mehrotra1996/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..ecfd76feb35d844efadbc86f4d4daab8555aaa79 --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4d1fcffce42b9a7eaacbc63942c7d4981b75e42483a07efeeb0fcbf8f826853 +size 1017 diff --git a/tasks/mehrotra1996/gurobi_solution_log/large_log_1.jsonl b/tasks/mehrotra1996/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..85364c04c43c068423e3499aaca53428728eddda --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fec206a101471df2a3afe178d2b9433c938ec5848ef8652ba627c22fd3ced9b1 +size 175 diff --git a/tasks/mehrotra1996/gurobi_solution_log/large_log_2.jsonl b/tasks/mehrotra1996/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..727573c2a0dad099d98f922f91aa61b6f57c5747 --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a1b1794ab25b09d2ce77a1ffdd46e8be2aec778fd1ca5a05b2381a3af74a04c +size 121 diff --git a/tasks/mehrotra1996/gurobi_solution_log/large_log_3.jsonl b/tasks/mehrotra1996/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..45ecf4724e4772581cade40490e19aa437f453ff --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e0b9643835c7d90c8bdef5f23431deddcf56103dfe1cda198ceecd784a80ab2 +size 40 diff --git a/tasks/mehrotra1996/gurobi_solution_log/large_log_4.jsonl b/tasks/mehrotra1996/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d86a7bd1f0644df7a93f4fb9a3291bb7bebb5ce2 --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd892bd2e5e98874c88c2a5b3c01615edc895506db4dc8480513f2a53c41f22a +size 40 diff --git a/tasks/mehrotra1996/gurobi_solution_log/large_log_5.jsonl b/tasks/mehrotra1996/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e583c987ad6e2f5c4235762c242fd33e2cc894fd --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:360af2f013aa7ec01f44ec75461a9850d3b95ec8ee6cb31240409a72d9731c22 +size 267 diff --git a/tasks/mehrotra1996/gurobi_solution_log/tiny_log.jsonl b/tasks/mehrotra1996/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6917e5f9b909922ff1231073f8e4f6d37389b222 --- /dev/null +++ b/tasks/mehrotra1996/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e5b7d652391f91a9a4a763290d0d3158a0d94799feeecde06bd2c77f3100b5a +size 40 diff --git a/tasks/mehrotra1996/instance/large_instance_1.json b/tasks/mehrotra1996/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..92cf2c8fba05b4685b3100e47cf3253495fd6218 --- /dev/null +++ b/tasks/mehrotra1996/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:276c290e999fe46741e2f68d57d1bb99fbf2150e99363bc1b06830b482984757 +size 1189375 diff --git a/tasks/mehrotra1996/instance/large_instance_2.json b/tasks/mehrotra1996/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..9b86d65c6c2797184322a136e007e780bd39f3fd --- /dev/null +++ b/tasks/mehrotra1996/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d148bf25709683ddbc712d81ade983d005053d975c6ae1349df83a88c2b7246 +size 1200142 diff --git a/tasks/mehrotra1996/instance/large_instance_3.json b/tasks/mehrotra1996/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..4f332d634deb7aa09a9d3b018b8c10140fc0d9df --- /dev/null +++ b/tasks/mehrotra1996/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b28547c73da103458751de7bad501f5df4450bbe3563dccd7b360f774235ae81 +size 1200255 diff --git a/tasks/mehrotra1996/instance/large_instance_4.json b/tasks/mehrotra1996/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..49a1106245261f76db79953765991be0efa494bc --- /dev/null +++ b/tasks/mehrotra1996/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53d4dc9c97994069fa137af349d999523853367f5cffa955bc7a5249df3df47e +size 1190047 diff --git a/tasks/mehrotra1996/instance/large_instance_5.json b/tasks/mehrotra1996/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..b504695240f711a8537cd9140d0a032ed2175c4f --- /dev/null +++ b/tasks/mehrotra1996/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9030dec21405bd4be10e8397e625e3fc5f4b0e631b87a8083b9694b25de3dc1e +size 1189337 diff --git a/tasks/mehrotra1996/instance/tiny_instance.json b/tasks/mehrotra1996/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..7f4e9c7c6dc3815aaf8f95bbaca35f6264450eef --- /dev/null +++ b/tasks/mehrotra1996/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6fdd18f52dde8c6f5997f80c8cbe83a4909c8f7dba1e686a171d9c5177c543e2 +size 6468 diff --git a/tasks/mehrotra1996/instance_schema.json b/tasks/mehrotra1996/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..36b4f8bac74448f516db745b520728716433ea98 --- /dev/null +++ b/tasks/mehrotra1996/instance_schema.json @@ -0,0 +1,8 @@ +{ + "graph": { + "num_nodes": " Total number of vertices in the graph.", + "num_edges": " Total number of edges in the graph.", + "nodes": " Vertices of the graph, each identified by a unique integer label.", + "edges": " Pairs of vertices connected by an edge, where each pair contains two distinct vertex labels." + } +} diff --git a/tasks/mehrotra1996/mathematical_formulation.md b/tasks/mehrotra1996/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..1cc6580cdad4738540781d1a39bd786c4bf27dc7 --- /dev/null +++ b/tasks/mehrotra1996/mathematical_formulation.md @@ -0,0 +1,28 @@ +# Original Formulation: Independent Set (IS) + +## Sets and Indices + +- $G = (V, E)$: undirected graph with vertex set $V$ ($|V| = n$) and edge set $E$. + +- $\mathcal{S}$: the set of all maximal independent sets of $G$. An independent set is a subset of $V$ containing no two endpoints of any edge; a maximal independent set is one not strictly contained in any other independent set. + +- $i \in V$: vertex index; $s \in \mathcal{S}$: maximal-independent-set index. + +- Membership: $i \in s$ means vertex $i$ belongs to the independent set $s$. + +## Decision Variables + +- $x_s \in \{0, 1\}$ for each $s \in \mathcal{S}$: 1 if independent set $s$ is selected (assigned a unique color), 0 otherwise. + +## Objective and Constraints + +$$\begin{align} +\min \quad & \sum_{s \in \mathcal{S}} x_s + \tag{1} \\ +\text{s.t.}\quad & \sum_{s \in \mathcal{S}\, :\, i \in s} x_s \geq 1 + && \forall i \in V, \tag{2} \\ +& x_s \in \{0, 1\} + && \forall s \in \mathcal{S}. \tag{3} +\end{align}$$ + +The objective counts the number of selected maximal independent sets, which equals the number of colors used. Constraint (2) requires that each vertex be covered by at least one selected independent set. diff --git a/tasks/mehrotra1996/problem_description.txt b/tasks/mehrotra1996/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..a78864e4472e02ccfaaa9b35c9616539b61ca777 --- /dev/null +++ b/tasks/mehrotra1996/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +Given an undirected graph with a specified set of vertices and a specified set of edges connecting pairs of vertices, the task is to assign a color to every vertex such that no two vertices connected by an edge receive the same color, while using the fewest colors possible. The number of vertices and the number of edges are provided, along with the complete list of edges as pairs of vertices. + +Every vertex must receive exactly one color. Two vertices that are directly connected by an edge must receive different colors. The goal is to minimize the total number of distinct colors used across all vertices. diff --git a/tasks/mehrotra1996/solution_logger.py b/tasks/mehrotra1996/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/mehrotra1996/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/mehrotra1996/solution_schema.json b/tasks/mehrotra1996/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5fd5a11aaec9c996660b0535cb67883f4424740f --- /dev/null +++ b/tasks/mehrotra1996/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Minimum number of colors used to color all vertices.", + "vertex_colors": " Color assigned to each vertex, represented as an integer label starting from 0.", + "color_classes": " Groups of vertices sharing the same color, where each group forms an independent set with no two vertices connected by an edge." +} diff --git a/tasks/mingozzi1999/feasibility_check.py b/tasks/mingozzi1999/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..186aa4067efe1459f56603ca3cda38c3de0378f0 --- /dev/null +++ b/tasks/mingozzi1999/feasibility_check.py @@ -0,0 +1,567 @@ +""" +Feasibility checker for the Vehicle Routing Problem with Backhauls (VRPB). + +Reference: Mingozzi, Giorgi, Baldacci (1999), +"An Exact Method for the Vehicle Routing Problem with Backhauls", +Transportation Science 33(3):315-329. + +Constraints numbered 1-6 match the paper's formulation order (Eqs. 4-9): + Constraint 1 (Eq. 4): Each linehaul customer visited exactly once. + Constraint 2 (Eq. 5): Each backhaul customer visited exactly once. + Constraint 3 (Eq. 6): Linehaul-path-end / arc linkage for each i in L. + Constraint 4 (Eq. 7): Backhaul-path-start / arc linkage for each j in B. + Constraint 5 (Eq. 8): Exactly M connecting arcs (i.e., exactly M routes). + Constraint 6 (Eq. 9): Integrality / binary (routes are well-formed). + Constraint 7 (Eq. 3): Objective consistency — reported objective_value + must equal the sum of distance_matrix[i][j] over + consecutive arcs of all routes (Tier C anti-gaming). + +Additionally, from the feasibility conditions and reproduction-critical comments: + - Each route must start and end at the depot. + - All linehaul customers in a route must precede all backhaul customers. + - Linehaul load on each route must not exceed Q. + - Backhaul load on each route must not exceed Q. + - Routes containing only backhaul customers are NOT allowed. +These structural requirements are embedded in the definition of feasible +paths in L and B and in the arc set A_0, so violations of these are +reported under the corresponding constraint that they make infeasible. +""" + +import json +import argparse + +# 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: + 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 save_json(obj, path): + with open(path, "w") as f: + json.dump(obj, f, indent=2) + + +def check_feasibility(instance, solution): + violations = [] + violation_magnitudes = [] + + # ---- Extract instance data ---- + depot = instance["depot"]["index"] + Q = instance["vehicle_capacity"] + M = instance["num_vehicles"] + n = instance["num_linehaul_customers"] + m = instance["num_backhaul_customers"] + + linehaul_set = set() + backhaul_set = set() + demands = {} + demands[depot] = 0 + + for c in instance["linehaul_customers"]: + idx = c["index"] + linehaul_set.add(idx) + demands[idx] = c["demand"] + + for c in instance["backhaul_customers"]: + idx = c["index"] + backhaul_set.add(idx) + demands[idx] = c["demand"] + + all_customers = linehaul_set | backhaul_set + + routes = solution["routes"] + + # ================================================================ + # Constraint 6 (Eq. 9): Integrality / binary — routes well-formed + # Each route must start and end at depot, contain only valid + # customer indices, and not be empty of customers. + # A route with only backhaul customers is also disallowed + # (reproduction comment 2), which violates the definition of + # feasible paths / arcs in A_0, hence constraint 6. + # ================================================================ + for r_idx, route in enumerate(routes): + # Route must start and end at depot + if len(route) < 2: + lhs = 0.0 + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + msg = f"Route {r_idx}: too short (length {len(route)}), must start and end at depot" + violations.append((6, msg, lhs, rhs, violation_amount)) + continue + + if route[0] != depot: + lhs = float(route[0]) + rhs = float(depot) + violation_amount = abs(lhs - rhs) + msg = f"Route {r_idx}: does not start at depot (starts at {route[0]})" + violations.append((6, msg, lhs, rhs, violation_amount)) + + if route[-1] != depot: + lhs = float(route[-1]) + rhs = float(depot) + violation_amount = abs(lhs - rhs) + msg = f"Route {r_idx}: does not end at depot (ends at {route[-1]})" + violations.append((6, msg, lhs, rhs, violation_amount)) + + # Check for invalid customer indices in interior + interior = route[1:-1] + for node in interior: + if node != depot and node not in all_customers: + lhs = 1.0 + rhs = 0.0 + violation_amount = abs(lhs - rhs) + msg = f"Route {r_idx}: contains invalid node {node}" + violations.append((6, msg, lhs, rhs, violation_amount)) + + # Check linehaul-before-backhaul ordering. + # A feasible route is: depot -> linehaul segment -> (arc to backhaul or depot) -> backhaul segment -> depot + # Once a backhaul customer is encountered, no linehaul customer may follow. + seen_backhaul = False + has_linehaul = False + for node in interior: + if node in backhaul_set: + seen_backhaul = True + elif node in linehaul_set: + if seen_backhaul: + lhs = 1.0 + rhs = 0.0 + violation_amount = abs(lhs - rhs) + msg = (f"Route {r_idx}: linehaul customer {node} appears after " + f"backhaul customer(s) — violates linehaul-before-backhaul ordering") + violations.append((6, msg, lhs, rhs, violation_amount)) + else: + has_linehaul = True + + # Routes containing only backhaul customers are NOT allowed (comment 2) + has_backhaul_only = (not has_linehaul and + any(node in backhaul_set for node in interior)) + if has_backhaul_only: + lhs = 0.0 + rhs = 1.0 + violation_amount = abs(lhs - rhs) + msg = f"Route {r_idx}: contains only backhaul customers (backhaul-only routes not allowed)" + violations.append((6, msg, lhs, rhs, violation_amount)) + + # Check that linehaul load on this route does not exceed Q + linehaul_load = sum(demands.get(node, 0) for node in interior if node in linehaul_set) + if linehaul_load > Q + TOL: + lhs = float(linehaul_load) + rhs = float(Q) + violation_amount = lhs - rhs + msg = (f"Route {r_idx}: linehaul load {linehaul_load} exceeds " + f"vehicle capacity {Q}") + violations.append((6, msg, lhs, rhs, violation_amount)) + + # Check that backhaul load on this route does not exceed Q + backhaul_load = sum(demands.get(node, 0) for node in interior if node in backhaul_set) + if backhaul_load > Q + TOL: + lhs = float(backhaul_load) + rhs = float(Q) + violation_amount = lhs - rhs + msg = (f"Route {r_idx}: backhaul load {backhaul_load} exceeds " + f"vehicle capacity {Q}") + violations.append((6, msg, lhs, rhs, violation_amount)) + + # ================================================================ + # Constraint 1 (Eq. 4): Each linehaul customer visited exactly once + # sum_{l in L_i} x_l = 1, for all i in L + # LHS = number of times customer i appears across all routes + # RHS = 1 + # ================================================================ + linehaul_visit_count = {i: 0 for i in linehaul_set} + for route in routes: + for node in route[1:-1]: + if node in linehaul_set: + linehaul_visit_count[node] += 1 + + for i in sorted(linehaul_set): + count = linehaul_visit_count[i] + lhs = float(count) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + if count == 0: + msg = f"Linehaul customer {i} is not visited" + else: + msg = f"Linehaul customer {i} visited {count} times (should be exactly once)" + violations.append((1, msg, lhs, rhs, violation_amount)) + + # ================================================================ + # Constraint 2 (Eq. 5): Each backhaul customer visited exactly once + # sum_{l in B_j} y_l = 1, for all j in B + # LHS = number of times customer j appears across all routes + # RHS = 1 + # ================================================================ + backhaul_visit_count = {j: 0 for j in backhaul_set} + for route in routes: + for node in route[1:-1]: + if node in backhaul_set: + backhaul_visit_count[node] += 1 + + for j in sorted(backhaul_set): + count = backhaul_visit_count[j] + lhs = float(count) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + if count == 0: + msg = f"Backhaul customer {j} is not visited" + else: + msg = f"Backhaul customer {j} visited {count} times (should be exactly once)" + violations.append((2, msg, lhs, rhs, violation_amount)) + + # ================================================================ + # Constraint 3 (Eq. 6): Linehaul-path-end / arc linkage + # For each i in L: + # sum_{l in L_i^E} x_l - sum_{j in B_0} xi_{ij} = 0 + # In route-level terms: the number of routes whose linehaul segment + # ends at customer i must equal the number of connecting arcs + # from i (to a backhaul customer or depot). + # In a well-formed solution each route has exactly one such arc, + # so this is automatically satisfied if: + # (# routes ending linehaul at i) == (# arcs from i to B_0 in solution) + # Both sides count the same thing from the route structure, so we + # check that every route has exactly one transition arc from the + # last linehaul customer. + # ================================================================ + # Extract the connecting arc (last linehaul -> first backhaul or depot) + # for each route, and verify consistency. + linehaul_end_count = {i: 0 for i in linehaul_set} + arc_from_count = {i: 0 for i in linehaul_set} + + for r_idx, route in enumerate(routes): + interior = route[1:-1] + if not interior: + continue + + # Find linehaul segment and backhaul segment + lh_segment = [] + bh_segment = [] + seen_bh = False + for node in interior: + if node in backhaul_set: + seen_bh = True + bh_segment.append(node) + elif node in linehaul_set: + if not seen_bh: + lh_segment.append(node) + # If seen_bh and linehaul node appears, it's an ordering violation + # already caught in constraint 6 + + if lh_segment: + last_lh = lh_segment[-1] + linehaul_end_count[last_lh] += 1 + # The arc from last_lh goes to first backhaul customer or depot + arc_from_count[last_lh] += 1 + + for i in sorted(linehaul_set): + lhs = float(linehaul_end_count[i] - arc_from_count[i]) + rhs = 0.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + msg = (f"Linehaul customer {i}: linehaul-path-end count " + f"({linehaul_end_count[i]}) != arc-from count ({arc_from_count[i]})") + violations.append((3, msg, lhs, rhs, violation_amount)) + + # ================================================================ + # Constraint 4 (Eq. 7): Backhaul-path-start / arc linkage + # For each j in B: + # sum_{l in B_j^S} y_l - sum_{i in L} xi_{ij} = 0 + # In route-level terms: the number of routes whose backhaul segment + # starts at customer j must equal the number of connecting arcs + # from some linehaul customer to j. + # ================================================================ + backhaul_start_count = {j: 0 for j in backhaul_set} + arc_to_count = {j: 0 for j in backhaul_set} + + for r_idx, route in enumerate(routes): + interior = route[1:-1] + if not interior: + continue + + # Find first backhaul customer in the route + bh_segment = [] + for node in interior: + if node in backhaul_set: + bh_segment.append(node) + + if bh_segment: + first_bh = bh_segment[0] + backhaul_start_count[first_bh] += 1 + arc_to_count[first_bh] += 1 + + for j in sorted(backhaul_set): + lhs = float(backhaul_start_count[j] - arc_to_count[j]) + rhs = 0.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + msg = (f"Backhaul customer {j}: backhaul-path-start count " + f"({backhaul_start_count[j]}) != arc-to count ({arc_to_count[j]})") + violations.append((4, msg, lhs, rhs, violation_amount)) + + # ================================================================ + # Constraint 5 (Eq. 8): Exactly M connecting arcs + # sum_{(i,j) in A_0} xi_{ij} = M + # A_0 arcs originate from a linehaul customer (i in L) and go to + # a backhaul customer or depot (j in B_0). Each route with at + # least one linehaul customer contributes exactly one such arc. + # Routes without any linehaul customer (e.g., empty [0,0]) do + # not contribute a connecting arc. + # ================================================================ + num_connecting_arcs = 0 + for route in routes: + interior = route[1:-1] + if any(node in linehaul_set for node in interior): + num_connecting_arcs += 1 + lhs = float(num_connecting_arcs) + rhs = float(M) + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + msg = (f"Number of connecting arcs (A_0) is {num_connecting_arcs}, " + f"should be exactly {M}") + violations.append((5, msg, lhs, rhs, violation_amount)) + + # ================================================================ + # Constraint 7 (Eq. 3): Objective consistency (Tier C anti-gaming) + # The reported objective_value must equal the sum of + # distance_matrix[route[i]][route[i+1]] over all consecutive arcs + # of all routes. The set-partitioning objective + # z = sum_l c_l x_l + sum_l c_l y_l + sum_(i,j) d_ij xi_ij + # is, at the route level, exactly the total travel distance across + # all selected routes (since each c_l is a sum of arc costs along + # the path and the inter-segment arc d_ij is the connector). All + # variables determining the obj (the routes) are present in the + # solution, so a full recompute applies. + # ================================================================ + reported_obj = solution.get("objective_value") + distance_matrix = instance.get("distance_matrix") + if reported_obj is not None and distance_matrix 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 a, b in zip(route[:-1], route[1:]): + true_obj += float(distance_matrix[a][b]) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor; distance + # matrices here are integer-valued so any real exploit + # (obj=0, obj=MAX_FLOAT, obj=1e6*ref) is well outside this. + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + lhs = reported + rhs = true_obj + violation_amount = abs_diff + msg = (f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed total route distance=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={tol:.3g})") + violations.append((7, msg, lhs, rhs, violation_amount)) + + # ================================================================ + # Build output + # ================================================================ + violated_constraint_indices = sorted(set(v[0] for v in violations)) + violation_messages = [] + magnitude_list = [] + + for v in violations: + c_idx, msg, lhs_val, rhs_val, raw_excess = v + violation_messages.append(msg) + normalizer = max(abs(rhs_val), EPS) + ratio = raw_excess / normalizer + magnitude_list.append({ + "constraint": c_idx, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + + feasible = len(violations) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_constraint_indices, + "violations": violation_messages, + "violation_magnitudes": magnitude_list + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for VRPB (Mingozzi et al., 1999)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + result = check_feasibility(instance, solution) + save_json(result, args.result_path) + print(f"Feasibility result saved to {args.result_path}") + print(f" Feasible: {result['feasible']}") + if not result["feasible"]: + 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/mingozzi1999/gurobi_code.py b/tasks/mingozzi1999/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..efafb942a61449d4222c77e34f701f9344c12bc2 --- /dev/null +++ b/tasks/mingozzi1999/gurobi_code.py @@ -0,0 +1,343 @@ +""" +Gurobi implementation of the VRPB set-partitioning IP formulation. + +Reference: Mingozzi, Giorgi, Baldacci (1999) +"An Exact Method for the Vehicle Routing Problem with Backhauls" +Transportation Science 33(3):315-329 + +The model (IP) is defined by Equations 3-9 in the paper: + min sum_{l in L} c_l x_l + sum_{l in B} c_l y_l + sum_{(i,j) in A0} d_ij xi_ij + s.t. + (4) sum_{l in L_i} x_l = 1, for all i in L (visit each linehaul customer once) + (5) sum_{l in B_j} y_l = 1, for all j in B (visit each backhaul customer once) + (6) sum_{l in L_i^E} x_l - sum_{j in B0} xi_ij = 0, for all i in L (link linehaul path end to A0 arc) + (7) sum_{l in B_j^S} y_l - sum_{i in L} xi_ij = 0, for all j in B (link backhaul path start to A0 arc) + (8) sum_{(i,j) in A0} xi_ij = M (exactly M routes) + (9) x, y, xi binary +""" + +import json +import argparse +import itertools +import sys +from gurobipy import Model, GRB, quicksum +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, 'r') as f: + return json.load(f) + + +def enumerate_feasible_paths_linehaul(linehaul_indices, depot, dist, demands, Q, Q_min_L): + """ + Enumerate all feasible elementary paths in G_L starting at the depot. + A feasible path P: depot -> i1 -> i2 -> ... -> ik where + Q_min_L <= sum of demands <= Q + Returns list of (path_as_tuple_of_customer_indices, cost, terminal_vertex). + """ + paths = [] + n_linehaul = len(linehaul_indices) + + # DFS enumeration + def dfs(current, visited, load, cost, path): + # Check if current path (excluding depot start) is feasible + if len(path) > 0 and Q_min_L <= load <= Q: + paths.append((tuple(path), cost, path[-1])) + # Try extending + for nxt in linehaul_indices: + if nxt not in visited: + new_load = load + demands[nxt] + if new_load <= Q: + new_cost = cost + dist[current][nxt] + visited.add(nxt) + path.append(nxt) + dfs(nxt, visited, new_load, new_cost, path) + path.pop() + visited.remove(nxt) + + dfs(depot, set(), 0, 0, []) + return paths + + +def enumerate_feasible_paths_backhaul(backhaul_indices, depot, dist, demands, Q, Q_min_B): + """ + Enumerate all feasible elementary paths in G_B ending at the depot. + A feasible path P: j1 -> j2 -> ... -> jk -> depot where + Q_min_B <= sum of demands <= Q + Returns list of (path_as_tuple_of_customer_indices, cost, starting_vertex). + The cost includes all arcs including the final arc to depot. + + NOTE: In the paper's formulation, backhaul path cost does NOT include + the arc to/from depot (that's handled by the A0 arcs and the depot return). + Actually, re-reading the paper: the backhaul path in G_B ends at vertex 0. + So the cost of a backhaul path includes the arc from the last backhaul + customer to the depot. But the starting arc from a linehaul customer to + the first backhaul customer is in A0 (not in the backhaul path). + + So backhaul path: j1 -> j2 -> ... -> jk -> 0 + Cost = d(j1,j2) + ... + d(j_{k-1},jk) + d(jk, 0) + Starting vertex = j1 + """ + paths = [] + + def dfs(current, visited, load, cost, path): + # Current path is path so far (list of backhaul customers) + if len(path) > 0 and Q_min_B <= load <= Q: + # Complete path by adding arc to depot + total_cost = cost + dist[current][depot] + paths.append((tuple(path), total_cost, path[0])) + # Try extending + for nxt in backhaul_indices: + if nxt not in visited: + new_load = load + demands[nxt] + if new_load <= Q: + new_cost = cost + dist[current][nxt] + visited.add(nxt) + path.append(nxt) + dfs(nxt, visited, new_load, new_cost, path) + path.pop() + visited.remove(nxt) + + # Start DFS from each backhaul customer as the first node + for start in backhaul_indices: + visited = {start} + dfs(start, visited, demands[start], 0, [start]) + + return paths + + +def solve_vrpb(instance, time_limit): + depot_idx = instance['depot']['index'] + n = instance['num_linehaul_customers'] + m = instance['num_backhaul_customers'] + M = instance['num_vehicles'] + Q = instance['vehicle_capacity'] + dist = instance['distance_matrix'] + + linehaul_indices = [c['index'] for c in instance['linehaul_customers']] + backhaul_indices = [c['index'] for c in instance['backhaul_customers']] + + demands = {} + demands[depot_idx] = 0 + for c in instance['linehaul_customers']: + demands[c['index']] = c['demand'] + for c in instance['backhaul_customers']: + demands[c['index']] = c['demand'] + + # Compute Q_min + sum_L = sum(demands[i] for i in linehaul_indices) + sum_B = sum(demands[j] for j in backhaul_indices) + Q_min_L = max(0, sum_L - (M - 1) * Q) + Q_min_B = max(0, sum_B - (M - 1) * Q) + + print(f"Problem: n={n}, m={m}, M={M}, Q={Q}") + print(f"Q_min_L={Q_min_L}, Q_min_B={Q_min_B}") + print(f"Sum linehaul demands={sum_L}, Sum backhaul demands={sum_B}") + + # Enumerate feasible linehaul paths (starting at depot) + print("Enumerating linehaul paths...") + linehaul_paths = enumerate_feasible_paths_linehaul( + linehaul_indices, depot_idx, dist, demands, Q, Q_min_L + ) + print(f" Found {len(linehaul_paths)} feasible linehaul paths") + + # Enumerate feasible backhaul paths (ending at depot) + print("Enumerating backhaul paths...") + backhaul_paths = enumerate_feasible_paths_backhaul( + backhaul_indices, depot_idx, dist, demands, Q, Q_min_B + ) + print(f" Found {len(backhaul_paths)} feasible backhaul paths") + + # Build index sets + # L_i: linehaul paths passing through customer i + # L_i^E: linehaul paths ending at customer i + L_i = {i: [] for i in linehaul_indices} + L_i_E = {i: [] for i in linehaul_indices} + for idx, (path, cost, terminal) in enumerate(linehaul_paths): + for i in path: + L_i[i].append(idx) + L_i_E[terminal].append(idx) + + # B_j: backhaul paths passing through customer j + # B_j^S: backhaul paths starting at customer j + B_j = {j: [] for j in backhaul_indices} + B_j_S = {j: [] for j in backhaul_indices} + for idx, (path, cost, start) in enumerate(backhaul_paths): + for j in path: + B_j[j].append(idx) + B_j_S[start].append(idx) + + # A0 = {(i,j) : i in L, j in B_0} where B_0 = B union {0} + B_0 = backhaul_indices + [depot_idx] + A0_arcs = [(i, j) for i in linehaul_indices for j in B_0] + + # Build Gurobi model + model = Model("VRPB") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + x = {} # x[l] for linehaul path l + for idx, (path, cost, terminal) in enumerate(linehaul_paths): + x[idx] = model.addVar(vtype=GRB.BINARY, obj=cost, name=f"x_{idx}") + + y = {} # y[l] for backhaul path l + for idx, (path, cost, start) in enumerate(backhaul_paths): + y[idx] = model.addVar(vtype=GRB.BINARY, obj=cost, name=f"y_{idx}") + + xi = {} # xi[i,j] for arc (i,j) in A0 + for (i, j) in A0_arcs: + xi[i, j] = model.addVar(vtype=GRB.BINARY, obj=dist[i][j], name=f"xi_{i}_{j}") + + model.update() + model.ModelSense = GRB.MINIMIZE + + # Constraint (4): each linehaul customer visited exactly once + for i in linehaul_indices: + model.addConstr( + quicksum(x[idx] for idx in L_i[i]) == 1, + name=f"visit_linehaul_{i}" + ) + + # Constraint (5): each backhaul customer visited exactly once + for j in backhaul_indices: + model.addConstr( + quicksum(y[idx] for idx in B_j[j]) == 1, + name=f"visit_backhaul_{j}" + ) + + # Constraint (6): link linehaul path ending to A0 arc + for i in linehaul_indices: + model.addConstr( + quicksum(x[idx] for idx in L_i_E[i]) + - quicksum(xi[i, j] for j in B_0) == 0, + name=f"link_linehaul_{i}" + ) + + # Constraint (7): link backhaul path starting to A0 arc + for j in backhaul_indices: + model.addConstr( + quicksum(y[idx] for idx in B_j_S[j]) + - quicksum(xi[i, j] for i in linehaul_indices) == 0, + name=f"link_backhaul_{j}" + ) + + # Constraint (8): exactly M arcs of A0 + model.addConstr( + quicksum(xi[i, j] for (i, j) in A0_arcs) == M, + name="num_routes" + ) + + # Optimize + model.optimize() + + # Extract solution + result = {"objective_value": None, "routes": [], "status": ""} + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + + # Reconstruct routes + selected_linehaul = [] + for idx in x: + if x[idx].X > 0.5: + path, cost, terminal = linehaul_paths[idx] + selected_linehaul.append((idx, path, cost, terminal)) + + selected_backhaul = [] + for idx in y: + if y[idx].X > 0.5: + path, cost, start = backhaul_paths[idx] + selected_backhaul.append((idx, path, cost, start)) + + selected_arcs = [] + for (i, j) in A0_arcs: + if xi[i, j].X > 0.5: + selected_arcs.append((i, j)) + + # Build routes by linking linehaul paths -> A0 arcs -> backhaul paths + routes = [] + for arc_i, arc_j in selected_arcs: + route = {"linehaul_path": None, "connecting_arc": (arc_i, arc_j), + "backhaul_path": None} + # Find linehaul path ending at arc_i + for idx, path, cost, terminal in selected_linehaul: + if terminal == arc_i: + route["linehaul_path"] = list(path) + route["linehaul_cost"] = cost + break + # If arc_j != depot, find backhaul path starting at arc_j + if arc_j != depot_idx: + for idx, path, cost, start in selected_backhaul: + if start == arc_j: + route["backhaul_path"] = list(path) + route["backhaul_cost"] = cost + break + + # Build full route sequence + full_route = [depot_idx] + if route["linehaul_path"]: + full_route.extend(route["linehaul_path"]) + if route["backhaul_path"]: + full_route.extend(route["backhaul_path"]) + full_route.append(depot_idx) + route["full_sequence"] = full_route + + routes.append(route) + + result["routes"] = [r["full_sequence"] for r in routes] + result["num_routes"] = len(routes) + + print(f"\nObjective value: {result['objective_value']}") + print(f"Number of routes: {result['num_routes']}") + for i, r in enumerate(routes): + print(f" Route {i+1}: {r['full_sequence']}") + else: + result["status"] = "infeasible" + result["objective_value"] = None + print("No feasible solution found.") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="VRPB solver using Gurobi (set-partitioning 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) + + instance = load_instance(args.instance_path) + result = solve_vrpb(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"\nSolution saved to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/mingozzi1999/gurobi_feasi_result/large_feasi_result_1.json b/tasks/mingozzi1999/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mingozzi1999/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/mingozzi1999/gurobi_feasi_result/large_feasi_result_2.json b/tasks/mingozzi1999/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mingozzi1999/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/mingozzi1999/gurobi_feasi_result/large_feasi_result_3.json b/tasks/mingozzi1999/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mingozzi1999/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/mingozzi1999/gurobi_feasi_result/large_feasi_result_4.json b/tasks/mingozzi1999/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mingozzi1999/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/mingozzi1999/gurobi_feasi_result/large_feasi_result_5.json b/tasks/mingozzi1999/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mingozzi1999/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/mingozzi1999/gurobi_feasi_result/tiny_feasi_result.json b/tasks/mingozzi1999/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mingozzi1999/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/mingozzi1999/gurobi_solution/large_solution_1.json b/tasks/mingozzi1999/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..b0048b94d04b92217bf505c8ab1d007cd767ab4b --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06f9ced5aea48adb55129c61f4d0215b7044536fec54bae2a150232005ddae22 +size 353 diff --git a/tasks/mingozzi1999/gurobi_solution/large_solution_2.json b/tasks/mingozzi1999/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..86ed46a57e8d579e5c9230709efbed96481ea485 --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8d16ab2bd7f79bdc5937569b41282a541c1a43bd86379fe7c59fcf0cd36dfe9 +size 353 diff --git a/tasks/mingozzi1999/gurobi_solution/large_solution_3.json b/tasks/mingozzi1999/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..3ce12d03ce99995677f1e222e795401d7e4bdd28 --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ceca91203da3dd66df17bffce368efa90dc81733e7998601864ee63eeae66cd +size 352 diff --git a/tasks/mingozzi1999/gurobi_solution/large_solution_4.json b/tasks/mingozzi1999/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ee9faa8e72e489352f28c1b23328443b4727b477 --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:293008235b9bf2ae90ba983f026940ac554f067154c3295aa0f410a5cfe0aa8d +size 352 diff --git a/tasks/mingozzi1999/gurobi_solution/large_solution_5.json b/tasks/mingozzi1999/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3e66fbe1c92256b8f464e3dda150b43bb6b391c7 --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b1a0788dcc01e8515268d3b9a40723e8b7ff2d7035ff284ff9964ee0c4390b6 +size 353 diff --git a/tasks/mingozzi1999/gurobi_solution/tiny_solution.json b/tasks/mingozzi1999/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..9657b24470c72176d94ad276a324124c90805de0 --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf1e2608dfd88dd26b4891de4f732d1f4fb122e4e5265fe650f5d328dab39374 +size 401 diff --git a/tasks/mingozzi1999/gurobi_solution_log/large_log_1.jsonl b/tasks/mingozzi1999/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e069e1e94a52aaae2bcde89838a957de1c76817d --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d666cd2420481a5ec45e6eb1cbaac4fb2aeded412c98522afe71679cab24dc5 +size 44 diff --git a/tasks/mingozzi1999/gurobi_solution_log/large_log_2.jsonl b/tasks/mingozzi1999/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8793b1894c8458f90fcbc9cdfafeb6dc8bce7919 --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef89ce88ffdd8df48f64bbf5d7049748288f9a63902bb45517e54ba429dcff7f +size 88 diff --git a/tasks/mingozzi1999/gurobi_solution_log/large_log_3.jsonl b/tasks/mingozzi1999/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..578de634f48cbd8ae20690ddc8873f9608268ac7 --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ad6f12e29c95ee24c09d592a5c3ba0760de0ee49609e718a9fc02b686ddfad8 +size 43 diff --git a/tasks/mingozzi1999/gurobi_solution_log/large_log_4.jsonl b/tasks/mingozzi1999/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f8f0853381967e0b1ef3048d9946088e2f759e3d --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20b1bda44cef1503e9ba6838a429ae215cebe3c60cb0b79cb6cd45decf0e7cf2 +size 43 diff --git a/tasks/mingozzi1999/gurobi_solution_log/large_log_5.jsonl b/tasks/mingozzi1999/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cab61e0aedf77f3be91582a06934fe9b00c2e88a --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6aaca4571d7e0ba0bf2d6188159b781047e1dc3dc341b42766b15b2e5f39e55e +size 44 diff --git a/tasks/mingozzi1999/gurobi_solution_log/tiny_log.jsonl b/tasks/mingozzi1999/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4582f1df174c615dc6afeb053a79d4c412b8c145 --- /dev/null +++ b/tasks/mingozzi1999/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ed644a0d9954ee72666897e267198a451302f114bb191500f20e568f71ed314 +size 42 diff --git a/tasks/mingozzi1999/instance/large_instance_1.json b/tasks/mingozzi1999/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..de486ddf476b49f4fd6aa371f5d1203bf10dc7c4 --- /dev/null +++ b/tasks/mingozzi1999/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c9e78bcc12bee4424dd4985230e796d9f379a3db37989cacaeb8699d28d4df3 +size 4748 diff --git a/tasks/mingozzi1999/instance/large_instance_2.json b/tasks/mingozzi1999/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c2fcf7f550320c64f7402827613e1c4aeb2805fe --- /dev/null +++ b/tasks/mingozzi1999/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f16de6abe7ea8bbeb857072569bfaa47638c93c896617cdabda382303af3196e +size 4676 diff --git a/tasks/mingozzi1999/instance/large_instance_3.json b/tasks/mingozzi1999/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..0074b24b43b7bf174a79f220004743954f71bf54 --- /dev/null +++ b/tasks/mingozzi1999/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b23e9190a965069b094fd436a77ef9bcf37691c90e28edcd23572d8820c95c17 +size 5239 diff --git a/tasks/mingozzi1999/instance/large_instance_4.json b/tasks/mingozzi1999/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8af5a555a3fd8fcf5de72213f93c96eee11a5a8c --- /dev/null +++ b/tasks/mingozzi1999/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5adc14f7b17d2c8cd2544b9a7c7c2458f394d90f3057ff2afcb6988609ca111 +size 4803 diff --git a/tasks/mingozzi1999/instance/large_instance_5.json b/tasks/mingozzi1999/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..40ee8dc5d2d8b529d76f3e4a4383944605230177 --- /dev/null +++ b/tasks/mingozzi1999/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75ee9496bd4d8bfa7fe6ce91297dc687c29c28ef4132c84d3bd4febf9fca76e4 +size 4742 diff --git a/tasks/mingozzi1999/instance/tiny_instance.json b/tasks/mingozzi1999/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..a81dd9c48517a94e02520f38160d1503807f47fd --- /dev/null +++ b/tasks/mingozzi1999/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f8027d19053a0f640d5a1b58dd45dc605d6a562274783cfd880d84f4ae3f787 +size 8067 diff --git a/tasks/mingozzi1999/instance_schema.json b/tasks/mingozzi1999/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d0aa6e9b089f3c51578ce2f738d8a6a281296ef5 --- /dev/null +++ b/tasks/mingozzi1999/instance_schema.json @@ -0,0 +1,35 @@ +{ + "num_linehaul_customers": " Number of linehaul customers requiring goods delivered from the depot.", + "num_backhaul_customers": " Number of backhaul customers with goods to be picked up and returned to the depot.", + "num_total_customers": " Total number of customers (linehaul plus backhaul).", + "num_vehicles": " Number of identical vehicles available in the fleet.", + "vehicle_capacity": " Maximum carrying capacity of each vehicle.", + "min_vehicles_linehaul": " Minimum number of vehicles needed to serve all linehaul customers, determined by bin packing.", + "min_vehicles_backhaul": " Minimum number of vehicles needed to serve all backhaul customers, determined by bin packing.", + "depot": { + "index": " Index of the depot in the distance matrix.", + "coordinates": " X and Y position of the depot on the grid." + }, + "linehaul_customers": [ + { + "index": " Index of this linehaul customer in the distance matrix.", + "coordinates": " X and Y position of this linehaul customer on the grid.", + "demand": " Quantity of goods to be delivered from the depot to this linehaul customer." + } + ], + "backhaul_customers": [ + { + "index": " Index of this backhaul customer in the distance matrix.", + "coordinates": " X and Y position of this backhaul customer on the grid.", + "demand": " Quantity of goods to be picked up from this backhaul customer and returned to the depot." + } + ], + "distance_matrix": " Travel cost between each pair of locations, where row 0 and column 0 correspond to the depot.", + "constraints": { + "linehaul_before_backhaul": " Whether all linehaul customers on a route must be served before any backhaul customer on that route.", + "backhaul_only_routes_allowed": " Whether routes serving only backhaul customers with no linehaul customers are permitted.", + "separate_capacity_for_linehaul_and_backhaul": " Whether linehaul and backhaul loads are checked independently against the vehicle capacity.", + "each_customer_visited_exactly_once": " Whether every customer must appear on exactly one route.", + "each_route_starts_and_ends_at_depot": " Whether every route must begin and end at the depot." + } +} diff --git a/tasks/mingozzi1999/mathematical_formulation.md b/tasks/mingozzi1999/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..ac328d58b4ef4818ae73138fd8bf62be43082dce --- /dev/null +++ b/tasks/mingozzi1999/mathematical_formulation.md @@ -0,0 +1,64 @@ +# Original Formulation (Eqs. 3–9) + +## Sets and Indices + +- $G = (V, A)$: directed graph with $V = \{0\} \cup L \cup B$. + +- $L = \{1, \ldots, n\}$: linehaul customers; $B = \{n+1, \ldots, n+m\}$: backhaul customers; vertex $0$ is the depot. + +- $L_0 = L \cup \{0\}$; $B_0 = B \cup \{0\}$. + +- $A_L = \{(i,j) \in A : i, j \in L_0\}$; $A_B = \{(i,j) \in A : i, j \in B_0\}$; $A_0 = \{(i,j) \in A : i \in L,\ j \in B_0\}$. + +- $\mathcal{L}$: set of all feasible linehaul paths (starting at 0 in $G_L$). + +- $\mathcal{B}$: set of all feasible backhaul paths (ending at 0 in $G_B$). + +- $\mathcal{L}_i \subseteq \mathcal{L}$: linehaul paths passing through customer $i \in L$. + +- $\mathcal{L}_i^E \subseteq \mathcal{L}$: linehaul paths ending at customer $i \in L$. + +- $\mathcal{B}_j \subseteq \mathcal{B}$: backhaul paths passing through customer $j \in B$. + +- $\mathcal{B}_j^S \subseteq \mathcal{B}$: backhaul paths starting at customer $j \in B$. + +## Parameters + +- $d_{ij} \geq 0$: cost of arc $(i,j) \in A$. + +- $q_i \in \mathbb{Z}_+$: demand of customer $i \in L \cup B$. + +- $Q$: vehicle capacity (identical for all vehicles). + +- $M \geq \max\{M_L, M_B\}$: number of identical vehicles, with $M_L, M_B$ the minimum numbers of vehicles needed to serve linehaul (resp. backhaul) customers. + +- $c_\ell$: cost of path $\ell \in \mathcal{L} \cup \mathcal{B}$ (sum of its arc costs). + +## Decision Variables + +- $x_\ell \in \{0, 1\}$, $\ell \in \mathcal{L}$: 1 if linehaul path $\ell$ is used. + +- $y_\ell \in \{0, 1\}$, $\ell \in \mathcal{B}$: 1 if backhaul path $\ell$ is used. + +- $\xi_{ij} \in \{0, 1\}$, $(i,j) \in A_0$: 1 if the connector arc $(i,j)$ is used. + +## Objective and Constraints + +$$\begin{align} +\min \quad & z(IP) = \sum_{\ell \in \mathcal{L}} c_\ell\, x_\ell + \sum_{\ell \in \mathcal{B}} c_\ell\, y_\ell + + \sum_{(i,j) \in A_0} d_{ij}\, \xi_{ij} + \tag{3} \\ +\text{s.t.}\quad & \sum_{\ell \in \mathcal{L}_i} x_\ell = 1 + && \forall i \in L, \tag{4} \\ +& \sum_{\ell \in \mathcal{B}_j} y_\ell = 1 + && \forall j \in B, \tag{5} \\ +& \sum_{\ell \in \mathcal{L}_i^E} x_\ell - \sum_{j \in B_0} \xi_{ij} = 0 + && \forall i \in L, \tag{6} \\ +& \sum_{\ell \in \mathcal{B}_j^S} y_\ell - \sum_{i \in L} \xi_{ij} = 0 + && \forall j \in B, \tag{7} \\ +& \sum_{(i,j) \in A_0} \xi_{ij} = M, + \tag{8} \\ +& x_\ell \in \{0,1\}\ \forall \ell \in \mathcal{L},\quad + y_\ell \in \{0,1\}\ \forall \ell \in \mathcal{B},\quad + \xi_{ij} \in \{0,1\}\ \forall (i,j) \in A_0. \tag{9} +\end{align}$$ diff --git a/tasks/mingozzi1999/problem_description.txt b/tasks/mingozzi1999/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..fafdb229b0baba6337b9eee9fc93f58ad1896d71 --- /dev/null +++ b/tasks/mingozzi1999/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A fleet of identical vehicles, each with a fixed carrying capacity, is stationed at a central depot and must serve a set of customers partitioned into two groups: linehaul customers and backhaul customers. Each linehaul customer has a known non-negative integer demand for goods to be delivered from the depot, and each backhaul customer has a known non-negative integer quantity of goods to be picked up and returned to the depot. The number of linehaul customers, the number of backhaul customers, the number of available vehicles, and the vehicle capacity are all given. A non-negative travel cost is specified for every ordered pair of locations, including the depot and all customers; these costs are generally asymmetric and are organized as a complete cost matrix over all locations. + +The task is to design exactly as many routes as there are vehicles, where every route starts and ends at the depot, so that each linehaul customer appears on exactly one route and each backhaul customer appears on exactly one route. Within any single route, all linehaul customers visited on that route must be served before any backhaul customer on that route. A route may serve only linehaul customers with no backhaul customers, but a route serving only backhaul customers with no linehaul customers is not permitted. The total demand of the linehaul customers assigned to any single route must not exceed the vehicle capacity, and, separately, the total demand of the backhaul customers assigned to that same route must also not exceed the vehicle capacity; these two capacity checks are independent of each other because the vehicle delivers all linehaul goods before it begins collecting backhaul goods. + +Each route therefore consists of a path from the depot through one or more linehaul customers, followed by a transition arc from the last linehaul customer either directly back to the depot or to a backhaul customer, and then optionally a path through one or more backhaul customers ending at the depot. The cost of a route is the sum of the travel costs along all arcs traversed on that route. + +The goal is to minimize the total travel cost across all routes, which equals the sum of the costs of all chosen linehaul paths, plus the costs of all chosen backhaul paths, plus the costs of all transition arcs connecting the linehaul portion of each route to its backhaul portion or to the depot. diff --git a/tasks/mingozzi1999/solution_logger.py b/tasks/mingozzi1999/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/mingozzi1999/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/mingozzi1999/solution_schema.json b/tasks/mingozzi1999/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..134fed7ffa1752c484211b18a4517db1740597b1 --- /dev/null +++ b/tasks/mingozzi1999/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total travel distance across all vehicle routes.", + "routes": " Ordered sequence of node indices visited by each vehicle, starting and ending at the depot with all linehaul customers served before any backhaul customers." +} diff --git a/tasks/morrison2016/feasibility_check.py b/tasks/morrison2016/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..0c345f5940e840e79a27670fcf5f18f63c6300dc --- /dev/null +++ b/tasks/morrison2016/feasibility_check.py @@ -0,0 +1,411 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Graph Coloring via Set Covering with Maximal Independent Sets. +Based on Morrison, Sewell, and Jacobson (2016). + +Constraints (from math_model.txt, top to bottom): + (1) Covering: sum_{S: v in S} x_S >= 1 for all v in V + (2) Binary domain: x_S in {0, 1} for all S in S + — S must be a maximal independent set in G. + — Since the solution encodes selected sets explicitly, binary is automatic. + We verify that each selected set is a valid maximal independent set. + (3) Domain checks on the `coloring` field (auto-generated). + (4) Objective consistency: reported objective_value must equal len(selected_sets), + which is the recomputed value of sum_{S in S} x_S since each x_S = 1 for a + listed set. Catches Tier-C exploits that fabricate `objective_value`. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('coloring', 'objective_value', 'selected_sets') +_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): + graph = instance["graph"] + num_vertices = graph["num_vertices"] + edges = graph["edges"] + + # Build adjacency sets + adj = [set() for _ in range(num_vertices)] + for u, v in edges: + adj[u].add(v) + adj[v].add(u) + + selected_sets = solution["selected_sets"] # list of lists of vertex indices + + tol = 1e-5 + eps = 1e-5 + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # --------------------------------------------------------------- + # Constraint (1): Covering — sum_{S: v in S} x_S >= 1 for all v + # LHS = number of selected sets containing v, RHS = 1 + # --------------------------------------------------------------- + for v in range(num_vertices): + count = sum(1 for s in selected_sets if v in s) + lhs = float(count) + rhs = 1.0 + # >= constraint: violation if rhs > lhs + violation_amount = rhs - lhs + if violation_amount > tol: + violated_constraints.add(1) + violations.append( + f"Vertex {v} is not covered: appears in {count} selected set(s), needs >= 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 (2): Binary domain — x_S in {0,1}, S in S (maximal independent sets) + # We verify each selected set (x_S = 1) is: + # (a) An independent set: no edge between any pair of vertices in S. + # (b) A maximal independent set: no vertex outside S can be added + # while maintaining independence. + # --------------------------------------------------------------- + + for idx, s in enumerate(selected_sets): + s_set = set(s) + + # (a) Independence check: for each edge (u,v), both u and v should + # not be in the same selected set. + # LHS = number of edges within S, RHS = 0 (equality: must be 0) + edge_count = 0 + edge_violations_detail = [] + for u, v in edges: + if u in s_set and v in s_set: + edge_count += 1 + edge_violations_detail.append((u, v)) + + if edge_count > 0: + lhs = float(edge_count) + rhs = 0.0 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + violated_constraints.add(2) + pairs_str = ", ".join(f"({u},{v})" for u, v in edge_violations_detail[:5]) + if len(edge_violations_detail) > 5: + pairs_str += f" ... ({len(edge_violations_detail)} total)" + violations.append( + f"Selected set {idx} is not independent: {edge_count} internal edge(s): {pairs_str}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # (b) Maximality check: for each vertex not in S, it must be adjacent + # to at least one vertex in S (otherwise it could be added). + # LHS = number of addable vertices, RHS = 0 (equality: must be 0) + addable = [] + for v in range(num_vertices): + if v not in s_set: + if not (adj[v] & s_set): + addable.append(v) + + if len(addable) > 0: + lhs = float(len(addable)) + rhs = 0.0 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + violated_constraints.add(2) + verts_str = ", ".join(str(v) for v in addable[:10]) + if len(addable) > 10: + verts_str += f" ... ({len(addable)} total)" + violations.append( + f"Selected set {idx} is not maximal: vertex(es) {verts_str} could be added" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # Variable Domain Checks (auto-generated by add_domain_checks.py) + # coloring: dict[vertex_str -> color_int]. Keys must be valid vertex indices in + # [0, num_vertices); values must be integer color indices in [0, num_colors_used). + # Every vertex must be assigned exactly one color, and adjacent vertices must differ. + coloring = solution.get("coloring", {}) + num_colors_used = len(selected_sets) + for vk, cv in coloring.items(): + try: + v = int(vk) + except (TypeError, ValueError): + v = -1 + if not (0 <= v < num_vertices): + violated_constraints.add(3) + violations.append( + f"Invalid vertex key in coloring: {vk!r} (valid range 0..{num_vertices-1})" + ) + violation_magnitudes.append({ + "constraint": 3, "lhs": float(v), "rhs": 0.0, + "raw_excess": 1.0, "normalizer": max(1.0, eps), "ratio": 1.0, + }) + continue + # Color must be a non-negative integer within the number of used colors + if not isinstance(cv, int) or cv < 0 or cv >= num_colors_used: + violated_constraints.add(3) + violations.append( + f"Invalid color for vertex {v} in coloring: {cv} " + f"(must be integer in [0,{num_colors_used-1}])" + ) + violation_magnitudes.append({ + "constraint": 3, "lhs": float(cv if isinstance(cv, (int, float)) else -1), + "rhs": 0.0, "raw_excess": 1.0, "normalizer": max(1.0, eps), "ratio": 1.0, + }) + # Every vertex in 0..num_vertices must be in coloring. + coloring_keys_int = set() + for vk in coloring.keys(): + try: coloring_keys_int.add(int(vk)) + except (TypeError, ValueError): pass + missing_v = set(range(num_vertices)) - coloring_keys_int + if missing_v: + violated_constraints.add(3) + violations.append( + f"coloring is missing {len(missing_v)} vertex assignment(s): " + f"{sorted(missing_v)[:8]}{'...' if len(missing_v) > 8 else ''}" + ) + violation_magnitudes.append({ + "constraint": 3, "lhs": float(num_vertices - len(missing_v)), + "rhs": float(num_vertices), "raw_excess": float(len(missing_v)), + "normalizer": float(num_vertices), "ratio": float(len(missing_v)) / max(num_vertices, 1), + }) + + # --------------------------------------------------------------- + # Constraint (4): Objective consistency (Tier-C anti-exploit). + # Objective = sum_{S in S} x_S = number of color classes used. + # Since the solution lists exactly the sets with x_S = 1, the true + # objective equals len(selected_sets). Compare against reported value. + # --------------------------------------------------------------- + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(len(selected_sets)) + abs_diff = abs(reported - true_obj) + # Objective is an integer count; require integer match (tol = 0.5). + obj_tol = 0.5 + if abs_diff > obj_tol: + violated_constraints.add(4) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed len(selected_sets)=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + # --------------------------------------------------------------- + # Build result + # --------------------------------------------------------------- + feasible = len(violated_constraints) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for graph coloring set-covering 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 the candidate solution JSON file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the feasibility result JSON file") + args = parser.parse_args() + + with open(args.instance_path, "r") as f: + instance = json.load(f) + with open(args.solution_path, "r") as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasibility: {'PASS' if result['feasible'] else 'FAIL'}") + 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/morrison2016/gurobi_code.py b/tasks/morrison2016/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..467633fb40c648208a6a582e78b08a4424cf7d09 --- /dev/null +++ b/tasks/morrison2016/gurobi_code.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +""" +Graph coloring via set-covering formulation (Morrison et al., 2016). + +Formulation: + minimize sum_{S in S} x_S + subject to sum_{S: v in S} x_S >= 1 for all v in V + x_S in {0, 1} for all S in S + +where S is the family of ALL maximal independent sets in G. +""" + +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_adjacency(num_vertices, edges): + """Build adjacency sets from edge list.""" + adj = [set() for _ in range(num_vertices)] + for u, v in edges: + adj[u].add(v) + adj[v].add(u) + return adj + + +def enumerate_maximal_independent_sets(num_vertices, adj): + """ + Enumerate all maximal independent sets using Bron-Kerbosch on the + complement graph. An independent set in G is a clique in the complement + of G, so we run Bron-Kerbosch with pivoting on the complement. + """ + # Build complement adjacency + comp_adj = [set() for _ in range(num_vertices)] + for v in range(num_vertices): + for u in range(num_vertices): + if u != v and u not in adj[v]: + comp_adj[v].add(u) + + maximal_independent_sets = [] + + def bron_kerbosch(R, P, X): + """Bron-Kerbosch with pivoting (finds maximal cliques in complement = maximal independent sets in G).""" + if not P and not X: + maximal_independent_sets.append(frozenset(R)) + return + + # Choose pivot to maximize |P intersect N(pivot)| in complement graph + pivot = max(P | X, key=lambda v: len(P & comp_adj[v])) + candidates = P - comp_adj[pivot] + + for v in list(candidates): + neighbors_v = comp_adj[v] + bron_kerbosch( + R | {v}, + P & neighbors_v, + X & neighbors_v, + ) + P = P - {v} + X = X | {v} + + bron_kerbosch(set(), set(range(num_vertices)), set()) + return maximal_independent_sets + + +def solve(instance_path, solution_path, time_limit): + """Load instance, enumerate maximal independent sets, solve IP.""" + with open(instance_path, "r") as f: + instance = json.load(f) + + instance_id = instance["instance_id"] + graph = instance["graph"] + num_vertices = graph["num_vertices"] + edges = graph["edges"] + + if solution_path is None: + solution_path = f"gurobi_solution_{instance_id}.json" + + adj = build_adjacency(num_vertices, edges) + + # Enumerate all maximal independent sets + t0 = time.time() + mis_list = enumerate_maximal_independent_sets(num_vertices, adj) + enum_time = time.time() - t0 + num_sets = len(mis_list) + + print(f"Enumerated {num_sets} maximal independent sets in {enum_time:.2f}s") + + # Build vertex-to-set incidence: for each vertex, which sets contain it + vertex_to_sets = [[] for _ in range(num_vertices)] + for idx, s in enumerate(mis_list): + for v in s: + vertex_to_sets[v].append(idx) + + # Build Gurobi model + model = gp.Model("graph_coloring_set_cover") + model.setParam("Threads", 1) + # Pass a slightly-shorter TimeLimit to gurobi so model.optimize() returns + # cleanly before the outer wrapper's 30s grace SIGKILL. Plan F 1h run found + # incumbent obj=35 (jsonl) but solution.json was missing — the final LP at + # node ~80 ran past 3600s and the wrapper killed before json.dump. + _internal_tl = max(60, time_limit - 120) if time_limit > 240 else time_limit + model.setParam("TimeLimit", _internal_tl) + model.setParam("OutputFlag", 1) + # Solver hints: l11 (n=300, |E|≈111K dense graph coloring) was 1h TLE + # with no incumbent in prior runs; MIPFocus=1 prioritizes finding any + # feasible incumbent over closing the LP-gap, and NoRelHeurTime gives + # gurobi a root-node heuristic budget before B&B starts. Other 4 + # instances already OPT-ed; expected minor slowdown is acceptable. + model.setParam("MIPFocus", 1) + model.setParam("NoRelHeurTime", min(60.0, time_limit * 0.05)) + + # One binary variable per maximal independent set + x = model.addVars(num_sets, vtype=GRB.BINARY, name="x") + + # Objective: minimize number of sets used + model.setObjective(gp.quicksum(x[i] for i in range(num_sets)), GRB.MINIMIZE) + + # Covering constraints: every vertex must be in at least one chosen set + for v in range(num_vertices): + model.addConstr( + gp.quicksum(x[i] for i in vertex_to_sets[v]) >= 1, + name=f"cover_{v}", + ) + + model.optimize() + + # Extract solution + solution = { + "instance_id": instance_id, + "problem": "graph_coloring", + "formulation": "set_covering_maximal_independent_sets", + "num_maximal_independent_sets": num_sets, + "enumeration_time_seconds": round(enum_time, 4), + } + + if model.SolCount > 0: + obj_val = round(model.ObjVal) + selected_sets = [] + for i in range(num_sets): + if x[i].X > 0.5: + selected_sets.append(sorted(mis_list[i])) + + # Build vertex-to-color mapping from selected sets + coloring = {} + for color_idx, s in enumerate(selected_sets): + for v in s: + if v not in coloring: + coloring[v] = color_idx + + solution["objective_value"] = obj_val + solution["status"] = model.Status + solution["status_name"] = ( + "OPTIMAL" if model.Status == GRB.OPTIMAL else "TIME_LIMIT" + ) + solution["mip_gap"] = model.MIPGap if hasattr(model, "MIPGap") else None + solution["selected_sets"] = selected_sets + solution["coloring"] = {str(v): coloring[v] for v in sorted(coloring)} + solution["solve_time_seconds"] = round(model.Runtime, 4) + else: + solution["objective_value"] = None + solution["status"] = model.Status + solution["status_name"] = "NO_SOLUTION" + solution["solve_time_seconds"] = round(model.Runtime, 4) + + 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 solution["objective_value"] is not None: + print(f"Chromatic number (objective): {solution['objective_value']}") + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Graph coloring via set-covering over maximal independent sets (Morrison et al., 2016)" + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to instance JSON file", + ) + parser.add_argument( + "--solution_path", + type=str, + default=None, + help="Path to write solution JSON (default: gurobi_solution_.json)", + ) + parser.add_argument( + "--time_limit", + type=int, + default=300, + help="Gurobi time limit in seconds (default: 300)", + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + solve(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/morrison2016/gurobi_feasi_result/large_feasi_result_1.json b/tasks/morrison2016/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/morrison2016/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/morrison2016/gurobi_feasi_result/large_feasi_result_2.json b/tasks/morrison2016/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/morrison2016/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/morrison2016/gurobi_feasi_result/large_feasi_result_3.json b/tasks/morrison2016/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/morrison2016/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/morrison2016/gurobi_feasi_result/large_feasi_result_4.json b/tasks/morrison2016/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/morrison2016/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/morrison2016/gurobi_feasi_result/large_feasi_result_5.json b/tasks/morrison2016/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/morrison2016/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/morrison2016/gurobi_feasi_result/tiny_feasi_result.json b/tasks/morrison2016/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/morrison2016/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/morrison2016/gurobi_solution/large_solution_1.json b/tasks/morrison2016/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..2d5371e38153e35cc96dcc28deb5e57883f47f2d --- /dev/null +++ b/tasks/morrison2016/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d97783240f580984e52ca100399c37fe6121dd6ffb43600c11159a4b308e21a3 +size 8665 diff --git a/tasks/morrison2016/gurobi_solution/large_solution_2.json b/tasks/morrison2016/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e4ceb7d00411f00dd1b529fc4bd10a2f4114afd1 --- /dev/null +++ b/tasks/morrison2016/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff336e250c9c266c52ea77dc90e62b5d17c2e66a0256c68606e74f55e3d037e4 +size 8935 diff --git a/tasks/morrison2016/gurobi_solution/large_solution_3.json b/tasks/morrison2016/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..2eade42231d391418b827a4d501c2aac29719165 --- /dev/null +++ b/tasks/morrison2016/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2feb8034de35af892e270a4de0e71a79c9a5c8a3dc1dfe797d9948fb31c8cef7 +size 9261 diff --git a/tasks/morrison2016/gurobi_solution/large_solution_4.json b/tasks/morrison2016/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..168c71e5a2c13b5afa3df9f3bb2a0d34b853e743 --- /dev/null +++ b/tasks/morrison2016/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:001f93758e659611ac4237741c140ace395524fe5588a2935dccf472660a194b +size 9210 diff --git a/tasks/morrison2016/gurobi_solution/large_solution_5.json b/tasks/morrison2016/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..88edc0bb86518d241d607ab853f10afa650a579d --- /dev/null +++ b/tasks/morrison2016/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4406571ee5342005bb14486222f4d1c28e99a565ffc98fa96f758d2ff2dba75a +size 16207 diff --git a/tasks/morrison2016/gurobi_solution/tiny_solution.json b/tasks/morrison2016/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..d0b755881f17aad45ad259a704f327642e20a6b6 --- /dev/null +++ b/tasks/morrison2016/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16fb8a3f71cefc4e64327d027c2a6bf1c5af7205dd4b456481a979ca38d6b755 +size 626 diff --git a/tasks/morrison2016/gurobi_solution_log/large_log_1.jsonl b/tasks/morrison2016/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..44e3ed230d7553e792dfaf0948b8596933f174bd --- /dev/null +++ b/tasks/morrison2016/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72617a16f76c47fa3a7db7783c0b50ce31db5789a8b3defd32408ef4eb956c12 +size 944 diff --git a/tasks/morrison2016/gurobi_solution_log/large_log_2.jsonl b/tasks/morrison2016/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c6b1215571948d31a86c53d63d29c068aeb2b575 --- /dev/null +++ b/tasks/morrison2016/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d1170ef75a0a6fd7cc224d73e6804fe0dac3d8c8347148154a3fda41b483224 +size 456 diff --git a/tasks/morrison2016/gurobi_solution_log/large_log_3.jsonl b/tasks/morrison2016/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8874e3295271ae8d1f76732942eed758a5cbe039 --- /dev/null +++ b/tasks/morrison2016/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51896918793c703a8466aaa3fbcd6ba53b30c963855d175b58533aead9ecd52e +size 729 diff --git a/tasks/morrison2016/gurobi_solution_log/large_log_4.jsonl b/tasks/morrison2016/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f0b14b6ba5636e8160bd571f5bca00ac6995c42f --- /dev/null +++ b/tasks/morrison2016/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1d49175734b6b5e0c9ef42473a55b710beb0803a83191dbcfafd078a8288030 +size 41 diff --git a/tasks/morrison2016/gurobi_solution_log/large_log_5.jsonl b/tasks/morrison2016/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c257a0a035cc5d610bd6510c9852b8d88f302860 --- /dev/null +++ b/tasks/morrison2016/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf0374475a20a65ab54038ed743283d9ea055d537501ca821c369514e5331a19 +size 295 diff --git a/tasks/morrison2016/gurobi_solution_log/tiny_log.jsonl b/tasks/morrison2016/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..25b527852d66ce723e1ff83cfa6cc95150c791d5 --- /dev/null +++ b/tasks/morrison2016/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e4122044a3cf9f4cb32c0836a4d2d1c6550b9668bf1bfc1692017b084ae4fc2 +size 39 diff --git a/tasks/morrison2016/instance/large_instance_1.json b/tasks/morrison2016/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..10cefe09c5e5a933b130a3ff91ddd8eb6c466ecc --- /dev/null +++ b/tasks/morrison2016/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d173b0659459ab6158affef790059026869dc84c11d8af1d0f88c91617663d4 +size 252895 diff --git a/tasks/morrison2016/instance/large_instance_2.json b/tasks/morrison2016/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..04987cf32770ffa0726484eca4826608abcdfbce --- /dev/null +++ b/tasks/morrison2016/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6171c03bff5fda404bb04e617e622fd221ef14224f06ce756266de6438553040 +size 455055 diff --git a/tasks/morrison2016/instance/large_instance_3.json b/tasks/morrison2016/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..117724f456663d6a2fb82f2590fdea658b4ca3c1 --- /dev/null +++ b/tasks/morrison2016/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:631fb92a77e43c352516ed4b20dd5007cefffa19a9613d82e2ab1fac28d65964 +size 230042 diff --git a/tasks/morrison2016/instance/large_instance_4.json b/tasks/morrison2016/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..34d250a9dc5f9b58639ef97e5bba9382aead63fd --- /dev/null +++ b/tasks/morrison2016/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4e82c9d8b146246faa10dfab4d727eda10015c2eb685a725de98fa7a96fd966 +size 490801 diff --git a/tasks/morrison2016/instance/large_instance_5.json b/tasks/morrison2016/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..08cbabf6a61ea23cf9dd25a35dab19dcf6585382 --- /dev/null +++ b/tasks/morrison2016/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e1530c92607dbdbf6afc13cbcf3064893761ebe5046aade2747a0ea60fcb998 +size 345632 diff --git a/tasks/morrison2016/instance/tiny_instance.json b/tasks/morrison2016/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c808b5ca66844f31394941702c80eb9b7c2cecef --- /dev/null +++ b/tasks/morrison2016/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15e13a03b81914868da3ee3581c5593b65746abf43cf37f36a1aff3087687c55 +size 840 diff --git a/tasks/morrison2016/instance_schema.json b/tasks/morrison2016/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..95b70f39b2e33b6a505a0c7bde56cab21916cea1 --- /dev/null +++ b/tasks/morrison2016/instance_schema.json @@ -0,0 +1,12 @@ +{ + "graph": { + "num_vertices": " Total number of vertices in the graph.", + "num_edges": " Total number of edges in the graph.", + "edge_density": " Fraction of all possible edges that are present in the graph.", + "edges": " Pairs of vertices connected by an edge, where each pair contains two distinct vertex indices." + }, + "bounds": { + "clique_lower_bound": " Largest clique size found in the graph, serving as a lower bound on the number of colors needed.", + "greedy_upper_bound": " Number of colors used by a greedy heuristic coloring, serving as an upper bound on the number of colors needed." + } +} diff --git a/tasks/morrison2016/mathematical_formulation.md b/tasks/morrison2016/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..9e54c8055cd0ebebfc496b1af6cab295af00505f --- /dev/null +++ b/tasks/morrison2016/mathematical_formulation.md @@ -0,0 +1,28 @@ +# Original Formulation: Graph Coloring via Set Covering (Mehrotra & Trick) + +**Source.** Morrison, Sewell, Jacobson (2016), “Solving the Pricing Problem in a Branch-and-Price Algorithm for Graph Coloring using Zero-Suppressed Binary Decision Diagrams,” Section 2.3. The formulation is originally due to Mehrotra and Trick (1996). + +## Sets and Indices + +- $G = (V, E)$ — input graph with vertex set $V$ and edge set $E$. + +- $\mathcal{S}$ — the family of all *maximal independent sets* of $G$ (each corresponds to a candidate color class). + +- $v \in V$ — a vertex. + +- $S \in \mathcal{S}$ — a maximal independent set. + +## Decision Variables + +$$x_S \in \{0,1\} \qquad \forall\, S \in \mathcal{S},$$ where $x_S = 1$ iff the maximal independent set $S$ is chosen as a color class in the coloring. + +## Formulation + +$$\begin{align} +\min\ & \sum_{S \in \mathcal{S}} x_S \tag{1} \\ +\text{s.t.}\ & \sum_{S \in \mathcal{S}\,:\, v \in S} x_S \ \ge\ 1 + \qquad \forall\, v \in V, \tag{2} \\ +& x_S \in \{0,1\} \qquad \forall\, S \in \mathcal{S}. \tag{3} +\end{align}$$ + +The objective (1) minimizes the number of color classes used. The covering constraints (2) require that every vertex appears in at least one selected maximal independent set. The integrality constraints (3) enforce binary selection of color classes. diff --git a/tasks/morrison2016/problem_description.txt b/tasks/morrison2016/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..74e5803c24a2f2a0732171c2ea07eea9ee6ded20 --- /dev/null +++ b/tasks/morrison2016/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +Given an undirected graph with a specified set of vertices and a specified set of edges connecting pairs of vertices, the task is to assign a color to every vertex such that no two vertices connected by an edge share the same color, using the fewest colors possible. The number of colors used equals the chromatic number of the graph. + +Every vertex must receive exactly one color. Two vertices that are directly connected by an edge must receive different colors. The goal is to minimize the total number of distinct colors used across all vertices. + +The input data for an instance consists of the number of vertices, the number of edges, and the list of edges, where each edge is an unordered pair of distinct vertices. An instance may also provide auxiliary lower and upper bounds on the chromatic number. diff --git a/tasks/morrison2016/solution_logger.py b/tasks/morrison2016/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/morrison2016/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/morrison2016/solution_schema.json b/tasks/morrison2016/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..c95ba1d61a1c60eba6846923b17aafc6bf84c519 --- /dev/null +++ b/tasks/morrison2016/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Minimum number of colors needed to properly color the graph (the chromatic number).", + "selected_sets": " Chosen color classes, where each inner list contains the vertices assigned to that color, sorted in ascending order.", + "coloring": " Color assigned to each vertex, identified by its index." +} diff --git a/tasks/muter2010/feasibility_check.py b/tasks/muter2010/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..b27ef02391cc908faa7b633d2ef63025b52d7152 --- /dev/null +++ b/tasks/muter2010/feasibility_check.py @@ -0,0 +1,480 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for VRPTW solutions modeled as a Set Covering Problem (SCP). + +Based on: Muter, Birbil, Sahin (2010) - VRPTW reformulated as SCP. + +Hard constraints checked (numbered top-to-bottom from the mathematical formulation): + Constraint 1: Coverage — each customer must be covered by at least one selected route + sum_{p in P} a_{ip} * y_p >= 1, for all i in C + Constraint 2: Integrality — y_p in {0, 1} (binary route selection) + Constraint 3: Capacity — total demand on each route <= vehicle capacity + Constraint 4: Time windows — vehicle arrives at each customer <= customer's due_date + Constraint 5: Depot return — vehicle returns to depot <= depot's due_date + Constraint 6: Variable domain — every customer id in any route must be valid + Constraint 7: Objective consistency — reported objective_value must match + recomputed total Euclidean travel distance over all routes + (Tier C defense against score-gaming exploits) +""" + +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_instance(path): + with open(path, "r") as f: + data = json.load(f) + depot = data["depot"] + customers = {c["id"]: c for c in data["customers"]} + capacity = data["vehicle_capacity"] + # Build node lookup (depot + customers) + nodes = {depot["id"]: depot} + nodes.update(customers) + return data, depot, customers, capacity, nodes + + +def load_solution(path): + with open(path, "r") as f: + return json.load(f) + + +def extract_routes(solution): + """Extract list of customer-id lists from either solution format.""" + routes = [] + for r in solution["routes"]: + if "customers" in r: + # efficient_algorithm format + routes.append(list(r["customers"])) + elif "customer_ids" in r: + # gurobi format + routes.append(list(r["customer_ids"])) + else: + routes.append([]) + return routes + + +def build_dist_lookup(nodes): + """Return a function that computes distance between two node ids.""" + cache = {} + + def dist(i, j): + key = (i, j) + if key not in cache: + cache[key] = euclidean_distance( + nodes[i]["x"], nodes[i]["y"], + nodes[j]["x"], nodes[j]["y"], + ) + return cache[key] + + return dist + + +def check_feasibility(instance_data, solution_data): + tol = 1e-5 + eps = 1e-5 + + depot = instance_data["depot"] + depot_id = depot["id"] + customers = {c["id"]: c for c in instance_data["customers"]} + capacity = instance_data["vehicle_capacity"] + customer_ids = set(customers.keys()) + + nodes = {depot_id: depot} + nodes.update(customers) + dist = build_dist_lookup(nodes) + + routes = extract_routes(solution_data) + + violations = [] + violation_magnitudes = [] + violated_constraint_set = set() + + # ------------------------------------------------------------------ + # Constraint 6: Variable domain — every customer id in any route must + # be a valid customer id in the instance. + # ------------------------------------------------------------------ + for r_idx, route in enumerate(routes): + for cid in route: + if cid not in customer_ids: + violated_constraint_set.add(6) + violations.append( + f"Route {r_idx} contains invalid customer id {cid!r} " + f"(not in instance customers)" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(cid) if isinstance(cid, (int, float)) else 0.0, + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + + # ------------------------------------------------------------------ + # Constraint 1: Coverage (sum a_{ip} y_p >= 1 for each customer i) + # ------------------------------------------------------------------ + covered = {} # customer_id -> count + for route in routes: + for cid in route: + covered[cid] = covered.get(cid, 0) + 1 + + uncovered = customer_ids - set(covered.keys()) + if uncovered: + violated_constraint_set.add(1) + for cid in sorted(uncovered): + lhs = 0.0 + rhs = 1.0 + violation_amount = rhs - lhs # 1.0 + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append(f"Customer {cid} is not covered by any route") + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint 2: Integrality (y_p in {0, 1}) + # The solution is expressed as a set of selected routes, so y_p is + # implicitly 1 for each listed route and 0 otherwise. Always satisfied. + # ------------------------------------------------------------------ + # (No violation possible given the solution format.) + + # ------------------------------------------------------------------ + # Constraint 3: Capacity (total demand on route <= vehicle capacity) + # For each route p: sum_{i in route_p} demand_i <= capacity + # ------------------------------------------------------------------ + for r_idx, route in enumerate(routes): + total_demand = sum(nodes[cid]["demand"] for cid in route) + lhs = total_demand + rhs = capacity + violation_amount = max(lhs - rhs, 0.0) + if violation_amount > tol: + violated_constraint_set.add(3) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Capacity exceeded on route {r_idx}: demand {total_demand} > capacity {capacity}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ------------------------------------------------------------------ + # Constraint 4: Time windows (arrival_i <= due_date_i for each customer) + # Constraint 5: Depot return (return time <= depot due_date) + # ------------------------------------------------------------------ + for r_idx, route in enumerate(routes): + if not route: + continue + t = 0.0 # depart depot at time 0 + prev = depot_id + for cid in route: + travel = dist(prev, cid) + arrival = t + travel + due = nodes[cid]["due_date"] + # Constraint 4: arrival <= due_date + lhs = arrival + rhs = due + violation_amount = max(lhs - rhs, 0.0) + if violation_amount > tol: + violated_constraint_set.add(4) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Time window violated for customer {cid} on route {r_idx}: " + f"arrival {arrival:.4f} > due_date {due}" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + # Wait if early + t = max(arrival, nodes[cid]["ready_time"]) + t += nodes[cid]["service_time"] + prev = cid + + # Constraint 5: return to depot <= depot due_date + return_time = t + dist(prev, depot_id) + lhs = return_time + rhs = depot["due_date"] + violation_amount = max(lhs - rhs, 0.0) + if violation_amount > tol: + violated_constraint_set.add(5) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Depot return time violated on route {r_idx}: " + f"return {return_time:.4f} > depot due_date {rhs}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ------------------------------------------------------------------ + # Constraint 7: Objective consistency — recompute the total Euclidean + # travel distance from the routes and reject if the reported value + # disagrees beyond tolerance. Tier C defense against score-gaming + # exploits that lie about objective_value while keeping the routes + # constraint-feasible. + # + # The VRPTW objective is sum over arcs (i,j) selected with + # x_{ijk} = 1 of c_{ij} = euclidean(i, j). For each route, the + # arcs are depot -> r[0] -> r[1] -> ... -> r[-1] -> depot. + # ------------------------------------------------------------------ + reported_obj = solution_data.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = 0.0 + for route in routes: + if not route: + continue + prev = depot_id + for cid in route: + if cid not in nodes: + # invalid customer id; constraint 6 will catch this. + # Skip the arc so distance lookup doesn't crash. + continue + true_obj += dist(prev, cid) + prev = cid + true_obj += dist(prev, depot_id) + 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_constraint_set.add(7) + normalizer = max(abs(true_obj), eps) + ratio = abs_diff / normalizer + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed total Euclidean travel " + f"distance={true_obj} (|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + 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 VRPTW / SCP 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_data, _, _, _, _ = load_instance(args.instance_path) + solution_data = load_solution(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution_data) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance_data, solution_data) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"{status}: {len(result['violated_constraints'])} constraint type(s) violated, " + f"{len(result['violation_magnitudes'])} violation(s) total.") + + +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/muter2010/gurobi_code.py b/tasks/muter2010/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..9138960915e3813cb72747f82dadfa875a39a4a0 --- /dev/null +++ b/tasks/muter2010/gurobi_code.py @@ -0,0 +1,958 @@ +#!/usr/bin/env python3 +""" +VRPTW as a Set Covering Problem solved with Gurobi. + +Based on: Muter, Birbil, Sahin (2010) - reformulation of VRPTW as SCP. + +The SCP formulation: + min sum_{p in P} c_p * y_p + s.t. sum_{p in P} a_{ip} * y_p >= 1 for all i in C + y_p in {0, 1} + +where: + C = set of customers + P = set of feasible routes (columns) + c_p = total travel distance of route p + a_{ip} = 1 if customer i is served by route p, 0 otherwise + +A route is feasible if: + 1. Total demand does not exceed vehicle capacity + 2. Vehicle arrives before end of each customer's time window + 3. If vehicle arrives early, it waits until ready_time + 4. Route starts and ends at depot (node 0) + +Legacy column-pool strategy (retained below for comparison): + 1. Enumerate all feasible short routes (1-3 customers) + 2. Solomon I1 insertion heuristic for initial feasible solution + 3. Nearest-neighbor heuristic variants (different starting customers) + 4. Savings algorithm (Clarke-Wright) + 5. Random insertion heuristics (multiple runs) + 6. 2-opt and Or-opt local search improvements on discovered routes + 7. Solve the SCP IP over all generated columns with Gurobi + +The released entry point no longer labels that restricted-pool optimum as the +VRPTW optimum. It solves the complete vehicle-indexed arc-flow formulation. +""" + +import argparse +import json +import math +import random +import time +import itertools +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass# --------------------------------------------------------------------------- +# Data structures and helpers +# --------------------------------------------------------------------------- + +class VRPTWInstance: + """Parsed VRPTW instance.""" + + def __init__(self, data: dict): + depot = data["depot"] + self.depot_id = depot["id"] + self.depot_x = depot["x"] + self.depot_y = depot["y"] + self.depot_ready = depot["ready_time"] + self.depot_due = depot["due_date"] + self.depot_service = depot["service_time"] + + self.capacity = data["vehicle_capacity"] + self.num_vehicles = data["num_vehicles"] + self.num_customers = data["num_customers"] + + # All nodes: depot (index 0) + customers (index 1..n) + self.x = [depot["x"]] + self.y = [depot["y"]] + self.demand = [depot["demand"]] + self.ready = [depot["ready_time"]] + self.due = [depot["due_date"]] + self.service = [depot["service_time"]] + self.customer_ids = [] # original customer ids (1-based) + + for c in data["customers"]: + self.x.append(c["x"]) + self.y.append(c["y"]) + self.demand.append(c["demand"]) + self.ready.append(c["ready_time"]) + self.due.append(c["due_date"]) + self.service.append(c["service_time"]) + self.customer_ids.append(c["id"]) + + self.n = len(self.customer_ids) # number of customers + self.N = self.n + 1 # total nodes (depot + customers) + + # Precompute Euclidean distance matrix (double precision, NOT rounded) + self.dist = [[0.0] * self.N for _ in range(self.N)] + for i in range(self.N): + for j in range(self.N): + dx = self.x[i] - self.x[j] + dy = self.y[i] - self.y[j] + self.dist[i][j] = math.sqrt(dx * dx + dy * dy) + + +def route_cost(inst: VRPTWInstance, route: list[int]) -> float: + """Compute total travel distance for a route (depot -> customers -> depot). + route is a list of customer node indices (1-based internal indices).""" + if not route: + return 0.0 + cost = inst.dist[0][route[0]] + for i in range(len(route) - 1): + cost += inst.dist[route[i]][route[i + 1]] + cost += inst.dist[route[-1]][0] + return cost + + +def check_route_feasibility(inst: VRPTWInstance, route: list[int]) -> bool: + """Check if a route (list of customer node indices) is feasible. + Returns True if feasible, False otherwise.""" + if not route: + return True + + # Check capacity + total_demand = sum(inst.demand[c] for c in route) + if total_demand > inst.capacity: + return False + + # Check time windows: simulate the route from depot + current_time = 0.0 + prev = 0 # depot + for c in route: + travel = inst.dist[prev][c] + arrival = current_time + travel + # Must arrive before due_date + if arrival > inst.due[c]: + return False + # Wait if arriving early + start_service = max(arrival, inst.ready[c]) + current_time = start_service + inst.service[c] + prev = c + + # Check return to depot is feasible + arrival_depot = current_time + inst.dist[prev][0] + if arrival_depot > inst.due[0]: + return False + + return True + + +def get_earliest_completion(inst: VRPTWInstance, route: list[int]) -> float: + """Return the time the vehicle finishes the last customer's service, + or -1 if the route is infeasible.""" + current_time = 0.0 + prev = 0 + for c in route: + travel = inst.dist[prev][c] + arrival = current_time + travel + if arrival > inst.due[c]: + return -1.0 + start_service = max(arrival, inst.ready[c]) + current_time = start_service + inst.service[c] + prev = c + return current_time + + +# --------------------------------------------------------------------------- +# Column generation: enumerate short routes +# --------------------------------------------------------------------------- + +def enumerate_short_routes(inst: VRPTWInstance, max_len: int = 3) -> list[tuple[int, ...]]: + """Enumerate all feasible routes of length 1 to max_len.""" + routes = [] + customers = list(range(1, inst.N)) + + for length in range(1, max_len + 1): + for combo in itertools.permutations(customers, length): + route = list(combo) + if check_route_feasibility(inst, route): + routes.append(tuple(route)) + return routes + + +# --------------------------------------------------------------------------- +# Column generation: Solomon I1 insertion heuristic +# --------------------------------------------------------------------------- + +def solomon_i1(inst: VRPTWInstance, seed_order: list[int] | None = None, + alpha1: float = 1.0, alpha2: float = 0.0, + mu: float = 1.0) -> list[list[int]]: + """Solomon's I1 sequential insertion heuristic. + + Parameters: + seed_order: order in which seed customers are chosen; if None, use + farthest-from-depot ordering. + alpha1, alpha2: weights for the two insertion cost criteria. + mu: weight balancing distance savings vs time urgency. + + Returns a list of routes (each route is a list of customer node indices). + """ + unrouted = set(range(1, inst.N)) + routes = [] + + if seed_order is None: + # Seed selection: farthest unrouted customer from depot + seed_order = sorted(range(1, inst.N), + key=lambda c: -inst.dist[0][c]) + + while unrouted: + # Pick seed + seed = None + for s in seed_order: + if s in unrouted: + seed = s + break + if seed is None: + break + + route = [seed] + unrouted.discard(seed) + + # Try to insert remaining customers + improved = True + while improved: + improved = False + best_customer = None + best_pos = None + best_c2 = -float("inf") + + for u in list(unrouted): + # Find best insertion position for customer u + best_c1_u = float("inf") + best_pos_u = None + + for pos in range(len(route) + 1): + trial = route[:pos] + [u] + route[pos:] + if not check_route_feasibility(inst, trial): + continue + + # c11: extra distance + if pos == 0: + prev_node = 0 + else: + prev_node = route[pos - 1] + if pos == len(route): + next_node = 0 + else: + next_node = route[pos] + + c11 = (inst.dist[prev_node][u] + inst.dist[u][next_node] + - mu * inst.dist[prev_node][next_node]) + + # c12: time push-forward (simplified) + # Assumption: using distance-based c12 approximation since + # the exact push-forward computation is complex and this is + # for column generation, not the final solve. + c12 = 0.0 # simplified + + c1 = alpha1 * c11 + alpha2 * c12 + if c1 < best_c1_u: + best_c1_u = c1 + best_pos_u = pos + + if best_pos_u is not None: + # c2 criterion: distance savings from direct service + c2 = inst.dist[0][u] + inst.dist[u][0] - best_c1_u + if c2 > best_c2: + best_c2 = c2 + best_customer = u + best_pos = best_pos_u + + if best_customer is not None: + route.insert(best_pos, best_customer) + unrouted.discard(best_customer) + improved = True + + routes.append(route) + + return routes + + +# --------------------------------------------------------------------------- +# Column generation: nearest neighbor heuristic +# --------------------------------------------------------------------------- + +def nearest_neighbor(inst: VRPTWInstance, start_customer: int) -> list[int]: + """Build a single route starting with start_customer using nearest-neighbor.""" + route = [start_customer] + unvisited = set(range(1, inst.N)) - {start_customer} + + while unvisited: + last = route[-1] + best_next = None + best_dist = float("inf") + for c in unvisited: + trial = route + [c] + if check_route_feasibility(inst, trial): + d = inst.dist[last][c] + if d < best_dist: + best_dist = d + best_next = c + if best_next is None: + break + route.append(best_next) + unvisited.discard(best_next) + + return route + + +def nearest_neighbor_all(inst: VRPTWInstance) -> list[list[int]]: + """Generate routes by nearest-neighbor starting from each customer.""" + routes = [] + for c in range(1, inst.N): + route = nearest_neighbor(inst, c) + if route and check_route_feasibility(inst, route): + routes.append(route) + return routes + + +# --------------------------------------------------------------------------- +# Column generation: Clarke-Wright savings algorithm +# --------------------------------------------------------------------------- + +def savings_algorithm(inst: VRPTWInstance) -> list[list[int]]: + """Clarke-Wright savings algorithm adapted for VRPTW.""" + # Start with each customer in its own route + routes = {c: [c] for c in range(1, inst.N)} + route_of = {c: c for c in range(1, inst.N)} # customer -> route key + + # Compute savings + savings = [] + for i in range(1, inst.N): + for j in range(i + 1, inst.N): + s = inst.dist[0][i] + inst.dist[0][j] - inst.dist[i][j] + savings.append((s, i, j)) + savings.sort(reverse=True) + + for s, i, j in savings: + ri = route_of[i] + rj = route_of[j] + if ri == rj: + continue + if ri not in routes or rj not in routes: + continue + + route_i = routes[ri] + route_j = routes[rj] + + # Try merging: i must be last in route_i, j must be first in route_j + # or vice versa + merged = None + if route_i[-1] == i and route_j[0] == j: + merged = route_i + route_j + elif route_j[-1] == j and route_i[0] == i: + merged = route_j + route_i + elif route_i[-1] == i and route_j[-1] == j: + merged = route_i + route_j[::-1] + elif route_i[0] == i and route_j[0] == j: + merged = route_i[::-1] + route_j + + if merged is not None and check_route_feasibility(inst, merged): + new_key = ri + routes[new_key] = merged + if rj in routes: + del routes[rj] + for c in merged: + route_of[c] = new_key + + return list(routes.values()) + + +# --------------------------------------------------------------------------- +# Column generation: random insertion +# --------------------------------------------------------------------------- + +def random_insertion(inst: VRPTWInstance, rng: random.Random) -> list[list[int]]: + """Build a full solution by randomly inserting customers into routes.""" + customers = list(range(1, inst.N)) + rng.shuffle(customers) + + routes = [] + unrouted = set(customers) + + while unrouted: + # Start a new route with a random unrouted customer + seed = rng.choice(list(unrouted)) + route = [seed] + unrouted.discard(seed) + + # Try inserting remaining customers in random order + candidates = list(unrouted) + rng.shuffle(candidates) + for u in candidates: + # Find best feasible insertion position + best_pos = None + best_cost = float("inf") + for pos in range(len(route) + 1): + trial = route[:pos] + [u] + route[pos:] + if check_route_feasibility(inst, trial): + cost = route_cost(inst, trial) + if cost < best_cost: + best_cost = cost + best_pos = pos + if best_pos is not None: + route.insert(best_pos, u) + unrouted.discard(u) + + routes.append(route) + + return routes + + +# --------------------------------------------------------------------------- +# Local search: 2-opt within a route +# --------------------------------------------------------------------------- + +def two_opt_improve(inst: VRPTWInstance, route: list[int]) -> list[int]: + """Apply 2-opt local search to improve a single route.""" + if len(route) <= 2: + return route + + improved = True + best = list(route) + while improved: + improved = False + for i in range(len(best) - 1): + for j in range(i + 1, len(best)): + new_route = best[:i] + best[i:j + 1][::-1] + best[j + 1:] + if check_route_feasibility(inst, new_route): + if route_cost(inst, new_route) < route_cost(inst, best): + best = new_route + improved = True + return best + + +# --------------------------------------------------------------------------- +# Local search: Or-opt (move a segment of 1-3 customers) +# --------------------------------------------------------------------------- + +def or_opt_improve(inst: VRPTWInstance, route: list[int]) -> list[int]: + """Apply Or-opt local search: relocate segments of 1, 2, or 3 customers.""" + if len(route) <= 1: + return route + + best = list(route) + improved = True + while improved: + improved = False + for seg_len in range(1, min(4, len(best) + 1)): + for i in range(len(best) - seg_len + 1): + segment = best[i:i + seg_len] + remainder = best[:i] + best[i + seg_len:] + for j in range(len(remainder) + 1): + new_route = remainder[:j] + segment + remainder[j:] + if new_route == best: + continue + if check_route_feasibility(inst, new_route): + if route_cost(inst, new_route) < route_cost(inst, best): + best = new_route + improved = True + break + if improved: + break + if improved: + break + return best + + +# --------------------------------------------------------------------------- +# Generate all sub-routes from a given route +# --------------------------------------------------------------------------- + +def extract_subroutes(inst: VRPTWInstance, route: list[int], + max_subroute_len: int | None = None) -> list[tuple[int, ...]]: + """Extract all feasible contiguous sub-routes from a given route.""" + if max_subroute_len is None: + max_subroute_len = len(route) + subroutes = [] + for length in range(1, min(max_subroute_len, len(route)) + 1): + for start in range(len(route) - length + 1): + sub = route[start:start + length] + if check_route_feasibility(inst, sub): + subroutes.append(tuple(sub)) + return subroutes + + +# --------------------------------------------------------------------------- +# Master column pool builder +# --------------------------------------------------------------------------- + +def build_column_pool(inst: VRPTWInstance, time_budget: float) -> list[tuple[int, ...]]: + """Generate a diverse set of feasible routes (columns) for the SCP. + + Uses multiple heuristics and local search to create a rich column pool. + time_budget is in seconds. + """ + start_time = time.time() + pool_set: set[tuple[int, ...]] = set() + + def add_routes(routes: list[list[int]]): + for r in routes: + if r and check_route_feasibility(inst, r): + pool_set.add(tuple(r)) + + def elapsed(): + return time.time() - start_time + + # --- Phase 1: Enumerate short routes (1-3 customers) --- + print(f" [ColGen] Phase 1: Enumerating short routes (1-3 customers)...") + short_routes = enumerate_short_routes(inst, max_len=3) + for r in short_routes: + pool_set.add(r) + print(f" [ColGen] Found {len(short_routes)} short routes, pool size = {len(pool_set)}") + + if elapsed() > time_budget * 0.8: + return list(pool_set) + + # --- Phase 2: Solomon I1 heuristic with different parameters --- + print(f" [ColGen] Phase 2: Solomon I1 insertion heuristic...") + for alpha1, alpha2, mu in [(1.0, 0.0, 1.0), (0.5, 0.5, 1.0), + (1.0, 0.0, 0.5), (0.0, 1.0, 1.0)]: + routes = solomon_i1(inst, alpha1=alpha1, alpha2=alpha2, mu=mu) + add_routes(routes) + # Also extract sub-routes and apply local search + for r in routes: + for sub in extract_subroutes(inst, r): + pool_set.add(sub) + improved = two_opt_improve(inst, r) + if improved and check_route_feasibility(inst, improved): + pool_set.add(tuple(improved)) + for sub in extract_subroutes(inst, improved): + pool_set.add(sub) + + # Also try with different seed orderings + # Seed by earliest due date + seed_by_due = sorted(range(1, inst.N), key=lambda c: inst.due[c]) + routes = solomon_i1(inst, seed_order=seed_by_due) + add_routes(routes) + for r in routes: + for sub in extract_subroutes(inst, r): + pool_set.add(sub) + + # Seed by earliest ready time + seed_by_ready = sorted(range(1, inst.N), key=lambda c: inst.ready[c]) + routes = solomon_i1(inst, seed_order=seed_by_ready) + add_routes(routes) + for r in routes: + for sub in extract_subroutes(inst, r): + pool_set.add(sub) + + print(f" [ColGen] Pool size = {len(pool_set)}") + + if elapsed() > time_budget * 0.8: + return list(pool_set) + + # --- Phase 3: Nearest-neighbor heuristic --- + print(f" [ColGen] Phase 3: Nearest-neighbor heuristic variants...") + nn_routes = nearest_neighbor_all(inst) + add_routes(nn_routes) + for r in nn_routes: + for sub in extract_subroutes(inst, r): + pool_set.add(sub) + improved = two_opt_improve(inst, r) + if improved and check_route_feasibility(inst, improved): + pool_set.add(tuple(improved)) + for sub in extract_subroutes(inst, improved): + pool_set.add(sub) + print(f" [ColGen] Pool size = {len(pool_set)}") + + if elapsed() > time_budget * 0.8: + return list(pool_set) + + # --- Phase 4: Clarke-Wright savings --- + print(f" [ColGen] Phase 4: Clarke-Wright savings algorithm...") + cw_routes = savings_algorithm(inst) + add_routes(cw_routes) + for r in cw_routes: + for sub in extract_subroutes(inst, r): + pool_set.add(sub) + improved = two_opt_improve(inst, r) + if improved and check_route_feasibility(inst, improved): + pool_set.add(tuple(improved)) + for sub in extract_subroutes(inst, improved): + pool_set.add(sub) + improved = or_opt_improve(inst, r) + if improved and check_route_feasibility(inst, improved): + pool_set.add(tuple(improved)) + for sub in extract_subroutes(inst, improved): + pool_set.add(sub) + print(f" [ColGen] Pool size = {len(pool_set)}") + + if elapsed() > time_budget * 0.8: + return list(pool_set) + + # --- Phase 5: Random insertion (multiple runs) --- + print(f" [ColGen] Phase 5: Random insertion heuristics...") + num_random_runs = 200 + for run in range(num_random_runs): + if elapsed() > time_budget * 0.6: + break + rng = random.Random(42 + run) + ri_routes = random_insertion(inst, rng) + add_routes(ri_routes) + for r in ri_routes: + for sub in extract_subroutes(inst, r): + pool_set.add(sub) + # Apply local search to some runs + if run < 50: + improved = two_opt_improve(inst, r) + if improved and check_route_feasibility(inst, improved): + pool_set.add(tuple(improved)) + for sub in extract_subroutes(inst, improved): + pool_set.add(sub) + print(f" [ColGen] Pool size = {len(pool_set)}") + + if elapsed() > time_budget * 0.8: + return list(pool_set) + + # --- Phase 6: Enumerate routes of length 4-5 if time permits --- + # Assumption: For 25 customers, length-4 permutations = 25*24*23*22 = 303,600 + # which is feasible to check. Length-5 may be too large, but we try with + # time bounds. + print(f" [ColGen] Phase 6: Enumerating medium-length routes...") + customers = list(range(1, inst.N)) + for length in range(4, 7): + count = 0 + for combo in itertools.permutations(customers, length): + if elapsed() > time_budget * 0.8: + break + route = list(combo) + # Quick demand check before full feasibility + total_demand = sum(inst.demand[c] for c in route) + if total_demand > inst.capacity: + continue + if check_route_feasibility(inst, route): + pool_set.add(tuple(route)) + count += 1 + print(f" [ColGen] Length {length}: found {count} routes, " + f"pool size = {len(pool_set)}") + if elapsed() > time_budget * 0.8: + break + + print(f" [ColGen] Final pool size = {len(pool_set)}") + return list(pool_set) + + +# --------------------------------------------------------------------------- +# Solve the Set Covering Problem with Gurobi +# --------------------------------------------------------------------------- + +def solve_scp(inst: VRPTWInstance, columns: list[tuple[int, ...]], + time_limit: float) -> dict: + """Solve the SCP formulation of VRPTW with Gurobi. + + Returns a dict with solution details. + """ + customers = list(range(1, inst.N)) # internal node indices + num_columns = len(columns) + + # Precompute column costs and coverage + col_costs = [] + col_coverage = [] # col_coverage[p] = set of customers covered + for p, route in enumerate(columns): + col_costs.append(route_cost(inst, list(route))) + col_coverage.append(set(route)) + + # Build coverage map: customer -> list of column indices + coverage_map = defaultdict(list) + for p, route in enumerate(columns): + for c in route: + coverage_map[c].append(p) + + # Check that every customer is covered by at least one column + uncovered = [c for c in customers if c not in coverage_map] + if uncovered: + print(f" [WARNING] {len(uncovered)} customers have no covering column!") + print(f" [WARNING] Uncovered customer nodes: {uncovered}") + # The model will be infeasible; we still build it so Gurobi reports this. + + print(f" [SCP] Building Gurobi model with {num_columns} columns " + f"and {len(customers)} covering constraints...") + + model = gp.Model("VRPTW_SCP") + model.setParam("Threads", 1) + # Pass shorter TimeLimit so optimize() returns before outer wrapper SIGKILL. + # Plan F 1h run found incumbent obj=2972.6 (jsonl) but solution.json missing + # — gurobi was mid-simplex at 2407s and got SIGKILLed at 3631s before + # json.dump ran. The 120s buffer lets the final LP wind down + writeback. + _internal_tl = max(60, time_limit - 120) if time_limit > 240 else time_limit + model.setParam("TimeLimit", _internal_tl) + model.setParam("OutputFlag", 1) + # Solver hints: l11 (33 customers, 11 vehicles VRPTW) was 1h TLE no + # incumbent in prior runs while l21-51 (same dims, different seeds) + # solved OPT in 800-1070s. MIPFocus=1 prioritizes finding feasible + # over closing gap; NoRelHeurTime budgets root-node heuristics. + model.setParam("MIPFocus", 1) + model.setParam("NoRelHeurTime", min(60.0, time_limit * 0.05)) + + # Decision variables: y_p in {0, 1} for each column p + y = model.addVars(num_columns, vtype=GRB.BINARY, name="y", + obj=col_costs) + + # Covering constraints: each customer must be served by at least one route + for c in customers: + covering_cols = coverage_map.get(c, []) + if covering_cols: + model.addConstr( + gp.quicksum(y[p] for p in covering_cols) >= 1, + name=f"cover_{c}" + ) + else: + # Add infeasible constraint so Gurobi reports infeasibility + model.addConstr(0 >= 1, name=f"cover_{c}_infeasible") + + model.setAttr("ModelSense", GRB.MINIMIZE) + model.update() + + # Solve + model.optimize() + + # Extract solution + result = { + "status": model.Status, + "status_name": _gurobi_status_name(model.Status), + "objective_value": None, + "routes": [], + "num_columns_generated": num_columns, + "gap": None, + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["gap"] = model.MIPGap if hasattr(model, "MIPGap") else None + + selected_routes = [] + for p in range(num_columns): + if y[p].X > 0.5: + route = list(columns[p]) + cost = col_costs[p] + # Map internal node indices back to original customer IDs + customer_ids = [inst.customer_ids[c - 1] for c in route] + selected_routes.append({ + "route_nodes": route, + "customer_ids": customer_ids, + "cost": cost, + "demand": sum(inst.demand[c] for c in route), + }) + result["routes"] = selected_routes + else: + print(" [SCP] No feasible solution found.") + + return result + + +def _gurobi_status_name(status: int) -> str: + """Convert Gurobi status code to human-readable name.""" + names = { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.NODE_LIMIT: "NODE_LIMIT", + GRB.SOLUTION_LIMIT: "SOLUTION_LIMIT", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + } + return names.get(status, f"UNKNOWN({status})") + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def solve_exact_vrptw(inst: VRPTWInstance, time_limit: float) -> dict: + """Solve the complete vehicle-indexed VRPTW arc-flow formulation.""" + customers = list(range(1, inst.N)) + nodes = list(range(inst.N)) + vehicles = list(range(inst.num_vehicles)) + arcs = [(i, j) for i in nodes for j in nodes if i != j] + model = gp.Model("exact_vrptw") + model.Params.Threads = 1 + model.Params.TimeLimit = max(1.0, float(time_limit)) + model.Params.MIPFocus = 1 + + x = model.addVars(arcs, vehicles, vtype=GRB.BINARY, name="x") + assigned = model.addVars(customers, vehicles, vtype=GRB.BINARY, name="z") + used = model.addVars(vehicles, vtype=GRB.BINARY, name="used") + start = model.addVars(customers, vehicles, lb=0.0, + ub=float(inst.depot_due), name="start") + + for customer in customers: + model.addConstr(gp.quicksum(assigned[customer, k] for k in vehicles) == 1) + for k in vehicles: + model.addConstr(gp.quicksum(x[0, j, k] for j in customers) == used[k]) + model.addConstr(gp.quicksum(x[i, 0, k] for i in customers) == used[k]) + model.addConstr( + gp.quicksum(inst.demand[i] * assigned[i, k] for i in customers) + <= inst.capacity + ) + for i in customers: + model.addConstr( + gp.quicksum(x[j, i, k] for j in nodes if j != i) + == assigned[i, k] + ) + model.addConstr( + gp.quicksum(x[i, j, k] for j in nodes if j != i) + == assigned[i, k] + ) + model.addConstr( + start[i, k] >= inst.ready[i] * assigned[i, k] + ) + model.addConstr( + start[i, k] <= inst.due[i] + inst.depot_due * (1 - assigned[i, k]) + ) + for k in range(len(vehicles) - 1): + model.addConstr(used[k] >= used[k + 1]) + + max_distance = max(max(row) for row in inst.dist) + big_m = float(inst.depot_due + max(inst.service) + max_distance + 1.0) + for k in vehicles: + for j in customers: + model.addConstr( + start[j, k] >= inst.depot_ready + inst.dist[0][j] + - big_m * (1 - x[0, j, k]) + ) + for i in customers: + model.addConstr( + start[i, k] + inst.service[i] + inst.dist[i][0] + <= inst.depot_due + big_m * (1 - x[i, 0, k]) + ) + for j in customers: + if i == j: + continue + model.addConstr( + start[j, k] >= start[i, k] + inst.service[i] + inst.dist[i][j] + - big_m * (1 - x[i, j, k]) + ) + + # A deterministic feasible heuristic gives Gurobi a useful incumbent. + heuristic = solomon_i1(inst) + if len(heuristic) <= len(vehicles): + for k in vehicles: + route = heuristic[k] if k < len(heuristic) else [] + used[k].Start = 1.0 if route else 0.0 + route_set = set(route) + for i in customers: + assigned[i, k].Start = 1.0 if i in route_set else 0.0 + path = [0] + route + [0] if route else [] + selected_arcs = set(zip(path, path[1:])) + for i, j in arcs: + x[i, j, k].Start = 1.0 if (i, j) in selected_arcs else 0.0 + + model.setObjective( + gp.quicksum(inst.dist[i][j] * x[i, j, k] for i, j in arcs for k in vehicles), + GRB.MINIMIZE, + ) + model.optimize() + + routes = [] + if model.SolCount: + for k in vehicles: + if used[k].X <= 0.5: + continue + route = [] + current = 0 + seen = set() + while True: + successors = [j for j in nodes if j != current and x[current, j, k].X > 0.5] + if not successors: + break + nxt = successors[0] + if nxt == 0: + break + if nxt in seen: + raise RuntimeError("cycle detected while extracting exact VRPTW route") + route.append(nxt) + seen.add(nxt) + current = nxt + customer_ids = [inst.customer_ids[i - 1] for i in route] + routes.append({ + "customer_ids": customer_ids, + "cost": route_cost(inst, route), + "demand": sum(inst.demand[i] for i in route), + }) + return { + "status": int(model.Status), + "status_name": _gurobi_status_name(model.Status), + "objective_value": float(model.ObjVal) if model.SolCount else None, + "best_bound": float(model.ObjBound) if model.SolCount else None, + "gap": float(model.MIPGap) if model.SolCount else None, + "routes": routes, + } + +def main(): + parser = argparse.ArgumentParser( + description="Solve the complete VRPTW arc-flow model using Gurobi." + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the VRPTW 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, required=True, + help="Time limit in seconds for the Gurobi solver.") + 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 + print(f"Loading instance from {args.instance_path}...") + with open(args.instance_path, "r") as f: + data = json.load(f) + inst = VRPTWInstance(data) + print(f" Customers: {inst.n}, Capacity: {inst.capacity}, " + f"Vehicles: {inst.num_vehicles}") + + overall_start = time.time() + result = solve_exact_vrptw(inst, args.time_limit) + total_elapsed = time.time() - overall_start + + # Build output JSON + output = { + "objective_value": result["objective_value"], + "solver_status": result["status_name"], + "mip_gap": result["gap"], + "best_bound": result["best_bound"], + "num_routes": len(result["routes"]), + "optimization_method": "exact_vehicle_indexed_arc_flow", + "total_time_seconds": round(total_elapsed, 2), + "routes": [], + } + + for i, r in enumerate(result["routes"]): + route_entry = { + "route_id": i + 1, + "customer_ids": r["customer_ids"], + "cost": round(r["cost"], 6), + "demand": r["demand"], + # Full path: depot -> customers -> depot + "path": [0] + r["customer_ids"] + [0], + } + output["routes"].append(route_entry) + + # 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"\nSolution written to {args.solution_path}") + print(f" Objective value: {result['objective_value']}") + print(f" Number of routes: {len(result['routes'])}") + print(f" Total time: {total_elapsed:.2f}s") + + +if __name__ == "__main__": + main() diff --git a/tasks/muter2010/gurobi_feasi_result/large_feasi_result_1.json b/tasks/muter2010/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/muter2010/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/muter2010/gurobi_feasi_result/large_feasi_result_2.json b/tasks/muter2010/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/muter2010/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/muter2010/gurobi_feasi_result/large_feasi_result_3.json b/tasks/muter2010/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/muter2010/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/muter2010/gurobi_feasi_result/large_feasi_result_4.json b/tasks/muter2010/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/muter2010/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/muter2010/gurobi_feasi_result/large_feasi_result_5.json b/tasks/muter2010/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/muter2010/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/muter2010/gurobi_feasi_result/tiny_feasi_result.json b/tasks/muter2010/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/muter2010/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/muter2010/gurobi_solution/large_solution_1.json b/tasks/muter2010/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d76c942d0e8c4262e474d59726fcd3cd2e6965a3 --- /dev/null +++ b/tasks/muter2010/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b5f628aa301158869786c962c3fa69e266e2aa48ee6c0e6d2d74160b600053d +size 1868 diff --git a/tasks/muter2010/gurobi_solution/large_solution_2.json b/tasks/muter2010/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..74123cf9f02a0dd2f4959fd9b53e9fdb0b1b7593 --- /dev/null +++ b/tasks/muter2010/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:478cd33ab1ebe017b10a53f61287e9aacb858d95ee30c23d003afb16d2ac1f62 +size 2491 diff --git a/tasks/muter2010/gurobi_solution/large_solution_3.json b/tasks/muter2010/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..09ed054e097754fdc5515aeb061b43af1f865772 --- /dev/null +++ b/tasks/muter2010/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ce924e9ba56fe122923da2a85db5f8c4dde247035d983ba601913ecd2aeafd1 +size 2160 diff --git a/tasks/muter2010/gurobi_solution/large_solution_4.json b/tasks/muter2010/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a1f582d8df1863dd308436f5a588e548a238c8e1 --- /dev/null +++ b/tasks/muter2010/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:decbd4e6f6b99286ca130585142680efd58a2ebf0d6756371df7d3872dd1b209 +size 1847 diff --git a/tasks/muter2010/gurobi_solution/large_solution_5.json b/tasks/muter2010/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d3d2f01903f0eaa37516ea8a559ea8e9023d6ee0 --- /dev/null +++ b/tasks/muter2010/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9837dc29dfec614d98ddb95856953522cc9e71c921ac7e5d2b19fdbaac819079 +size 2340 diff --git a/tasks/muter2010/gurobi_solution/tiny_solution.json b/tasks/muter2010/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..0aa4c9226528251cc3db3ff1f16183706bebdce3 --- /dev/null +++ b/tasks/muter2010/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4113dfda4f61866a172b01229e05b998b94196c44ed3438587df29456055d10d +size 2279 diff --git a/tasks/muter2010/gurobi_solution_log/large_log_1.jsonl b/tasks/muter2010/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9fa2e0751d287d8d5226b80f5cbba8ea77b1001f --- /dev/null +++ b/tasks/muter2010/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:485122a631e7fe1b5917a8a002206bd06401aa939f5abffc5c1c53b0a5ed87c4 +size 173 diff --git a/tasks/muter2010/gurobi_solution_log/large_log_2.jsonl b/tasks/muter2010/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b0e783f241eec986be2ead2538bb53889a04dcc6 --- /dev/null +++ b/tasks/muter2010/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:478a477dfb029f8517cd2ddb4d86396805428fdf7c25fc9996624085e74ce383 +size 56 diff --git a/tasks/muter2010/gurobi_solution_log/large_log_3.jsonl b/tasks/muter2010/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..19f789593e300e161a19d5e89fa94996512d8fe9 --- /dev/null +++ b/tasks/muter2010/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:918398f066f1c36e451e984fcc8ae08c392b5bedf25acae94f722f408db4145b +size 616 diff --git a/tasks/muter2010/gurobi_solution_log/large_log_4.jsonl b/tasks/muter2010/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8cb85d5de0710bef1e594e7bd0f14dde5d17b9a1 --- /dev/null +++ b/tasks/muter2010/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:169268c67f5dab70b29af72bec107872d7028591a778e365ab805e229de7ee34 +size 689 diff --git a/tasks/muter2010/gurobi_solution_log/large_log_5.jsonl b/tasks/muter2010/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5def3874438307f5911901e5429d614e7b9f0589 --- /dev/null +++ b/tasks/muter2010/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb6d8804c477f6cf4fd4a5404cbc9e2d71a7074211f135e9bcf23add7ebe5ec5 +size 114 diff --git a/tasks/muter2010/gurobi_solution_log/tiny_log.jsonl b/tasks/muter2010/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d2485366bef7588e2e9bbb4dcf159c803eeb30d1 --- /dev/null +++ b/tasks/muter2010/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f862c90083fb3d0e61cdf9797635e3547777a35de86c2d9bc9e15aa0944a4380 +size 56 diff --git a/tasks/muter2010/instance/large_instance_1.json b/tasks/muter2010/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..cd421446d1d49737e635ec0b7d0b0db191111786 --- /dev/null +++ b/tasks/muter2010/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad41ec24eb4a17fa9f3ef074533a9708de1a4f4fbf07ca5ca57b81dd9424a872 +size 5639 diff --git a/tasks/muter2010/instance/large_instance_2.json b/tasks/muter2010/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d763de66299a668835247ddbe5e36cd033aa75b4 --- /dev/null +++ b/tasks/muter2010/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:345aaa48025b17b6797a27acde74b87c34259ac12b6d9a0b1f4717cb5d033606 +size 5606 diff --git a/tasks/muter2010/instance/large_instance_3.json b/tasks/muter2010/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1040b07dd79b87c97d580e9040c9a749ba2f886c --- /dev/null +++ b/tasks/muter2010/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63989dac6c1451c971612a77990e316918cb4c4ffe6328e470f3a881028b7fc2 +size 5627 diff --git a/tasks/muter2010/instance/large_instance_4.json b/tasks/muter2010/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..3c9530b12bd45a70b4baf97492aeae1e379fe9a4 --- /dev/null +++ b/tasks/muter2010/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bf4ed644dfeb2948f0c03ab1cc29df8e4de93836ccca0c35ec39cbf7aa02625 +size 5687 diff --git a/tasks/muter2010/instance/large_instance_5.json b/tasks/muter2010/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..084b47102b144d38fec4975b7a1afec94a70af3f --- /dev/null +++ b/tasks/muter2010/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5c3bebd3c98bb68359cf77ec713196f11fae1f553c873b780943c1b7be554fc +size 5613 diff --git a/tasks/muter2010/instance/tiny_instance.json b/tasks/muter2010/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c1398b317628644a0dab2ebd0a4c22dd4057fd84 --- /dev/null +++ b/tasks/muter2010/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ec15b833512665d6553dd103e2f616879cedf03e3d4b50f4563ce955ec634ae +size 4170 diff --git a/tasks/muter2010/instance_schema.json b/tasks/muter2010/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..7fc5108eea72b302759861bb1498a640f097023a --- /dev/null +++ b/tasks/muter2010/instance_schema.json @@ -0,0 +1,25 @@ +{ + "num_customers": " Total number of customers to be served.", + "depot": { + "id": " Identifier for the depot location.", + "x": " Horizontal coordinate of the depot in the service area.", + "y": " Vertical coordinate of the depot in the service area.", + "demand": " Demand at the depot, always zero.", + "ready_time": " Earliest time at which vehicles may depart from the depot.", + "due_date": " Latest time by which all vehicles must return to the depot.", + "service_time": " Service duration at the depot, always zero." + }, + "vehicle_capacity": " Maximum total demand that a single vehicle can carry on one route.", + "num_vehicles": " Number of identical vehicles available in the fleet.", + "customers": [ + { + "id": " Unique identifier for the customer.", + "x": " Horizontal coordinate of the customer in the service area.", + "y": " Vertical coordinate of the customer in the service area.", + "demand": " Quantity of goods that must be delivered to the customer.", + "ready_time": " Earliest time at which a vehicle may begin serving the customer.", + "due_date": " Latest time by which a vehicle must arrive at the customer.", + "service_time": " Duration a vehicle must spend at the customer location to complete the delivery." + } + ] +} diff --git a/tasks/muter2010/mathematical_formulation.md b/tasks/muter2010/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..9ef48822641cf44d36cfe3ab518454f4f30d4207 --- /dev/null +++ b/tasks/muter2010/mathematical_formulation.md @@ -0,0 +1,32 @@ +# Original Formulation: Set Covering Problem (SCP) + +*Source: Combination of Metaheuristic and Exact Algorithms for Solving Set Covering-Type Optimization Problems, İbrahim Muter, Ş. İlker Birbil, Güvenç Şahin, 2010 (INFORMS Journal on Computing, 22(4), pp. 603–619).* + +The paper studies set covering-type optimization problems and states the problem it operates on (equation (1), §1) as the Set Covering Problem (SCP). This is the first formulation written and the one whose notation ($C,\;P,\;c_p,\;a_{ip},\;y_p$) is carried into every subsequent section (restricted SCP, its LP relaxation, the reduced cost, and the MetaOpt algorithm). The vehicle routing problem with time windows (VRPTW) of §4 is solved as an instance of this SCP; the experiments report objective values for this formulation. The instantiation of the symbols for VRPTW is given in **Remarks**. + +## Sets and Parameters + +- $C$ : a nonempty, finite set of elements to be covered; indexed by $i$. (VRPTW: the set of customers.) + +- $P$ : the set of feasible subsets of $C$; indexed by $p$ (the “columns”). (VRPTW: the set of all feasible vehicle routes.) + +- $c_p$ : cost of subset $p \in P$. (VRPTW: total travel distance of route $p$.) + +- $a_{ip}$ : $a_{ip}=1$ if element $i \in p$, and $a_{ip}=0$ otherwise. (VRPTW: $1$ if customer $i$ is served by route $p$, $0$ otherwise.) + +## Decision Variables + +- $y_p \in \{0,1\}$ : $1$ iff subset (column) $p \in P$ is selected. + +## Objective + +$$\begin{equation*} + \min \; \sum_{p \in P} c_p\, y_p \tag{1} +\end{equation*}$$ + +## Constraints + +$$\begin{align*} + \sum_{p \in P} a_{ip}\, y_p &\geq 1, & & i \in C, \tag{1} \\[2pt] + y_p &\in \{0,1\}, & & p \in P. \tag{1} +\end{align*}$$ SCP finds the least costly collection of subsets in $P$ such that each element $i \in C$ belongs to at least one of the selected subsets. (The paper tags the objective, the covering constraints, and the integrality requirement together as block (1).) diff --git a/tasks/muter2010/problem_description.txt b/tasks/muter2010/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..69f101ff4aadd6bebd6bc6aeffcc1ee3b6946b5a --- /dev/null +++ b/tasks/muter2010/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A delivery company operates a homogeneous fleet of vehicles from a single depot to serve a set of customers. The depot and each customer are located at known positions in a two-dimensional plane, specified by their x- and y-coordinates. Each customer has a known demand quantity, a time window defined by an earliest service start time (ready time) and a latest arrival time (due date), and a fixed service duration that the vehicle must spend at the customer's location once service begins. The depot itself has a time window representing the scheduling horizon within which all vehicle operations must occur, zero demand, and zero service time. All vehicles are identical and share the same carrying capacity. There is no limit on the number of vehicles that may be used. + +The company must select a collection of delivery routes, where each route is performed by one vehicle, begins at the depot, visits a sequence of one or more customers, and returns to the depot. Every customer must be visited by at least one route. A route is considered operationally valid only if the total demand of all customers assigned to that route does not exceed the vehicle's carrying capacity, and the vehicle respects every customer's time window along the route. Specifically, a vehicle traveling a route must arrive at each customer no later than that customer's due date. If the vehicle arrives at a customer before the customer's ready time, the vehicle must wait until the ready time before beginning service. Travel times between any two locations equal their Euclidean distances. After completing service at one customer (which takes the full service duration), the vehicle departs immediately to the next customer on the route or returns to the depot. + +The goal is to determine which routes to operate so that every customer is served while minimizing the total travel distance across all selected routes, computed as the sum of the Euclidean distances traversed along each route. diff --git a/tasks/muter2010/solution_logger.py b/tasks/muter2010/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/muter2010/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/muter2010/solution_schema.json b/tasks/muter2010/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5a674bf3305561f84c143b31cd54fe8f786e5f9f --- /dev/null +++ b/tasks/muter2010/solution_schema.json @@ -0,0 +1,9 @@ +{ + "objective_value": " Total Euclidean travel distance across all operated delivery routes.", + "routes": [ + { + "customer_ids": " Customers served by the vehicle on this route, listed in visit order.", + "path": " Full node sequence traversed by the vehicle, starting and ending at the depot." + } + ] +} diff --git a/tasks/nagy2015/feasibility_check.py b/tasks/nagy2015/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f00496d615020e13d0746ffc04d1385edeaf08 --- /dev/null +++ b/tasks/nagy2015/feasibility_check.py @@ -0,0 +1,769 @@ +#!/usr/bin/env python3 +""" +Feasibility Checker for VRPDDP (Vehicle Routing Problem with Divisible Deliveries and Pickups) + +Checks all hard constraints from the mathematical formulation in math_model.txt: + Constraint 1: Objective function (not checked -- it is the objective, not a constraint) + Constraint 2: In-degree = 1 for every customer j in L ∪ B + Constraint 3: Out-degree = 1 for every customer j in L ∪ B + Constraint 4: Delivery flow conservation at linehaul customers + Constraint 5: Delivery flow conservation at backhaul customers + Constraint 6: Pickup flow conservation at linehaul customers + Constraint 7: Pickup flow conservation at backhaul customers + Constraint 8: Vehicles start with zero pickup load (P leaving depot = 0) + Constraint 9: Vehicles finish with zero delivery load (R returning to depot = 0) + Constraint 10: Capacity constraint R_ij + P_ij <= C * x_ij + Constraint 11: Binary domain for x_ij + Constraint 12: Non-negativity of R_ij + Constraint 13: Non-negativity of P_ij + Constraint 14: No self-loops x_ii = 0 + Constraint 15: No arc from backhaul n+i to its linehaul i + Constraint 16: Minimum vehicles sum x_{0,i} >= (1/C) * sum q_i (i in L) + Constraint 17: No 2-cycles x_ij + x_ji <= 1 for i,j in L ∪ B + Constraint 18: Objective consistency -- reported objective_value must equal + sum_{i,j in V} d_ij * x_ij (Tier C anti-exploit check) +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'routes', 'routes_detailed') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('routes_detailed',) +_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 build_vrpmdp_from_instance(instance): + """ + Build the VRPMDP formulation sets and parameters from the instance. + + Returns: + n: number of original customers + C: vehicle capacity + V: set of all vertex indices {0, 1, ..., 2n} (0 = depot) + L: set of linehaul nodes {1, ..., n} + B: set of backhaul nodes {n+1, ..., 2n} + q: demand dict q[i] for i in L ∪ B + d: distance matrix dict d[(i,j)] for i,j in V + customers: list of customer dicts from instance + """ + n = instance["num_customers"] + C = instance["vehicle_capacity"] + customers = instance["customers"] + dist_raw = instance["distance_matrix"] + + # In the VRPMDP formulation: + # Depot = node 0 + # Linehaul customer i (i=1..n) corresponds to original customer i + # Backhaul customer n+i (i=1..n) is co-located with customer i + V = set(range(0, 2 * n + 1)) + L = set(range(1, n + 1)) + B = set(range(n + 1, 2 * n + 1)) + + # Demands: q[i] = delivery demand for linehaul i, pickup demand for backhaul n+i + cust_map = {c["id"]: c for c in customers} + q = {} + for i in range(1, n + 1): + q[i] = cust_map[i]["delivery_demand"] # linehaul + q[n + i] = cust_map[i]["pickup_demand"] # backhaul + + # Distance matrix in VRPMDP space. + # dist_raw is (n+1) x (n+1) indexed by original ids 0..n. + # Backhaul n+i is co-located with linehaul i, so distance to/from n+i + # equals distance to/from i (the original customer). + def orig(node): + """Map VRPMDP node to original customer id for distance lookup.""" + if node == 0: + return 0 + if node <= n: + return node + return node - n # backhaul n+i -> original i + + d = {} + for i in V: + for j in V: + d[(i, j)] = dist_raw[orig(i)][orig(j)] + + return n, C, V, L, B, q, d, customers + + +def extract_arcs_and_flows(instance, solution): + """ + Extract arcs (x), delivery flow (R), and pickup flow (P) from the solution. + + Handles two solution formats: + 1. Efficient algorithm format: routes with 'visits' and 'detail' + 2. Gurobi format: routes with node IDs directly (possibly with routes_detailed) + + Returns: + x: dict x[(i,j)] = 1 for active arcs + R: dict R[(i,j)] = delivery goods on arc (i,j) + P: dict P[(i,j)] = pickup goods on arc (i,j) + """ + n = instance["num_customers"] + C = instance["vehicle_capacity"] + + x = {} + R = {} + P = {} + + # Detect solution format + if "routes" in solution and len(solution["routes"]) > 0: + first_route = solution["routes"][0] + if isinstance(first_route, dict) and "visits" in first_route: + # Efficient algorithm format + return _extract_efficient_format(instance, solution, n, C) + elif isinstance(first_route, list): + # Gurobi format: routes are lists of node IDs + return _extract_gurobi_format(instance, solution, n, C) + + raise ValueError("Unrecognized solution format") + + +def _extract_efficient_format(instance, solution, n, C): + """ + Extract arcs and flows from the efficient algorithm solution format. + + In this format, each route has: + - 'visits': list of original customer IDs (with depot 0 at start/end) + - 'detail': list of dicts with customer_id, entity_type, delivery, pickup + + We need to map these to the VRPMDP node space: + - 'linehaul' entity for customer i -> node i + - 'backhaul' entity for customer i -> node n+i + - 'combined' entity for customer i -> we treat it as visiting both node i + and node n+i consecutively (linehaul then backhaul, co-located) + """ + x = {} + R = {} + P = {} + + for route_data in solution["routes"]: + detail = route_data["detail"] + + # Build the sequence of VRPMDP nodes for this route + nodes = [0] # start at depot + for entry in detail: + cid = entry["customer_id"] + etype = entry["entity_type"] + if etype == "linehaul": + nodes.append(cid) # linehaul node + elif etype == "backhaul": + nodes.append(n + cid) # backhaul node + elif etype == "combined": + # Combined: visit linehaul i then backhaul n+i + nodes.append(cid) # linehaul node + nodes.append(n + cid) # backhaul node + nodes.append(0) # return to depot + + # Set arcs + for k in range(len(nodes) - 1): + arc = (nodes[k], nodes[k + 1]) + x[arc] = x.get(arc, 0) + 1 + + # Compute flows along arcs. + # Delivery flow (R): starts with total delivery demand on route, + # decreases at each linehaul node. + # Pickup flow (P): starts at 0, increases at each backhaul node. + + # Collect demands for each VRPMDP node in this route + cust_map = {c["id"]: c for c in instance["customers"]} + node_delivery = {} # delivery consumed at node + node_pickup = {} # pickup added at node + for entry in detail: + cid = entry["customer_id"] + etype = entry["entity_type"] + if etype == "linehaul": + node_delivery[cid] = entry["delivery"] + # backhaul node not visited in this entry + elif etype == "backhaul": + node_pickup[n + cid] = entry["pickup"] + elif etype == "combined": + node_delivery[cid] = entry["delivery"] + node_pickup[n + cid] = entry["pickup"] + + # Compute R and P along arcs + delivery_load = sum(node_delivery.get(nd, 0) for nd in nodes if nd != 0) + pickup_load = 0.0 + + for k in range(len(nodes) - 1): + arc = (nodes[k], nodes[k + 1]) + # At node nodes[k], if it's a linehaul node, delivery is dropped off + # before departing (flow decreases). If backhaul, pickup is loaded. + nd = nodes[k] + if nd != 0: + if nd in node_delivery: + delivery_load -= node_delivery[nd] + if nd in node_pickup: + pickup_load += node_pickup[nd] + R[arc] = R.get(arc, 0) + delivery_load + P[arc] = P.get(arc, 0) + pickup_load + + return x, R, P + + +def _extract_gurobi_format(instance, solution, n, C): + """ + Extract arcs and flows from the Gurobi solution format. + + Routes are lists of node IDs in VRPMDP space (0=depot, 1..n=linehaul, n+1..2n=backhaul). + """ + x = {} + R = {} + P = {} + + cust_map = {c["id"]: c for c in instance["customers"]} + q = {} + for i in range(1, n + 1): + q[i] = cust_map[i]["delivery_demand"] + q[n + i] = cust_map[i]["pickup_demand"] + + for route_nodes in solution["routes"]: + # route_nodes is e.g. [0, 12, 27, 1, 4, 19, 0] + # Set arcs + for k in range(len(route_nodes) - 1): + arc = (route_nodes[k], route_nodes[k + 1]) + x[arc] = x.get(arc, 0) + 1 + + # Compute delivery and pickup flows + # Delivery load starts at sum of delivery demands of linehaul nodes on route + inner_nodes = route_nodes[1:-1] # exclude depot at start and end + delivery_load = sum(q.get(nd, 0) for nd in inner_nodes if 1 <= nd <= n) + pickup_load = 0.0 + + for k in range(len(route_nodes) - 1): + nd = route_nodes[k] + # At each node, consume delivery (if linehaul) or add pickup (if backhaul) + if 1 <= nd <= n: + delivery_load -= q.get(nd, 0) + elif n + 1 <= nd <= 2 * n: + pickup_load += q.get(nd, 0) + arc = (route_nodes[k], route_nodes[k + 1]) + R[arc] = R.get(arc, 0) + delivery_load + P[arc] = P.get(arc, 0) + pickup_load + + return x, R, P + + +def check_feasibility(instance, solution): + """ + Check all hard constraints of the VRPDDP formulation. + + Returns: + result dict with feasible, violated_constraints, violations, violation_magnitudes + """ + n, C, V, L, B, q, d, customers = build_vrpmdp_from_instance(instance) + x, R, P = extract_arcs_and_flows(instance, solution) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + def record_violation(constraint_idx, msg, lhs, rhs, operator): + """Record a constraint violation with normalized magnitude.""" + if operator in ("<=", "<"): + violation_amount = lhs - rhs + elif operator in (">=", ">"): + violation_amount = rhs - lhs + elif operator == "=": + violation_amount = abs(lhs - rhs) + else: + violation_amount = abs(lhs - rhs) + + if violation_amount > TOL: + violated_constraints.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # Helper: get x value + def get_x(i, j): + return x.get((i, j), 0) + + def get_R(i, j): + return R.get((i, j), 0.0) + + def get_P(i, j): + return P.get((i, j), 0.0) + + # ----------------------------------------------------------------------- + # Constraint 2: sum_{i in V} x_{ij} = 1 for j in L ∪ B + # In-degree = 1 for every customer node + # ----------------------------------------------------------------------- + for j in sorted(L | B): + lhs = sum(get_x(i, j) for i in V) + rhs = 1 + if abs(lhs - rhs) > TOL: + if j <= n: + node_type = "linehaul" + orig_cust = j + else: + node_type = "backhaul" + orig_cust = j - n + record_violation( + 2, + f"Constraint 2: In-degree of {node_type} node {j} (customer {orig_cust}) is {lhs}, expected 1", + lhs, rhs, "=" + ) + + # ----------------------------------------------------------------------- + # Constraint 3: sum_{i in V} x_{ji} = 1 for j in L ∪ B + # Out-degree = 1 for every customer node + # ----------------------------------------------------------------------- + for j in sorted(L | B): + lhs = sum(get_x(j, i) for i in V) + rhs = 1 + if abs(lhs - rhs) > TOL: + if j <= n: + node_type = "linehaul" + orig_cust = j + else: + node_type = "backhaul" + orig_cust = j - n + record_violation( + 3, + f"Constraint 3: Out-degree of {node_type} node {j} (customer {orig_cust}) is {lhs}, expected 1", + lhs, rhs, "=" + ) + + # ----------------------------------------------------------------------- + # Constraint 4: sum_{i in V} R_{ij} - q_j = sum_{i in V} R_{ji} for j in L + # Delivery flow conservation at linehaul customers + # Rewritten: sum R_{ij} - sum R_{ji} = q_j (equality) + # ----------------------------------------------------------------------- + for j in sorted(L): + lhs = sum(get_R(i, j) for i in V) - sum(get_R(j, i) for i in V) + rhs = q[j] + if abs(lhs - rhs) > TOL: + record_violation( + 4, + f"Constraint 4: Delivery flow conservation at linehaul node {j} " + f"(customer {j}): R_in - R_out = {lhs}, expected q_{j} = {rhs}", + lhs, rhs, "=" + ) + + # ----------------------------------------------------------------------- + # Constraint 5: sum_{i in V} R_{ij} = sum_{i in V} R_{ji} for j in B + # Delivery flow conservation at backhaul customers (no delivery consumed) + # Rewritten: sum R_{ij} - sum R_{ji} = 0 + # ----------------------------------------------------------------------- + for j in sorted(B): + lhs = sum(get_R(i, j) for i in V) - sum(get_R(j, i) for i in V) + rhs = 0.0 + if abs(lhs - rhs) > TOL: + orig_cust = j - n + record_violation( + 5, + f"Constraint 5: Delivery flow conservation at backhaul node {j} " + f"(customer {orig_cust}): R_in - R_out = {lhs}, expected 0", + lhs, rhs, "=" + ) + + # ----------------------------------------------------------------------- + # Constraint 6: sum_{i in V} P_{ij} = sum_{i in V} P_{ji} for j in L + # Pickup flow conservation at linehaul customers (no pickup added) + # Rewritten: sum P_{ij} - sum P_{ji} = 0 + # ----------------------------------------------------------------------- + for j in sorted(L): + lhs = sum(get_P(i, j) for i in V) - sum(get_P(j, i) for i in V) + rhs = 0.0 + if abs(lhs - rhs) > TOL: + record_violation( + 6, + f"Constraint 6: Pickup flow conservation at linehaul node {j} " + f"(customer {j}): P_in - P_out = {lhs}, expected 0", + lhs, rhs, "=" + ) + + # ----------------------------------------------------------------------- + # Constraint 7: sum_{i in V} P_{ij} + q_j = sum_{i in V} P_{ji} for j in B + # Pickup flow conservation at backhaul customers + # Rewritten: sum P_{ji} - sum P_{ij} = q_j + # ----------------------------------------------------------------------- + for j in sorted(B): + lhs = sum(get_P(j, i) for i in V) - sum(get_P(i, j) for i in V) + rhs = q[j] + if abs(lhs - rhs) > TOL: + orig_cust = j - n + record_violation( + 7, + f"Constraint 7: Pickup flow conservation at backhaul node {j} " + f"(customer {orig_cust}): P_out - P_in = {lhs}, expected q_{j} = {rhs}", + lhs, rhs, "=" + ) + + # ----------------------------------------------------------------------- + # Constraint 8: sum_{i in L ∪ B} P_{0,i} = 0 + # Vehicles start with zero pickup load + # ----------------------------------------------------------------------- + lhs_8 = sum(get_P(0, i) for i in (L | B)) + rhs_8 = 0.0 + if abs(lhs_8 - rhs_8) > TOL: + record_violation( + 8, + f"Constraint 8: Total pickup flow leaving depot = {lhs_8}, expected 0", + lhs_8, rhs_8, "=" + ) + + # ----------------------------------------------------------------------- + # Constraint 9: sum_{i in L ∪ B} R_{i,0} = 0 + # Vehicles finish with zero delivery load + # ----------------------------------------------------------------------- + lhs_9 = sum(get_R(i, 0) for i in (L | B)) + rhs_9 = 0.0 + if abs(lhs_9 - rhs_9) > TOL: + record_violation( + 9, + f"Constraint 9: Total delivery flow returning to depot = {lhs_9}, expected 0", + lhs_9, rhs_9, "=" + ) + + # ----------------------------------------------------------------------- + # Constraint 10: R_{ij} + P_{ij} <= C * x_{ij} for all i,j in V + # Capacity constraint on each arc + # ----------------------------------------------------------------------- + all_arcs = set(x.keys()) | set(R.keys()) | set(P.keys()) + for (i, j) in sorted(all_arcs): + lhs_val = get_R(i, j) + get_P(i, j) + rhs_val = C * get_x(i, j) + if lhs_val - rhs_val > TOL: + record_violation( + 10, + f"Constraint 10: Capacity on arc ({i},{j}): R+P = {lhs_val} > C*x = {rhs_val}", + lhs_val, rhs_val, "<=" + ) + + # ----------------------------------------------------------------------- + # Constraint 11: x_{ij} in {0, 1} for all i,j in V + # Binary domain + # ----------------------------------------------------------------------- + for (i, j), val in sorted(x.items()): + if val not in (0, 1): + record_violation( + 11, + f"Constraint 11: x({i},{j}) = {val}, not binary", + float(val), 1.0, "<=" + ) + + # ----------------------------------------------------------------------- + # Constraint 12: R_{ij} >= 0 for all i,j in V + # Non-negativity of delivery flow + # ----------------------------------------------------------------------- + for (i, j), val in sorted(R.items()): + if val < -TOL: + record_violation( + 12, + f"Constraint 12: R({i},{j}) = {val} < 0", + val, 0.0, ">=" + ) + + # ----------------------------------------------------------------------- + # Constraint 13: P_{ij} >= 0 for all i,j in V + # Non-negativity of pickup flow + # ----------------------------------------------------------------------- + for (i, j), val in sorted(P.items()): + if val < -TOL: + record_violation( + 13, + f"Constraint 13: P({i},{j}) = {val} < 0", + val, 0.0, ">=" + ) + + # ----------------------------------------------------------------------- + # Constraint 14: x_{ii} = 0 for all i in V + # No self-loops + # ----------------------------------------------------------------------- + for i in sorted(V): + val = get_x(i, i) + if abs(val) > TOL: + record_violation( + 14, + f"Constraint 14: Self-loop x({i},{i}) = {val}, expected 0", + float(val), 0.0, "=" + ) + + # ----------------------------------------------------------------------- + # Constraint 15: x_{(n+i), i} = 0 for i in L + # No arc from backhaul n+i to its corresponding linehaul i + # ----------------------------------------------------------------------- + for i in sorted(L): + val = get_x(n + i, i) + if abs(val) > TOL: + record_violation( + 15, + f"Constraint 15: Arc from backhaul {n+i} to linehaul {i} " + f"(customer {i}): x = {val}, expected 0", + float(val), 0.0, "=" + ) + + # ----------------------------------------------------------------------- + # Constraints 16 and 17 SKIPPED: valid inequalities added by the paper + # for LP-relaxation strengthening. + # (16) min-vehicles sum x_{0,i} >= (1/C)*sum q_i (valid for any + # feasible routing that respects capacity). + # (17) no 2-cycles x_{ij} + x_{ji} <= 1 (redundant under single-visit + # VRPMDP structure). + # Neither appears in the business description; any feasible routing that + # satisfies capacity and customer-visit rules automatically satisfies them. + # ----------------------------------------------------------------------- + + # ----------------------------------------------------------------------- + # Constraint 18: Objective consistency (Tier C anti-exploit check). + # Recompute Z = sum_{i,j in V} d_ij * x_ij from the solution's arcs and + # the instance's (integer, rounded-Euclidean) distance matrix. Reject when + # the reported objective_value disagrees beyond a 0.1% relative tolerance + # with a 1e-3 absolute floor. The recompute is exact (integer arithmetic) + # because all obj-determining variables (x_ij) are derivable from + # `routes`, so there is no missing-variable slack to absorb. + # ----------------------------------------------------------------------- + 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(d[(i, j)] * xv for (i, j), xv in x.items())) + abs_diff = abs(reported - true_obj) + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + record_violation( + 18, + f"Constraint 18: Objective consistency violated -- " + f"reported objective_value={reported} differs from " + f"recomputed sum_(i,j) d_ij*x_ij = {true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})", + reported, true_obj, "=" + ) + + # Build result + sorted_violated = sorted(violated_constraints) + feasible = len(sorted_violated) == 0 + + # Aggregate violation messages per constraint + aggregated_violations = [] + for cidx in sorted_violated: + msgs = [v for v, m in zip(violations, violation_magnitudes) if m["constraint"] == cidx] + if not msgs: + msgs = [v for v in violations if v.startswith(f"Constraint {cidx}:")] + count = len(msgs) + if count <= 3: + aggregated_violations.extend(msgs) + else: + aggregated_violations.extend(msgs[:2]) + aggregated_violations.append( + f"... and {count - 2} more violations of constraint {cidx}" + ) + + 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 VRPDDP 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() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("FEASIBLE: All hard constraints satisfied.") + else: + print(f"INFEASIBLE: Violated constraints: {result['violated_constraints']}") + for v in result["violations"][:10]: + 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/nagy2015/gurobi_code.py b/tasks/nagy2015/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..4981164ca72f3041865a1f57a08a445145a5e2f7 --- /dev/null +++ b/tasks/nagy2015/gurobi_code.py @@ -0,0 +1,503 @@ +""" +Gurobi implementation of the VRPDDP (Vehicle Routing Problem with Divisible +Deliveries and Pickups) mathematical formulation. + +Reference: Nagy, Wassan, Speranza, Archetti (2015) +"The Vehicle Routing Problem with Divisible Deliveries and Pickups" +Transportation Science 49(2), pp. 271-294. + +The VRPDDP is modelled as a VRPMDP by creating a pair of fictitious co-located +customers for each original customer: + - Linehaul customer i in L = {1, ..., n} with delivery demand + - Backhaul customer n+i in B = {n+1, ..., 2n} with pickup demand + +Decision variables: + x_ij in {0,1}: 1 if a vehicle travels from i to j + R_ij >= 0: delivery goods on arc (i,j) + P_ij >= 0: pickup goods on arc (i,j) + +Objective: Minimise total distance = sum_{i,j} d_ij * x_ij +""" + +import json +import argparse +import math +import os +import sys +import re +from gurobipy import Model, GRB, quicksum +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load a VRPDDP instance from a JSON file.""" + with open(path, "r") as f: + return json.load(f) + + +def build_expanded_distance_matrix(instance): + """ + Build the expanded distance matrix for the VRPMDP formulation. + + Original nodes: 0 (depot), 1..n (customers) + Expanded nodes: 0 (depot), 1..n (linehaul), n+1..2n (backhaul) + + Backhaul customer n+i is co-located with linehaul customer i, so: + d[i][n+j] = d[i][j] (linehaul to backhaul) + d[n+i][j] = d[i][j] (backhaul to linehaul) + d[n+i][n+j] = d[i][j] (backhaul to backhaul) + d[i][n+i] = 0 (co-located pair) + d[n+i][i] = 0 (co-located pair) + """ + n = instance["num_customers"] + orig_dist = instance["distance_matrix"] # (n+1) x (n+1) matrix for nodes 0..n + size = 2 * n + 1 # nodes 0, 1..n, n+1..2n + + dist = [[0] * size for _ in range(size)] + + for i in range(n + 1): # i in {0, 1, ..., n} + for j in range(n + 1): # j in {0, 1, ..., n} + d_val = orig_dist[i][j] + + # Original-to-original (depot-depot, depot-linehaul, linehaul-linehaul) + dist[i][j] = d_val + + # Original-to-backhaul: dist[i][n+j] = dist[i][j] for j >= 1 + if j >= 1: + dist[i][n + j] = d_val + + # Backhaul-to-original: dist[n+i][j] = dist[i][j] for i >= 1 + if i >= 1: + dist[n + i][j] = d_val + + # Backhaul-to-backhaul: dist[n+i][n+j] = dist[i][j] for i,j >= 1 + if i >= 1 and j >= 1: + dist[n + i][n + j] = d_val + + # Co-located pairs: distance between linehaul i and backhaul n+i is 0 + for i in range(1, n + 1): + dist[i][n + i] = 0 + dist[n + i][i] = 0 + + return dist + + +def build_demands(instance): + """ + Build the demand array for the expanded node set. + + q[i] for i in L: delivery demand of original customer i + q[n+i] for n+i in B: pickup demand of original customer i + q[0] = 0 (depot) + """ + n = instance["num_customers"] + size = 2 * n + 1 + q = [0] * size + + for cust in instance["customers"]: + cid = cust["id"] # 1-indexed + q[cid] = cust["delivery_demand"] # linehaul demand + q[n + cid] = cust["pickup_demand"] # backhaul demand + + return q + + +def solve_vrpddp(instance, time_limit): + """ + Solve the VRPDDP using the two-index MILP formulation from the paper. + """ + n = instance["num_customers"] + C = instance["vehicle_capacity"] + + # Build expanded data + dist = build_expanded_distance_matrix(instance) + q = build_demands(instance) + + size = 2 * n + 1 # total number of nodes: 0, 1..n, n+1..2n + + # Define sets + depot = 0 + L = list(range(1, n + 1)) # linehaul customers + B = list(range(n + 1, 2 * n + 1)) # backhaul customers + LB = L + B # all customers + V = [depot] + LB # all vertices + + print(f"Problem size: n={n}, expanded nodes={size}, capacity={C}") + print(f" Linehaul customers (L): {len(L)}") + print(f" Backhaul customers (B): {len(B)}") + print(f" Total delivery demand: {sum(q[i] for i in L)}") + print(f" Total pickup demand: {sum(q[i] for i in B)}") + + # ========================================================================= + # Build Gurobi model + # ========================================================================= + model = Model("VRPDDP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # ----- Decision variables ----- + # x[i,j] in {0,1}: 1 if vehicle travels from i to j + x = {} + for i in V: + for j in V: + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + # R[i,j] >= 0: delivery goods on arc (i,j) + R = {} + for i in V: + for j in V: + R[i, j] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"R_{i}_{j}") + + # P[i,j] >= 0: pickup goods on arc (i,j) + P = {} + for i in V: + for j in V: + P[i, j] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"P_{i}_{j}") + + model.update() + + # ----- Objective (1): Minimise total distance ----- + model.setObjective( + quicksum(dist[i][j] * x[i, j] for i in V for j in V), + GRB.MINIMIZE + ) + + # ----- Constraints ----- + + # (2) In-degree: each customer visited exactly once + for j in LB: + model.addConstr( + quicksum(x[i, j] for i in V) == 1, + name=f"indegree_{j}" + ) + + # (3) Out-degree: each customer leaves exactly once + for j in LB: + model.addConstr( + quicksum(x[j, i] for i in V) == 1, + name=f"outdegree_{j}" + ) + + # (4) Delivery flow conservation at linehaul customers: + # sum_i R[i,j] - q[j] = sum_i R[j,i], j in L + for j in L: + model.addConstr( + quicksum(R[i, j] for i in V) - q[j] == quicksum(R[j, i] for i in V), + name=f"delivery_flow_linehaul_{j}" + ) + + # (5) Delivery flow conservation at backhaul customers (pass-through): + # sum_i R[i,j] = sum_i R[j,i], j in B + for j in B: + model.addConstr( + quicksum(R[i, j] for i in V) == quicksum(R[j, i] for i in V), + name=f"delivery_flow_backhaul_{j}" + ) + + # (6) Pickup flow conservation at linehaul customers (pass-through): + # sum_i P[i,j] = sum_i P[j,i], j in L + for j in L: + model.addConstr( + quicksum(P[i, j] for i in V) == quicksum(P[j, i] for i in V), + name=f"pickup_flow_linehaul_{j}" + ) + + # (7) Pickup flow conservation at backhaul customers: + # sum_i P[i,j] + q[j] = sum_i P[j,i], j in B + for j in B: + model.addConstr( + quicksum(P[i, j] for i in V) + q[j] == quicksum(P[j, i] for i in V), + name=f"pickup_flow_backhaul_{j}" + ) + + # (8) Vehicles start with zero pickup load: + # sum_{i in L union B} P[0,i] = 0 + model.addConstr( + quicksum(P[depot, i] for i in LB) == 0, + name="zero_initial_pickup" + ) + + # (9) Vehicles finish with zero delivery load: + # sum_{i in L union B} R[i,0] = 0 + model.addConstr( + quicksum(R[i, depot] for i in LB) == 0, + name="zero_final_delivery" + ) + + # (10) Capacity constraint on each arc: + # R[i,j] + P[i,j] <= C * x[i,j] + for i in V: + for j in V: + model.addConstr( + R[i, j] + P[i, j] <= C * x[i, j], + name=f"capacity_{i}_{j}" + ) + + # ========================================================================= + # Valid inequalities / cuts + # ========================================================================= + + # (14) No self-loops: x[i,i] = 0 + for i in V: + model.addConstr(x[i, i] == 0, name=f"no_selfloop_{i}") + + # (15) No arc from backhaul n+i to its corresponding linehaul i: + # x[n+i, i] = 0 + for i in L: + model.addConstr(x[n + i, i] == 0, name=f"no_back_to_line_{i}") + + # (16) Minimum number of vehicles: + # sum_{i in L union B} x[0,i] >= ceil( sum_{i in L} q[i] / C ) + total_delivery = sum(q[i] for i in L) + total_pickup = sum(q[i] for i in B) + min_vehicles_delivery = math.ceil(total_delivery / C) + min_vehicles_pickup = math.ceil(total_pickup / C) + min_vehicles = max(min_vehicles_delivery, min_vehicles_pickup) + print(f" Minimum vehicles (delivery): {min_vehicles_delivery}") + print(f" Minimum vehicles (pickup): {min_vehicles_pickup}") + print(f" Minimum vehicles (overall): {min_vehicles}") + + # The paper's constraint (16) uses delivery demand for the lower bound. + # We add both delivery and pickup lower bounds for tighter relaxation. + model.addConstr( + quicksum(x[depot, i] for i in LB) >= min_vehicles_delivery, + name="min_vehicles_delivery" + ) + model.addConstr( + quicksum(x[depot, i] for i in LB) >= min_vehicles_pickup, + name="min_vehicles_pickup" + ) + + # (17) Subtour elimination for pairs: x[i,j] + x[j,i] <= 1 + for i in LB: + for j in LB: + if i < j: + model.addConstr( + x[i, j] + x[j, i] <= 1, + name=f"pair_subtour_{i}_{j}" + ) + + # ----- Flow balance at depot: vehicles that leave must return ----- + model.addConstr( + quicksum(x[depot, j] for j in LB) == quicksum(x[j, depot] for j in LB), + name="depot_flow_balance" + ) + + # ========================================================================= + # Solve + # ========================================================================= + print(f"\nSolving with time limit = {time_limit} seconds...") + model.optimize() + + # ========================================================================= + # Extract solution + # ========================================================================= + result = { + "objective_value": None, + "routes": [], + "num_routes": 0, + "status": "", + "mip_gap": None, + "solve_time": model.Runtime, + } + + if model.SolCount > 0: + obj_val = model.ObjVal + result["objective_value"] = obj_val + result["mip_gap"] = model.MIPGap + + if model.Status == GRB.OPTIMAL: + result["status"] = "optimal" + elif model.Status == GRB.TIME_LIMIT: + result["status"] = "time_limit" + else: + result["status"] = "feasible" + + # Reconstruct routes by following arcs from the depot + # Build adjacency from selected arcs + adj = {} + for i in V: + for j in V: + if x[i, j].X > 0.5: + adj[i] = j + + # Extract routes starting from depot + routes = [] + visited_from_depot = set() + + for j in LB: + if x[depot, j].X > 0.5 and j not in visited_from_depot: + # Trace route: depot -> j -> ... -> depot + route = [depot] + current = j + route_visited = set() + while current != depot: + if current in route_visited: + # Safety: avoid infinite loop from numerical issues + print(f" WARNING: cycle detected in route at node {current}") + break + route_visited.add(current) + visited_from_depot.add(current) + route.append(current) + current = adj.get(current, depot) + route.append(depot) + routes.append(route) + + result["routes"] = routes + result["num_routes"] = len(routes) + + # Map expanded node IDs back to original customer IDs for readability + routes_original = [] + for route in routes: + original_route = [] + for node in route: + if node == 0: + original_route.append({"node": 0, "type": "depot"}) + elif 1 <= node <= n: + original_route.append({ + "node": node, + "type": "linehaul", + "original_customer": node, + "delivery_demand": q[node], + }) + else: + orig_cust = node - n + original_route.append({ + "node": node, + "type": "backhaul", + "original_customer": orig_cust, + "pickup_demand": q[node], + }) + routes_original.append(original_route) + + result["routes_detailed"] = routes_original + + # Compute per-route distances + route_distances = [] + for route in routes: + route_dist = 0 + for k in range(len(route) - 1): + route_dist += dist[route[k]][route[k + 1]] + route_distances.append(route_dist) + result["route_distances"] = route_distances + + # Print solution summary + print(f"\n{'='*60}") + print(f"Solution found!") + print(f" Objective value: {obj_val}") + print(f" MIP gap: {model.MIPGap:.4%}") + print(f" Solve time: {model.Runtime:.2f} seconds") + print(f" Number of routes: {len(routes)}") + print(f"{'='*60}") + for idx, route in enumerate(routes): + desc_parts = [] + for node in route: + if node == 0: + desc_parts.append("depot") + elif 1 <= node <= n: + desc_parts.append(f"L{node}") + else: + desc_parts.append(f"B{node - n}") + print(f" Route {idx + 1} (dist={route_distances[idx]}): " + f"{' -> '.join(desc_parts)}") + else: + if model.Status == GRB.INFEASIBLE: + result["status"] = "infeasible" + print("Model is infeasible.") + # Compute IIS for debugging + try: + model.computeIIS() + print("IIS constraints:") + for c in model.getConstrs(): + if c.IISConstr: + print(f" {c.ConstrName}") + except Exception: + pass + elif model.Status == GRB.TIME_LIMIT: + result["status"] = "time_limit_no_solution" + print("Time limit reached with no feasible solution.") + else: + result["status"] = f"gurobi_status_{model.Status}" + print(f"Gurobi status: {model.Status}") + + return result + + +def extract_instance_id(instance_path): + """Extract the instance number from a path like .../instance_3.json.""" + basename = os.path.basename(instance_path) + match = re.search(r"(\d+)", basename) + if match: + return match.group(1) + return "unknown" + + +def main(): + parser = argparse.ArgumentParser( + description=( + "VRPDDP solver using Gurobi (two-index MILP formulation). " + "Based on Nagy, Wassan, Speranza, Archetti (2015), " + "Transportation Science 49(2):271-294." + ) + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to the JSON instance file", + ) + parser.add_argument( + "--solution_path", + type=str, + default=None, + help=( + "Path for the output solution JSON file. " + "Default: gurobi_solution_{i}.json in the instance directory" + ), + ) + 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) + + # Determine solution path + if args.solution_path is None: + inst_id = extract_instance_id(args.instance_path) + inst_dir = os.path.dirname(args.instance_path) + args.solution_path = os.path.join(inst_dir, f"gurobi_solution_{inst_id}.json") + + print(f"Instance: {args.instance_path}") + print(f"Solution: {args.solution_path}") + print(f"Time limit: {args.time_limit} seconds") + print() + + instance = load_instance(args.instance_path) + result = solve_vrpddp(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"\nSolution saved to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/nagy2015/gurobi_feasi_result/large_feasi_result_1.json b/tasks/nagy2015/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/nagy2015/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/nagy2015/gurobi_feasi_result/large_feasi_result_2.json b/tasks/nagy2015/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/nagy2015/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/nagy2015/gurobi_feasi_result/large_feasi_result_3.json b/tasks/nagy2015/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/nagy2015/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/nagy2015/gurobi_feasi_result/large_feasi_result_4.json b/tasks/nagy2015/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/nagy2015/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/nagy2015/gurobi_feasi_result/large_feasi_result_5.json b/tasks/nagy2015/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/nagy2015/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/nagy2015/gurobi_feasi_result/tiny_feasi_result.json b/tasks/nagy2015/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/nagy2015/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/nagy2015/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/nagy2015/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/nagy2015/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/nagy2015/gurobi_solution/large_solution_1.json b/tasks/nagy2015/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..51a1bf0e3c7f127892e7403791ab56af96ae191c --- /dev/null +++ b/tasks/nagy2015/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b77fbe8892ec93ccdfe83a5b08a71f9977bdbe254f9dccc6554fa22f0a512622 +size 80959 diff --git a/tasks/nagy2015/gurobi_solution/large_solution_2.json b/tasks/nagy2015/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d6c2e68438e03cd2df6daecd6ddf1bdacca84617 --- /dev/null +++ b/tasks/nagy2015/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5dd2d139896654be6287ab58002a32e2936c9148d4c68ce158d983d8c0dfcf7 +size 60746 diff --git a/tasks/nagy2015/gurobi_solution/large_solution_3.json b/tasks/nagy2015/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..9cb08d7a7bca349ca0432f014a3c52613eabba12 --- /dev/null +++ b/tasks/nagy2015/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bebf0e91de4043de397f78567cacae2a00d7d0821626871a95c06fca012f61b2 +size 79974 diff --git a/tasks/nagy2015/gurobi_solution/large_solution_4.json b/tasks/nagy2015/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..1d71da06c33f5ad13bb8af044a7440769c4b873e --- /dev/null +++ b/tasks/nagy2015/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6e30582ddab07d2c1f8219c17f5ea59d9e4dab5f98a3ce42d9adcf6882f411e6 +size 60405 diff --git a/tasks/nagy2015/gurobi_solution/large_solution_5.json b/tasks/nagy2015/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9b282ce0c74393ebbacf3382ecd07ced463b2e7d --- /dev/null +++ b/tasks/nagy2015/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9fd0b72ded3602e62e648835e53269964d537cbb7d388006d00971047adceee7 +size 79939 diff --git a/tasks/nagy2015/gurobi_solution/tiny_solution.json b/tasks/nagy2015/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..757652dc2978d88ee21be7694f6e82fcc1cacec8 --- /dev/null +++ b/tasks/nagy2015/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28a43325f2b5aa9d31c719dd69b4e2a7d208592e30c89f3ad764b34cfb392701 +size 4644 diff --git a/tasks/nagy2015/gurobi_solution/tiny_solution_2.json b/tasks/nagy2015/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d6822db278dc7d969cfa3d58e1221eb2fdb8e573 --- /dev/null +++ b/tasks/nagy2015/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a667ce4ef9fc64fdea3fb067b3799750b5cb66563a8ac39fef7d1b0446c393fa +size 6217 diff --git a/tasks/nagy2015/gurobi_solution_log/large_log_1.jsonl b/tasks/nagy2015/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c34d9b9f629c73db8376cbbb852a20a63fa69f74 --- /dev/null +++ b/tasks/nagy2015/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92a6c396dcd9cc1821d4ca78a9bdb163001dc86267f38d23337f9e65076c4dfe +size 1015 diff --git a/tasks/nagy2015/gurobi_solution_log/large_log_2.jsonl b/tasks/nagy2015/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..541928eaaf2675bc178172c74ed3766b7bc987e7 --- /dev/null +++ b/tasks/nagy2015/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8deefee3f42fdabb04b99b802ef3ecf5c9f6aa14af6c85dead934593259f69c +size 972 diff --git a/tasks/nagy2015/gurobi_solution_log/large_log_3.jsonl b/tasks/nagy2015/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d39758052928474abbba8de505426dbf68a35700 --- /dev/null +++ b/tasks/nagy2015/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77eb676f6c069fc3e7ab6d58146db44067ed650616e609dc968a35cc78be7717 +size 877 diff --git a/tasks/nagy2015/gurobi_solution_log/large_log_4.jsonl b/tasks/nagy2015/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1d86cf5330fcd1c8c14c9247e8e00a5258e260b2 --- /dev/null +++ b/tasks/nagy2015/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a131c08538e841c6a087c0f8b5efb334ea00d6e68187370f2eb1975bd1217dd4 +size 1374 diff --git a/tasks/nagy2015/gurobi_solution_log/large_log_5.jsonl b/tasks/nagy2015/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..80cc8396139d3b1d9e5352efc01d56f4438199be --- /dev/null +++ b/tasks/nagy2015/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e18d7061ec8fc2683cf91a97010530f0fd2cf67484a31b4cb9399e616953600b +size 1014 diff --git a/tasks/nagy2015/gurobi_solution_log/tiny_log.jsonl b/tasks/nagy2015/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0d32239c099f399b9715988ce17fe8043ad03b37 --- /dev/null +++ b/tasks/nagy2015/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:775d8032b35cc1d72c1c35c70795a08e4348b4d24e7a54e5a564d3211a785a15 +size 43 diff --git a/tasks/nagy2015/instance/large_instance_1.json b/tasks/nagy2015/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..b6376104426e70f8a1925e224700ed5cb8431739 --- /dev/null +++ b/tasks/nagy2015/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0022b7919ad50ed999a388fb330a5e8dce1451536157a3e73095911d3556cffb +size 426077 diff --git a/tasks/nagy2015/instance/large_instance_2.json b/tasks/nagy2015/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..75aa7591687362a00677266f1a5522230bb52ea3 --- /dev/null +++ b/tasks/nagy2015/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4961384e34ed8d877ccf0124065739240400e72948521eb54ee12be5f465e01f +size 425878 diff --git a/tasks/nagy2015/instance/large_instance_3.json b/tasks/nagy2015/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..85684f3f007e68327be5f9177bac48a69a4f8361 --- /dev/null +++ b/tasks/nagy2015/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a6700b33cb373a106af5b57c7445dee6ec3dd12b6515ddb5b83c0e394531018 +size 426212 diff --git a/tasks/nagy2015/instance/large_instance_4.json b/tasks/nagy2015/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..334a0b0fea95c8435d9b0c3c743f3f8b6fe9bd98 --- /dev/null +++ b/tasks/nagy2015/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f8ed3143c06d30519a4e470fa43e268b13857b877ea61e356244b21c8e540ff +size 426199 diff --git a/tasks/nagy2015/instance/large_instance_5.json b/tasks/nagy2015/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..981a92dee1e24a1df6d26da99f853c2abe1144ea --- /dev/null +++ b/tasks/nagy2015/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:930b88455361da50985c16c8d29775bb280b1230406d203e11bc242aedd89701 +size 426467 diff --git a/tasks/nagy2015/instance/tiny_instance.json b/tasks/nagy2015/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..cc80c78398161fed298b36c6c62e0cd7bbbbddf4 --- /dev/null +++ b/tasks/nagy2015/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ded205b0a721dc2979bd354430dc2a015753ad8b1fe398c81393bf220dd8ffcc +size 3589 diff --git a/tasks/nagy2015/instance/tiny_instance_2.json b/tasks/nagy2015/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..11a70f6cb2bce1bfda203684e27b7751bfa76205 --- /dev/null +++ b/tasks/nagy2015/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b3f52b7294f7e580c0df79323d5ef84b98d44271860ef0b0ed9a87395aa73c0 +size 5313 diff --git a/tasks/nagy2015/instance_schema.json b/tasks/nagy2015/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..fe4f360c2cf8f2b41f202cf3907a2c053299cd0b --- /dev/null +++ b/tasks/nagy2015/instance_schema.json @@ -0,0 +1,19 @@ +{ + "num_customers": " Number of original customers to be served.", + "vehicle_capacity": " Maximum combined delivery and pickup load a single vehicle can carry at any time.", + "depot": { + "id": " Identifier for the depot node (always 0).", + "x": " Horizontal coordinate of the depot.", + "y": " Vertical coordinate of the depot." + }, + "customers": [ + { + "id": " Unique identifier for the customer (1-indexed).", + "x": " Horizontal coordinate of the customer location.", + "y": " Vertical coordinate of the customer location.", + "delivery_demand": " Quantity of goods to be delivered from the depot to this customer.", + "pickup_demand": " Quantity of goods to be picked up from this customer and returned to the depot." + } + ], + "distance_matrix": " Rounded Euclidean distance between each pair of locations, where row/column 0 is the depot and rows/columns 1 through num_customers are the customers." +} \ No newline at end of file diff --git a/tasks/nagy2015/mathematical_formulation.md b/tasks/nagy2015/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..25d06f9aa1ce3bb9cb6ada75fa7e4ee506a33464 --- /dev/null +++ b/tasks/nagy2015/mathematical_formulation.md @@ -0,0 +1,59 @@ +# Original Formulation: VRP with Divisible Deliveries and Pickups (as VRPMDP) + +**Source.** Nagy, Wassan, Speranza, Archetti (2015), *Transportation Science* 49(2):271–294. Section 5.1 modelling of the VRPDDP as a VRP with Mixed Deliveries and Pickups (VRPMDP) by splitting each original customer into a co-located linehaul/backhaul pair. + +## Sets and Indices + +$$\begin{align*} +&\mathbf{D} = \{0\} && \text{single depot} \\ +&\mathbf{L} = \{1,\ldots,n\} && \text{linehaul (delivery) customers} \\ +&\mathbf{B} = \{n+1,\ldots,2n\} && \text{backhaul (pickup) customers; $n+i$ is co-located with $i\in\mathbf{L}$} \\ +&\mathbf{V} = \mathbf{D}\cup\mathbf{L}\cup\mathbf{B} && \text{all vertices} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +& d_{ij} && \text{distance between locations $i$ and $j$, $i,j \in \mathbf{V}$} \\ +& q_i && \text{demand of customer $i$ (delivery if $i\in\mathbf{L}$, pickup if $i\in\mathbf{B}$)} \\ +& C && \text{vehicle capacity} +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +& x_{ij} \in \{0,1\} && \text{$=1$ if a vehicle travels from $i$ to $j$} \\ +& R_{ij} \ge 0 && \text{delivery load carried on arc $(i,j)$} \\ +& P_{ij} \ge 0 && \text{pickup load carried on arc $(i,j)$} +\end{align*}$$ + +## Formulation + +$$\begin{align} +\min\ Z\ =\ & \sum_{i\in\mathbf{V}} \sum_{j\in\mathbf{V}} d_{ij}\,x_{ij} \tag{1}\\ +\text{s.t.}\ +& \sum_{i\in\mathbf{V}} x_{ij} \;=\; 1 + && \forall\, j \in \mathbf{L}\cup\mathbf{B} \tag{2}\\ +& \sum_{i\in\mathbf{V}} x_{ji} \;=\; 1 + && \forall\, j \in \mathbf{L}\cup\mathbf{B} \tag{3}\\ +& \sum_{i\in\mathbf{V}} R_{ij}\;-\;q_j \;=\; \sum_{i\in\mathbf{V}} R_{ji} + && \forall\, j \in \mathbf{L} \tag{4}\\ +& \sum_{i\in\mathbf{V}} R_{ij} \;=\; \sum_{i\in\mathbf{V}} R_{ji} + && \forall\, j \in \mathbf{B} \tag{5}\\ +& \sum_{i\in\mathbf{V}} P_{ij} \;=\; \sum_{i\in\mathbf{V}} P_{ji} + && \forall\, j \in \mathbf{L} \tag{6}\\ +& \sum_{i\in\mathbf{V}} P_{ij}\;+\;q_j \;=\; \sum_{i\in\mathbf{V}} P_{ji} + && \forall\, j \in \mathbf{B} \tag{7}\\ +& \sum_{i\in\mathbf{L}\cup\mathbf{B}} P_{0i} \;=\; 0 \tag{8}\\ +& \sum_{i\in\mathbf{L}\cup\mathbf{B}} R_{i0} \;=\; 0 \tag{9}\\ +& R_{ij} + P_{ij} \;\le\; C\,x_{ij} + && \forall\, i,j \in \mathbf{V} \tag{10}\\ +& x_{ij} \in \{0,1\} + && \forall\, i,j \in \mathbf{V} \tag{11}\\ +& R_{ij} \ge 0 + && \forall\, i,j \in \mathbf{V} \tag{12}\\ +& P_{ij} \ge 0 + && \forall\, i,j \in \mathbf{V} \tag{13} +\end{align}$$ + +\(1\) minimizes total travel distance. (2)–(3) enforce exactly one predecessor/successor for each customer. (4)–(7) are flow conservation of delivery and pickup loads at linehaul and backhaul customers. (8)–(9) initialize vehicles with zero pickup load leaving the depot and require zero delivery load returning to the depot. (10) enforces vehicle capacity on every arc used. (11)–(13) are variable domains. diff --git a/tasks/nagy2015/problem_description.txt b/tasks/nagy2015/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..ef3575064f0c79ca3c0f60fbdffa9885f4b014a1 --- /dev/null +++ b/tasks/nagy2015/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A logistics company operates a fleet of identical vehicles from a single depot to serve a set of customers. Each customer has a delivery demand (goods to be brought from the depot) and a pickup demand (goods to be collected and returned to the depot). All delivery goods originate at the depot and all pickup goods must be transported back to the depot; goods may not be transferred directly between customers. The key feature of this problem is that a customer's delivery request and its pickup request may be served on separate visits by different vehicles. Each individual request (delivery or pickup) must, however, be fulfilled entirely in a single visit. The company has an unlimited number of vehicles available, all sharing the same capacity. + +The input data consists of the number of customers n, the vehicle capacity C, the delivery demand for each customer, the pickup demand for each customer, and a symmetric distance matrix giving the distance between the depot and every customer and between every pair of customers. Distances are Euclidean, rounded to the nearest integer. + +The company must design vehicle routes that serve every customer's delivery demand and every customer's pickup demand. Each individual delivery request must be fulfilled in a single visit by one vehicle, and each individual pickup request must be fulfilled in a single visit by one vehicle; the delivery and pickup for the same customer may be performed on the same trip or on separate trips by different vehicles. Each vehicle starts and ends at the depot. At any point during a vehicle's trip the total cargo on board (delivery goods still to be dropped off plus pickup goods already collected) must not exceed the vehicle capacity. A vehicle leaves the depot carrying only delivery goods and returns to the depot carrying only pickup goods. + +The goal is to minimize the total distance traveled by all vehicles, summed over all legs of all trips. diff --git a/tasks/nagy2015/solution_logger.py b/tasks/nagy2015/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/nagy2015/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/nagy2015/solution_schema.json b/tasks/nagy2015/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..713156fbca0f018b0850864ab45c7935571bebd6 --- /dev/null +++ b/tasks/nagy2015/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total distance traveled by all vehicles across every arc of every route.", + "routes": " Sequence of expanded node IDs visited by each vehicle, beginning and ending at the depot (node 0), with linehaul nodes numbered 1..n and backhaul nodes numbered n+1..2n.", + "routes_detailed": " Same per-vehicle visit sequences as 'routes' with each stop annotated by its role (depot, linehaul, or backhaul), the original customer it corresponds to, and the delivery or pickup quantity served at that stop." +} diff --git a/tasks/oliveira2020/feasibility_check.py b/tasks/oliveira2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..8ce4153769be4f2af9fd90f30a0240e0f8c2b187 --- /dev/null +++ b/tasks/oliveira2020/feasibility_check.py @@ -0,0 +1,495 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for P || sum w_j T_j +(Identical parallel machine scheduling minimizing total weighted tardiness) + +Based on the Arc-Time-Indexed Formulation (ATIF) from: +"An Improved Branch-Cut-and-Price Algorithm for Parallel Machine Scheduling Problems" +Oliveira & Pessoa (2019/2020), INFORMS Journal on Computing + +Checks constraints (1b)-(1g) from the ATIF formulation, numbered 1-6 top to bottom, +plus an added objective-consistency check (constraint 7) defending against +LLM score-gaming exploits that lie about objective_value. + +Constraint 1 (1b): Machine capacity — at most m jobs active simultaneously +Constraint 2 (1c): Job assignment — each job j in J scheduled exactly once +Constraint 3 (1d): Flow conservation — completion = start + processing time; + predecessor consistency for arc-based solutions +Constraint 4 (1e): Idle flow conservation — total processing fits within m*T +Constraint 5 (1f): Integrality — completion times are non-negative integers, + C_j >= p_j +Constraint 6 (1g): Domain bounds — start >= 0, completion <= T +Constraint 7 (obj, eq 1a): Objective consistency — reported objective_value + must equal the recomputed total weighted tardiness + sum_j w_j * max(0, C_j - d_j) within tolerance. Full + recompute is possible because every job's completion + time is in the solution and w_j, d_j are deterministic + instance data. +""" + +import argparse +import json +import math +from collections import Counter + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + # ---- Extract instance data ---- + jobs_data = instance["jobs"] + n = instance["parameters"]["n"] + m = instance["parameters"]["m"] + + p = {} + w = {} + d = {} + for job in jobs_data: + p[job["id"]] = job["processing_time"] + w[job["id"]] = job["weight"] + d[job["id"]] = job["due_date"] + + # Compute time horizon T = floor((sum p_j - p_max) / m) + p_max + total_p = sum(j["processing_time"] for j in jobs_data) + p_max = max(j["processing_time"] for j in jobs_data) + T = (total_p - p_max) // m + p_max + # Use instance-provided T if available + if "time_horizon" in instance: + T = instance["time_horizon"] + + violations = [] + violation_magnitudes = [] + violated_constraints = set() + + # ---- Validate and extract the complete public schedule certificate ---- + if not isinstance(solution, dict): + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": ["solution must be a JSON object"], + "violation_magnitudes": [], + } + schedule = solution.get("schedule") + reported_raw = solution.get("objective_value") + schema_errors = [] + if not isinstance(schedule, list): + schema_errors.append("schedule must be a list") + schedule = [] + if ( + isinstance(reported_raw, bool) + or not isinstance(reported_raw, (int, float)) + or not math.isfinite(float(reported_raw)) + ): + schema_errors.append("objective_value must be a finite JSON number") + + required = { + "job", "machine_id", "prev_job", "start_time", "completion_time", + "weighted_tardiness", + } + for index, entry in enumerate(schedule): + if not isinstance(entry, dict): + schema_errors.append(f"schedule[{index}] must be an object") + continue + missing_fields = sorted(required - set(entry)) + if missing_fields: + schema_errors.append( + f"schedule[{index}] is missing fields: {missing_fields}" + ) + continue + if ( + isinstance(entry["job"], bool) + or not isinstance(entry["job"], int) + or isinstance(entry["machine_id"], bool) + or not isinstance(entry["machine_id"], int) + or isinstance(entry["prev_job"], bool) + or not isinstance(entry["prev_job"], int) + ): + schema_errors.append( + f"schedule[{index}] job, machine_id, and prev_job must be integers" + ) + for field in ("start_time", "completion_time", "weighted_tardiness"): + value = entry[field] + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(float(value)) + ): + schema_errors.append( + f"schedule[{index}].{field} must be a finite number" + ) + if schema_errors: + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": schema_errors, + "violation_magnitudes": [], + } + + # Build per-job data + job_entries = {} + job_ids_list = [] + for entry in schedule: + jid = entry["job"] + job_ids_list.append(jid) + C_j = entry["completion_time"] + S_j = entry["start_time"] + job_entries[jid] = { + "completion_time": C_j, + "start_time": S_j, + "prev_job": entry["prev_job"], + "machine_id": entry["machine_id"], + "weighted_tardiness": entry["weighted_tardiness"], + } + + # ================================================================ + # Constraint 1 (1b): Machine capacity + # ================================================================ + if job_entries: + events = [] + for jid, info in job_entries.items(): + events.append((info["start_time"], +1)) + events.append((info["completion_time"], -1)) + events.sort(key=lambda e: (e[0], e[1])) + + current = 0 + max_concurrent = 0 + max_time = None + for t_val, delta in events: + current += delta + if current > max_concurrent: + max_concurrent = current + max_time = t_val + + if max_concurrent > m + tol: + violation_amount = float(max_concurrent - m) + rhs = float(m) + normalizer = max(abs(rhs), eps) + violations.append( + f"Machine capacity exceeded: {max_concurrent} jobs active " + f"simultaneously at time {max_time}, limit is {m}" + ) + violated_constraints.add(1) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(max_concurrent), + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # The certificate names the machine explicitly. Validate each + # machine's sequence, which is stronger than merely checking aggregate + # concurrency and makes the assignment independently reproducible. + by_machine = {k: [] for k in range(m)} + for jid, info in job_entries.items(): + machine_id = info["machine_id"] + if machine_id not in by_machine: + violations.append( + f"Job {jid}: machine_id {machine_id} is outside 0..{m - 1}" + ) + violated_constraints.add(1) + continue + by_machine[machine_id].append(jid) + for machine_id, sequence in by_machine.items(): + sequence.sort(key=lambda jid: (job_entries[jid]["start_time"], jid)) + previous = 0 + previous_completion = 0.0 + for jid in sequence: + info = job_entries[jid] + if info["start_time"] < previous_completion - tol: + violations.append( + f"Machine {machine_id}: job {jid} starts at " + f"{info['start_time']} before the preceding job finishes " + f"at {previous_completion}" + ) + violated_constraints.add(1) + if info["prev_job"] != previous: + violations.append( + f"Machine {machine_id}: job {jid} reports prev_job=" + f"{info['prev_job']}, expected {previous}" + ) + violated_constraints.add(3) + previous = jid + previous_completion = info["completion_time"] + + # ================================================================ + # Constraint 2 (1c): Each job j in J processed exactly once + # ================================================================ + expected_jobs = set(range(1, n + 1)) + scheduled_jobs = set(job_entries.keys()) + missing = sorted(expected_jobs - scheduled_jobs) + extra = sorted(scheduled_jobs - expected_jobs) + job_counts = Counter(job_ids_list) + duplicates = sorted(j for j, c in job_counts.items() if c > 1) + + if missing: + violations.append( + f"Jobs not scheduled (each must appear exactly once): {missing}" + ) + violated_constraints.add(2) + for jid in missing: + violation_magnitudes.append({ + "constraint": 2, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + + if duplicates: + for jid in duplicates: + cnt = job_counts[jid] + violations.append(f"Job {jid} scheduled {cnt} times instead of 1") + violated_constraints.add(2) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(cnt), + "rhs": 1.0, + "raw_excess": float(cnt - 1), + "normalizer": 1.0, + "ratio": float(cnt - 1), + }) + + if extra: + violations.append(f"Unknown jobs in schedule: {extra}") + violated_constraints.add(2) + for jid in extra: + violation_magnitudes.append({ + "constraint": 2, + "lhs": 1.0, + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": eps, + "ratio": 1.0 / eps, + }) + + # ================================================================ + # Constraint 3 (1d): Flow conservation for jobs + # ================================================================ + for jid in sorted(job_entries.keys()): + if jid not in p: + continue + info = job_entries[jid] + C_j = info["completion_time"] + S_j = info["start_time"] + expected_C = S_j + p[jid] + diff = abs(C_j - expected_C) + if diff > tol: + rhs_val = float(expected_C) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Job {jid}: completion_time {C_j} != start_time {S_j} " + f"+ processing_time {p[jid]} = {expected_C}" + ) + violated_constraints.add(3) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(C_j), + "rhs": rhs_val, + "raw_excess": diff, + "normalizer": normalizer, + "ratio": diff / normalizer, + }) + + # ================================================================ + # Constraint 4 (1e): Idle flow conservation + # ================================================================ + scheduled_total_p = sum(p.get(jid, 0) for jid in job_entries.keys()) + capacity = m * T + if scheduled_total_p > capacity + tol: + violation_amount = float(scheduled_total_p - capacity) + rhs_val = float(capacity) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Total processing time {scheduled_total_p} exceeds total " + f"machine capacity m*T = {m}*{T} = {capacity}" + ) + violated_constraints.add(4) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(scheduled_total_p), + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ================================================================ + # Constraint 5 (1f): Integrality of arc variables + # ================================================================ + for jid in sorted(job_entries.keys()): + if jid not in p: + continue + info = job_entries[jid] + C_j = info["completion_time"] + + if abs(C_j - round(C_j)) > tol: + rounded = round(C_j) + diff = abs(C_j - rounded) + normalizer = max(abs(float(rounded)), eps) + violations.append( + f"Job {jid}: completion_time {C_j} is not an integer" + ) + violated_constraints.add(5) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(C_j), + "rhs": float(rounded), + "raw_excess": diff, + "normalizer": normalizer, + "ratio": diff / normalizer, + }) + + if C_j < p[jid] - tol: + violation_amount = float(p[jid] - C_j) + rhs_val = float(p[jid]) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Job {jid}: completion_time {C_j} < processing_time {p[jid]}" + ) + violated_constraints.add(5) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(C_j), + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ================================================================ + # Constraint 6 (1g): Domain bounds for idle arcs / time bounds + # ================================================================ + for jid in sorted(job_entries.keys()): + if jid not in p: + continue + info = job_entries[jid] + C_j = info["completion_time"] + S_j = info["start_time"] + + if S_j < -tol: + violation_amount = abs(S_j) + rhs_val = 0.0 + normalizer = max(abs(rhs_val), eps) + violations.append(f"Job {jid}: start_time {S_j} < 0") + violated_constraints.add(6) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(S_j), + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + if C_j > T + tol: + violation_amount = float(C_j - T) + rhs_val = float(T) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Job {jid}: completion_time {C_j} > time horizon T={T}" + ) + violated_constraints.add(6) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(C_j), + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ================================================================ + # Constraint 7 (obj, eq 1a): Objective consistency. + # The objective is total weighted tardiness: + # z = sum_{j in J} w_j * max(0, C_j - d_j) + # Every job's completion time is in the schedule, and w_j, d_j are + # deterministic instance data, so we full-recompute z and compare to + # the reported objective_value. This rejects LLM exploits that lie + # about objective_value while returning a constraint-feasible schedule. + # ================================================================ + if job_entries: + reported = float(reported_raw) + if reported is not None: + true_obj = 0.0 + for jid, info in job_entries.items(): + if jid not in w or jid not in d: + continue # job id outside instance — handled by constraint 2 + C_j = info["completion_time"] + tardiness = max(0.0, float(C_j) - float(d[jid])) + expected_contribution = float(w[jid]) * tardiness + true_obj += expected_contribution + contribution_diff = abs( + float(info["weighted_tardiness"]) - expected_contribution + ) + if contribution_diff > tol: + violations.append( + f"Job {jid}: weighted_tardiness=" + f"{info['weighted_tardiness']} does not match " + f"{expected_contribution}" + ) + violated_constraints.add(7) + abs_diff = abs(reported - true_obj) + obj_tol = max(1e-5, 1e-8 * abs(true_obj)) + if abs_diff > obj_tol: + rhs_val = float(true_obj) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum_j w_j*max(0,C_j-d_j)={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + violated_constraints.add(7) + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(reported), + "rhs": rhs_val, + "raw_excess": float(abs_diff), + "normalizer": normalizer, + "ratio": float(abs_diff) / normalizer, + }) + + feasible = len(violated_constraints) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes if not feasible else [], + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for P || sum w_j T_j schedules." + ) + parser.add_argument("--instance_path", required=True, + help="Path to instance JSON file.") + parser.add_argument("--solution_path", required=True, + help="Path to solution JSON file.") + parser.add_argument("--result_path", required=True, + help="Path to write feasibility result JSON.") + args = parser.parse_args() + + with open(args.instance_path) as f: + instance = json.load(f) + with open(args.solution_path) as f: + solution = json.load(f) + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasibility: {result['feasible']}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + main() diff --git a/tasks/oliveira2020/gurobi_code.py b/tasks/oliveira2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..7168315a94188f1c92e63bdd19769a2317a1c7b7 --- /dev/null +++ b/tasks/oliveira2020/gurobi_code.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Solve P||sum(w_j T_j) and emit a complete schedule certificate. + +The paper presents an arc-time-indexed formulation. The released solver uses +an equivalent compact disjunctive MILP because the literal arc expansion is +unnecessarily large for the public instances. Both formulations have the same +schedule semantics checked by ``feasibility_check.py``. +""" + +import argparse +import json +import os as _os +import sys as _sys + +import gurobipy as gp +from gurobipy import GRB +import time + + +_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): + del log_path + + +def compute_time_horizon(jobs, machine_count): + total = sum(job["processing_time"] for job in jobs) + largest = max(job["processing_time"] for job in jobs) + return (total - largest) // machine_count + largest + + +def greedy_start(jobs, machine_count, horizon): + """Return a deterministic feasible MIP start when list scheduling fits.""" + ordered = sorted( + jobs, + key=lambda job: ( + job["due_date"], + job["processing_time"] / max(job["weight"], 1), + job["id"], + ), + ) + machine_jobs = [[] for _ in range(machine_count)] + loads = [0] * machine_count + for job in ordered: + machine = min(range(machine_count), key=lambda k: (loads[k], k)) + machine_jobs[machine].append(job["id"]) + loads[machine] += job["processing_time"] + if max(loads, default=0) > horizon: + return None + return machine_jobs + + +def solve(instance_path, solution_path, time_limit): + with open(instance_path) as handle: + data = json.load(handle) + + jobs = sorted(data["jobs"], key=lambda job: job["id"]) + job_ids = [job["id"] for job in jobs] + p = {job["id"]: int(job["processing_time"]) for job in jobs} + w = {job["id"]: int(job["weight"]) for job in jobs} + due = {job["id"]: int(job["due_date"]) for job in jobs} + machine_count = int(data["parameters"]["m"]) + horizon = int(data.get("time_horizon", compute_time_horizon(jobs, machine_count))) + + model = gp.Model("parallel_machine_weighted_tardiness") + model.Params.Threads = 1 + model.Params.TimeLimit = time_limit + model.Params.OutputFlag = 1 + model.Params.MIPFocus = 1 + + assigned = model.addVars(job_ids, range(machine_count), vtype=GRB.BINARY, name="a") + start = { + j: model.addVar(lb=0.0, ub=horizon - p[j], vtype=GRB.CONTINUOUS, name=f"S_{j}") + for j in job_ids + } + tardiness = { + j: model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, name=f"Tard_{j}") + for j in job_ids + } + + before = {} + for pos, i in enumerate(job_ids): + for j in job_ids[pos + 1:]: + for k in range(machine_count): + before[i, j, k] = model.addVar(vtype=GRB.BINARY, name=f"b_{i}_{j}_{k}") + before[j, i, k] = model.addVar(vtype=GRB.BINARY, name=f"b_{j}_{i}_{k}") + + for j in job_ids: + model.addConstr(assigned.sum(j, "*") == 1, name=f"assign_{j}") + model.addConstr(tardiness[j] >= start[j] + p[j] - due[j], name=f"tardy_{j}") + + big_m = float(horizon) + for pos, i in enumerate(job_ids): + for j in job_ids[pos + 1:]: + for k in range(machine_count): + bij = before[i, j, k] + bji = before[j, i, k] + model.addConstr(bij <= assigned[i, k]) + model.addConstr(bij <= assigned[j, k]) + model.addConstr(bji <= assigned[i, k]) + model.addConstr(bji <= assigned[j, k]) + model.addConstr( + bij + bji >= assigned[i, k] + assigned[j, k] - 1 + ) + model.addConstr(bij + bji <= 1) + model.addConstr(start[j] >= start[i] + p[i] - big_m * (1 - bij)) + model.addConstr(start[i] >= start[j] + p[j] - big_m * (1 - bji)) + + model.setObjective( + gp.quicksum(w[j] * tardiness[j] for j in job_ids), + GRB.MINIMIZE, + ) + + initial = greedy_start(jobs, machine_count, horizon) + if initial is not None: + initial_machine = {} + initial_start = {} + for k, sequence in enumerate(initial): + clock = 0 + for j in sequence: + initial_machine[j] = k + initial_start[j] = clock + clock += p[j] + for j in job_ids: + start[j].Start = initial_start[j] + tardiness[j].Start = max(0, initial_start[j] + p[j] - due[j]) + for k in range(machine_count): + assigned[j, k].Start = int(initial_machine[j] == k) + for (i, j, k), variable in before.items(): + variable.Start = int( + initial_machine[i] == k + and initial_machine[j] == k + and initial_start[i] < initial_start[j] + ) + + model.optimize() + + result = { + "instance_id": data.get("instance_id", ""), + "solver": "Gurobi_compact_disjunctive_MILP", + "status": int(model.Status), + "solver_status": { + GRB.OPTIMAL: "optimal", + GRB.TIME_LIMIT: "time_limit", + GRB.INFEASIBLE: "infeasible", + }.get(model.Status, "other"), + "n": len(job_ids), + "m": machine_count, + "T": horizon, + "objective_value": None, + "schedule": [], + } + + if model.SolCount > 0: + machine_of = { + j: max(range(machine_count), key=lambda k: assigned[j, k].X) + for j in job_ids + } + machine_sequences = {k: [] for k in range(machine_count)} + for j in job_ids: + machine_sequences[machine_of[j]].append(j) + for k, sequence in machine_sequences.items(): + sequence.sort(key=lambda j: (start[j].X, j)) + previous = 0 + for j in sequence: + start_value = round(start[j].X) + completion = start_value + p[j] + result["schedule"].append({ + "machine_id": k, + "prev_job": previous, + "job": j, + "start_time": start_value, + "completion_time": completion, + "weighted_tardiness": w[j] * max(0, completion - due[j]), + }) + previous = j + result["schedule"].sort( + key=lambda row: (row["start_time"], row["machine_id"], row["job"]) + ) + result["objective_value"] = sum( + row["weighted_tardiness"] for row in result["schedule"] + ) + result["best_bound"] = float(model.ObjBound) + result["optimality_gap"] = float(model.MIPGap) + + with open(solution_path, "w") as handle: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, handle, indent=2) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Solve P||sum(w_j T_j).") + parser.add_argument("--instance_path", required=True) + parser.add_argument("--solution_path", required=True) + parser.add_argument("--time_limit", type=int, default=3600) + parser.add_argument("--log_path", default=None) + arguments = parser.parse_args() + install_gurobi_logger(arguments.log_path) + solve(arguments.instance_path, arguments.solution_path, arguments.time_limit) diff --git a/tasks/oliveira2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/oliveira2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/oliveira2020/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/oliveira2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/oliveira2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/oliveira2020/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/oliveira2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/oliveira2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/oliveira2020/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/oliveira2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/oliveira2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/oliveira2020/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/oliveira2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/oliveira2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/oliveira2020/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/oliveira2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/oliveira2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/oliveira2020/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/oliveira2020/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/oliveira2020/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/oliveira2020/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/oliveira2020/gurobi_solution/large_solution_1.json b/tasks/oliveira2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d5a0d8a16ecd1935e33606d4780f433ad239b5c4 --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18907c8baa80df87f9f2698b07c22ec611d1f2f2bb4d0d0ee57018720febd672 +size 2653 diff --git a/tasks/oliveira2020/gurobi_solution/large_solution_2.json b/tasks/oliveira2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..263a72348fc3f6b849b814825b39dcc3a8cb8907 --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bd0636d9fc5ebc35c73291e28b1024574d0fa83ba44983552ec7574d0cfcf57 +size 2655 diff --git a/tasks/oliveira2020/gurobi_solution/large_solution_3.json b/tasks/oliveira2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..08289637ceb79e41b5be5512f629cf96fd356be8 --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2883377228a92f58ea057eccb8ed6600fb973badc649e511411ac2e2ec228216 +size 2655 diff --git a/tasks/oliveira2020/gurobi_solution/large_solution_4.json b/tasks/oliveira2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c07ad968bd5884943f5621582b301a703060fb4d --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0942f4d0728354522b5fd9d93d29ad255024adf4cfa25438adbae8080dcde7f6 +size 2652 diff --git a/tasks/oliveira2020/gurobi_solution/large_solution_5.json b/tasks/oliveira2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..f547bb1216ffbff50574b85992f7ac9118286428 --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9c3a5317d5c2e060ec3e4ef65640701c97c2dc769cba6de66be6dd0a0f4edc6 +size 2654 diff --git a/tasks/oliveira2020/gurobi_solution/tiny_solution.json b/tasks/oliveira2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..9cc2b31fc7573999f553205c781bc56b51ae6650 --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cf2600bc1502e7034131d40c32e2d307b8301f23f1033848913bd1f35c5ab2b +size 3121 diff --git a/tasks/oliveira2020/gurobi_solution/tiny_solution_2.json b/tasks/oliveira2020/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..af1bceb229e7452629c614be56865f769e4e658c --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:026119de2a26d3b55caf5084a0c7a99a43b1a64500ded53b5b4f14801903169a +size 6650 diff --git a/tasks/oliveira2020/gurobi_solution_log/large_log_1.jsonl b/tasks/oliveira2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..67204de644dcd7c37f865864cd72dca23302885d --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20e24bd53abd4a9ad4a4f481912c7a44dfb853d2a7a1387ea2bc31ebb94cba1e +size 41 diff --git a/tasks/oliveira2020/gurobi_solution_log/large_log_2.jsonl b/tasks/oliveira2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e700ef37fcc9e1f9d85d4b0443d822a9dc4d252a --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c7318c0d564912913bc035e762900c609d4432789108bff887b7baf47efe978 +size 41 diff --git a/tasks/oliveira2020/gurobi_solution_log/large_log_3.jsonl b/tasks/oliveira2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..24c95500cc7b2c4de5ebc6c424a32c56ab3458a1 --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fba023c3db7764c0cc6f66cdb0192d457e079aa69662c7c71f833d35ee21a5e6 +size 42 diff --git a/tasks/oliveira2020/gurobi_solution_log/large_log_4.jsonl b/tasks/oliveira2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d7109e39911372d802611ceb6f3b9a1103aeed32 --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b824fceacee6360487a629b3f82e98d3b50b32e91db59934a4645d59472f9df +size 42 diff --git a/tasks/oliveira2020/gurobi_solution_log/large_log_5.jsonl b/tasks/oliveira2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..afa6373ea12f8062608a418feb05ae9af5b5f800 --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1974908529e4f565bfd79bec55c6c730f02827d813efeef332af1eff55ffe320 +size 41 diff --git a/tasks/oliveira2020/gurobi_solution_log/tiny_log.jsonl b/tasks/oliveira2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c364e2e0d745ad91fe6167c6e957f83970313238 --- /dev/null +++ b/tasks/oliveira2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:23128e66b45f62a6b0ee0a9a79f628e0eff267abc138d96155bd7a25c2e638b1 +size 44 diff --git a/tasks/oliveira2020/instance/large_instance_1.json b/tasks/oliveira2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..046a9ad95efec2da8efbb713cc96e1312d762e52 --- /dev/null +++ b/tasks/oliveira2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d25e0b24f22abff9d3e6ff4e9968a7a0bc9c8534d35791c7dd60edc73a280ef +size 2071 diff --git a/tasks/oliveira2020/instance/large_instance_2.json b/tasks/oliveira2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..5f6b21c78e9464a470bf73aa791cda8933d7fa90 --- /dev/null +++ b/tasks/oliveira2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6c964ea5887257eef62b848436a056a797d6bf184411408d49d64a2f14173ad +size 2085 diff --git a/tasks/oliveira2020/instance/large_instance_3.json b/tasks/oliveira2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..11f9bfe722362b6d9519ce953b2fa63d239a48fc --- /dev/null +++ b/tasks/oliveira2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:788e7e3107766e2b28d17357580b5aa9316a44e6e9e1bd2bd0d9d642f23076b1 +size 2079 diff --git a/tasks/oliveira2020/instance/large_instance_4.json b/tasks/oliveira2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..7171ef0b9961131e33b8bdfc47609bd522b7b455 --- /dev/null +++ b/tasks/oliveira2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b723d2591dc927b6c056443bc04e296f629d7baba0517679f51ba548a1180323 +size 2075 diff --git a/tasks/oliveira2020/instance/large_instance_5.json b/tasks/oliveira2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..ec91af834f7d7ad835e117ca44f648337bbe7cd7 --- /dev/null +++ b/tasks/oliveira2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83bd9d965609d2fea3d062e73939788aae66ec27c83bebd38faa2af4d1a2b58a +size 2073 diff --git a/tasks/oliveira2020/instance/tiny_instance.json b/tasks/oliveira2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..6d23e225bf9930f4d878829add9e92cafd14750d --- /dev/null +++ b/tasks/oliveira2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c2e26750bf5562370399a5fc99bedcc619bdee6d504f69628df7dd52189fbe3 +size 2271 diff --git a/tasks/oliveira2020/instance/tiny_instance_2.json b/tasks/oliveira2020/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..f1da411fbef36d3d67fe4f612e1f607785af7565 --- /dev/null +++ b/tasks/oliveira2020/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9f95891d221d7920f88da0fbf0d10f541173356ebcec4342aa755b45dbc56ff +size 4452 diff --git a/tasks/oliveira2020/instance_schema.json b/tasks/oliveira2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b2bb3e800ff38de71e17680f5af02dbbeb62f275 --- /dev/null +++ b/tasks/oliveira2020/instance_schema.json @@ -0,0 +1,17 @@ +{ + "time_horizon": " Latest time unit in the discrete planning horizon by which all jobs must finish.", + "total_processing_time": " Sum of processing times across all jobs.", + "p_max": " Longest processing time among all jobs.", + "jobs": [ + { + "id": " Unique identifier for the job (1-indexed).", + "processing_time": " Number of time units required to complete the job on a machine.", + "weight": " Importance weight of the job, used to penalize late completion.", + "due_date": " Time by which the job should ideally be completed to avoid a tardiness penalty." + } + ], + "parameters": { + "n": " Number of jobs to be scheduled.", + "m": " Number of identical parallel machines available." + } +} diff --git a/tasks/oliveira2020/mathematical_formulation.md b/tasks/oliveira2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..5cfde26e52adff677e2c033e833c5006902abc7b --- /dev/null +++ b/tasks/oliveira2020/mathematical_formulation.md @@ -0,0 +1,62 @@ +# Original Formulation: Arc-Time-Indexed Formulation (ATIF) + +**Source.** Oliveira and Pessoa (2020), “An Improved Branch-Cut-and-Price Algorithm for Parallel Machine Scheduling Problems,” *INFORMS Journal on Computing*. Section 2.1, equations (1a)–(1g). + +**Problem.** Identical parallel machine scheduling $P\,\|\,\sum f_j(C_j)$ minimizing a generic regular function of job completion times (weighted tardiness in the computational study: $f_j(C_j) = w_j\max\{0,C_j-d_j\}$). + +## Sets and Parameters + +- $J = \{1,\ldots,n\}$ — set of jobs. + +- $J_0 = J \cup \{0\}$ — jobs plus dummy job 0 with $p_0 = 0$. + +- $m$ — number of identical parallel machines. + +- $p_j$ — processing time of job $j$. + +- $f_j(\cdot)$ — cost as a function of completion time. + +- $T$ — time horizon (latest possible completion in an optimal schedule); a valid choice is $T = \lfloor (\sum_{j\in J} p_j - p_{\max})/m \rfloor + p_{\max}$ with $p_{\max} = \max_j p_j$. + +## Decision Variables + +Arc-time-indexed variables on a job-time graph: $$x^t_{ij} \in \mathbb{Z}_+$$ indicates that on some machine job $i$ finishes and job $j$ starts at time $t$ (so job $j$ completes at $t + p_j$). The variable $x^t_{00}$ represents a machine-idle arc at time $t$. + +## Formulation + +$$\begin{align} +\min\ & \sum_{i\in J_0}\ \sum_{j\in J\setminus\{i\}}\ \sum_{t=p_i}^{T-p_j} + f_j(t+p_j)\, x^t_{ij} \tag{1a}\\[2pt] +\text{s.t.}\ +& \sum_{j\in J_0} x^{0}_{0j} \;=\; m \tag{1b}\\[2pt] +& \sum_{i\in J_0\setminus\{j\}}\ \sum_{t=p_i}^{T-p_j} x^t_{ij} \;=\; 1 + && \forall\, j \in J \tag{1c}\\[2pt] +& \sum_{\substack{j\in J_0\setminus\{i\} \\ t-p_j\ge 0}} x^{t}_{ji} + \;-\; + \sum_{\substack{j\in J_0\setminus\{i\} \\ t+p_i\le T}} x^{t}_{ij} + \;=\; 0 + && \forall\, i\in J,\ t=0,\ldots,T-p_i \tag{1d}\\[2pt] +& \sum_{\substack{j\in J_0 \\ t-p_j\ge 0}} x^{t}_{j0} + \;-\; + \sum_{\substack{j\in J_0 \\ t+p_j+1\le T}} x^{t+1}_{0j} + \;=\; 0 + && t = 0,\ldots,T-1 \tag{1e}\\[2pt] +& x^t_{ij} \in \mathbb{Z}_+ + && \forall\, i\in J_0,\ j\in J_0\setminus\{i\},\ t=p_i,\ldots,T-p_j \tag{1f}\\ +& x^t_{00} \in \mathbb{Z}_+ + && t = 0,\ldots,T-1 \tag{1g} +\end{align}$$ + +(1a) minimizes total completion-time cost. (1b) dispatches $m$ machines from the source node at time $0$. (1c) assigns every job exactly once. (1d) is flow conservation at each job-time node. (1e) is flow conservation for idle arcs through the dummy job. (1f)–(1g) are the integer domains. + +## Released executable formulation and certificate + +The public `gurobi_code.py` solves the same scheduling problem with a compact +disjunctive MILP (job-to-machine assignment, start times, and pairwise order) +instead of materializing every arc-time variable. This avoids a roughly +900,000-binary expansion on `tiny_instance_2.json`; it does not change the +feasible schedules or the weighted-tardiness objective. The released solution +certificate explicitly records `machine_id`, the immediate `prev_job`, start +and completion times, and each job's weighted-tardiness contribution. The +checker requires exact job coverage, verifies every named machine sequence and +the horizon, and recomputes the objective from the certificate. diff --git a/tasks/oliveira2020/problem_description.txt b/tasks/oliveira2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..96cc269147337c3124d671697feb4b4112604227 --- /dev/null +++ b/tasks/oliveira2020/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A manufacturing facility has a set of jobs that must be processed on a given number of identical parallel machines. Each job has a known integer processing time, a positive integer weight reflecting its importance, and an integer due date by which it should ideally be completed. Each machine can process only one job at a time, and once a job begins processing on a machine it must run to completion without interruption or transfer to another machine. Every job must be processed exactly once on exactly one machine. + +Time is divided into unit-length periods from zero up to a planning horizon. The planning horizon is computed by taking the total processing time of all jobs, subtracting the largest individual processing time, dividing the result by the number of machines, taking the floor of that quotient, and then adding back the largest individual processing time. All machines are available starting at time zero. The scheduler must determine which machine each job is assigned to, the order in which jobs are processed on each machine, and the exact integer start time of each job, such that no two jobs overlap on the same machine. A job finishes at its start time plus its processing time. Idle time between consecutive jobs on the same machine is permitted. + +The tardiness of a job is defined as the amount by which its completion time exceeds its due date, or zero if the job finishes on or before its due date. The weighted tardiness of a job is the product of its weight and its tardiness. The goal is to find a schedule that minimizes the total weighted tardiness summed over all jobs. diff --git a/tasks/oliveira2020/solution_logger.py b/tasks/oliveira2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/oliveira2020/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/oliveira2020/solution_schema.json b/tasks/oliveira2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..2328cac0e9db26ce4f83e434513ecf051fa5b717 --- /dev/null +++ b/tasks/oliveira2020/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total weighted tardiness of the schedule, summed over all jobs.", + "schedule": " One entry per job. 'machine_id' is an integer in 0..m-1; 'prev_job' is the id of the immediately preceding job on that machine (0 for the first); 'job' is the job id; 'start_time' and 'completion_time' are integer times; and 'weighted_tardiness' is this job's exact objective contribution." +} diff --git a/tasks/ozturk2020/feasibility_check.py b/tasks/ozturk2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..4b2472d623d37b8eb9fb8faa717894bad3155e54 --- /dev/null +++ b/tasks/ozturk2020/feasibility_check.py @@ -0,0 +1,417 @@ +""" +Feasibility checker for Parallel Batch Scheduling (Ozturk 2020). +Checks all hard constraints from the MILP formulation in math_model.txt. + +Constraints (numbered top-to-bottom from the formulation): + (1) Each job assigned to exactly one batch on one machine + (2) Capacity constraint for each batch + (3) Batch processing time >= processing time of any assigned job + (4) Batch start time >= release date of any assigned job + (5) Consecutive batches on the same machine do not overlap + (6) Completion time of each job >= batch end time for its assigned batch + (7) Variable domains: x in {0,1}, S >= 0, p >= 0 (C >= 0 implied) + (8) Objective consistency: reported objective_value must equal sum_j C_j + (full recompute; falls back to a lower bound via batch_end for any + missing completion times). +""" + +import json +import argparse +import math + + +def load_instance(instance_path): + with open(instance_path, 'r') as f: + return json.load(f) + + +def load_solution(solution_path): + with open(solution_path, 'r') as f: + return json.load(f) + + +def parse_solution(sol, instance): + """ + Normalize both efficient and gurobi solution formats into a common structure. + Returns: + batches: list of dicts with keys: jobs, machine, start_time, processing_time + job_completions: dict mapping job_id (int) -> completion_time (float) + """ + batches = [] + job_completions = {} + + for b in sol.get("batches", []): + batch = { + "jobs": b["jobs"], + "machine": b["machine"], + "start_time": b["start_time"], + "processing_time": b["processing_time"], + } + # Some formats store batch_id + if "batch_id" in b: + batch["batch_id"] = b["batch_id"] + batches.append(batch) + + # Efficient solution format: job_completions dict + if "job_completions" in sol: + for jid_str, ct in sol["job_completions"].items(): + job_completions[int(jid_str)] = float(ct) + + # Gurobi solution format: job_assignments dict + if "job_assignments" in sol: + for jid_str, info in sol["job_assignments"].items(): + job_completions[int(jid_str)] = float(info["completion_time"]) + + return batches, job_completions + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + N = instance["num_jobs"] + M = instance["num_machines"] + Cap = instance["batch_capacity"] + jobs = instance["jobs"] + + schema_errors = [] + if not isinstance(solution, dict): + schema_errors.append("solution must be a JSON object") + else: + for field in ("objective_value", "batches", "job_assignments"): + if field not in solution or solution[field] is None: + schema_errors.append(f"missing required solution field: {field}") + 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") + if not isinstance(solution.get("batches"), list) or not solution.get("batches"): + schema_errors.append("batches must be a non-empty list") + assignments = solution.get("job_assignments") + expected_job_keys = {str(job["job_id"]) for job in jobs} + if not isinstance(assignments, dict) or set(assignments) != expected_job_keys: + actual = set(assignments) if isinstance(assignments, dict) else set() + schema_errors.append( + "job_assignments must cover every job exactly once; " + f"missing={sorted(expected_job_keys - actual)}, " + f"extra={sorted(actual - expected_job_keys)}" + ) + if schema_errors: + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": schema_errors, + "violation_magnitudes": [], + } + + # Build job lookup by job_id + job_by_id = {} + for j in jobs: + job_by_id[j["job_id"]] = j + + batches, job_completions = parse_solution(solution, instance) + + violations = [] + violation_magnitudes = [] + violated_constraints_set = set() + + def record_violation(constraint_idx, message, lhs, rhs, operator=">="): + """Record a violation with normalized magnitude.""" + if operator == ">=": + violation_amount = rhs - lhs + elif operator == "<=": + violation_amount = lhs - rhs + elif operator == "=": + violation_amount = abs(lhs - rhs) + else: + violation_amount = 0.0 + + if violation_amount > tol: + violated_constraints_set.add(constraint_idx) + violations.append((constraint_idx, message)) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ========================================================================= + # Constraint (1): Each job assigned to exactly one batch on one machine + # sum_k sum_m x_{jkm} = 1 for all j + # ========================================================================= + job_assignment_count = {j["job_id"]: 0 for j in jobs} + for b in batches: + for jid in b["jobs"]: + if jid in job_assignment_count: + job_assignment_count[jid] += 1 + + for j in jobs: + jid = j["job_id"] + count = job_assignment_count[jid] + if abs(count - 1) > tol: + record_violation( + 1, + f"Job {jid} is assigned to {count} batch(es) instead of exactly 1", + float(count), 1.0, "=" + ) + + # ========================================================================= + # Constraint (2): Capacity constraint + # sum_j x_{jkm} * v_j <= Cap for each batch + # ========================================================================= + for i, b in enumerate(batches): + total_size = sum(job_by_id[jid]["size"] for jid in b["jobs"] if jid in job_by_id) + if total_size - Cap > tol: + record_violation( + 2, + f"Batch {i+1} on machine {b['machine']}: total size {total_size} exceeds capacity {Cap}", + float(total_size), float(Cap), "<=" + ) + + # ========================================================================= + # Constraint (3): Batch processing time >= processing time of any assigned job + # p_{km} >= x_{jkm} * p_j + # ========================================================================= + for i, b in enumerate(batches): + p_km = b["processing_time"] + for jid in b["jobs"]: + if jid in job_by_id: + p_j = job_by_id[jid]["processing_time"] + if p_j - p_km > tol: + record_violation( + 3, + f"Batch {i+1} on machine {b['machine']}: processing time {p_km} < job {jid} processing time {p_j}", + float(p_km), float(p_j), ">=" + ) + + # ========================================================================= + # Constraint (4): Batch start time >= release date of any assigned job + # S_{km} >= x_{jkm} * r_j + # ========================================================================= + for i, b in enumerate(batches): + s_km = b["start_time"] + for jid in b["jobs"]: + if jid in job_by_id: + r_j = job_by_id[jid]["release_date"] + if r_j - s_km > tol: + record_violation( + 4, + f"Batch {i+1} on machine {b['machine']}: start time {s_km} < release date {r_j} of job {jid}", + float(s_km), float(r_j), ">=" + ) + + # ========================================================================= + # Constraint (5): Consecutive batches on same machine do not overlap + # S_{km} >= S_{k-1,m} + p_{k-1,m} + # Sort batches on each machine by start time and check non-overlapping. + # ========================================================================= + machine_batches = {} + for i, b in enumerate(batches): + m = b["machine"] + if m not in machine_batches: + machine_batches[m] = [] + machine_batches[m].append((i, b)) + + for m, mb_list in machine_batches.items(): + # Sort by start time + mb_list.sort(key=lambda x: x[1]["start_time"]) + for idx in range(1, len(mb_list)): + prev_i, prev_b = mb_list[idx - 1] + curr_i, curr_b = mb_list[idx] + prev_end = prev_b["start_time"] + prev_b["processing_time"] + curr_start = curr_b["start_time"] + if prev_end - curr_start > tol: + record_violation( + 5, + f"Machine {m}: batch {prev_i+1} ends at {prev_end} but batch {curr_i+1} starts at {curr_start} (overlap)", + float(curr_start), float(prev_end), ">=" + ) + + # ========================================================================= + # Constraint (6): Completion time of each job + # C_j >= (S_{km} + p_{km}) - Q(1 - x_{jkm}) + # For assigned jobs (x=1): C_j >= S_{km} + p_{km} + # ========================================================================= + # Build mapping: job_id -> (batch start_time, batch processing_time) + job_batch_info = {} + for i, b in enumerate(batches): + batch_end = b["start_time"] + b["processing_time"] + for jid in b["jobs"]: + job_batch_info[jid] = ( + b["start_time"], + b["processing_time"], + batch_end, + i, + b.get("batch_id"), + b["machine"], + ) + + for j in jobs: + jid = j["job_id"] + if jid in job_completions and jid in job_batch_info: + c_j = job_completions[jid] + s_km, p_km, batch_end, batch_idx, batch_id, machine = job_batch_info[jid] + if batch_end - c_j > tol: + record_violation( + 6, + f"Job {jid}: completion time {c_j} < batch end time {batch_end} (batch {batch_idx+1})", + float(c_j), float(batch_end), ">=" + ) + assignment = solution["job_assignments"][str(jid)] + if assignment.get("batch") != batch_id: + record_violation( + 6, + f"Job {jid}: reported batch {assignment.get('batch')} " + f"does not match containing batch {batch_id}", + 1.0, 0.0, "=" + ) + if assignment.get("machine") != machine: + record_violation( + 6, + f"Job {jid}: reported machine {assignment.get('machine')} " + f"does not match containing machine {machine}", + 1.0, 0.0, "=" + ) + + # ========================================================================= + # Constraint (7): Variable domains + # S_{km} >= 0, p_{km} >= 0, C_j >= 0 + # (x binary is structural and checked implicitly via constraint 1) + # ========================================================================= + for i, b in enumerate(batches): + if b["start_time"] < -tol: + record_violation( + 7, + f"Batch {i+1} on machine {b['machine']}: start time {b['start_time']} is negative", + float(b["start_time"]), 0.0, ">=" + ) + if b["processing_time"] < -tol: + record_violation( + 7, + f"Batch {i+1} on machine {b['machine']}: processing time {b['processing_time']} is negative", + float(b["processing_time"]), 0.0, ">=" + ) + + for j in jobs: + jid = j["job_id"] + if jid in job_completions and job_completions[jid] < -tol: + record_violation( + 7, + f"Job {jid}: completion time {job_completions[jid]} is negative", + float(job_completions[jid]), 0.0, ">=" + ) + + # ========================================================================= + # Constraint (8): Objective consistency + # objective_value must equal sum_j C_j (total flow time). + # Full recompute when every job has a completion time in the solution; + # otherwise fall back to a per-job lower bound using its batch_end + # (since constraint 6 forces C_j >= batch_end). + # ========================================================================= + reported_obj = solution.get("objective_value") + try: + reported_obj = float(reported_obj) if reported_obj is not None else None + except (TypeError, ValueError): + reported_obj = None + + if reported_obj is not None: + parts = [] + have_all = True + for j in jobs: + jid = j["job_id"] + if jid in job_completions: + parts.append(float(job_completions[jid])) + elif jid in job_batch_info: + _, _, batch_end, _, _, _ = job_batch_info[jid] + parts.append(float(batch_end)) + have_all = False + else: + # Job is unassigned (constraint 1 will already flag); contribute 0 + # so we don't over-constrain the lower bound here. + have_all = False + + recomputed = float(sum(parts)) + # 0.1% relative tolerance with 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(recomputed)) + + if have_all: + # Equality check (full recompute). + abs_diff = abs(reported_obj - recomputed) + if abs_diff > obj_tol: + record_violation( + 8, + f"Objective consistency violated: reported objective_value=" + f"{reported_obj} differs from recomputed sum_j(C_j)=" + f"{recomputed} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + float(reported_obj), float(recomputed), "=" + ) + else: + # Lower-bound check: reported_obj must be at least sum of + # known C_j (or batch_end fallbacks). Only catches under-reporting. + shortfall = recomputed - reported_obj + if shortfall > obj_tol: + record_violation( + 8, + f"Objective consistency violated: reported objective_value=" + f"{reported_obj} is below lower bound sum_j(C_j or batch_end)=" + f"{recomputed} (shortfall={shortfall:.6g}, tol={obj_tol:.6g})", + float(reported_obj), float(recomputed), ">=" + ) + + # Build output + violated_constraints = sorted(violated_constraints_set) + # Aggregate violation messages by constraint index + violation_messages = [] + seen_constraints_msg = set() + for cidx, msg in violations: + violation_messages.append(msg) + + feasible = len(violated_constraints) == 0 + + result = { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violation_messages, + "violation_magnitudes": violation_magnitudes, + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Parallel Batch Scheduling (Ozturk 2020)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result") + args = parser.parse_args() + + instance = load_instance(args.instance_path) + solution = load_solution(args.solution_path) + 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__": + main() diff --git a/tasks/ozturk2020/gurobi_code.py b/tasks/ozturk2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..17960977155342c21f4d9f8414d8fbdde1ed6e2d --- /dev/null +++ b/tasks/ozturk2020/gurobi_code.py @@ -0,0 +1,217 @@ +""" +Gurobi implementation of the MILP model for Parallel Batch Scheduling +to Minimize Total Flow Time. + +Paper: Ozturk (2020) - "A truncated column generation algorithm for the + parallel batch scheduling problem to minimize total flow time" + +Problem: P/p-Batch, r_j, p_j, v_j, Cap / sum(C_j) + +MILP Model (Section 3): + min sum C_j + s.t. + (1) sum_k sum_m x_{jkm} = 1, for all j + (2) sum_j x_{jkm} * v_j <= Cap, for all k, m + (3) p_{km} >= x_{jkm} * p_j, for all j, k, m + (4) S_{km} >= x_{jkm} * r_j, for all j, k, m + (5) S_{km} >= S_{k-1,m} + p_{k-1,m}, for k>=2, all m + (6) C_j >= (S_{km} + p_{km}) - Q(1 - x_{jkm}), for all j, k, m + (7) x_{jkm} in {0,1}, S_{km} >= 0, p_{km} >= 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 solve(instance_path, solution_path, time_limit): + # Load instance + with open(instance_path, 'r') as f: + data = json.load(f) + + N = data['num_jobs'] + M = data['num_machines'] + Cap = data['batch_capacity'] + jobs = data['jobs'] + + # Extract job parameters (0-indexed internally) + r = [jobs[j]['release_date'] for j in range(N)] + p = [jobs[j]['processing_time'] for j in range(N)] + v = [jobs[j]['size'] for j in range(N)] + + # Big-M: upper bound on any completion time + # ASSUMPTION (NOT SPECIFIED IN PAPER): Q = sum of all release dates + sum of all processing times + max release date + # This is a safe upper bound on the latest possible completion time. + Q = sum(r) + sum(p) + max(r) + max(p) + + model = gp.Model("BatchScheduling") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # --- Decision Variables --- + # x[j,k,m]: 1 if job j is in batch k on machine m + x = {} + for j in range(N): + for k in range(N): + for m in range(M): + x[j, k, m] = model.addVar(vtype=GRB.BINARY, name=f"x_{j}_{k}_{m}") + + # p_batch[k,m]: processing duration of batch k on machine m + p_batch = {} + for k in range(N): + for m in range(M): + p_batch[k, m] = model.addVar(lb=0, vtype=GRB.CONTINUOUS, name=f"p_{k}_{m}") + + # S[k,m]: start time of batch k on machine m + S = {} + for k in range(N): + for m in range(M): + S[k, m] = model.addVar(lb=0, vtype=GRB.CONTINUOUS, name=f"S_{k}_{m}") + + # C[j]: completion time (flow time) of job j + C = {} + for j in range(N): + C[j] = model.addVar(lb=0, vtype=GRB.CONTINUOUS, name=f"C_{j}") + + model.update() + + # --- Objective: minimize sum of completion times --- + model.setObjective(gp.quicksum(C[j] for j in range(N)), GRB.MINIMIZE) + + # --- Constraints --- + + # (1) Each job assigned to exactly one batch on one machine + for j in range(N): + model.addConstr( + gp.quicksum(x[j, k, m] for k in range(N) for m in range(M)) == 1, + name=f"assign_{j}" + ) + + # (2) Capacity constraint + for k in range(N): + for m in range(M): + model.addConstr( + gp.quicksum(x[j, k, m] * v[j] for j in range(N)) <= Cap, + name=f"cap_{k}_{m}" + ) + + # (3) Batch processing duration >= processing time of any assigned job + for j in range(N): + for k in range(N): + for m in range(M): + model.addConstr( + p_batch[k, m] >= x[j, k, m] * p[j], + name=f"proc_{j}_{k}_{m}" + ) + + # (4) Batch start time >= release date of any assigned job + for j in range(N): + for k in range(N): + for m in range(M): + model.addConstr( + S[k, m] >= x[j, k, m] * r[j], + name=f"release_{j}_{k}_{m}" + ) + + # (5) Consecutive batches on the same machine don't overlap + for k in range(1, N): + for m in range(M): + model.addConstr( + S[k, m] >= S[k - 1, m] + p_batch[k - 1, m], + name=f"seq_{k}_{m}" + ) + + # (6) Flow time (completion time) of each job + for j in range(N): + for k in range(N): + for m in range(M): + model.addConstr( + C[j] >= (S[k, m] + p_batch[k, m]) - Q * (1 - x[j, k, m]), + name=f"flow_{j}_{k}_{m}" + ) + + # --- Solve --- + model.optimize() + + # --- Extract solution --- + result = {"objective_value": None, "status": None, "batches": [], "job_assignments": {}} + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + + # Extract job assignments + for j in range(N): + for k in range(N): + for m in range(M): + if x[j, k, m].X > 0.5: + job_id = jobs[j]['job_id'] + result["job_assignments"][str(job_id)] = { + "batch": k + 1, + "machine": m + 1, + "completion_time": C[j].X + } + break + else: + continue + break + + # Extract batch info + for k in range(N): + for m in range(M): + if p_batch[k, m].X > 1e-6: + batch_jobs = [] + for j in range(N): + if x[j, k, m].X > 0.5: + batch_jobs.append(jobs[j]['job_id']) + if batch_jobs: + result["batches"].append({ + "batch_id": k + 1, + "machine": m + 1, + "start_time": S[k, m].X, + "processing_time": p_batch[k, m].X, + "jobs": batch_jobs + }) + else: + result["status"] = "infeasible_or_no_solution" + result["objective_value"] = None + + # Write solution + with open(solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Gurobi MILP for Parallel Batch Scheduling (Ozturk 2020)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/ozturk2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/ozturk2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ozturk2020/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/ozturk2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/ozturk2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ozturk2020/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/ozturk2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/ozturk2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ozturk2020/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/ozturk2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/ozturk2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ozturk2020/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/ozturk2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/ozturk2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ozturk2020/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/ozturk2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/ozturk2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ozturk2020/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/ozturk2020/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/ozturk2020/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ozturk2020/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/ozturk2020/gurobi_solution/large_solution_1.json b/tasks/ozturk2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f6ce6033c08a8fe6e62cb62c6f860bae4b979ade --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49303b18cefa67119022259cf069befee31bc7ecfb19cf7565710337400f8e50 +size 7497 diff --git a/tasks/ozturk2020/gurobi_solution/large_solution_2.json b/tasks/ozturk2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..0045d380054893b48656e02b754cf20c6023cf6c --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70f5b1483da60f09ad43cd8df3aab722e06feee48340774470e9c41b6bed3e04 +size 8283 diff --git a/tasks/ozturk2020/gurobi_solution/large_solution_3.json b/tasks/ozturk2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ea3b059a6d50ec8cd264b03ce1123f8e09237b78 --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab5cf824e7a9a8a3601f12f9a8bc73e8c1958cf9ce08b3921cbe80961222c8bb +size 11743 diff --git a/tasks/ozturk2020/gurobi_solution/large_solution_4.json b/tasks/ozturk2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e3f0d15c90c92cd391cb779de7b13ad4ebe98eda --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5e2d9f37aed6569eaaf0a3680bc6432a1373868269b02f3f556649db238d701 +size 7343 diff --git a/tasks/ozturk2020/gurobi_solution/large_solution_5.json b/tasks/ozturk2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..99451e5152c6845b4d5736a7d57b22b18198be73 --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a72f242f9c185b31ae110da2b62e3e91706a9d9c2e87b1cc530172cf03bc977e +size 7730 diff --git a/tasks/ozturk2020/gurobi_solution/tiny_solution.json b/tasks/ozturk2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..2f5c1164590266730841f20dc6e4c130ff6ae37c --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98096ab3e1a0f7b2ef5350e57fb6d5525b88c05eecf129a9733c7094e1c38e96 +size 1356 diff --git a/tasks/ozturk2020/gurobi_solution/tiny_solution_2.json b/tasks/ozturk2020/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..34b41e7aea9bbfa87b2119f6764a386cc7afa8f9 --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87efc379cc16e7e3840deb9a94c7cb69c975ca22e08d43b1f036b16dc44ea190 +size 1632 diff --git a/tasks/ozturk2020/gurobi_solution_log/large_log_1.jsonl b/tasks/ozturk2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd00c3361290f7cc29386936ae689aaa9f6f92e4 --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7888b3f5ed9d08a96967b44782ed6dba6e7a637c936f8a7b36830d8d460e81b5 +size 1067 diff --git a/tasks/ozturk2020/gurobi_solution_log/large_log_2.jsonl b/tasks/ozturk2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3c0c42d3da1adf3397b683049085d0ea58fc54a5 --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:abe8576a43beca34ab418b8c5a5654caacee85c6b807c5efd4958831ae484e70 +size 2589 diff --git a/tasks/ozturk2020/gurobi_solution_log/large_log_3.jsonl b/tasks/ozturk2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..13ca6336bf2a537b8265182f3f0f80cee441a803 --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be2b3df77b191c234bbc268fac41f27f5383b6c4d2347e0766a908b9fbda76a9 +size 1528 diff --git a/tasks/ozturk2020/gurobi_solution_log/large_log_4.jsonl b/tasks/ozturk2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..06f06f175dd6c0fb54ed45c8badc049c66944e53 --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd64c6a641743f69e60e5ff6b44c6d2a0e245da651997ce799e40bfc2766047c +size 1678 diff --git a/tasks/ozturk2020/gurobi_solution_log/large_log_5.jsonl b/tasks/ozturk2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2653b62edce3627f0e8fdc6eed6a74e5e54e06f5 --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a9d869707979eaae1bd3d2c021003ba805904e7d39d9968f1b277833cc37f90 +size 1809 diff --git a/tasks/ozturk2020/gurobi_solution_log/tiny_log.jsonl b/tasks/ozturk2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..04f057e24b9bb9c1db056ee5453b370acf73241d --- /dev/null +++ b/tasks/ozturk2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7ff94bd8e06d2a9575a53e150190e4db7890d8ebc77566a98738eb23265b25c +size 41 diff --git a/tasks/ozturk2020/instance/large_instance_1.json b/tasks/ozturk2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..155a364546212c0d29e08db3e135dfdb5fece4b8 --- /dev/null +++ b/tasks/ozturk2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d5bd7d2f321cf4826f32968f3842740443cfe15e42bc324dbb656863925b2c9 +size 5374 diff --git a/tasks/ozturk2020/instance/large_instance_2.json b/tasks/ozturk2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a502d15cbb003507f54f355773993f314d2c2fba --- /dev/null +++ b/tasks/ozturk2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e74d7fc7e0115138f3102764f63fe3fd3ce79d74789882f76192df9776a1fed +size 5416 diff --git a/tasks/ozturk2020/instance/large_instance_3.json b/tasks/ozturk2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..66812f900ecd899a11db109237fa9cf08b90f8c5 --- /dev/null +++ b/tasks/ozturk2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f478a1be774cf129f2f7538c1000837d83cb002b3ad91b176fda3341f29afd3 +size 5463 diff --git a/tasks/ozturk2020/instance/large_instance_4.json b/tasks/ozturk2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..0b89132b21a383b3e5d9e8c044273dd8957fe7ca --- /dev/null +++ b/tasks/ozturk2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:27002d9c630874bacbe1a029ccf2ad67745f45df413d9060d0f5bff03afe5882 +size 5363 diff --git a/tasks/ozturk2020/instance/large_instance_5.json b/tasks/ozturk2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..5440b057988d3a720b718414d1471dcbe89340ed --- /dev/null +++ b/tasks/ozturk2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e499a42da1f99d85ebb8f7f544859277470b80e32513b40585ef1f9a037d69e3 +size 5343 diff --git a/tasks/ozturk2020/instance/tiny_instance.json b/tasks/ozturk2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..b353542768e95bbd769b7f076affa9619e260f59 --- /dev/null +++ b/tasks/ozturk2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20a419af16ede022e741028db3fbc17ea124854fdc08e25a3c60481fb24d7377 +size 852 diff --git a/tasks/ozturk2020/instance/tiny_instance_2.json b/tasks/ozturk2020/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c8a17eed0e06b4f5c369cbac35fdf3c6b662ff5b --- /dev/null +++ b/tasks/ozturk2020/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60f31fb71de45992a347e95138413d2a8e1d3d722fb46da911cb7b1ac5d8bd97 +size 1255 diff --git a/tasks/ozturk2020/instance_schema.json b/tasks/ozturk2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e314bbd51caf8571c271f0cca36ea3c71d767af9 --- /dev/null +++ b/tasks/ozturk2020/instance_schema.json @@ -0,0 +1,13 @@ +{ + "num_jobs": " Total number of jobs to be processed across all machines.", + "num_machines": " Number of identical parallel batch-processing machines available.", + "batch_capacity": " Maximum total size of jobs that can be processed together in a single batch.", + "jobs": [ + { + "job_id": " Unique identifier for the job.", + "release_date": " Earliest time at which the job becomes available for processing.", + "processing_time": " Duration required to process the job.", + "size": " Amount of machine capacity the job consumes when assigned to a batch." + } + ] +} diff --git a/tasks/ozturk2020/mathematical_formulation.md b/tasks/ozturk2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..4515d8ae5f082ceb64e4e47d6d2471c60e61428d --- /dev/null +++ b/tasks/ozturk2020/mathematical_formulation.md @@ -0,0 +1,49 @@ +# Original Formulation: Parallel Batch Scheduling to Minimize Total Flow Time + +**Source.** Ozturk (2020), “A truncated column generation algorithm for the parallel batch scheduling problem to minimize total flow time,” Section 3 (straightforward MILP), equations (1)–(7). + +**Problem.** $P\,/\,p\text{-Batch},\,r_j,\,p_j,\,v_j,\,\mathrm{Cap}\,/\,\sum C_j$. + +## Sets and Indices + +- $j = 1,\ldots,N$ — jobs. + +- $k = 1,\ldots,N$ — batches (up to $N$ batches may be needed). + +- $m = 1,\ldots,M$ — machines. + +## Parameters + +$r_j$ release date, $p_j$ processing time, $v_j$ size of job $j$; $\mathrm{Cap}$ batch/machine capacity; $Q$ a sufficiently large big-M constant. + +## Decision Variables + +$$\begin{align*} +& x_{jkm} \in \{0,1\} && \text{$=1$ iff job $j$ is processed in batch $k$ on machine $m$} \\ +& p_{km} \ge 0 && \text{processing duration of batch $k$ on machine $m$} \\ +& S_{km} \ge 0 && \text{start time of batch $k$ on machine $m$} \\ +& C_j \ge 0 && \text{completion (flow) time of job $j$} +\end{align*}$$ + +## Formulation + +$$\begin{align} +\min\ & \sum_{j=1}^{N} C_j \tag{1}\\[2pt] +\text{s.t.}\ +& \sum_{k=1}^{N}\sum_{m=1}^{M} x_{jkm} \;=\; 1 + && \forall\, j=1,\ldots,N \tag{2}\\ +& \sum_{j=1}^{N} v_j\,x_{jkm} \;\le\; \mathrm{Cap} + && \forall\, k=1,\ldots,N,\ m=1,\ldots,M \tag{3}\\ +& p_{km} \;\ge\; p_j\,x_{jkm} + && \forall\, j,k=1,\ldots,N,\ m=1,\ldots,M \tag{4}\\ +& S_{km} \;\ge\; r_j\,x_{jkm} + && \forall\, j,k=1,\ldots,N,\ m=1,\ldots,M \tag{5}\\ +& S_{km} \;\ge\; S_{k-1,m} + p_{k-1,m} + && \forall\, k=2,\ldots,N,\ m=1,\ldots,M \tag{6}\\ +& C_j \;\ge\; (S_{km} + p_{km}) - Q(1 - x_{jkm}) + && \forall\, j,k=1,\ldots,N,\ m=1,\ldots,M \tag{7}\\ +& x_{jkm} \in \{0,1\},\ p_{km},S_{km},C_j \ge 0 + && \forall\, j,k,m.\notag +\end{align}$$ + +\(1\) minimises total flow time. (2) assigns each job to exactly one batch on one machine. (3) enforces batch capacity. (4) makes the batch duration at least as long as the processing time of any job it contains. (5) makes the batch start no earlier than any of its jobs’ release dates. (6) enforces sequential non-overlap of consecutive batches on the same machine. (7) defines the completion time of each job through the start/duration of the batch that contains it, linearized by big-$Q$. diff --git a/tasks/ozturk2020/problem_description.txt b/tasks/ozturk2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..4911a4e77f462704e93c48eaa5a9b6752ca419f0 --- /dev/null +++ b/tasks/ozturk2020/problem_description.txt @@ -0,0 +1,3 @@ +# Problem Description + +A facility operates M identical parallel batch-processing machines, each with the same capacity Cap. There are N jobs to be processed, and each job has three attributes: a release date (the earliest time at which the job becomes available for processing), a processing time, and a size (an integer quantity representing how much of a machine's capacity the job consumes). Jobs must be grouped into batches and each batch is assigned to exactly one machine. Every job must appear in exactly one batch on exactly one machine. The total size of all jobs assigned to a given batch must not exceed Cap. All jobs in the same batch are processed simultaneously: the batch begins processing at a single start time and runs for a single duration, after which every job in that batch is complete. The processing duration of a batch equals the longest processing time among the jobs it contains; specifically, the batch duration must be at least as large as the processing time of every job assigned to that batch. The start time of a batch must be no earlier than the release date of every job assigned to that batch, ensuring that no job is processed before it becomes available. On each machine, batches are processed sequentially in a fixed order indexed from one up to at most N (since at most N batches can exist). For every pair of consecutively indexed batches on the same machine, the later batch cannot start before the earlier batch has finished, meaning the start time of each batch is at least the start time of the preceding batch on that machine plus the preceding batch's processing duration. The completion time of each job equals the finish time of the batch it belongs to, that is, the start time of that batch plus the batch's processing duration. The goal is to minimize the total flow time, defined as the sum of completion times across all N jobs. diff --git a/tasks/ozturk2020/solution_logger.py b/tasks/ozturk2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/ozturk2020/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/ozturk2020/solution_schema.json b/tasks/ozturk2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..ea2bd257a676bef8fcbb3463b61feef8ad923b4d --- /dev/null +++ b/tasks/ozturk2020/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total flow time, equal to the sum of completion times across all jobs.", + "batches": " One entry per non-empty batch that is actually used, where 'batch_id' is the batch's sequential position on its machine, 'machine' is the machine on which the batch runs, 'start_time' is the time at which the batch begins processing, 'processing_time' is the batch's processing duration (the longest processing time among its jobs), and 'jobs' is the list of job ids assigned to the batch.", + "job_assignments": " For each job, 'batch' is the sequential batch index on its machine, 'machine' is the machine that processes the job, and 'completion_time' is the time at which the job finishes processing." +} diff --git a/tasks/pecin2017/feasibility_check.py b/tasks/pecin2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc605ccb12b55ac066a98ffe2cfd8017ecbab90 --- /dev/null +++ b/tasks/pecin2017/feasibility_check.py @@ -0,0 +1,430 @@ +#!/usr/bin/env python3 +""" +feasibility_check.py + +Feasibility checker for VRPTW solutions based on Pecin et al. (2017). +Checks all hard constraints from the mathematical formulation in math_model.txt. + +Constraint numbering (top to bottom in formulation): + 1: Objective (min total route cost) — not a constraint, skip + 2: Customer coverage: each customer visited exactly once + 3: Binary lambda_r — satisfied by construction (route list) + 4: Pricing objective — not a constraint, skip + 5: Depot flow: route starts at depot 0, ends at depot n+1 + 6: Flow conservation at customer nodes + 7: Vehicle capacity per route + 8: Time propagation on active arcs + 9: Time windows at all nodes + 10: Binary x_{ij} — satisfied by construction + 11-18: Valid inequalities (RCC, 2PC, SRC, rank-1, elementary) — implied by + integer feasibility of (2)-(3) with feasible routes; checking all + subsets is computationally intractable (exponential). + Constraint 13 is a reduced-cost formula definition, not a constraint. + 19: Objective consistency — reported objective_value must equal the + Euclidean travel cost summed over all arcs in the given routes + (Tier C defense against LLM score-gaming exploits that fabricate + objective_value while keeping the route structure feasible). +""" + +import argparse +import json +import math + + +def euclidean(x1, y1, x2, y2): + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + 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") + if "routes" not in solution or not isinstance(solution["routes"], list): + schema_errors.append("routes must be a list") + if schema_errors: + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": schema_errors, + "violation_magnitudes": [], + } + + nodes = instance["nodes"] + n_nodes = instance["problem_parameters"]["n_nodes"] + n_customers = instance["problem_parameters"]["n_customers"] + Q = instance["problem_parameters"]["vehicle_capacity"] + H = instance["problem_parameters"]["planning_horizon"] + + depot_source = 0 + depot_sink = n_nodes - 1 + customers = list(range(1, n_customers + 1)) + + # Extract node data + node_x = [0.0] * n_nodes + node_y = [0.0] * n_nodes + demand = [0.0] * n_nodes + tw_open = [0.0] * n_nodes + tw_close = [float(H)] * n_nodes + svc = [0.0] * n_nodes + + for node in nodes: + i = node["id"] + node_x[i] = node["x"] + node_y[i] = node["y"] + demand[i] = node["demand"] + tw_open[i] = node["time_window_open"] + tw_close[i] = node["time_window_close"] + svc[i] = node["service_time"] + + def dist(i, j): + return euclidean(node_x[i], node_y[i], node_x[j], node_y[j]) + + routes = solution.get("routes", []) + + violations = [] + violation_magnitudes = [] + violated_constraints = set() + + # ========================================================================= + # Constraint 2: Customer coverage (equality) + # sum_r a^r_i * lambda_r = 1, for all i in V+ + # ========================================================================= + visit_count = {c: 0 for c in customers} + for route in routes: + for node_id in route: + if 1 <= node_id <= n_customers: + visit_count[node_id] += 1 + + for c in customers: + cnt = visit_count[c] + violation_amount = abs(cnt - 1) + if violation_amount > tol: + violated_constraints.add(2) + rhs = 1.0 + normalizer = max(abs(rhs), eps) + if cnt == 0: + violations.append( + f"Constraint 2: Customer {c} is not visited by any route") + else: + violations.append( + f"Constraint 2: Customer {c} is visited {cnt} times " + f"instead of exactly once") + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(cnt), + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # ========================================================================= + # Constraint 3: Binary lambda_r + # Satisfied by construction — routes are either in the list or not. + # ========================================================================= + + # ========================================================================= + # Constraint 5: Depot flow + # sum_{(0,j)} x_{0j} = sum_{(i,n+1)} x_{i,n+1} = 1 (per route) + # Each route must start at depot_source and end at depot_sink. + # ========================================================================= + for r_idx, route in enumerate(routes): + if len(route) < 2: + violated_constraints.add(5) + violations.append( + f"Constraint 5: Route {r_idx} has fewer than 2 nodes") + violation_magnitudes.append({ + "constraint": 5, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0 + }) + continue + + if route[0] != depot_source: + violated_constraints.add(5) + violations.append( + f"Constraint 5: Route {r_idx} does not start at depot source " + f"(node {depot_source}), starts at node {route[0]}") + violation_magnitudes.append({ + "constraint": 5, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0 + }) + + if route[-1] != depot_sink: + violated_constraints.add(5) + violations.append( + f"Constraint 5: Route {r_idx} does not end at depot sink " + f"(node {depot_sink}), ends at node {route[-1]}") + violation_magnitudes.append({ + "constraint": 5, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0 + }) + + # ========================================================================= + # Constraint 6: Flow conservation at customer nodes + # sum_{(i,j)} x_{ij} - sum_{(j,i)} x_{ji} = 0, for all i in V+ + # In route representation: no depot node should appear in route interior. + # ========================================================================= + for r_idx, route in enumerate(routes): + for pos in range(1, len(route) - 1): + node_id = route[pos] + if node_id == depot_source or node_id == depot_sink: + violated_constraints.add(6) + violations.append( + f"Constraint 6: Route {r_idx} has depot node {node_id} " + f"at interior position {pos}") + violation_magnitudes.append({ + "constraint": 6, + "lhs": 1.0, + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": eps, + "ratio": 1.0 / eps + }) + + # ========================================================================= + # Constraint 7: Vehicle capacity (<=) + # sum_{(i,j) in A} d_i * x_{ij} <= Q (per route) + # ========================================================================= + for r_idx, route in enumerate(routes): + total_demand = sum(demand[node_id] for node_id in route) + lhs = total_demand + rhs = float(Q) + violation_amount = max(0.0, lhs - rhs) + if violation_amount > tol: + violated_constraints.add(7) + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 7: Route {r_idx} total demand {lhs:.1f} " + f"exceeds vehicle capacity {rhs:.1f}") + violation_magnitudes.append({ + "constraint": 7, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # ========================================================================= + # Constraint 8: Time propagation on active arcs (<=) + # x_{ij}(T_i + s_i + t_{ij}) <= T_j, for all (i,j) in A + # For active arcs: T_i + s_i + t_{ij} <= T_j + # + # Constraint 9: Time windows (bounds) + # e_i <= T_i <= l_i, for all i in V + # + # We compute T_k = max(e_{route[k]}, T_{k-1} + svc[route[k-1]] + dist(...)) + # By construction, constraint 8 (T_i + s_i + t_{ij} <= T_j) is always + # satisfied. The only possible violations are in constraint 9 (T_i > l_i). + # ========================================================================= + for r_idx, route in enumerate(routes): + if len(route) < 2: + continue + + # Compute service start times along the route + T = [0.0] * len(route) + T[0] = tw_open[route[0]] + + for k in range(1, len(route)): + i_node = route[k - 1] + j_node = route[k] + arrival = T[k - 1] + svc[i_node] + dist(i_node, j_node) + T[k] = max(tw_open[j_node], arrival) + + # Check constraint 8: T_i + s_i + t_{ij} <= T_j for active arcs + for k in range(1, len(route)): + i_node = route[k - 1] + j_node = route[k] + lhs = T[k - 1] + svc[i_node] + dist(i_node, j_node) + rhs_val = T[k] + violation_amount = max(0.0, lhs - rhs_val) + if violation_amount > tol: + violated_constraints.add(8) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Constraint 8: Route {r_idx}, arc ({i_node},{j_node}): " + f"arrival {lhs:.4f} > service start {rhs_val:.4f}") + violation_magnitudes.append({ + "constraint": 8, + "lhs": lhs, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # Check constraint 9: e_i <= T_i <= l_i + for k in range(len(route)): + node_id = route[k] + + # Lower bound: T_i >= e_i (>= constraint) + lb_violation = max(0.0, tw_open[node_id] - T[k]) + if lb_violation > tol: + violated_constraints.add(9) + normalizer = max(abs(tw_open[node_id]), eps) + violations.append( + f"Constraint 9: Route {r_idx}, node {node_id}: " + f"service start {T[k]:.4f} < earliest {tw_open[node_id]:.4f}") + violation_magnitudes.append({ + "constraint": 9, + "lhs": tw_open[node_id], + "rhs": T[k], + "raw_excess": lb_violation, + "normalizer": normalizer, + "ratio": lb_violation / normalizer + }) + + # Upper bound: T_i <= l_i (<= constraint) + ub_violation = max(0.0, T[k] - tw_close[node_id]) + if ub_violation > tol: + violated_constraints.add(9) + normalizer = max(abs(tw_close[node_id]), eps) + violations.append( + f"Constraint 9: Route {r_idx}, node {node_id}: " + f"service start {T[k]:.4f} > latest {tw_close[node_id]:.4f}") + violation_magnitudes.append({ + "constraint": 9, + "lhs": T[k], + "rhs": tw_close[node_id], + "raw_excess": ub_violation, + "normalizer": normalizer, + "ratio": ub_violation / normalizer + }) + + # ========================================================================= + # Constraint 10: Binary x_{ij} — satisfied by construction. + # ========================================================================= + + # ========================================================================= + # Constraints 11-18: Valid inequalities (RCC, 2PC, rank-1, elementary). + # These are cutting planes parameterized by customer subsets S ⊆ V+. + # For integer feasible solutions satisfying constraints (2)-(10), these + # are automatically satisfied. Enumerating all subsets is intractable. + # Constraint 13 is a reduced-cost formula, not a constraint. + # ========================================================================= + + # ========================================================================= + # Constraint 19: Objective consistency (Tier C anti-score-gaming check). + # Recompute the total Euclidean travel cost from the given routes and + # verify it matches the reported objective_value. The solution contains + # every variable the objective formula c_r = sum c_{ij} depends on + # (the full route sequences), so a full recompute is exact. + # ========================================================================= + 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 route in routes: + for k in range(1, len(route)): + true_obj += dist(route[k - 1], route[k]) + 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(19) + normalizer = max(abs(true_obj), eps) + violations.append( + f"Constraint 19: Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"recomputed total route cost={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={obj_tol:.6g})") + violation_magnitudes.append({ + "constraint": 19, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer + }) + elif reported is not None: + # Non-finite reported obj (inf/nan): always reject. + true_obj = 0.0 + for route in routes: + for k in range(1, len(route)): + true_obj += dist(route[k - 1], route[k]) + violated_constraints.add(19) + normalizer = max(abs(true_obj), eps) + violations.append( + f"Constraint 19: Objective consistency violated: " + f"reported objective_value={reported} is not finite; " + f"recomputed total route cost={true_obj}") + violation_magnitudes.append({ + "constraint": 19, + "lhs": reported, + "rhs": true_obj, + "raw_excess": float("inf"), + "normalizer": normalizer, + "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="VRPTW Feasibility Checker") + parser.add_argument("--instance_path", required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", required=True, + help="Path to the JSON solution file.") + parser.add_argument("--result_path", required=True, + help="Path to write the JSON feasibility result.") + args = parser.parse_args() + + with open(args.instance_path) as f: + instance = json.load(f) + with open(args.solution_path) as f: + solution = json.load(f) + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: " + f"{result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + main() diff --git a/tasks/pecin2017/gurobi_code.py b/tasks/pecin2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..3a46cbe46aef16beb86f582d84d9257c1de49433 --- /dev/null +++ b/tasks/pecin2017/gurobi_code.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python3 +""" +gurobi_code.py + +Compact arc-flow MIP formulation for the Vehicle Routing Problem with Time Windows (VRPTW). + +Paper: Pecin, Contardo, Desaulniers, Uchoa (2017) + "New Enhancements for the Exact Solution of the Vehicle Routing Problem + with Time Windows" + INFORMS Journal on Computing, Vol. 29, No. 3, pp. 489-502. + +Mathematical model source: math_model.txt + +IMPLEMENTATION NOTE: +The paper's master problem (1)-(3) is a Set Partitioning Formulation (SPF) with an +exponential number of variables (one per feasible route). It cannot be solved directly +by a MIP solver without column generation. Since column generation requires a specialized +BPC framework, we implement the equivalent compact arc-flow MIP formulation here. + +INFERRED ASSUMPTION: We use the standard compact arc-flow MIP with: + - Binary arc variables x_{ij} in {0,1} + - Continuous service-start-time variables T_i + - Continuous cumulative-load variables u_i (MTZ-style subtour/capacity elimination) +This is mathematically equivalent to the pricing subproblem (4)-(10) extended to a +full multi-vehicle setting, and yields the same optimal solution as the SPF. + +The big-M value for time propagation is set to H (the planning horizon), which is a +valid upper bound since T_i <= l_i <= H for all nodes. +""" + +import argparse +import json +import math +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def euclidean(xi, yi, xj, yj): + return math.sqrt((xi - xj) ** 2 + (yi - yj) ** 2) + + +def load_instance(path): + with open(path) as f: + return json.load(f) + + +def solve(instance, time_limit): + """ + Build and solve the compact VRPTW MIP with Gurobi. + Returns a solution dict with 'objective_value' and route information. + """ + nodes = instance["nodes"] + n_nodes = instance["problem_parameters"]["n_nodes"] + n_customers = instance["problem_parameters"]["n_customers"] + Q = instance["problem_parameters"]["vehicle_capacity"] + H = instance["problem_parameters"]["planning_horizon"] + + # Node indexing: 0 = depot source, 1..n = customers, n+1 = depot sink + depot_source = 0 + depot_sink = n_nodes - 1 # = n+1 in paper notation + customers = list(range(1, n_customers + 1)) + customers_set = set(customers) + + # Extract node attributes + node_x = [0.0] * n_nodes + node_y = [0.0] * n_nodes + demand = [0.0] * n_nodes + e = [0.0] * n_nodes # time window open (earliest service start) + l = [float(H)] * n_nodes # time window close (latest service start) + svc = [0.0] * n_nodes # service time + + for node in nodes: + i = node["id"] + node_x[i] = node["x"] + node_y[i] = node["y"] + demand[i] = node["demand"] + e[i] = node["time_window_open"] + l[i] = node["time_window_close"] + svc[i] = node["service_time"] + + # Travel cost c_{ij} = travel time t_{ij} = Euclidean distance (per paper Section 1) + dist = {} + for i in range(n_nodes): + for j in range(n_nodes): + if i != j: + dist[i, j] = euclidean(node_x[i], node_y[i], node_x[j], node_y[j]) + + # Feasible arc set A (Section 2 of paper, math_model.txt): + # A = {(i,j): i in V\{n+1}, j in V\{0}, i != j, + # d_i + d_j <= Q, e_i + s_i + t_{ij} <= l_j} + A = [] + out_nbrs = defaultdict(list) + in_nbrs = defaultdict(list) + for i in range(n_nodes - 1): # i in V\{n+1} + for j in range(1, n_nodes): # j in V\{0} + if i == j: + continue + if demand[i] + demand[j] <= Q: + if e[i] + svc[i] + dist[i, j] <= l[j]: + A.append((i, j)) + out_nbrs[i].append(j) + in_nbrs[j].append(i) + + # --------------------------------------------------------------------------- + # Build Gurobi model + # --------------------------------------------------------------------------- + model = gp.Model("VRPTW_compact_arcflow") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # --- Decision variables --- + + # x[i,j] in {0,1}: 1 if arc (i,j) is used (eq. 10) + x = model.addVars(A, vtype=GRB.BINARY, name="x") + + # T[i] >= 0: service start time at node i (eq. 9) + T = model.addVars(range(n_nodes), lb=0.0, ub=H, vtype=GRB.CONTINUOUS, name="T") + + # u[i] >= 0: cumulative load when vehicle leaves node i + # INFERRED ASSUMPTION: MTZ-style load variable for capacity/subtour elimination. + # u[depot_source] = 0; for customers: demand[i] <= u[i] <= Q. + u = model.addVars(range(n_nodes), lb=0.0, ub=Q, vtype=GRB.CONTINUOUS, name="u") + + # --- Objective: minimize total travel cost (eq. 1 restated as arc costs) --- + model.setObjective( + gp.quicksum(dist[i, j] * x[i, j] for (i, j) in A), + GRB.MINIMIZE + ) + + # --- Constraints --- + + # Each customer visited exactly once: in-flow = 1 (equivalent to eq. 2) + for c in customers: + if in_nbrs[c]: + model.addConstr( + gp.quicksum(x[i, c] for i in in_nbrs[c]) == 1, + name=f"visit_in_{c}" + ) + + # Each customer visited exactly once: out-flow = 1 + for c in customers: + if out_nbrs[c]: + model.addConstr( + gp.quicksum(x[c, j] for j in out_nbrs[c]) == 1, + name=f"visit_out_{c}" + ) + + # Depot balance: number of vehicles departing = number arriving (eq. 5) + model.addConstr( + gp.quicksum(x[depot_source, j] for j in out_nbrs[depot_source]) == + gp.quicksum(x[i, depot_sink] for i in in_nbrs[depot_sink]), + name="depot_balance" + ) + + # Time propagation: if x[i,j]=1 then T[j] >= T[i] + svc[i] + dist[i,j] (eq. 8) + # Linearized via big-M = H (valid upper bound on time variables) + M_time = H + for (i, j) in A: + model.addConstr( + T[i] + svc[i] + dist[i, j] <= T[j] + M_time * (1 - x[i, j]), + name=f"tw_prop_{i}_{j}" + ) + + # Time window bounds at all nodes (eq. 9) + for i in range(n_nodes): + model.addConstr(T[i] >= e[i], name=f"tw_lb_{i}") + model.addConstr(T[i] <= l[i], name=f"tw_ub_{i}") + + # Capacity via MTZ-style constraints (equiv. to eq. 7): + # Depot source has zero initial load + model.addConstr(u[depot_source] == 0.0, name="load_depot_source") + + # Customer load bounds + for c in customers: + model.addConstr(u[c] >= demand[c], name=f"load_lb_{c}") + # Upper bound u[c] <= Q already set in variable definition + + # MTZ capacity propagation: if x[i,j]=1 then u[j] >= u[i] + demand[j] + # Linearized: u[j] >= u[i] + demand[j] - Q*(1 - x[i,j]) + for (i, j) in A: + if j in customers_set: + model.addConstr( + u[j] >= u[i] + demand[j] - Q * (1 - x[i, j]), + name=f"cap_mtz_{i}_{j}" + ) + + # --------------------------------------------------------------------------- + # Solve + # --------------------------------------------------------------------------- + model.optimize() + + # --------------------------------------------------------------------------- + # Extract and return solution + # --------------------------------------------------------------------------- + status = model.Status + has_solution = (status == GRB.OPTIMAL) or ( + status == GRB.TIME_LIMIT and model.SolCount > 0 + ) + + if not has_solution: + return { + "objective_value": None, + "status": "no_feasible_solution", + "routes": [], + "n_routes": 0 + } + + obj_val = model.ObjVal + + # Extract active arcs (x[i,j] > 0.5 in best incumbent) + active_arcs = [(i, j) for (i, j) in A if x[i, j].X > 0.5] + + # Build adjacency list for route extraction + adj = defaultdict(list) + for (i, j) in active_arcs: + adj[i].append(j) + + # Extract individual routes (paths from depot_source to depot_sink) + routes = [] + while adj[depot_source]: + j = adj[depot_source].pop(0) + route = [depot_source, j] + cur = j + while cur != depot_sink: + if not adj[cur]: + break # should not happen in a feasible solution + nxt = adj[cur].pop(0) + route.append(nxt) + cur = nxt + routes.append(route) + + status_str = "optimal" if status == GRB.OPTIMAL else "time_limit" + + return { + "objective_value": obj_val, + "status": status_str, + "routes": routes, + "n_routes": len(routes) + } + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi compact arc-flow MIP solver for VRPTW " + "(Pecin et al. 2017)" + ) + parser.add_argument( + "--instance_path", required=True, + help="Path to the JSON file containing the problem instance." + ) + parser.add_argument( + "--solution_path", required=True, + help="Path where the final solution JSON file will be written " + "(e.g., gurobi_solution_1.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) + + instance = load_instance(args.instance_path) + solution = 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) + + print(f"Solution written to {args.solution_path}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']:.4f}") + print(f"Status: {solution['status']}") + print(f"Number of routes: {solution['n_routes']}") + else: + print("No feasible solution found within the time limit.") + + +if __name__ == "__main__": + main() diff --git a/tasks/pecin2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/pecin2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pecin2017/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/pecin2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/pecin2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pecin2017/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/pecin2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/pecin2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pecin2017/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/pecin2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/pecin2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pecin2017/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/pecin2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/pecin2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pecin2017/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/pecin2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/pecin2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pecin2017/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/pecin2017/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/pecin2017/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pecin2017/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/pecin2017/gurobi_solution/large_solution_1.json b/tasks/pecin2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f74e38bdfaf759570d8f8934ae26ba70bbd056ef --- /dev/null +++ b/tasks/pecin2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7e7be7d5f0ed2d7426111fc0d605bd9e294ed7f77d2146d3348d38cf309f8b8 +size 2604 diff --git a/tasks/pecin2017/gurobi_solution/large_solution_2.json b/tasks/pecin2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..fe05d50cb7d08787c5d7b5ac6d9057310929d3a9 --- /dev/null +++ b/tasks/pecin2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e607499413307f690cc841aef2974e95497705e9cab99f097eab7c4c23be6fd7 +size 3371 diff --git a/tasks/pecin2017/gurobi_solution/large_solution_3.json b/tasks/pecin2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1413dd881056402210a32f54570a1dc70f6691f6 --- /dev/null +++ b/tasks/pecin2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd060637d5f6e7500558b05f65797409569bea1b0a22ff4aee8f3ee1088f6203 +size 3436 diff --git a/tasks/pecin2017/gurobi_solution/large_solution_4.json b/tasks/pecin2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..69ddb14a4172a93cb42a53c9ac49559c8f7df02f --- /dev/null +++ b/tasks/pecin2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76b7d5eca0cd33d743715e4d2ebf0ae368e9f7ac5cbac43fe02f3c4a3bd94d69 +size 2539 diff --git a/tasks/pecin2017/gurobi_solution/large_solution_5.json b/tasks/pecin2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..83a74ae2b0e412db82ca4aa1270883ed9dc801e9 --- /dev/null +++ b/tasks/pecin2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:284be832fba24e55ab8b783632597218c6c5759607f7b396f3512a55e3444c85 +size 2572 diff --git a/tasks/pecin2017/gurobi_solution/tiny_solution.json b/tasks/pecin2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..7a5fd09a3bc3f9b2efd054e2ee735c7eb810946f --- /dev/null +++ b/tasks/pecin2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14a5f9203e0de583c37ea98cb53f6cf63a0ab6a67ba1a5c606228dba182f6737 +size 467 diff --git a/tasks/pecin2017/gurobi_solution/tiny_solution_2.json b/tasks/pecin2017/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..0411703f89deda7aa658400980292e076906b7c9 --- /dev/null +++ b/tasks/pecin2017/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c2c5fa8cde6dec0f8b4d7aed120ed0338e0b4fbd67f421545710046637f4e17 +size 1802 diff --git a/tasks/pecin2017/gurobi_solution_log/tiny_log.jsonl b/tasks/pecin2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dd0b36d4d0cf253366471c860b6d2c4b46fc6ad3 --- /dev/null +++ b/tasks/pecin2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dcdbcafe90c232769ce7746d0dfe2d9d079d61f2433f5b6acd0108b80d4c4c3a +size 217 diff --git a/tasks/pecin2017/instance/large_instance_1.json b/tasks/pecin2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3ceb69bd30798be7eb22391a5395516110e84e55 --- /dev/null +++ b/tasks/pecin2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24797b09af25f939066435d1353ea241781cc719f1f596f3111a94d2eee39c77 +size 41176 diff --git a/tasks/pecin2017/instance/large_instance_2.json b/tasks/pecin2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..478c3f0b25021498b7220f8f2b202d0a0392d3a3 --- /dev/null +++ b/tasks/pecin2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:654338f445ad43a00e98890dae6a2c2ec69afd8abe3ddaa1d7ca7ac2ef921ed9 +size 41007 diff --git a/tasks/pecin2017/instance/large_instance_3.json b/tasks/pecin2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..fd5381c06366e8ee72c3812292e0516aad0020d6 --- /dev/null +++ b/tasks/pecin2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afeef6b3aae4792376f6dbcfa9d7c3a0a1a7d2274c5cf12c1355858fa732cfae +size 41015 diff --git a/tasks/pecin2017/instance/large_instance_4.json b/tasks/pecin2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..bfe51584cf8372f929d1b55c2a57d10d1e7b351e --- /dev/null +++ b/tasks/pecin2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef85418ddbd0267f8427038c7d3a9b3bb5612299cb10aaabaaa330db6589a420 +size 41204 diff --git a/tasks/pecin2017/instance/large_instance_5.json b/tasks/pecin2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..1975a090c531772a0db3cfe5af6e2720938272a8 --- /dev/null +++ b/tasks/pecin2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0bd79eda2b5226faea65d3bcd2e99789828e7b327dee8ef29a287a39240456ce +size 41176 diff --git a/tasks/pecin2017/instance/tiny_instance.json b/tasks/pecin2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c131c3267b3c20fd06a4a2fe7ada54160fcd9c09 --- /dev/null +++ b/tasks/pecin2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52e55a08e8fb458ad639ea892acda8ddc9ee0bb4e112f76d2f64c6e2d33e4999 +size 5110 diff --git a/tasks/pecin2017/instance/tiny_instance_2.json b/tasks/pecin2017/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..76c81aff460beb3c2d53b0c12f6f6c526baeaa8b --- /dev/null +++ b/tasks/pecin2017/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05dcd9f3d8696be83213b1b3f9e74fcdb913631ff6894f51f022b7e89ab443f2 +size 20973 diff --git a/tasks/pecin2017/instance_schema.json b/tasks/pecin2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..964a7e18e3f97ef84423818d253c17b8bb745398 --- /dev/null +++ b/tasks/pecin2017/instance_schema.json @@ -0,0 +1,22 @@ +{ + "problem_parameters": { + "n_nodes": " Total number of nodes including the depot source, all customers, and the depot sink.", + "n_customers": " Number of customers that must be served.", + "vehicle_capacity": " Maximum total demand that a single vehicle can carry on one route.", + "planning_horizon": " Latest time by which all vehicles must return to the depot.", + "travel_cost_type": " Method used to compute travel cost between every pair of locations.", + "travel_time_type": " Method used to compute travel time between every pair of locations." + }, + "nodes": [ + { + "id": " Unique index of this node in the node list.", + "type": " Role of this node: 'depot_source' for the starting depot, 'customer' for a delivery location, or 'depot_sink' for the return depot.", + "x": " Horizontal coordinate of this node in the two-dimensional plane.", + "y": " Vertical coordinate of this node in the two-dimensional plane.", + "demand": " Quantity of goods that must be delivered to this node.", + "service_time": " Time a vehicle must spend at this node once service begins.", + "time_window_open": " Earliest time at which service may begin at this node.", + "time_window_close": " Latest time at which service may begin at this node." + } + ] +} diff --git a/tasks/pecin2017/mathematical_formulation.md b/tasks/pecin2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..d2aef68b23188e4f0bc7c5dc8c8f0a34d1a257f4 --- /dev/null +++ b/tasks/pecin2017/mathematical_formulation.md @@ -0,0 +1,51 @@ +# Original Formulation: Vehicle Routing Problem with Time Windows (VRPTW) + +*Source: New Enhancements for the Exact Solution of the Vehicle Routing Problem with Time Windows, Diego Pecin, Claudio Contardo, Guy Desaulniers, Eduardo Uchoa, 2017.* + +## Sets and Indices + +$$\begin{align*} +V &= \{0, 1, \dots, n+1\} && \text{set of nodes; nodes $0$ and $n+1$ are two copies of the depot}\\ +V^{+} &= V \setminus \{0, n+1\} && \text{set of customers}\\ +A &= \{(i,j): i \in V\setminus\{n+1\},\ j \in V\setminus\{0\},\ i \ne j,\\ + &\qquad\ d_i + d_j \le Q,\ e_i + s_i + t_{ij} \le l_j\} && \text{set of feasible arcs}\\ +\Omega &&& \text{set of all feasible routes} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +d_i &\quad \text{demand of customer } i \in V^{+},\ d_i > 0; \quad d_0 = d_{n+1} = 0\\ +[e_i, l_i] &\quad \text{time window of node } i,\ 0 \le e_i \le l_i; \quad [e_0,l_0]=[e_{n+1},l_{n+1}]=[0,H]\\ +s_i &\quad \text{service time at customer } i \in V^{+},\ s_i > 0; \quad s_0 = s_{n+1} = 0\\ +H &\quad \text{planning horizon length},\ H > 0\\ +c_{ij} &\quad \text{traveling cost on arc } (i,j),\ c_{ij} \ge 0\\ +t_{ij} &\quad \text{traveling time on arc } (i,j),\ t_{ij} \ge 0\\ +Q &\quad \text{capacity of each (identical, unlimited fleet) vehicle},\ Q > 0\\ +c_r &\quad \text{cost of route } r \in \Omega:\quad + c_r = c_{0,i_1} + \sum_{h=1}^{k-1} c_{i_h,i_{h+1}} + c_{i_k,n+1}\\ +a^r_i &\quad \text{number of visits to customer } i \in V^{+} \text{ in route } r \in \Omega +\end{align*}$$ + +*Route feasibility.* A route $r=(i_0=0,i_1,\dots,i_k,i_{k+1}=n+1)$ visiting $k\ge 1$ customers $i_1,\dots,i_k \in V^{+}$ is feasible if (i) $\sum_{h=1}^{k} d_{i_h} \le Q$ (capacity); (ii) $e_{i_h} \le T_h \le l_{i_h}$ for $1 \le h \le k$ (time windows); and (iii) $T_{k+1} \le H$ (route end time), where $T_0 = 0$, $T_h = \max\{e_{i_h},\, T_{h-1}+s_{i_{h-1}}+t_{i_{h-1},i_h}\}$ for $h>0$, and $T_{k+1} = T_k + s_{i_k} + t_{i_k,n+1}$. + +## Decision Variables + +$$\begin{align*} +\lambda_r \in \{0,1\} &\quad \text{equals 1 if route } r \in \Omega \text{ is selected in the solution, 0 otherwise} +\end{align*}$$ + +## Objective + +$$\begin{align} +\min\ \sum_{r \in \Omega} c_r\, \lambda_r \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{r \in \Omega} a^r_i\, \lambda_r &= 1, & \forall i \in V^{+} \tag{2}\\ +\lambda_r &\in \{0,1\}, & \forall r \in \Omega \tag{3} +\end{align}$$ + +The objective (1) minimizes the overall cost of the selected routes. Constraints (2) guarantee that each customer is served by exactly one route. Constraints (3) force the route-selection variables to be binary. diff --git a/tasks/pecin2017/problem_description.txt b/tasks/pecin2017/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..3384db731aab25c9b7845c78de4f74b167360aa6 --- /dev/null +++ b/tasks/pecin2017/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A delivery company operates an unlimited fleet of identical vehicles, each with the same carrying capacity, from a single depot. The company must deliver goods to a set of customers, where each customer has a known positive demand, a location specified by coordinates in a two-dimensional plane, a time window defined by an earliest and latest allowable start of service, and a service time representing how long the vehicle must spend at that customer once service begins. The depot has zero demand and zero service time, and its time window spans the entire planning horizon from time zero to a given horizon length. Travel costs and travel times between every pair of locations are given; in particular, they equal the Euclidean distance between the two locations. + +The company must design a set of vehicle routes, where each route begins at the depot, visits a sequence of one or more customers, and returns to the depot. Every customer must appear on exactly one route. A direct connection from one location to another is only available if the combined demands of the two endpoints do not exceed the vehicle capacity and if a vehicle that begins service at the origin at the earliest allowable time, completes service, and travels directly to the destination can arrive no later than the destination's latest allowable service start time. Each route must satisfy three requirements: the total demand of all customers on the route must not exceed the vehicle capacity; at each stop along the route, service must begin within the customer's time window, where the earliest possible start of service at each successive stop is the later of that customer's earliest time and the previous customer's service start plus that customer's service time plus the travel time between the two customers; and the vehicle must return to the depot within the planning horizon, meaning the departure time from the last customer (its service start plus its service time) plus the travel time back to the depot must not exceed the horizon length. A vehicle may arrive at a customer before the opening of the customer's time window and wait, but it may not begin service after the closing of the time window. + +The goal is to select a collection of routes that satisfy these requirements, one for each vehicle used, such that every customer is served by exactly one route and the total cost, defined as the sum of the travel costs along all connections used across all selected routes, is minimized. diff --git a/tasks/pecin2017/solution_logger.py b/tasks/pecin2017/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/pecin2017/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/pecin2017/solution_schema.json b/tasks/pecin2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8c7957e22a4d9cda6e9b6c587d40f849b6d7f3ca --- /dev/null +++ b/tasks/pecin2017/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total travel cost summed over all arcs traversed across all vehicle routes.", + "routes": " Ordered sequence of node indices visited on each vehicle route, starting at the depot source and ending at the depot sink." +} diff --git a/tasks/pedersen2024/feasibility_check.py b/tasks/pedersen2024/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..25d9f0bcd6e13d3dddbd8bfe06ee3f3d05694036 --- /dev/null +++ b/tasks/pedersen2024/feasibility_check.py @@ -0,0 +1,485 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Quota Steiner Tree Problem (QSTP). + +Checks a candidate solution against all hard constraints from the mathematical +formulation in Pedersen et al. (2024). Constraints are numbered 1-14 counting +strictly from top to bottom in the formulation sections of math_model.txt, +plus a new constraint 15 added by this _new variant for obj-consistency +(Tier C defense against fabricated objective values): + + Constraint 1 (Eq 2): Quota in original QSTP: sum q_i >= Q + Constraint 2 (Eq 5): Steiner cut for fixed terminals (connectivity) + Constraint 3 (Eq 6): Steiner cut for selected potential terminals + Constraint 4 (Eq 7): Quota in directed cut formulation + Constraint 5 (Eq 8): Binary x, y variables + valid edges/turbines + Constraint 6 (Eq 11): Steiner cut in transformed graph + Constraint 7 (Eq 12): Transformed quota constraint + Constraint 8 (Eq 13): Binary x in transformed graph + Constraint 9 (Eq 25): Quota in flow-based MIP + Constraint 10 (Eq 26): Flow balance (connectivity via flow) + Constraint 11 (Eq 27): Arc-terminal linking: x_a <= y_v + Constraint 12 (Eq 28): Flow capacity: f_a <= M * x_a + Constraint 13 (Eq 29): Binary y in flow-based MIP + Constraint 14 (Eq 30): Binary x, f >= 0 in flow-based MIP + Constraint 15 (Eq 21/23 obj): Reported objective_value must match + alpha * (edge cost + turbine cost) + + (1-alpha) * (edge scenic + turbine scenic). +""" + +import argparse +import json +from collections import defaultdict, deque + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'selected_edges', 'selected_turbines') +_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 + + violations = [] + violation_magnitudes = [] + violated_constraints = set() + + # --- Extract instance data --- + nodes = instance["nodes"] + edges = instance["edges"] + params = instance["parameters"] + Q = params["quota"] + alpha = params["alpha"] + + node_by_id = {n["id"]: n for n in nodes} + T_f = [n["id"] for n in nodes if n["type"] == "substation"] + T_p = [n["id"] for n in nodes if n["type"] == "potential_turbine"] + T_p_set = set(T_p) + T_f_set = set(T_f) + + # Valid undirected edges from instance + valid_edges = set() + edge_by_pair = {} + for e in edges: + valid_edges.add((e["from"], e["to"])) + valid_edges.add((e["to"], e["from"])) + edge_by_pair[(e["from"], e["to"])] = e + edge_by_pair[(e["to"], e["from"])] = e + + # --- Extract solution data --- + selected_turbines = set(solution.get("selected_turbines", [])) + selected_edges = solution.get("selected_edges", []) + selected_arcs = [(e["from"], e["to"]) for e in selected_edges] + + # --- Vertex profits --- + vertex_profit = {n["id"]: n["profit"] for n in nodes} + total_profit = sum(vertex_profit[t] for t in selected_turbines) + total_available_profit = sum(vertex_profit[t] for t in T_p) + + # --- Connectivity (undirected) from root --- + r = T_f[0] + adj_undirected = defaultdict(set) + for u, v in selected_arcs: + adj_undirected[u].add(v) + adj_undirected[v].add(u) + + reachable = set() + queue = deque([r]) + reachable.add(r) + while queue: + u = queue.popleft() + for v in adj_undirected[u]: + if v not in reachable: + reachable.add(v) + queue.append(v) + + # Big-M value for flow formulation + M = len(T_f) + len(T_p) + + # --- Helper to record a violation --- + def record(constraint_idx, msg, lhs, rhs, violation_amount): + if violation_amount > tol: + violated_constraints.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ================================================================ + # Constraint 1 (Eq 2): Q(S) = sum_{i in T_p cap V'} q_i >= Q + # ================================================================ + lhs_val = total_profit + rhs_val = Q + va = max(rhs_val - lhs_val, 0.0) + record(1, f"Quota not met (original QSTP): total profit {lhs_val:.4f} < Q = {rhs_val:.4f}", lhs_val, rhs_val, va) + + # ================================================================ + # Constraint 2 (Eq 5): Steiner cut for fixed terminals + # All fixed terminals must be reachable from root via selected edges. + # ================================================================ + for t in T_f: + if t != r and t not in reachable: + record(2, f"Fixed terminal {t} not connected to root {r}", 0.0, 1.0, 1.0) + + # ================================================================ + # Constraint 3 (Eq 6): Steiner cut for selected potential terminals + # Each selected potential terminal must be reachable from root. + # ================================================================ + for t in sorted(selected_turbines): + if t not in reachable: + record(3, f"Selected turbine {t} not connected to root {r}", 0.0, 1.0, 1.0) + + # ================================================================ + # Constraint 4 (Eq 7): sum_{v_i in T_p} q_i * y_i >= Q + # ================================================================ + lhs_val = total_profit + rhs_val = Q + va = max(rhs_val - lhs_val, 0.0) + record(4, f"Quota not met (directed cut): sum q_i*y_i = {lhs_val:.4f} < Q = {rhs_val:.4f}", lhs_val, rhs_val, va) + + # ================================================================ + # Constraint 5 (Eq 8): x_{ij}, y_k in {0,1} + # Check that selected turbines are valid potential turbines + # and selected edges correspond to valid edges in the instance. + # ================================================================ + for t in sorted(selected_turbines): + if t not in T_p_set: + record(5, f"Selected turbine {t} is not a valid potential turbine", 1.0, 0.0, 1.0) + for e in selected_edges: + u, v = e["from"], e["to"] + if (u, v) not in valid_edges: + record(5, f"Selected arc ({u},{v}) does not correspond to a valid edge", 1.0, 0.0, 1.0) + + # ================================================================ + # Constraint 6 (Eq 11): Steiner cut in transformed graph + # In the transformed QSTP, all terminals (original fixed + new fixed) + # must be connected. In original space: all fixed terminals and all + # selected potential terminals must be reachable from root. + # ================================================================ + disconnected = [] + for t in T_f: + if t != r and t not in reachable: + disconnected.append(t) + for t in sorted(selected_turbines): + if t not in reachable: + disconnected.append(t) + if disconnected: + record(6, f"Steiner cut violated (transformed): nodes {disconnected} disconnected from root", 0.0, 1.0, 1.0) + + # ================================================================ + # Constraint 7 (Eq 12): Transformed quota + # sum_{v_{i'} in T'_f} q_{i'} * x_{r,i'} <= sum_{v_{i'} in T'_f} q_{i'} - Q + # In original space: profit of UNselected turbines <= total_available - Q + # Equivalently: selected profit >= Q (same as constraint 1). + # ================================================================ + unselected_profit = total_available_profit - total_profit + rhs_val = total_available_profit - Q + lhs_val = unselected_profit + # This is a <= constraint: lhs <= rhs + va = max(lhs_val - rhs_val, 0.0) + record(7, f"Transformed quota violated: unselected profit {lhs_val:.4f} > allowed {rhs_val:.4f}", lhs_val, rhs_val, va) + + # ================================================================ + # Constraint 8 (Eq 13): x_{ij} in {0,1} (transformed) + # Auto-satisfied by the solution representation (list-based). + # Check that no duplicate arcs exist. + # ================================================================ + arc_counts = defaultdict(int) + for u, v in selected_arcs: + arc_counts[(u, v)] += 1 + for arc, count in arc_counts.items(): + if count > 1: + record(8, f"Duplicate arc {arc} appears {count} times (should be binary)", float(count), 1.0, float(count - 1)) + + # ================================================================ + # Constraint 9 (Eq 25): sum_{v in T_p} q_v * y_v >= Q (flow MIP) + # ================================================================ + lhs_val = total_profit + rhs_val = Q + va = max(rhs_val - lhs_val, 0.0) + record(9, f"Quota not met (flow MIP): sum q_v*y_v = {lhs_val:.4f} < Q = {rhs_val:.4f}", lhs_val, rhs_val, va) + + # ================================================================ + # Constraint 10 (Eq 26): Flow balance + # Fixed terminals (not root): net inflow = 1 + # Potential terminals: net inflow = y_v + # Steiner nodes: net inflow = 0 + # Check indirectly: each fixed terminal (not root) and each selected + # potential terminal must be reachable from root. + # Also: non-selected potential terminals should not have net inflow. + # ================================================================ + for t in T_f: + if t != r and t not in reachable: + record(10, f"Flow balance violated: fixed terminal {t} unreachable from root", 0.0, 1.0, 1.0) + for t in sorted(selected_turbines): + if t not in reachable: + record(10, f"Flow balance violated: selected turbine {t} unreachable from root", 0.0, 1.0, 1.0) + + # ================================================================ + # Constraint 11 (Eq 27): x_a <= y_v for all a in delta^-(v), v in T_p + # If a selected arc enters a potential turbine, that turbine must be + # selected. + # ================================================================ + for e in selected_edges: + v = e["to"] + if v in T_p_set and v not in selected_turbines: + record(11, f"Arc ({e['from']},{v}) enters non-selected turbine {v} (x_a=1 but y_{v}=0)", 1.0, 0.0, 1.0) + + # ================================================================ + # Constraint 12 (Eq 28): f_a <= M * x_a + # For selected arcs (x_a = 1), flow is bounded by M (auto-satisfied). + # For non-selected arcs (x_a = 0), no flow passes (not checkable + # without flow variables, but structurally satisfied). + # No violation possible from the solution representation. + # ================================================================ + # Auto-satisfied: flow variables are internal to the solver. + + # ================================================================ + # Constraint 13 (Eq 29): y_v in {0,1} for all v in T_p + # Auto-satisfied: solution represents y as a list of selected turbines. + # ================================================================ + # Already checked in constraint 5 that selected turbines are valid T_p. + + # ================================================================ + # Constraint 14 (Eq 30): x_a in {0,1}, f_a >= 0 + # Auto-satisfied by the solution representation. + # ================================================================ + # Already checked in constraints 5 and 8. + + # ================================================================ + # Constraint 15 (Eq 21/23 obj): Reported objective_value must match + # the recomputed value + # obj = sum_{a in selected_edges} (alpha * c_e + (1-alpha) * s(e)) + # + sum_{v in selected_turbines} (alpha * w(v) + (1-alpha) * s^v(v)) + # where for each directed arc (u,v) in selected_edges, c_e and s(e) + # come from the corresponding undirected edge in the instance (Gurobi + # selects directed arcs from the flow MIP, so each undirected edge may + # appear in either or both orientations). Invalid arcs (already flagged + # by constraint 5) are skipped here so they don't double-fire. + # Tolerance: max(1e-3, 1e-3 * |recomputed|) — 0.1% relative. + # ================================================================ + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + edge_obj = 0.0 + for a in selected_edges: + u, v = a["from"], a["to"] + e = edge_by_pair.get((u, v)) + if e is None: + continue # invalid arc, already flagged by constraint 5 + edge_obj += alpha * float(e["cost"]) + (1.0 - alpha) * float(e["scenic_impact"]) + turbine_obj = 0.0 + for t in selected_turbines: + n = node_by_id.get(t) + if n is None or n["type"] != "potential_turbine": + continue # invalid turbine, already flagged by constraint 5 + turbine_obj += alpha * float(n["cost"]) + (1.0 - alpha) * float(n["scenic_impact"]) + true_obj = edge_obj + turbine_obj + abs_diff = abs(reported - true_obj) + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + record( + 15, + f"Objective consistency violated: reported objective_value={reported} " + f"differs from recomputed alpha*cost+(1-alpha)*scenic_impact " + f"(edges={edge_obj:.6f}, turbines={turbine_obj:.6f}, " + f"total={true_obj:.6f}); |diff|={abs_diff:.6g}, tol={obj_tol:.3g}", + reported, true_obj, abs_diff, + ) + + # --- Build result --- + result = { + "feasible": len(violated_constraints) == 0, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes if violation_magnitudes else [], + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Check feasibility of a QSTP candidate solution." + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file.") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result.") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"FEASIBLE - No constraint violations found.") + else: + print(f"INFEASIBLE - 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/pedersen2024/gurobi_code.py b/tasks/pedersen2024/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a2805c3194e3f0f8b3a7fc96f251bf7a0ef5ee --- /dev/null +++ b/tasks/pedersen2024/gurobi_code.py @@ -0,0 +1,350 @@ +#!/usr/bin/env python3 +""" +Flow-based MIP formulation (FLOW) for the Quota Steiner Tree Problem (QSTP). + +Implements the formulation from Pedersen et al. (2024), equations (23)-(30): + min c^T x + w^T y + s.t. + sum_{v in T_p} q_v * y_v >= Q (25) + flow balance constraints (26) + x_a <= y_v for all a in delta^-(v), v in T_p (27) + f_a <= M * x_a for all a in A (28) + y_v in {0,1} for all v in T_p (29) + x_a in {0,1}, f_a >= 0 for all a in A (30) + +The bi-objective extension uses the weighted-sum approach (eq. 21): + C_bar(S) = alpha * C(S) + (1-alpha) * L(S) + +Reference: Pedersen et al. (2024) - "An efficient solver for large-scale +onshore wind farm siting including cable routing", EJOR 317(2), 616-630. +""" + +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 a QSTP 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 build_and_solve(instance_data, time_limit): + """ + Build and solve the flow-based MIP formulation for the QSTP. + + Parameters + ---------- + instance_data : dict + The parsed JSON instance data. + time_limit : int + Maximum solver runtime in seconds. + + Returns + ------- + dict + Solution dictionary with objective_value and solution details. + """ + params = instance_data["parameters"] + alpha = params["alpha"] + Q = params["quota"] + nodes = instance_data["nodes"] + edges = instance_data["edges"] + + # Build node lookup + node_by_id = {n["id"]: n for n in nodes} + + # Classify nodes + T_f = [n["id"] for n in nodes if n["type"] == "substation"] + T_p = [n["id"] for n in nodes if n["type"] == "potential_turbine"] + steiner_nodes = [n["id"] for n in nodes if n["type"] == "steiner"] + all_nodes = [n["id"] for n in nodes] + + # Choose an arbitrary root from fixed terminals + # As stated in the paper (Section 3.1.2): all substations are interconnected + # by edges of zero cost, so the choice of root does not matter. + r = T_f[0] + + # Compute combined edge costs and vertex costs using bi-objective + # weighted-sum approach (eq. 21): + # c_bar(e) = alpha * c(e) + (1-alpha) * s(e) + # w_bar(v) = alpha * w(v) + (1-alpha) * s^v(v) + vertex_cost = {} + vertex_profit = {} + for n in nodes: + if n["type"] == "potential_turbine": + vertex_cost[n["id"]] = alpha * n["cost"] + (1.0 - alpha) * n["scenic_impact"] + vertex_profit[n["id"]] = n["profit"] + else: + vertex_cost[n["id"]] = 0.0 + vertex_profit[n["id"]] = 0.0 + + edge_cost = {} + for e in edges: + u, v = e["from"], e["to"] + c_bar = alpha * e["cost"] + (1.0 - alpha) * e["scenic_impact"] + edge_cost[(u, v)] = c_bar + + # Build directed arcs: for each undirected edge (u,v), create arcs (u,v) and (v,u) + # Arc costs incorporate vertex-cost shifting (eq. 3): + # c(i,j) = c_e + w_j if j in T_p + # c(i,j) = c_e otherwise + arcs = [] + arc_cost = {} + for e in edges: + u, v = e["from"], e["to"] + c_bar = edge_cost[(u, v)] + + # Arc (u, v) + cost_uv = c_bar + vertex_cost.get(v, 0.0) if v in vertex_cost and node_by_id[v]["type"] == "potential_turbine" else c_bar + arcs.append((u, v)) + arc_cost[(u, v)] = cost_uv + + # Arc (v, u) + cost_vu = c_bar + vertex_cost.get(u, 0.0) if u in vertex_cost and node_by_id[u]["type"] == "potential_turbine" else c_bar + arcs.append((v, u)) + arc_cost[(v, u)] = cost_vu + + # Big-M value (as per paper Section 3.1.2): M = |T_f union T_p| + M = len(T_f) + len(T_p) + + # Build Gurobi model + model = gp.Model("QSTP_FLOW") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + # Suppress output for cleaner execution + model.setParam("OutputFlag", 1) + + # --- Decision variables --- + # x_a in {0,1}: arc selection + x = {} + for a in arcs: + x[a] = model.addVar(vtype=GRB.BINARY, name=f"x_{a[0]}_{a[1]}") + + # y_v in {0,1}: potential terminal selection + y = {} + for v in T_p: + y[v] = model.addVar(vtype=GRB.BINARY, name=f"y_{v}") + + # f_a >= 0: flow on arcs + f = {} + for a in arcs: + f[a] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"f_{a[0]}_{a[1]}") + + model.update() + + # --- Objective (eq. 23) --- + # Note: In the flow-based formulation, the objective is c^T x + w^T y. + # However, since we use vertex-cost shifting in arc costs (c(i,j) = c_e + w_j + # for j in T_p), the vertex costs are already embedded in the arc costs. + # The paper's flow formulation (Section 3.1.2) uses the ORIGINAL (unshifted) + # arc costs plus explicit w^T y terms. + # We implement it as stated: min c^T x + w^T y where c here are the + # ORIGINAL edge costs (not shifted), and w are vertex costs. + + # Re-compute arc costs WITHOUT vertex-cost shifting for the flow formulation + # since the formulation explicitly includes + w^T y + arc_cost_unshifted = {} + for e in edges: + u, v = e["from"], e["to"] + c_bar = alpha * e["cost"] + (1.0 - alpha) * e["scenic_impact"] + arc_cost_unshifted[(u, v)] = c_bar + arc_cost_unshifted[(v, u)] = c_bar + + obj = gp.LinExpr() + for a in arcs: + obj += arc_cost_unshifted[a] * x[a] + for v in T_p: + obj += vertex_cost[v] * y[v] + + model.setObjective(obj, GRB.MINIMIZE) + + # --- Constraint (25): Quota constraint --- + model.addConstr( + gp.quicksum(vertex_profit[v] * y[v] for v in T_p) >= Q, + name="quota" + ) + + # --- Constraint (26): Flow balance --- + # Build adjacency lists for incoming and outgoing arcs + delta_minus = {v: [] for v in all_nodes} # incoming arcs + delta_plus = {v: [] for v in all_nodes} # outgoing arcs + for a in arcs: + delta_minus[a[1]].append(a) + delta_plus[a[0]].append(a) + + T_p_set = set(T_p) + T_f_set = set(T_f) + + for v in all_nodes: + flow_in = gp.quicksum(f[a] for a in delta_minus[v]) + flow_out = gp.quicksum(f[a] for a in delta_plus[v]) + + if v == r: + # Root node: no explicit constraint (it is the source of flow) + # The root sends flow out; its balance is determined implicitly. + continue + elif v in T_f_set and v != r: + # Fixed terminal (not root): must receive 1 unit of flow (eq. 26) + model.addConstr(flow_in - flow_out == 1, name=f"flow_balance_{v}") + elif v in T_p_set: + # Potential terminal: receives flow = y_v (eq. 26) + model.addConstr(flow_in - flow_out == y[v], name=f"flow_balance_{v}") + else: + # Steiner node: flow conservation (eq. 26) + model.addConstr(flow_in - flow_out == 0, name=f"flow_balance_{v}") + + # --- Constraint (27): x_a <= y_v for all incoming arcs of potential terminals --- + for v in T_p: + for a in delta_minus[v]: + model.addConstr(x[a] <= y[v], name=f"link_arc_terminal_{a[0]}_{a[1]}") + + # --- Constraint (28): f_a <= M * x_a --- + for a in arcs: + model.addConstr(f[a] <= M * x[a], name=f"flow_cap_{a[0]}_{a[1]}") + + # Optimize + model.optimize() + + # Extract solution + solution = { + "instance_name": instance_data.get("instance_name", "unknown"), + "solver": "Gurobi", + "formulation": "FLOW (flow-based MIP)", + "status": None, + "objective_value": None, + "selected_turbines": [], + "selected_edges": [], + "total_edge_cost": 0.0, + "total_vertex_cost": 0.0, + "total_profit": 0.0, + } + + if model.SolCount > 0: + solution["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + solution["objective_value"] = model.ObjVal + + # Extract selected turbines + for v in T_p: + if y[v].X > 0.5: + solution["selected_turbines"].append(v) + solution["total_vertex_cost"] += vertex_cost[v] + solution["total_profit"] += vertex_profit[v] + + # Extract selected arcs (as undirected edges) + selected_arcs = [] + for a in arcs: + if x[a].X > 0.5: + selected_arcs.append({"from": a[0], "to": a[1], "cost": arc_cost_unshifted[a]}) + solution["total_edge_cost"] += arc_cost_unshifted[a] + + solution["selected_edges"] = selected_arcs + + # Compute the original cost C(S) and scenic impact L(S) + C_S = 0.0 + L_S = 0.0 + for a_info in selected_arcs: + u, v_node = a_info["from"], a_info["to"] + # Find the original undirected edge + for e in edges: + if (e["from"] == u and e["to"] == v_node) or (e["from"] == v_node and e["to"] == u): + C_S += e["cost"] + L_S += e["scenic_impact"] + break + for v in solution["selected_turbines"]: + n = node_by_id[v] + C_S += n["cost"] + L_S += n["scenic_impact"] + + solution["cost_C"] = C_S + solution["scenic_impact_L"] = L_S + solution["alpha"] = alpha + + else: + solution["status"] = "infeasible_or_no_solution" + solution["objective_value"] = None + + # Add solver statistics + solution["solver_stats"] = { + "runtime_seconds": model.Runtime, + "mip_gap": model.MIPGap if model.SolCount > 0 else None, + "node_count": int(model.NodeCount), + "status_code": model.Status, + } + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the Quota Steiner Tree Problem (QSTP) using Gurobi's flow-based MIP formulation." + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to the JSON file containing the QSTP instance.", + ) + parser.add_argument( + "--solution_path", + type=str, + required=True, + help="Path where the solution JSON file will be written.", + ) + parser.add_argument( + "--time_limit", + type=int, + required=True, + help="Maximum solver runtime in seconds.", + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # Load instance + instance_data = load_instance(args.instance_path) + + # Solve + solution = build_and_solve(instance_data, args.time_limit) + + # Write solution + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']:.4f}") + print(f"Status: {solution['status']}") + print(f"Selected turbines: {solution['selected_turbines']}") + print(f"Total profit: {solution['total_profit']:.4f}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/pedersen2024/gurobi_feasi_result/large_feasi_result_1.json b/tasks/pedersen2024/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pedersen2024/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/pedersen2024/gurobi_feasi_result/large_feasi_result_2.json b/tasks/pedersen2024/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pedersen2024/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/pedersen2024/gurobi_feasi_result/large_feasi_result_3.json b/tasks/pedersen2024/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pedersen2024/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/pedersen2024/gurobi_feasi_result/large_feasi_result_4.json b/tasks/pedersen2024/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pedersen2024/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/pedersen2024/gurobi_feasi_result/large_feasi_result_5.json b/tasks/pedersen2024/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pedersen2024/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/pedersen2024/gurobi_feasi_result/tiny_feasi_result.json b/tasks/pedersen2024/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pedersen2024/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/pedersen2024/gurobi_solution/large_solution_1.json b/tasks/pedersen2024/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a958705a62ecb41031a518c18e29449165cab244 --- /dev/null +++ b/tasks/pedersen2024/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ceff96f7c187f46ac3782a8f1536b10b737774f2c6f06ccdb605771b39867f3d +size 104453 diff --git a/tasks/pedersen2024/gurobi_solution/large_solution_2.json b/tasks/pedersen2024/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c13a2e8fb7edc234773a4ddd1403da6343ce5f55 --- /dev/null +++ b/tasks/pedersen2024/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0248f7297436fa87a5bbbe03e3167beeff1bec23c9b2c2a284f6349fe9fda64 +size 105177 diff --git a/tasks/pedersen2024/gurobi_solution/large_solution_3.json b/tasks/pedersen2024/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..a09d022096b4775df6cb5d828d71460bf83ab32f --- /dev/null +++ b/tasks/pedersen2024/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4faa1aaa60e7fb0ecc08ba83e909d4335b10a6b4cb10794671abcc89ec3e11ea +size 102568 diff --git a/tasks/pedersen2024/gurobi_solution/large_solution_4.json b/tasks/pedersen2024/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8bf451e61f1ca07f46e5383da2eb5ec258d22228 --- /dev/null +++ b/tasks/pedersen2024/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:696e3371fe2365b3939f83b35563630c8d3b82a809e747495742d7f8a89bd0eb +size 103400 diff --git a/tasks/pedersen2024/gurobi_solution/large_solution_5.json b/tasks/pedersen2024/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..fe3eb97fd51b8f1308666a4df8f387102b8accb5 --- /dev/null +++ b/tasks/pedersen2024/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61b29a45e5093df5643095db7c4e9b314181e1888e95460cbb8a792f71e9059c +size 100536 diff --git a/tasks/pedersen2024/gurobi_solution/tiny_solution.json b/tasks/pedersen2024/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..6d5d15d287b33239b83cb3101999251662bf87fa --- /dev/null +++ b/tasks/pedersen2024/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d389af64e32975bf4d5d07419d6dadc8519efecbf0408631380f43953ecbdfa6 +size 932 diff --git a/tasks/pedersen2024/gurobi_solution_log/tiny_log.jsonl b/tasks/pedersen2024/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..30c45f2084c1fd976c262243cdc4341bf274a910 --- /dev/null +++ b/tasks/pedersen2024/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f432ea0c9991eac4d497433c33f57c9240ff2c21088421179e4039e7102a209d +size 44 diff --git a/tasks/pedersen2024/instance/large_instance_1.json b/tasks/pedersen2024/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..7a35a4acdd6b06327d8ea7c8fc2f21049012071c --- /dev/null +++ b/tasks/pedersen2024/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93eef1c8d3cdd5a4518aedc757d0bd74f049cb69a496af8601f1169da71c5013 +size 27336423 diff --git a/tasks/pedersen2024/instance/large_instance_2.json b/tasks/pedersen2024/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4e3f19416554fc936519245b543bcfcbb5b7fff8 --- /dev/null +++ b/tasks/pedersen2024/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9a45a5e4d138c6913f0da2952c20229180ac02f9bf367dc48fc443399704847 +size 27336429 diff --git a/tasks/pedersen2024/instance/large_instance_3.json b/tasks/pedersen2024/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..3fcd67b988027594a9214c29d10b249b54efe2ce --- /dev/null +++ b/tasks/pedersen2024/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0e8ccd490ebf8dd59e426c08b893408a43ce13b19e3b9b0c65f43b585ef1ed0 +size 27336429 diff --git a/tasks/pedersen2024/instance/large_instance_4.json b/tasks/pedersen2024/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..1956881eedbdf221e8f4785326c36b18ce298a38 --- /dev/null +++ b/tasks/pedersen2024/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b18c64f56350f493c3fee16422fa3324debdcd8c3052ad4215fb602b6e8e687d +size 27336429 diff --git a/tasks/pedersen2024/instance/large_instance_5.json b/tasks/pedersen2024/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..744834dae402080344a835462c6576cb32e81032 --- /dev/null +++ b/tasks/pedersen2024/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:acc2e6bdd4c358d0d304a35768631d8de5a17e7c3fe8903b1de59eabb794e453 +size 27336429 diff --git a/tasks/pedersen2024/instance/tiny_instance.json b/tasks/pedersen2024/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..f4b523aba427248db212d1fad9bbf1f47876a2c5 --- /dev/null +++ b/tasks/pedersen2024/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44de0291454001c9f86ae29726ae4879a99d5597634f5e00ff0a4bdc615b915c +size 10548 diff --git a/tasks/pedersen2024/instance_schema.json b/tasks/pedersen2024/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5f6591a74e8d5cfee30b37fda8a35c3eaba9928e --- /dev/null +++ b/tasks/pedersen2024/instance_schema.json @@ -0,0 +1,31 @@ +{ + "parameters": { + "num_potential_turbines": " Number of candidate turbine sites in the region.", + "num_substations": " Number of fixed grid substations in the region.", + "num_steiner_nodes": " Number of intermediate cable routing points that cannot host turbines.", + "total_nodes": " Total number of locations (substations, candidate turbine sites, and Steiner nodes).", + "total_edges": " Total number of feasible cable connections between pairs of locations.", + "quota": " Minimum total annual energy yield that the selected turbines must collectively achieve.", + "alpha": " Weight given to financial cost in the combined objective, with the remainder weighting scenic impact." + }, + "nodes": [ + { + "id": " Unique identifier for this location.", + "type": " Role of this location: 'substation', 'potential_turbine', or 'steiner'.", + "x": " Horizontal coordinate of this location in kilometers.", + "y": " Vertical coordinate of this location in kilometers.", + "cost": " Installation cost of building a turbine at this location (zero for substations and Steiner nodes).", + "profit": " Annual energy yield from a turbine at this location (zero for substations and Steiner nodes).", + "scenic_impact": " Visual burden imposed on the landscape by placing a turbine at this location (zero for substations and Steiner nodes)." + } + ], + "edges": [ + { + "id": " Unique identifier for this cable connection.", + "from": " Node identifier of one endpoint of this cable connection.", + "to": " Node identifier of the other endpoint of this cable connection.", + "cost": " Financial cost of laying this cable segment (zero between substations).", + "scenic_impact": " Visual burden imposed on the landscape by this cable route (zero between substations)." + } + ] +} diff --git a/tasks/pedersen2024/mathematical_formulation.md b/tasks/pedersen2024/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..74e55f0ca6f117b68014b45759914b096e975a06 --- /dev/null +++ b/tasks/pedersen2024/mathematical_formulation.md @@ -0,0 +1,61 @@ +# Original Formulation: Quota Steiner Tree Problem (QSTP) + +*Source: An efficient solver for large-scale onshore wind farm siting including cable routing, Jaap Pedersen, Jann Michael Weinand, Chloi Syranidou, Daniel Rehfeldt, 2024.* + +## Sets and Indices + +$$\begin{align*} +G = (V,E) &: \text{undirected graph (turbine sites, substations, Steiner nodes).}\\ +T_f \subset V &: \text{set of fixed terminals (grid substations).}\\ +T_p \subset V &: \text{set of potential terminals (turbine positions), } T_f \cap T_p = \emptyset.\\ +v \in V \setminus (T_f \cup T_p) &: \text{Steiner node.}\\ +D = (V,A) &: \text{directed graph with } A := \{(i,j),(j,i)\mid \forall (i,j)\in E\}.\\ +r \in T_f &: \text{arbitrary root node chosen among the fixed terminals.}\\ +\delta^+(W) &= \{(i,j)\in A : i\in W,\, j\in V\setminus W\} \quad \text{(outgoing arcs of } W).\\ +\delta^-(W) &= \{(i,j)\in A : i\in V\setminus W,\, j\in W\} \quad \text{(incoming arcs of } W). +\end{align*}$$ For a single vertex $v_i$ we write $\delta^+(v_i):=\delta^+(\{v_i\})$ and $\delta^-(v_i):=\delta^-(\{v_i\})$. For any arc set $K$, $x(K):=\sum_{(i,j)\in K} x_{ij}$. + +## Parameters + +$$\begin{align*} +c : E \to \mathbb{R}_{\geq 0} &: \text{cable (edge) cost; } c_e \text{ cost of edge } e=(i,j).\\ +w : T_p \to \mathbb{R}_{>0} &: \text{vertex (turbine installation) cost.}\\ +q : T_p \to \mathbb{R}_{>0} &: \text{quota profit (annual energy yield) of a potential terminal.}\\ +Q \in \mathbb{R}_{>0} &: \text{minimum quota (minimum total energy yield required).} +\end{align*}$$ Vertex costs are shifted onto incoming arc costs, giving directed arc costs $c:A\to\mathbb{R}_{\geq 0}$: $$\begin{equation} +c(i,j)= +\begin{cases} +c_e + w_j & \text{if } j \in T_p,\\ +c_e & \text{otherwise,} +\end{cases} +\qquad \forall a=(i,j)\in A. \tag{3} +\end{equation}$$ + +## Decision Variables + +$$\begin{align*} +x_{ij} &\in \{0,1\} : \text{1 if arc } (i,j)\in A \text{ is in the Steiner arborescence, 0 otherwise.}\\ +y_{k} &\in \{0,1\} : \text{1 if potential terminal } v_k \in T_p \text{ is chosen, 0 otherwise.} +\end{align*}$$ + +## Objective + +The QSTP seeks a tree $S=(V',E')\subseteq G$ containing all fixed terminals $T_f$ that minimizes the total cable and turbine cost $$\begin{equation} +C(S) = \sum_{(i,j)\in E'} c_{ij} + \sum_{i \in T_p \cap V'} w_i \tag{1} +\end{equation}$$ subject to a fulfilled quota $$\begin{equation} +Q(S)=\sum_{i\in T_p\cap V'} q_i \geq Q. \tag{2} +\end{equation}$$ Modeled as a rooted Steiner arborescence problem with the shifted arc costs $c$ of $(3)$, the objective is $$\begin{equation} +\min \quad c^T x. \tag{4} +\end{equation}$$ + +## Constraints + +$$\begin{align} +x(\delta^-(W)) &\geq 1 + && \forall W \subset V,\; r \notin W,\; |W \cap T_f| \geq 1, \tag{5}\\[2pt] +x(\delta^-(W)) &\geq y_i + && \forall W \subset V,\; r \notin W,\; |W \cap T_p| \geq 1,\; v_i \in T_p, \tag{6}\\[2pt] +\sum_{v_i \in T_p} q_i\, y_i &\geq Q, && \tag{7}\\[2pt] +x_{ij},\, y_k &\in \{0,1\} + && \forall (i,j) \in A,\; \forall v_k \in T_p. \tag{8} +\end{align}$$ diff --git a/tasks/pedersen2024/problem_description.txt b/tasks/pedersen2024/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..731f720868c6a02bd6d7bf90027d0d7619ee5a87 --- /dev/null +++ b/tasks/pedersen2024/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A wind energy developer plans an onshore wind farm over a region containing three types of locations: grid substations, potential turbine sites, and optional intermediate routing points (called Steiner nodes). The substations are fixed connection points to the electrical grid. The potential turbine sites are candidate locations where a wind turbine may be installed. The Steiner nodes exist solely to provide additional flexibility for cable routing between turbines and substations; they cannot host turbines and produce no energy. The region is represented as an undirected graph whose nodes are the union of all substations, potential turbine sites, and Steiner nodes, and whose edges are the feasible cable connections between pairs of nodes. + +Each potential turbine site has an installation cost, an annual energy yield, and a scenic impact value reflecting the visual burden that placing a turbine there would impose on the surrounding landscape. Each edge has a cable cost representing the expense of laying that cable segment, and a scenic impact value representing the visual burden of that cable route on the landscape. Substations and Steiner nodes carry no installation cost, no energy yield, and no scenic impact. All substations are mutually interconnected by edges of zero cost and zero scenic impact, reflecting their shared connection to the existing power grid. + +The developer must decide which subset of potential turbine sites to build and which cable connections to lay. The chosen cables, together with the built turbine sites, the substations, and any Steiner nodes used for routing, must form a single connected tree (no cycles, no disconnected components). Every substation must lie on this tree. A potential turbine site is considered built if and only if it lies on the tree; any candidate site not on the tree is not built. The total annual energy yield of the built turbine sites must meet or exceed a prescribed minimum quota. + +The problem has two competing goals: total financial cost and total scenic impact. The total financial cost is the sum of the cable costs of all edges included in the tree plus the installation costs of all built turbine sites. The total scenic impact is the sum of the scenic impact values of all edges included in the tree plus the scenic impact values of all built turbine sites. These two goals are combined into a single weighted sum using a parameter alpha between zero and one inclusive: the weighted sum equals alpha times the total financial cost plus one minus alpha times the total scenic impact. When alpha equals one the problem considers only financial cost; when alpha equals zero it considers only scenic impact. The goal is to minimize this weighted sum while meeting the energy yield quota. + +To summarize the input data: the graph specifies for every node its type (substation, potential turbine, or Steiner node), its spatial coordinates, its installation cost (positive only for potential turbines), its annual energy yield (positive only for potential turbines), and its scenic impact (positive only for potential turbines); for every edge it specifies the two endpoints, the cable cost, and the scenic impact; and globally the instance specifies the minimum energy quota and the weighting parameter alpha. The decisions to be made are which potential turbine sites to build and which edges to include, such that the selected edges and nodes form a tree containing every substation, the total energy yield of chosen turbines meets the quota, and the weighted combination of financial cost and scenic impact is minimized. diff --git a/tasks/pedersen2024/solution_logger.py b/tasks/pedersen2024/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/pedersen2024/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/pedersen2024/solution_schema.json b/tasks/pedersen2024/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b2d661ca34086fab558b5d90bf03412dddeba9da --- /dev/null +++ b/tasks/pedersen2024/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Weighted-sum of total financial cost and total scenic impact for the chosen turbines and cables.", + "selected_turbines": " Identifiers of the potential turbine sites chosen to be built.", + "selected_edges": " Cable connections included in the wind farm network, each specifying the two node endpoints it links." +} diff --git a/tasks/pessoa2021/feasibility_check.py b/tasks/pessoa2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..39a82f62e6145335912998b14c78c2b1e33bf8b4 --- /dev/null +++ b/tasks/pessoa2021/feasibility_check.py @@ -0,0 +1,486 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Robust Capacitated Vehicle Routing Problem (RCVRP) +with Knapsack Uncertainty, based on Pessoa et al. (2021). + +Checks constraints numbered from the formulation (top to bottom): + Constraint 1 (Eq 15): Each customer visited exactly once + Constraint 2 (Eq 16): Exactly m vehicles used + Constraint 3 (Eq 17): Integrality (lambda_r in Z+) + Constraint 4 (Eq 18): Robust rounded capacity inequalities + Constraint 5 (Eq 19): New robust capacity inequalities + Constraint 6 (Eq 20): Strongest combined capacity inequalities + Constraint 7 (Eq 14): Objective consistency -- the reported + objective_value must equal the total transportation cost + recomputed from the routes using the distance matrix + (depot -> custs[0] -> ... -> custs[-1] -> depot). + +For integer route-based solutions, constraints 4-6 reduce to checking that +each route's worst-case demand does not exceed vehicle capacity C. +""" + +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 compute_worst_case_demand_card(customer_ids, bar_d, hat_d, Gamma): + """ + For D^{card}: worst-case demand = sum of nominal demands + sum of + Gamma largest deviations among customers in the route. + """ + nominal = sum(bar_d[i] for i in customer_ids) + devs = sorted([hat_d[i] for i in customer_ids], reverse=True) + dev_sum = sum(devs[:min(Gamma, len(devs))]) + return nominal + dev_sum + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + # If the solver reported infeasible/no solution, return null (not false) + status = solution.get('status', '') + obj = solution.get('objective_value') + if obj is None or (isinstance(status, str) and status.lower() in ('infeasible', 'no_solution')): + return { + "feasible": None, + "violated_constraints": [], + "violations": ["No solution found (solver status: {}).".format(status)], + "violation_magnitudes": [], + } + + n = instance['num_customers'] + m = instance['num_vehicles'] + C = instance['vehicle_capacity'] + customers = instance['customers'] + dist = instance['distance_matrix'] + unc = instance['uncertainty_set'] + Gamma = unc['Gamma'] + + bar_d = {c['id']: c['nominal_demand'] for c in customers} + hat_d = {c['id']: c['demand_deviation'] for c in customers} + + routes = solution.get('routes', []) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint 1 (Eq 15): Each customer i in V0 is visited exactly once + # sum_{theta} sum_{r in R_theta} a_i^r * lambda_r = 1, for all i in V0 + # ========================================================================= + visit_count = {} + for route in routes: + for cust in route['customers']: + visit_count[cust] = visit_count.get(cust, 0) + 1 + + for i in range(1, n + 1): + count = visit_count.get(i, 0) + lhs = float(count) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + violated_constraints.add(1) + if count == 0: + violations.append(f"Customer {i} is not visited by any route") + else: + violations.append( + f"Customer {i} is visited {count} times instead of exactly once" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 2 (Eq 16): Exactly m vehicles are used + # sum_{theta} sum_{r in R_theta} lambda_r = m + # ========================================================================= + num_routes = len(routes) + lhs = float(num_routes) + rhs = float(m) + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + violated_constraints.add(2) + violations.append( + f"Number of routes is {num_routes}, expected exactly {m}" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 3 (Eq 17): Integrality — lambda_r in Z+ + # In route-based solutions each route is used exactly once (lambda=1). + # We verify that route usage counts are non-negative integers and that + # customer IDs are valid. + # ========================================================================= + for r_idx, route in enumerate(routes): + for cust in route['customers']: + if not isinstance(cust, int) or cust < 1 or cust > n: + lhs = float(cust) if isinstance(cust, (int, float)) else 0.0 + rhs = 0.0 # expected valid range [1, n] + violation_amount = 1.0 + normalizer = max(abs(rhs), eps) + violated_constraints.add(3) + violations.append( + f"Route {r_idx + 1} contains invalid customer ID {cust} " + f"(must be integer in [1, {n}])" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraints 4-6 (Eqs 18-20): Robust capacity inequalities + # + # For integer route-based solutions where customers are partitioned among + # routes, all three capacity inequalities reduce to verifying that each + # route's worst-case demand does not exceed vehicle capacity C: + # max_{d in D} sum_{i in route} d_i <= C + # + # For D^{card}: worst_case = sum(bar_d_i) + sum of Gamma largest hat_d_i + # + # A violation of route capacity implies violation of Eq (18) for S = route + # customers, since ceil(worst_case / C) > 1 but only 1 vehicle serves them. + # Eqs (19) and (20) give tighter bounds but are also violated whenever + # Eq (18) is violated for an individual route. + # ========================================================================= + for r_idx, route in enumerate(routes): + custs = route['customers'] + if not custs: + continue + + # Guard: only score if every customer is in bar_d (otherwise constraint + # 3 will already have flagged the invalid ID and a KeyError would + # break the checker). + if not all(c in bar_d for c in custs): + continue + + worst_case = compute_worst_case_demand_card(custs, bar_d, hat_d, Gamma) + lhs = float(worst_case) + rhs_cap = float(C) + + # This is a <= constraint: worst_case_demand <= C + violation_amount = max(0.0, lhs - rhs_cap) + if violation_amount > tol: + normalizer = max(abs(rhs_cap), eps) + + # Report under constraint 4 (Eq 18) — the primary capacity inequality + violated_constraints.add(4) + violations.append( + f"Route {r_idx + 1} (customers {custs}): worst-case demand " + f"{worst_case} exceeds vehicle capacity {C}" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs, + "rhs": rhs_cap, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # The same route also violates Eqs (19) and (20) + violated_constraints.add(5) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs, + "rhs": rhs_cap, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + violated_constraints.add(6) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs, + "rhs": rhs_cap, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 7 (Eq 14): Objective consistency. + # Full recompute -- every variable the obj depends on (the route arcs) is + # present in the solution, and arc costs c_{ij} are given by the instance + # distance matrix. Each route is the closed tour + # depot(0) -> custs[0] -> ... -> custs[-1] -> depot(0) + # and the objective is sum over routes of the sum of arc costs. + # Reject when reported_obj disagrees with the recomputed total. + # ========================================================================= + try: + reported = float(obj) + except (TypeError, ValueError): + reported = None + + if reported is not None and isinstance(dist, list) and len(dist) > 0: + depot_id = 0 + n_nodes = len(dist) + recompute_ok = True + true_obj = 0.0 + for route in routes: + custs = route['customers'] + prev = depot_id + for c in custs: + if not isinstance(c, int) or c < 0 or c >= n_nodes: + # Invalid ID -- constraint 3 already covers it; skip + # obj recompute on this route rather than crash. + recompute_ok = False + break + true_obj += float(dist[prev][c]) + prev = c + if not recompute_ok: + break + if not (0 <= prev < n_nodes): + recompute_ok = False + break + true_obj += float(dist[prev][depot_id]) + + if recompute_ok: + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance, 1e-3 absolute floor. + tol_obj = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol_obj: + normalizer = max(abs(true_obj), eps) + violated_constraints.add(7) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed sum of route arc costs=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={tol_obj:.6g})" + ) + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": normalizer, + "ratio": float(abs_diff) / normalizer, + }) + + # ========================================================================= + # Build result + # ========================================================================= + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes if not feasible else [], + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Robust CVRP (Pessoa et al. 2021)" + ) + 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("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/pessoa2021/gurobi_code.py b/tasks/pessoa2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..89da4c210773de021c134ebc1d7c0397aef62b12 --- /dev/null +++ b/tasks/pessoa2021/gurobi_code.py @@ -0,0 +1,312 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Robust Capacitated Vehicle Routing Problem (RCVRP) +with Knapsack Uncertainty, based on Pessoa et al. (2021). + +Since the set-partitioning formulation (14)-(17) has an exponential number of +variables (one per feasible route per vehicle type), it cannot be solved directly. +Instead, we use a compact two-index vehicle flow formulation with robust capacity +constraints, which can be handled directly by Gurobi. + +The two-index formulation uses binary arc variables x_{ij} and enforces robust +capacity via subtour elimination / capacity inequalities. For D^{card}, the +worst-case demand for a subset S is computed via a sorting-based approach. +""" + +import argparse +import json +import math +import itertools +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def load_instance(path): + with open(path, 'r') as f: + data = json.load(f) + return data + + +def compute_worst_case_demand_card(customers_in_S, Gamma): + """ + For D^{card}: max_{d in D} sum_{i in S} d_i + = sum_{i in S} bar_d_i + hat_d_Gamma(S) + where hat_d_Gamma(S) = sum of the Gamma largest deviations in S. + """ + nominal_sum = sum(c['nominal_demand'] for c in customers_in_S) + deviations = sorted([c['demand_deviation'] for c in customers_in_S], reverse=True) + dev_sum = sum(deviations[:min(Gamma, len(deviations))]) + return nominal_sum + dev_sum + + +def solve_rcvrp(instance, time_limit): + n = instance['num_customers'] + m_vehicles = instance['num_vehicles'] + C = instance['vehicle_capacity'] + depot = instance['depot'] + customers = instance['customers'] + dist = instance['distance_matrix'] + unc = instance['uncertainty_set'] + Gamma = unc['Gamma'] + + # Nodes: 0 = depot, 1..n = customers + V = list(range(n + 1)) + V0 = list(range(1, n + 1)) # customer nodes + + # Customer data indexed by node id (1..n) + bar_d = {c['id']: c['nominal_demand'] for c in customers} + hat_d = {c['id']: c['demand_deviation'] for c in customers} + cust_by_id = {c['id']: c for c in customers} + + # Create model + model = gp.Model("RCVRP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables: x[i,j] = 1 if arc (i,j) is used + x = {} + for i in V: + for j in V: + if i != j: + x[i, j] = model.addVar(vtype=GRB.BINARY, obj=dist[i][j], + name=f"x_{i}_{j}") + + model.update() + + # Constraint: each customer is visited exactly once (in-degree = 1) + for j in V0: + model.addConstr( + gp.quicksum(x[i, j] for i in V if i != j) == 1, + name=f"in_{j}" + ) + + # Constraint: each customer is left exactly once (out-degree = 1) + for i in V0: + model.addConstr( + gp.quicksum(x[i, j] for j in V if j != i) == 1, + name=f"out_{i}" + ) + + # Constraint: exactly m vehicles leave the depot + model.addConstr( + gp.quicksum(x[0, j] for j in V0) == m_vehicles, + name="depot_out" + ) + + # Constraint: exactly m vehicles return to the depot + model.addConstr( + gp.quicksum(x[i, 0] for i in V0) == m_vehicles, + name="depot_in" + ) + + # Subtour elimination and robust capacity constraints via lazy constraints. + # We use a callback approach: whenever an integer solution is found, + # check for subtours and add robust capacity inequalities. + + # We also add MTZ-like constraints as a starting point to help with subtours. + # u[i] = cumulative demand up to customer i in its route (under nominal demand). + # This is a simplification; the robust capacity is enforced via callbacks. + u = {} + for i in V0: + u[i] = model.addVar(lb=bar_d[i], ub=C, vtype=GRB.CONTINUOUS, name=f"u_{i}") + + model.update() + + # MTZ constraints with nominal demands (provides a lower bound on capacity) + for i in V0: + for j in V0: + if i != j: + model.addConstr( + u[j] >= u[i] + bar_d[j] - C * (1 - x[i, j]), + name=f"mtz_{i}_{j}" + ) + + # Use lazy constraints callback for robust capacity cuts + def callback(model, where): + if where == GRB.Callback.MIPSOL: + x_val = model.cbGetSolution(x) + + # Build adjacency from solution + adj = {i: [] for i in V} + for (i, j), var in x.items(): + if x_val[i, j] > 0.5: + adj[i].append(j) + + # Find routes starting from depot + visited = set() + routes = [] + for j in adj[0]: + if j == 0: + continue + route = [] + cur = j + while cur != 0 and cur not in visited: + visited.add(cur) + route.append(cur) + nexts = adj[cur] + if nexts: + cur = nexts[0] + else: + break + if route: + routes.append(route) + + # Check for subtours (nodes not connected to depot) + all_visited = set() + for r in routes: + all_visited.update(r) + + # Find any customer nodes forming subtours (not connected to depot) + unvisited = set(V0) - all_visited + if unvisited: + # Find connected components among unvisited nodes + remaining = set(unvisited) + while remaining: + # BFS to find a component + start = next(iter(remaining)) + component = set() + queue = [start] + while queue: + node = queue.pop(0) + if node in component: + continue + component.add(node) + for j in V: + if j != node and (node, j) in x and x_val[node, j] > 0.5: + if j in remaining and j not in component: + queue.append(j) + remaining -= component + S = list(component) + # Add subtour elimination constraint + model.cbLazy( + gp.quicksum(x[i, j] for i in V if i not in component + for j in S if i != j and (i, j) in x) >= 1 + ) + + # Check robust capacity for each route + for route in routes: + route_customers = [cust_by_id[i] for i in route] + wc_demand = compute_worst_case_demand_card(route_customers, Gamma) + if wc_demand > C + 1e-6: + S = set(route) + # Compute the minimum number of vehicles needed for this subset + # under robust capacity: ceil(wc_demand / C) + min_vehicles = math.ceil(wc_demand / C) + model.cbLazy( + gp.quicksum(x[i, j] for i in V if i not in S + for j in S if (i, j) in x) >= min_vehicles + ) + + # Also add some initial robust rounded capacity inequalities (Eq. 18) + # for small subsets to strengthen the formulation + if n <= 20: + for size in range(2, min(n + 1, 6)): + for S_tuple in itertools.combinations(V0, size): + S = list(S_tuple) + S_set = set(S) + route_customers = [cust_by_id[i] for i in S] + wc_demand = compute_worst_case_demand_card(route_customers, Gamma) + min_vehicles = math.ceil(wc_demand / C) + if min_vehicles >= 2: + model.addConstr( + gp.quicksum(x[i, j] for i in V if i not in S_set + for j in S if (i, j) in x) >= min_vehicles, + name=f"rcc_{'_'.join(str(s) for s in S)}" + ) + + model.setParam("LazyConstraints", 1) + model.optimize(callback) + + # Extract solution + solution = { + "objective_value": None, + "status": None, + "routes": [] + } + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + solution["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + + # Extract routes + adj = {i: [] for i in V} + for (i, j) in x: + if x[i, j].X > 0.5: + adj[i].append(j) + + visited = set() + for j in sorted(adj[0]): + if j == 0: + continue + route = [] + cur = j + while cur != 0 and cur not in visited: + visited.add(cur) + route.append(cur) + nexts = adj[cur] + if nexts: + cur = nexts[0] + else: + break + if route: + route_customers = [cust_by_id[i] for i in route] + route_cost = dist[0][route[0]] + for idx in range(len(route) - 1): + route_cost += dist[route[idx]][route[idx + 1]] + route_cost += dist[route[-1]][0] + wc_demand = compute_worst_case_demand_card(route_customers, Gamma) + solution["routes"].append({ + "customers": route, + "cost": route_cost, + "worst_case_demand": wc_demand + }) + else: + solution["objective_value"] = None + solution["status"] = "infeasible" + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for Robust CVRP with Knapsack Uncertainty (Pessoa et al. 2021)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + instance = load_instance(args.instance_path) + solution = solve_rcvrp(instance, args.time_limit) + + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/pessoa2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/pessoa2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pessoa2021/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/pessoa2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/pessoa2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pessoa2021/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/pessoa2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/pessoa2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pessoa2021/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/pessoa2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/pessoa2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pessoa2021/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/pessoa2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/pessoa2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pessoa2021/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/pessoa2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/pessoa2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pessoa2021/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/pessoa2021/gurobi_solution/large_solution_1.json b/tasks/pessoa2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6a099fcaaef3c7ddc0717ff820321eaaf3381a04 --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b18802af09ce792f99802ca4df23c16b20144b724512a7a759a789ce187275c +size 4384 diff --git a/tasks/pessoa2021/gurobi_solution/large_solution_2.json b/tasks/pessoa2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..bd1171e2de63e2eae24cda1f5bc89c8618f3b065 --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd3aa0c352a7b481472dc3e2de8433c95ac8b5c19db6e08438b2b985e0d94bf4 +size 3787 diff --git a/tasks/pessoa2021/gurobi_solution/large_solution_3.json b/tasks/pessoa2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..cbefeea83eb942edd66a96f094a646b1dfa5da15 --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0542ec5d359cf7011ca78213389fea9203a35c41fbec2a832d01b5095b11aaaf +size 4382 diff --git a/tasks/pessoa2021/gurobi_solution/large_solution_4.json b/tasks/pessoa2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8694c09fd41e2b86ac41f4959dcb95602972a8c0 --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98c64e446ad3b44a0feef0a1ee832ad56806d7607b2c51f3789a557270268a31 +size 3789 diff --git a/tasks/pessoa2021/gurobi_solution/large_solution_5.json b/tasks/pessoa2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..f75738f85c115cc5b94ca1118a9bc37c481def07 --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5bcac354862f2d072dddab9a77f22b637d2d63df6ac1b319775e4f0212676265 +size 4387 diff --git a/tasks/pessoa2021/gurobi_solution/tiny_solution.json b/tasks/pessoa2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..87dd5717c204b0d92643e38c747511a290408a70 --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5375d16c0f86489d81d0535db34ddc2f3999c5dbfb68f7d3530e72ac3698fc8 +size 502 diff --git a/tasks/pessoa2021/gurobi_solution_log/large_log_1.jsonl b/tasks/pessoa2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9efb7ac3dcc00d328652617a296fa660e8e525ca --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0559e5fd12a9f35d3f9207e5cfc0e5b9bc43378157db0ffd98929b3c8a9cd865 +size 558 diff --git a/tasks/pessoa2021/gurobi_solution_log/large_log_2.jsonl b/tasks/pessoa2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f0048ba04d3e9498491fd5545d172335e962df21 --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f59ed5840132d9d3c66a0f0f7a2159562c959f8724969da3e8244e52fe194a3 +size 343 diff --git a/tasks/pessoa2021/gurobi_solution_log/large_log_3.jsonl b/tasks/pessoa2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3234e459f99fb02f1927f0543e7109b740e30e16 --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07dfc8fba7c21b971c74c14ea22c7aa40b88fd82fa0d786e13142f2f811c30c2 +size 257 diff --git a/tasks/pessoa2021/gurobi_solution_log/large_log_4.jsonl b/tasks/pessoa2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..49c404339edccc40ddca7fa5617439a090d929f5 --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7e08c2815ab929ab34275d7134bac3b1fd7e6fdb858679cd94db7d39fd57512 +size 387 diff --git a/tasks/pessoa2021/gurobi_solution_log/large_log_5.jsonl b/tasks/pessoa2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0739010a154cacdd3b2adf8d81263ed97fb9cb3a --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8e315e3d114449a14092204ee530291dd38d2a033839700ee027a16b7b15920 +size 444 diff --git a/tasks/pessoa2021/gurobi_solution_log/tiny_log.jsonl b/tasks/pessoa2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fa3f5a330e634db953bef307c894fe2292b17c7e --- /dev/null +++ b/tasks/pessoa2021/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cda979b3f46d05534a95cd9f40a63403d445229d6449518ac308eaf4dedd61ec +size 84 diff --git a/tasks/pessoa2021/instance/large_instance_1.json b/tasks/pessoa2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9dbe9b187748dbc81529d689b395c4425911b0dd --- /dev/null +++ b/tasks/pessoa2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3179dfcb69dd2e8d901af271f52a60a1eaa0f69c9ff38c87290e0b462b178c38 +size 61373 diff --git a/tasks/pessoa2021/instance/large_instance_2.json b/tasks/pessoa2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e826b76cf9bfd35bee787d0ab8044300a0ea23d1 --- /dev/null +++ b/tasks/pessoa2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16552a4a7e0c33efe3fba172498c5ca3d7633d2e64e1a65602075ef661d4e0b9 +size 29447 diff --git a/tasks/pessoa2021/instance/large_instance_3.json b/tasks/pessoa2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..7e7350ccd5071d7887d228fc8fb1584e48bc8c40 --- /dev/null +++ b/tasks/pessoa2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de42ff587dc82fe8ee5659011bd4d1d231dbe8a81874b8379a9c8e990bb67cc9 +size 61392 diff --git a/tasks/pessoa2021/instance/large_instance_4.json b/tasks/pessoa2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..be49f4a11b51a57015a7be6bc3f78ecdf5aca9b1 --- /dev/null +++ b/tasks/pessoa2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd33fc3f43fab887961725c49ab89ad47de286bd4200a3ed6fa3e9c9c71db4b8 +size 29474 diff --git a/tasks/pessoa2021/instance/large_instance_5.json b/tasks/pessoa2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..47403dcc4b20467e30ed0f5386aad89fce118f38 --- /dev/null +++ b/tasks/pessoa2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52352755dc2de38a8ca8ad79943292827a05dd2690152406d63e6891899ab8d5 +size 61359 diff --git a/tasks/pessoa2021/instance/tiny_instance.json b/tasks/pessoa2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..8b536e06768dc31df35be4abb2ac6494f0b74f2d --- /dev/null +++ b/tasks/pessoa2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4cf3400bde39ff7564e5f60d276bad5d6725cff9170746a7b7aaf30a89355ef +size 3641 diff --git a/tasks/pessoa2021/instance_schema.json b/tasks/pessoa2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..6a4ca60f05cfd36435eaceeed3727deba265d372 --- /dev/null +++ b/tasks/pessoa2021/instance_schema.json @@ -0,0 +1,23 @@ +{ + "num_customers": " Total number of customers to be served.", + "num_vehicles": " Number of identical vehicles available in the fleet.", + "vehicle_capacity": " Maximum total demand each vehicle can carry under any realized demand scenario.", + "uncertainty_set": { + "Gamma": " Maximum number of customers whose demands may simultaneously deviate from their nominal values." + }, + "depot": { + "id": " Identifier for the depot node in the distance matrix.", + "x": " Horizontal coordinate of the depot.", + "y": " Vertical coordinate of the depot." + }, + "customers": [ + { + "id": " Unique identifier for the customer, used as a node index in the distance matrix.", + "x": " Horizontal coordinate of the customer location.", + "y": " Vertical coordinate of the customer location.", + "nominal_demand": " Expected demand quantity for the customer under normal conditions.", + "demand_deviation": " Maximum amount by which the customer's actual demand can exceed its nominal demand." + } + ], + "distance_matrix": " Transportation cost between each pair of locations, where row/column 0 is the depot and rows/columns 1 through num_customers are customers." +} diff --git a/tasks/pessoa2021/mathematical_formulation.md b/tasks/pessoa2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..73e657369754dabe4f5e369907b54815c9ef2791 --- /dev/null +++ b/tasks/pessoa2021/mathematical_formulation.md @@ -0,0 +1,72 @@ +# Original Formulation: Robust Capacitated Vehicle Routing Problem with Knapsack Uncertainty (Robust CVRP) + +*Source: Branch-cut-and-price for the robust capacitated vehicle routing problem with knapsack uncertainty, Artur Alves Pessoa, Michael Poss, Ruslan Sadykov, François Vanderbeck, 2021 (Operations Research 69(3), 739–754).* + +The problem the paper studies is the robust counterpart of the CVRP. Following the authors’ development (Section 2 reduces the robust feasibility set to a union of deterministic ones; Section 3.2 then states the path/set-partitioning model), the formulation that *defines* the studied problem and is carried into the branch-cut-and-price algorithm and the experiments is the robust path formulation (14)–(17). It is an exponential-column (set-partitioning) model with one route variable per feasible robust route, organized by “vehicle type” $\theta$. + +## Sets and Indices + +- $G=(V,A)$: complete digraph with node set $V=\{0,1,\dots,n\}$ and arc set $A=\{(i,j)\in V\times V : i\neq j\}$. Node $0$ is the unique depot. + +- $V^0=V\setminus\{0\}=\{1,\dots,n\}$: set of customers (written $V_0$ in the tagged equations). + +- $R^0$: set of all routes in $G$ starting and ending at the depot (a route visits each other node at most once). + +- $V_1,\dots,V_s$: a partition of $\{1,\dots,n\}$ defining the knapsack uncertainty set; $k(i)$ denotes the unique index $k$ with $i\in V_k$. + +- $\mathcal{D}$: the knapsack demand-uncertainty set (defined below). + +- $\Theta$: finite set of dual vectors $\theta\in\mathbb{R}_+^s$ indexing the deterministic subproblems, given by Eq. (6): $\Theta=\bigl(\{0\}\cup\{\theta^i_{k(i)}\mid i\in V_1\}\bigr)\times\cdots\times + \bigl(\{0\}\cup\{\theta^i_{k(i)}\mid i\in V_s\}\bigr)$, with $\theta^0_k=0$ and $\theta^i_{k(i)}=\hat{d}_i/w_i$. + +- $\Theta^*\subseteq\Theta$: any set large enough to contain a minimizer of the function minimized in Eq. (4) for each $y\in Y^0$ (e.g. $\Theta$ itself, or $\Theta^{card}$ for $\mathcal{D}^{card}$). + +- $\bar{\Theta}\equiv\{\theta\in\Theta^* : \tilde{\mathcal{R}}_\theta\neq\emptyset\}$: the vehicle types surviving the preprocessing test (those whose tightened route set is non-empty). This is the index set actually summed over in the formulation. + +- For each $\theta\in\bar{\Theta}$, the robust-feasible route set for type $\theta$: $$\mathcal{R}_\theta\equiv\Bigl\{\, r\in R^0 \ \Big|\ \textstyle\sum_{i\in r} d_i^\theta \le C-b^\top\theta \,\Bigr\}.$$ + +## Parameters + +- $n$: number of customers; $m$: number of homogeneous vehicles. + +- $C\in\mathbb{R}_+$: vehicle capacity. + +- $c_{ij}\in\mathbb{R}_+$: transportation cost of arc $(i,j)\in A$. + +- $\bar{d}_i\in\mathbb{R}_+$: nominal demand of customer $i\in V^0$. + +- $\hat{d}_i\in\mathbb{R}_+$: maximum demand deviation of customer $i\in V^0$. + +- $w'\in\mathbb{R}_+^n$, $b'\in\mathbb{R}_+^s$: weights and budgets defining $\mathcal{D}$. + +- Derived (Section 2): $w_i=w'_i\hat{d}_i$ for $i=1,\dots,n$; $b_k=b'_k-\sum_{i\in V_k} w'_i\bar{d}_i$ for $k=1,\dots,s$. + +- For each $\theta\in\Theta$, the type-$\theta$ demand vector $d_i^\theta=\bar{d}_i+\max\{0,\ \hat{d}_i-w_i\theta_{k(i)}\}$, $i=1,\dots,n$, and the type-$\theta$ effective capacity $C-b^\top\theta$. + +- $c_r$: cost of route $r$ (sum of arc costs $c_{ij}$ along $r$). + +- $a_i^r\in\{0,1\}$: $1$ iff customer $i$ is visited by route $r$. + +Demand-uncertainty set (general knapsack form, Section 2.1): $$\mathcal{D}=\Bigl\{\, d\in[\bar{d},\,\bar{d}+\hat{d}] \ \Big|\ \textstyle\sum_{i\in V_k} w'_i d_i \le b'_k,\ k=1,\dots,s \,\Bigr\}.$$ The set of *robust routes* is then $\mathcal{R}\equiv\bigl\{ r\in R^0 \mid \sum_{i\in r} d_i \le C,\ \forall d\in\mathcal{D}\bigr\}$, which by Theorem 3 / Eq. (13) decomposes as $\mathcal{R}=\bigcup_{\theta\in\bar{\Theta}}\mathcal{R}_\theta$. + +## Decision Variables + +$$\lambda_r\in\mathbb{Z}_+ : \text{number of times route } r \text{ is used,} + \quad \text{for } \theta\in\bar{\Theta},\ r\in\mathcal{R}_\theta .$$ The model has an exponential number of such route variables. + +## Objective + +$$\begin{equation} + \min\ \sum_{\theta\in\bar{\Theta}}\ \sum_{r\in\mathcal{R}_\theta} c_r\,\lambda_r \tag{14} +\end{equation}$$ + +## Constraints + +$$\begin{align} + \text{s.t.}\quad + & \sum_{\theta\in\bar{\Theta}}\ \sum_{r\in\mathcal{R}_\theta} a_i^r\,\lambda_r = 1, + && i\in V_0, \tag{15}\\[4pt] + & \sum_{\theta\in\bar{\Theta}}\ \sum_{r\in\mathcal{R}_\theta} \lambda_r = m, \tag{16}\\[4pt] + & \lambda_r\in\mathbb{Z}_+, + && \theta\in\bar{\Theta},\ r\in\mathcal{R}_\theta. \tag{17} +\end{align}$$ Constraints (15) ensure each customer is served by exactly one route; constraint (16) fixes the number of used vehicles (routes) to $m$. diff --git a/tasks/pessoa2021/problem_description.txt b/tasks/pessoa2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..dfe9d299530bb4d526140d73ee0fc7fc19f9f083 --- /dev/null +++ b/tasks/pessoa2021/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A delivery company operates a fleet of identical vehicles out of a single depot to serve a set of customers. The road network is modeled as a complete directed graph on the depot and the customers, with a known transportation cost on every arc between each pair of locations. The input data specifies the number of customers, the number of available vehicles, the common capacity of each vehicle, the two-dimensional coordinates of the depot and every customer, and the matrix of pairwise transportation costs. + +Customer demands are not known exactly at the time routes must be planned. For each customer the company knows a nominal demand and a maximum demand deviation (the largest additional amount by which the actual demand could exceed the nominal value). To express the limited amount of total deviation the company is willing to hedge against, an uncertainty budget Gamma is given. In any realized demand scenario, each customer's actual demand lies between its nominal value and its nominal value plus its deviation, and the sum over all customers of the fractional deviation (the realized increase above nominal divided by that customer's maximum deviation) may not exceed Gamma. In other words, at most Gamma customers can simultaneously deviate fully from their nominal demands, with partial deviations counted proportionally. + +The company must design a set of vehicle routes, one per vehicle, such that every route starts and ends at the depot and visits a sequence of distinct customers. Every customer must appear on exactly one route, and the total number of routes used must equal the number of available vehicles. The essential operational requirement is robustness: the routes must be feasible under every demand realization allowed by the uncertainty budget. That is, for every scenario in which customer demands respect the nominal-plus-deviation bounds and the total fractional deviation does not exceed Gamma, the total demand of the customers visited by each route must not exceed the vehicle capacity. + +The objective is to minimize the total transportation cost, defined as the sum of the arc costs along the chosen routes. diff --git a/tasks/pessoa2021/solution_logger.py b/tasks/pessoa2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/pessoa2021/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/pessoa2021/solution_schema.json b/tasks/pessoa2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..ba2f74963cad8959c0283a9cf651af9d791c12c3 --- /dev/null +++ b/tasks/pessoa2021/solution_schema.json @@ -0,0 +1,10 @@ +{ + "objective_value": " Total transportation cost across all vehicle routes.", + "routes": [ + { + "customers": " Ordered sequence of customer identifiers visited by this vehicle, starting after the depot and ending before the return to depot.", + "cost": " Total travel distance for this route, including departure from and return to the depot.", + "worst_case_demand": " Maximum possible total demand of the customers on this route over all demand realizations within the uncertainty set." + } + ] +} diff --git a/tasks/pettersson2020/feasibility_check.py b/tasks/pettersson2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..840b89fe4fd99455b406117d0082576a8f05d22e --- /dev/null +++ b/tasks/pettersson2020/feasibility_check.py @@ -0,0 +1,420 @@ +""" +Feasibility checker for Multi-Objective Integer Programming (MOIP) solutions. + +Checks candidate solutions against the hard constraints from the mathematical +formulation in Pettersson & Ozlen (2020): + + min f_1(x), ..., f_n(x) + s.t. Ax <= C -- Constraint (1): Knapsack capacity + x in Z^c -- Constraint (2): Integrality (binary) + +Tier-C addition (Constraint 3): objective consistency. +The program reports `objective_value` (count of non-dominated vectors) and +a list of `non_dominated_objective_vectors`. Both are trivially forgeable +by an exploit (e.g. `objective_value = sys.float_info.max` with the +trivial empty selection). This constraint recomputes each claimed +objective vector from `solutions` and `objective_coefficients` and +verifies count parity, so a candidate that lies about either gets +rejected as infeasible. +""" + +import argparse +import itertools +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('non_dominated_objective_vectors', 'objective_value', 'solutions') +_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): + """Return a dict with feasibility verdict and per-constraint details. + + Matches the original `main()` output shape exactly (the eval pipeline + JSON contract): {feasible, violated_constraints, violations, + violation_magnitudes}. + """ + tol = 1e-5 + eps = 1e-5 + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + num_items = instance["num_items"] + weights = instance["weights"] + capacity = instance["capacity"] + obj_coeffs = instance["objective_coefficients"] + num_objectives = instance["num_objectives"] + variable_type = instance.get("variable_type", "binary") + + solutions = solution["solutions"] + reported_obj_vectors = solution.get("non_dominated_objective_vectors", []) + + for sol_idx, x in enumerate(solutions): + # ===================================================================== + # Constraint (1): Ax <= C (knapsack capacity) + # sum(weights[i] * x[i]) <= capacity + # ===================================================================== + lhs = sum(weights[i] * x[i] for i in range(num_items)) + rhs = capacity + violation_amount = max(0.0, lhs - rhs) + if violation_amount > tol: + if 1 not in violated_constraints: + violated_constraints.add(1) + violations.append( + f"Constraint 1 (capacity) violated: solution {sol_idx} " + f"has total weight {lhs} exceeding capacity {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): x in Z^c (integrality / binary) + # Each variable must be integer; for binary problems, x[i] in {0, 1} + # ===================================================================== + for i in range(num_items): + val = x[i] + if variable_type == "binary": + # Must be 0 or 1 + violation_amount = min(abs(val - 0), abs(val - 1)) + else: + # Must be integer + violation_amount = abs(val - round(val)) + + if violation_amount > tol: + if 2 not in violated_constraints: + violated_constraints.add(2) + violations.append( + f"Constraint 2 (integrality) violated: solution {sol_idx}, " + f"variable x[{i}] = {val} is not " + f"{'binary' if variable_type == 'binary' else 'integer'}" + ) + # For integrality, RHS is the nearest feasible integer value + if variable_type == "binary": + nearest = 0 if abs(val) < abs(val - 1) else 1 + else: + nearest = round(val) + rhs_val = float(nearest) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(val), + "rhs": rhs_val, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ========================================================================= + # Constraint (3): Objective consistency (Tier-C anti-exploit) + # + # (a) `objective_value` must equal len(solutions) (it is the count of + # non-dominated objective vectors reported). + # (b) len(solutions) must equal len(non_dominated_objective_vectors). + # (c) For each i, k: + # non_dominated_objective_vectors[i][k] + # == sum_j (objective_coefficients[k][j] * solutions[i][j]) + # + # Tolerance is 0.5 because every quantity here is integer-valued + # (counts and sums of integer coefficients times binary variables); + # an exploit lying by even a single unit must trip the check, while + # legitimate solutions agree exactly. + # ========================================================================= + reported_obj = solution.get("objective_value") + n_sols = len(solutions) + n_vecs = len(reported_obj_vectors) + + def _record_obj_violation(message, lhs_val, rhs_val, raw_excess): + if 3 not in violated_constraints: + violated_constraints.add(3) + violations.append(f"Constraint 3 (objective consistency) violated: {message}") + try: + rhs_f = float(rhs_val) + except (TypeError, ValueError): + rhs_f = 0.0 + try: + lhs_f = float(lhs_val) + except (TypeError, ValueError): + lhs_f = 0.0 + try: + excess_f = float(raw_excess) + except (TypeError, ValueError): + excess_f = 1.0 + normalizer = max(abs(rhs_f), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs_f, + "rhs": rhs_f, + "raw_excess": excess_f, + "normalizer": float(normalizer), + "ratio": float(excess_f / normalizer), + }) + + # (a) reported objective_value must equal the integer count of solutions + try: + reported_count = float(reported_obj) + reported_finite = True + except (TypeError, ValueError): + reported_count = float("nan") + reported_finite = False + + if not reported_finite or reported_count != reported_count: # missing or NaN + _record_obj_violation( + f"objective_value={reported_obj!r} is missing or not numeric " + f"(expected count of non-dominated vectors = {n_sols})", + reported_obj if isinstance(reported_obj, (int, float)) else 0.0, + n_sols, + abs(n_sols), + ) + elif abs(reported_count - n_sols) > 0.5: + _record_obj_violation( + f"objective_value={reported_count} differs from count of solutions={n_sols}", + reported_count, + n_sols, + abs(reported_count - n_sols), + ) + + # (b) the two reported lists must have the same length + if n_sols != n_vecs: + _record_obj_violation( + f"len(solutions)={n_sols} differs from " + f"len(non_dominated_objective_vectors)={n_vecs}", + n_sols, + n_vecs, + abs(n_sols - n_vecs), + ) + + # (c) each claimed obj vector must match the recomputed sum from its + # solution. Only run when shapes line up so we never index out of range. + if n_sols == n_vecs and n_sols > 0: + for sol_idx, (x, claimed_vec) in enumerate(zip(solutions, reported_obj_vectors)): + if not isinstance(claimed_vec, (list, tuple)) or len(claimed_vec) != num_objectives: + _record_obj_violation( + f"solution {sol_idx}: claimed obj vector has wrong length " + f"({len(claimed_vec) if hasattr(claimed_vec, '__len__') else 'N/A'} " + f"vs expected {num_objectives})", + len(claimed_vec) if hasattr(claimed_vec, "__len__") else 0, + num_objectives, + 1.0, + ) + continue + + # itertools.compress is C-implemented and ~10x faster than a + # Python multiply-and-sum loop on the binary path, which matters + # because num_items can be 1e7. + binary_path = (variable_type == "binary") and all(v in (0, 1) for v in x[:min(64, len(x))]) + for k in range(num_objectives): + if binary_path: + recomputed_k = sum(itertools.compress(obj_coeffs[k], x)) + else: + recomputed_k = sum(obj_coeffs[k][j] * x[j] for j in range(num_items)) + try: + claimed_k = float(claimed_vec[k]) + except (TypeError, ValueError): + _record_obj_violation( + f"solution {sol_idx} objective {k}: claimed value " + f"{claimed_vec[k]!r} is not numeric (recomputed={recomputed_k})", + 0.0, float(recomputed_k), 1.0, + ) + continue + diff = abs(claimed_k - float(recomputed_k)) + if diff > 0.5: + _record_obj_violation( + f"solution {sol_idx} objective {k}: claimed value " + f"{claimed_k} differs from recomputed " + f"sum_j(obj_coeffs[{k}][j]*x[j])={recomputed_k} " + f"(|diff|={diff})", + claimed_k, float(recomputed_k), 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 MOIP knapsack 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() + + with open(args.instance_path, 'r') as f: + instance = json.load(f) + with open(args.solution_path, 'r') as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"Result: {status}") + if not result["feasible"]: + 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/pettersson2020/gurobi_code.py b/tasks/pettersson2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..24eaa350c538bf9edf1fdd69d546ddac397c5164 --- /dev/null +++ b/tasks/pettersson2020/gurobi_code.py @@ -0,0 +1,267 @@ +""" +Gurobi-based exact solver for Multi-Objective Integer Programming (MOIP). + +Implements the AIRA algorithm (Algorithm 3 from Pettersson & Ozlen 2020) using +the identity permutation to find all non-dominated objective vectors for a +multi-objective knapsack problem. + +The algorithm recursively solves constrained lexicographic subproblems +OIP_s^n(k, (a_{s(k+1)}, ..., a_{s(n)})) using Gurobi as the single-objective +IP solver. +""" + +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_base_model(instance): + """Build the base Gurobi model for the knapsack problem (constraints only).""" + n_items = instance["num_items"] + weights = instance["weights"] + capacity = instance["capacity"] + + model = gp.Model("moip_knapsack") + model.setParam("OutputFlag", 0) + + # Binary decision variables + x = model.addVars(n_items, vtype=GRB.BINARY, name="x") + + # Knapsack capacity constraint: sum(w_i * x_i) <= capacity + model.addConstr( + gp.quicksum(weights[i] * x[i] for i in range(n_items)) <= capacity, + name="capacity" + ) + + model.update() + return model, x + + +def solve_single_objective_ip(instance, obj_index, upper_bounds, perm, time_limit_remaining): + """ + Solve a single-objective IP: + min f_{perm[0]}(x) + s.t. Ax <= C + f_{perm[i]}(x) <= upper_bounds[perm[i]] for i in {1, ..., n-1} + x in {0,1}^c + + Returns the solution x and objective values, or None if infeasible. + """ + if time_limit_remaining <= 0: + return None + + n_items = instance["num_items"] + obj_coeffs = instance["objective_coefficients"] + n_obj = instance["num_objectives"] + + model, x = build_base_model(instance) + model.setParam("TimeLimit", max(1, time_limit_remaining)) + model.setParam("Threads", 1) + + # Set objective: minimize f_{perm[0]} + # Since this is a knapsack where we MINIMIZE, and the paper says minimize, + # we minimize the sum of selected item coefficients. + primary_obj = perm[obj_index] + model.setObjective( + gp.quicksum(obj_coeffs[primary_obj][i] * x[i] for i in range(n_items)), + GRB.MINIMIZE + ) + + # Add upper bound constraints for constrained objectives + for idx in range(n_obj): + obj_id = perm[idx] + if obj_id in upper_bounds and upper_bounds[obj_id] < float('inf'): + model.addConstr( + gp.quicksum(obj_coeffs[obj_id][i] * x[i] for i in range(n_items)) <= upper_bounds[obj_id], + name=f"ub_obj_{obj_id}" + ) + + model.optimize() + + if model.status == GRB.OPTIMAL or (model.status == GRB.TIME_LIMIT and model.SolCount > 0): + sol = [int(round(x[i].X)) for i in range(n_items)] + obj_vals = [] + for o in range(n_obj): + val = sum(obj_coeffs[o][i] * sol[i] for i in range(n_items)) + obj_vals.append(val) + return {"solution": sol, "obj_vals": obj_vals} + else: + return None + + +def is_dominated(obj_a, obj_b): + """Check if obj_a is dominated by obj_b (all minimize).""" + all_leq = all(b <= a for a, b in zip(obj_a, obj_b)) + any_lt = any(b < a for a, b in zip(obj_a, obj_b)) + return all_leq and any_lt + + +def filter_dominated(nd_set): + """Remove dominated solutions from the set.""" + filtered = [] + for i, sol_i in enumerate(nd_set): + dominated = False + for j, sol_j in enumerate(nd_set): + if i != j and is_dominated(sol_i["obj_vals"], sol_j["obj_vals"]): + dominated = True + break + if not dominated: + filtered.append(sol_i) + return filtered + + +def aira_worker(instance, perm, k, upper_bounds, start_time, time_limit, prev_solutions=None): + """ + Algorithm 3: Worker thread (sequential version for Gurobi baseline). + + Solves OIP_s^n(k, (a_{s(k+1)}, ..., a_{s(n)})) where: + - perm defines the ordering s + - k is the number of free objectives (1-indexed) + - upper_bounds maps objective index -> upper bound value + + Returns list of non-dominated solutions. + """ + elapsed = time.time() - start_time + if elapsed >= time_limit: + return [] + + n_obj = instance["num_objectives"] + nd_k = [] + + # Step 2: Relaxation reuse check + # If previous solutions all satisfy current bounds, reuse them + if prev_solutions is not None: + all_satisfy = True + for sol in prev_solutions: + for idx in range(k, n_obj): + obj_id = perm[idx] + if obj_id in upper_bounds and sol["obj_vals"][obj_id] > upper_bounds[obj_id]: + all_satisfy = False + break + if not all_satisfy: + break + if all_satisfy and len(prev_solutions) > 0: + return prev_solutions + + # Step 3: Base case (k == 1) + if k == 1: + time_remaining = time_limit - (time.time() - start_time) + result = solve_single_objective_ip(instance, 0, upper_bounds, perm, time_remaining) + if result is not None: + nd_k = [result] + return nd_k + + # Step 4: Recursive case (k > 1) + # Let a_{s(k)} = infinity (index k-1 in 0-based perm) + current_obj = perm[k - 1] # The k-th objective in permuted order (0-based: k-1) + + # Create bounds for subproblem: add current_obj with bound = infinity + sub_bounds = dict(upper_bounds) + sub_bounds[current_obj] = float('inf') + + # Solve P = OIP_s^n(k-1, (a_{s(k)}, a_{s(k+1)}, ..., a_{s(n)})) + prev_sol = None + Y = aira_worker(instance, perm, k - 1, sub_bounds, start_time, time_limit, prev_sol) + + while len(Y) > 0: + elapsed = time.time() - start_time + if elapsed >= time_limit: + break + + # Step 4a: Collect solutions + nd_k.extend(Y) + + # Step 4b: Update bound on f_{s(k)} + # a_{s(k)} = max{f_{s(k)}(x) | x in Y} - 1 + # We subtract 1 because variables are integer, so we need strictly less + max_val = max(sol["obj_vals"][current_obj] for sol in Y) + new_bound = max_val - 1 # Integer variables: strict < is equivalent to <= (val-1) + + if current_obj in sub_bounds and sub_bounds[current_obj] != float('inf'): + # If we already have a bound, take the minimum (tighter) + sub_bounds[current_obj] = min(sub_bounds[current_obj], new_bound) + else: + sub_bounds[current_obj] = new_bound + + # Step 4d: Re-solve with updated bound + prev_sol = Y + Y = aira_worker(instance, perm, k - 1, sub_bounds, start_time, time_limit, prev_sol) + + # Filter dominated solutions + nd_k = filter_dominated(nd_k) + return nd_k + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi-based AIRA solver for Multi-Objective Integer Programming" + ) + 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) + n_obj = instance["num_objectives"] + + start_time = time.time() + + # Use identity permutation: s = (0, 1, 2, ..., n-1) (0-indexed) + perm = list(range(n_obj)) + upper_bounds = {} # No initial upper bounds + + # Run AIRA (Algorithm 3) with k = n (all objectives free) + nd_solutions = aira_worker(instance, perm, n_obj, upper_bounds, start_time, args.time_limit) + + # Filter dominated across all found solutions + nd_solutions = filter_dominated(nd_solutions) + + elapsed = time.time() - start_time + + # Compute objective_value as the number of non-dominated solutions found + # **INFERRED ASSUMPTION**: Since this is a multi-objective problem with no single + # scalar objective, we report the count of non-dominated solutions as the + # objective_value. This is a reasonable proxy for solution quality. + result = { + "objective_value": len(nd_solutions), + "num_non_dominated_solutions": len(nd_solutions), + "non_dominated_objective_vectors": [sol["obj_vals"] for sol in nd_solutions], + "solutions": [sol["solution"] for sol in nd_solutions], + "elapsed_time": elapsed, + "time_limit_reached": elapsed >= 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"Found {len(nd_solutions)} non-dominated solutions in {elapsed:.2f}s") + + +if __name__ == "__main__": + main() diff --git a/tasks/pettersson2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/pettersson2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pettersson2020/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/pettersson2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/pettersson2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pettersson2020/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/pettersson2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/pettersson2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pettersson2020/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/pettersson2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/pettersson2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pettersson2020/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/pettersson2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/pettersson2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pettersson2020/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/pettersson2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/pettersson2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pettersson2020/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/pettersson2020/gurobi_solution/large_solution_1.json b/tasks/pettersson2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f61cfd3241eb323c45811b0eb0ccd1ba6f3a6400 --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8017e8bbea90b0f06e8f45ed9b3be1bcc4438722874e7c7def9c5b6a3fc79a9f +size 90000268 diff --git a/tasks/pettersson2020/gurobi_solution/large_solution_2.json b/tasks/pettersson2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..38b01724578ec41c5a99358c0a8b25d8cff360da --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb8ad31e967b30425ad190cef3073925b0983f7251f45170844d351683ae0cbb +size 90000267 diff --git a/tasks/pettersson2020/gurobi_solution/large_solution_3.json b/tasks/pettersson2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d40b9b140643b85814ffcf8be7abde6b89777b3d --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a28369275cd2ceb2ed184467db99aaa55dc63b3a5367076cca57a499159d3bad +size 90000267 diff --git a/tasks/pettersson2020/gurobi_solution/large_solution_4.json b/tasks/pettersson2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..6062e8e63e090a562d42ca1fb389136af069c030 --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd1ae045d7caf8f8bde8eade15af53c14bdae48c68d2a44331b27f1694da7ee7 +size 90000267 diff --git a/tasks/pettersson2020/gurobi_solution/large_solution_5.json b/tasks/pettersson2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..6427a1571d571f83ae89f774b44ed3aac2a116f4 --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0556724ac06f8b829118f9d7ecd972cd10f29d49e31fd04bb5aa1e75fa414fae +size 90000266 diff --git a/tasks/pettersson2020/gurobi_solution/tiny_solution.json b/tasks/pettersson2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..6ce2724c518548973a6abc97d9dec0367fe47793 --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4cdf20bed380aa20f677a4c2599f3ded26aa219b04c7ba3f01b118fa0c91d9e +size 457 diff --git a/tasks/pettersson2020/gurobi_solution_log/large_log_1.jsonl b/tasks/pettersson2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..00468d88f5c34b74a4fe83dcc166f536d06bd46a --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00a576fb0fec42a32d5dbc34c78aeb421eed8e81c4e0f2d082cac3c866a87e98 +size 41 diff --git a/tasks/pettersson2020/gurobi_solution_log/large_log_2.jsonl b/tasks/pettersson2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c7dc340e2596eb939f797c28e894673ae74d55e3 --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c7dad598932fa9c5b37222678c4598d279fba3d953de9a32f5c37b8e54d947be +size 41 diff --git a/tasks/pettersson2020/gurobi_solution_log/large_log_3.jsonl b/tasks/pettersson2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e5587c7e94cddf4852d8fecf39bad53d89bbc0d6 --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc50c15db2019a83af6b76c3e32ef80b63a404e45f4008faf7c4e858ac6fc167 +size 41 diff --git a/tasks/pettersson2020/gurobi_solution_log/large_log_4.jsonl b/tasks/pettersson2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..48aea285053b977fce335387268795ec6865a5bb --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9dfe16a48d2cef90f2006044128907a3efabcc1ba746ebfb9cc3b4d90fa6df64 +size 41 diff --git a/tasks/pettersson2020/gurobi_solution_log/large_log_5.jsonl b/tasks/pettersson2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d2cdf0fa7d3332392af4b3b6db580564c6642148 --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e467b787bf30a0c6651d3073e45423ad94ef383db7b0a041a47a8edd23d62578 +size 41 diff --git a/tasks/pettersson2020/gurobi_solution_log/tiny_log.jsonl b/tasks/pettersson2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..298b55e9d44438fcb6c905ac21f2fe9567c44797 --- /dev/null +++ b/tasks/pettersson2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d2957ef530f44294d0e0d42db45190aeef0814d3c44921e7182d06ddae728a4 +size 40 diff --git a/tasks/pettersson2020/instance/large_instance_1.json b/tasks/pettersson2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ba0e9baa9f270437ab7d2b093bef83520e148936 --- /dev/null +++ b/tasks/pettersson2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:653b65a054d02f8d0f78b733c26afea8abe42cdf0d9739ac32f40541da0512f9 +size 380975636 diff --git a/tasks/pettersson2020/instance/large_instance_2.json b/tasks/pettersson2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a120b23ebb99eea9877fc6813ea036738fa2218b --- /dev/null +++ b/tasks/pettersson2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04249b618edbeaeb75792328a54f6564581be2d730c1bf8056a38e10b37d32ef +size 380789229 diff --git a/tasks/pettersson2020/instance/large_instance_3.json b/tasks/pettersson2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1e69408a2d1b3dd7ab77437ded0fc28f98628b4a --- /dev/null +++ b/tasks/pettersson2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d2e8c4935ee4411aafd5ea4db594fa6e38a1ef0f3a4042a0e32a7502c1f4ae2 +size 381949978 diff --git a/tasks/pettersson2020/instance/large_instance_4.json b/tasks/pettersson2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..88ca5d6165f1cd3ab5f1afd75ea98cf1c071dfff --- /dev/null +++ b/tasks/pettersson2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:487adf09315d940dd1c1130a9a9ebf7cfb164a114bc6528ea509fc14f095ee32 +size 380976326 diff --git a/tasks/pettersson2020/instance/large_instance_5.json b/tasks/pettersson2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..78461c9e73bdb48b457e1c9adbd87fbc991d8125 --- /dev/null +++ b/tasks/pettersson2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70804be1b8456ec389441c75a89b013314fe9481fee018e40d2a7bf7af720fba +size 380972587 diff --git a/tasks/pettersson2020/instance/tiny_instance.json b/tasks/pettersson2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..dabc01a4ac3638fb2ffb9d6729d7a37e8a9f9e9d --- /dev/null +++ b/tasks/pettersson2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a7ce27f1e4340bdbcc53c996de883084f2dfc781f4131d16c96702184485c4d +size 1649 diff --git a/tasks/pettersson2020/instance_schema.json b/tasks/pettersson2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e08ad9129e7499b32eb31d388c4b2fda6b92eec4 --- /dev/null +++ b/tasks/pettersson2020/instance_schema.json @@ -0,0 +1,7 @@ +{ + "num_items": " Number of items available for selection.", + "num_objectives": " Number of objectives to be simultaneously minimized.", + "weights": " Weight of each item.", + "capacity": " Maximum total weight the knapsack can hold.", + "objective_coefficients": " Contribution of each item to each objective when selected." +} \ No newline at end of file diff --git a/tasks/pettersson2020/mathematical_formulation.md b/tasks/pettersson2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..e005af2128425b56a8d63802474d1a3cc08e8dce --- /dev/null +++ b/tasks/pettersson2020/mathematical_formulation.md @@ -0,0 +1,35 @@ +# Original Formulation: Multi-Objective Integer Program (MOIP) + +**Source.** Pettersson & Ozlen (2020), “Multi-objective integer programming: Synergistic parallel approaches,” Section 2.2. + +The paper states the abstract multi-objective integer program (MOIP) that the proposed parallel algorithms operate on; single-objective integer leaf subproblems of the same abstract form are what is ultimately handed to the solver. For the knapsack problem instance used in the computational experiments, the integer vector specializes to a binary vector. + +## Notation + +- $n$ — number of objective functions (all minimized). + +- $c$ — dimension of the decision vector. + +- $f_1(\mathbf{x}),\ldots,f_n(\mathbf{x})$ — linear objective functions. + +- $A$, $C$ — constraint matrix and right-hand-side vector. + +- $\mathbf{x} \in \mathbb{Z}^c$ — integer decision vector. + +## Abstract MOIP + +$$\begin{align} +\min\quad +& \bigl(f_1(\mathbf{x}),\; f_2(\mathbf{x}),\; \ldots,\; f_n(\mathbf{x})\bigr) \tag{1}\\ +\text{s.t.}\quad +& A\,\mathbf{x} \;\le\; C, \tag{2}\\ +& \mathbf{x} \in \mathbb{Z}^c. \tag{3} +\end{align}$$ + +A feasible objective vector $(z_1,\ldots,z_n)$ is *dominated* by $(z'_1,\ldots,z'_n)$ iff $z'_k\le z_k$ for all $k$ with at least one strict inequality; the target is the set of non-dominated objective vectors. + +## Binary Knapsack Specialization + +For the 0-1 multi-objective knapsack instances of Section 4.2, (3) is replaced by $$\begin{align} +& \mathbf{x} \in \{0,1\}^c. \tag{3'} +\end{align}$$ All $f_\ell(\mathbf{x}) = -\mathbf{p}_\ell^{\top}\mathbf{x}$ are linear (equivalently, maximizing profits), and the single linear constraint $A\mathbf{x}\le C$ is the capacity constraint $\sum_{i=1}^{c} w_i x_i \le W$. diff --git a/tasks/pettersson2020/problem_description.txt b/tasks/pettersson2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..4139f4c92fe432400b908bf07a762c3d8343bf8f --- /dev/null +++ b/tasks/pettersson2020/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A collection of items is available for selection, where each item either is or is not included. The number of items and the number of objectives are given as input. Each item has a known integer weight, and there is a single knapsack with a known integer capacity. Each objective is defined by a vector of integer coefficients, one per item, and the value of that objective for a given selection equals the sum of the coefficients of the selected items. The total weight of all selected items must not exceed the knapsack capacity. + +All objectives are to be simultaneously minimized. Because the objectives generally conflict, no single selection of items will minimize every objective at once. Instead, the goal is to identify the complete set of non-dominated objective vectors. An objective vector is the tuple of objective values produced by a particular selection of items. One objective vector dominates another if it is at least as good (no greater) on every objective and strictly better (strictly less) on at least one objective. A non-dominated objective vector is one that is not dominated by any other achievable objective vector. The task is to enumerate every non-dominated objective vector, along with a corresponding item selection that satisfies the capacity limit and produces it. + +The input data for an instance specifies the number of items, the number of objectives, the integer weight of each item, the integer knapsack capacity, and for each objective the integer coefficient associated with every item. Weights and coefficients are drawn from the range sixty through one hundred inclusive, and the capacity equals the integer part of half the sum of all item weights. diff --git a/tasks/pettersson2020/solution_logger.py b/tasks/pettersson2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/pettersson2020/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/pettersson2020/solution_schema.json b/tasks/pettersson2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..0b1ed0f732dd7aac55595f92875d3b7c8225391e --- /dev/null +++ b/tasks/pettersson2020/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total number of non-dominated objective vectors found.", + "non_dominated_objective_vectors": " Objective values achieved by each non-dominated item selection.", + "solutions": " Item selections corresponding to each non-dominated objective vector (1 = included, 0 = excluded)." +} \ No newline at end of file diff --git a/tasks/pinnoi1997/feasibility_check.py b/tasks/pinnoi1997/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7537fe709984e7c2a9e5eceab9c88044caf93e1e --- /dev/null +++ b/tasks/pinnoi1997/feasibility_check.py @@ -0,0 +1,455 @@ +""" +Feasibility Checker for the Workload Smoothing Problem (WSP) +From: "A Branch and Cut Approach for Workload Smoothing on Assembly Lines" +by Anulark Pinnoi and Wilbert F. Wilhelm (1997). + +Checks constraints (2)-(7) of the WSP formulation against a candidate solution +plus a new constraint (8) for objective-value consistency (Tier-C defense +against LLM score-gaming exploits that fabricate `objective_value`). + +Constraints (numbered as in the paper, except (8) which is checker-internal): + (2) Assignment: each task assigned to exactly one station + (3) Precedence: if (i,j) in Theta, station(i) <= station(j) + (4) Capacity: sum of processing times at each station <= cycle_time + (5) Binary/integrality: x_{si} in {0,1} (task assigned to integer station in valid range) + (6) Idle time: workload at each station + z_max >= cycle_time + (7) Non-negativity: z_max >= 0 + (8) Objective consistency: reported objective_value must equal + max(0, max_s (cycle_time - workload(s))) within tol = 0.5 + (z_max is integer-valued per the paper). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'task_assignments') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + violations = [] + violation_magnitudes = [] + violated_set = set() + + # --- Extract instance data --- + tasks = sorted(int(t) for t in instance["task_processing_times"].keys()) + p = {int(t): v for t, v in instance["task_processing_times"].items()} + c = instance["cycle_time"] + S_star = instance["num_stations"] + arcs = [(a[0], a[1]) for a in instance["precedence_arcs"]] + E = {int(t): v for t, v in instance["earliest_station"].items()} + L = {int(t): v for t, v in instance["latest_station"].items()} + + # --- Extract solution data --- + task_assignments = {int(t): int(s) for t, s in solution["task_assignments"].items()} + z_max = solution.get("z_max", solution.get("objective_value")) + if z_max is None: + z_max = 0.0 + z_max = float(z_max) + + # Helper to record a violation + def record(constraint_idx, msg, lhs, rhs, operator): + """Record a constraint violation. + operator: 'eq', 'leq', 'geq' + """ + if operator == "leq": + violation_amount = lhs - rhs + elif operator == "geq": + violation_amount = rhs - lhs + elif operator == "eq": + violation_amount = abs(lhs - rhs) + else: + violation_amount = 0.0 + + if violation_amount > tol: + violated_set.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ===================================================================== + # Constraint (2): Assignment — each task assigned to exactly one station + # sum_{s=E_i}^{L_i} x_{si} = 1 for all i in T + # + # In the solution representation, each task maps to one station. + # We check: (a) every task is assigned, (b) no task assigned multiple + # times (impossible with dict), (c) assignment count == 1. + # ===================================================================== + for i in tasks: + if i not in task_assignments: + # Task not assigned at all => LHS=0, RHS=1 + record(2, f"Constraint (2): Task {i} is not assigned to any station.", + 0.0, 1.0, "eq") + + # Check for tasks in solution that are not in instance + for i in task_assignments: + if i not in p: + record(2, f"Constraint (2): Task {i} in solution is not a valid task.", + 0.0, 1.0, "eq") + + # ===================================================================== + # Constraint (3): Precedence + # sum s*x_{si} - sum s*x_{sj} <= 0 for all (i,j) in Theta + # i.e., station(i) <= station(j) + # ===================================================================== + for (i, j) in arcs: + if i in task_assignments and j in task_assignments: + s_i = task_assignments[i] + s_j = task_assignments[j] + lhs = float(s_i - s_j) + rhs = 0.0 + if lhs > tol: + record(3, + f"Constraint (3): Precedence violated for arc ({i},{j}): " + f"task {i} at station {s_i}, task {j} at station {s_j} " + f"(requires station({i}) <= station({j})).", + lhs, rhs, "leq") + + # ===================================================================== + # Constraint (4): Capacity + # sum_{i in T(s)} p_i * x_{si} <= c for all s = 1,...,S* + # ===================================================================== + from collections import defaultdict + station_workloads = defaultdict(int) + for i, s in task_assignments.items(): + if i in p: + station_workloads[s] += p[i] + + for s in range(1, S_star + 1): + workload = station_workloads[s] + lhs = float(workload) + rhs = float(c) + if lhs - rhs > tol: + record(4, + f"Constraint (4): Capacity exceeded at station {s}: " + f"workload {workload} > cycle time {c}.", + lhs, rhs, "leq") + + # ===================================================================== + # Constraint (5): Binary/integrality domain + # x_{si} in {0,1} for s = E_i,...,L_i and i in T + # + # In the solution, task i is assigned to station s. We verify: + # (a) s is an integer + # (b) E_i <= s <= L_i (valid station range) + # (c) 1 <= s <= S* + # ===================================================================== + for i in tasks: + if i not in task_assignments: + continue # already caught by constraint (2) + s = task_assignments[i] + # Check station is in valid range [1, S*] + if s < 1 or s > S_star: + lhs = float(s) + if s < 1: + rhs_val = 1.0 + record(5, + f"Constraint (5): Task {i} assigned to station {s}, " + f"which is below the minimum station 1.", + lhs, rhs_val, "geq") + else: + rhs_val = float(S_star) + record(5, + f"Constraint (5): Task {i} assigned to station {s}, " + f"which exceeds the number of stations S*={S_star}.", + lhs, rhs_val, "leq") + # Check station is within task-specific bounds [E_i, L_i] + e_i = E.get(i, 1) + l_i = L.get(i, S_star) + if s < e_i: + record(5, + f"Constraint (5): Task {i} assigned to station {s}, " + f"which is below its earliest station E_{i}={e_i}.", + float(s), float(e_i), "geq") + elif s > l_i: + record(5, + f"Constraint (5): Task {i} assigned to station {s}, " + f"which exceeds its latest station L_{i}={l_i}.", + float(s), float(l_i), "leq") + + # ===================================================================== + # Constraint (6): Idle time + # sum_i p_i * x_{si} + z_max >= c for all s = 1,...,S* + # ===================================================================== + for s in range(1, S_star + 1): + workload = station_workloads[s] + lhs = float(workload) + z_max + rhs = float(c) + if rhs - lhs > tol: + record(6, + f"Constraint (6): Idle time constraint violated at station {s}: " + f"workload ({workload}) + z_max ({z_max}) = {lhs} < cycle time {c}.", + lhs, rhs, "geq") + + # ===================================================================== + # Constraint (7): Non-negativity + # z_max >= 0 + # ===================================================================== + lhs_z = z_max + rhs_z = 0.0 + if rhs_z - lhs_z > tol: + record(7, + f"Constraint (7): z_max = {z_max} is negative.", + lhs_z, rhs_z, "geq") + + # ===================================================================== + # Constraint (8): Objective consistency (Tier-C anti-exploit defense) + # reported objective_value must equal the true z_max computed from the + # solution: true_z_max = max(0, max_{s=1..S*} (c - workload(s))). + # All obj-determining variables (task_assignments) are present in the + # solution, so this is a full recompute. Tolerance 0.5 because c and + # p_t are integers and the paper notes z_max attains integer values. + # ===================================================================== + 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 not math.isnan(reported_obj): + # Compute true z_max from task assignments and instance data. + # Only iterate s = 1..S* to match the formulation's index range + # for constraints (4) and (6); idle is clamped at 0 to match + # constraint (7) (z_max >= 0). + max_idle = 0.0 + for s in range(1, S_star + 1): + idle = float(c) - float(station_workloads[s]) + if idle > max_idle: + max_idle = idle + true_z_max = max_idle # already >= 0 + abs_diff = abs(reported_obj - true_z_max) + # Integer-valued objective: tighten to 0.5 so a mismatch of >=1 + # always fires while floating-point noise around an integer + # is tolerated. + obj_tol = 0.5 + if abs_diff > obj_tol: + violated_set.add(8) + msg = ( + f"Constraint (8): Objective consistency violated: " + f"reported objective_value={reported_obj} differs from " + f"recomputed z_max=max(0, max_s(c - workload(s)))={true_z_max} " + f"(|diff|={abs_diff:.3g}, tol={obj_tol})." + ) + violations.append(msg) + normalizer = max(abs(true_z_max), eps) + ratio = abs_diff / normalizer + violation_magnitudes.append({ + "constraint": 8, + "lhs": float(reported_obj), + "rhs": float(true_z_max), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # --- Build result --- + feasible = len(violated_set) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the Workload Smoothing Problem (WSP)." + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON candidate solution file.") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result.") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + 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__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/pinnoi1997/gurobi_code.py b/tasks/pinnoi1997/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..f170e786e885bb170d80c6c3b4fe70fd97ddfa30 --- /dev/null +++ b/tasks/pinnoi1997/gurobi_code.py @@ -0,0 +1,272 @@ +""" +Gurobi implementation of the Workload Smoothing Problem (WSP) from: +"A Branch and Cut Approach for Workload Smoothing on Assembly Lines" +by Anulark Pinnoi and Wilbert F. Wilhelm (1997). + +The WSP assigns tasks to S* stations (optimal number) while minimizing +the maximum idle time on any station to balance workloads. +""" + +import argparse +import json +import math +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def load_instance(path): + with open(path, "r") as f: + data = json.load(f) + return data + + +def compute_predecessors_successors(tasks, arcs): + """Compute immediate and transitive predecessor/successor sets.""" + # M(t): immediate predecessors + M = defaultdict(set) + # R(t): immediate successors + R = defaultdict(set) + for (i, j) in arcs: + M[j].add(i) + R[i].add(j) + + # A(t): all predecessors (transitive closure) + A = defaultdict(set) + # B(t): all successors (transitive closure) + B = defaultdict(set) + + # Topological order for predecessor computation + # BFS-based transitive closure + for t in tasks: + # Compute A(t) by BFS backward + visited = set() + stack = list(M[t]) + while stack: + node = stack.pop() + if node not in visited: + visited.add(node) + stack.extend(M[node]) + A[t] = visited + + for t in tasks: + visited = set() + stack = list(R[t]) + while stack: + node = stack.pop() + if node not in visited: + visited.add(node) + stack.extend(R[node]) + B[t] = visited + + return M, R, A, B + + +def compute_E_L(tasks, p, c, S_star, A, B): + """ + Compute earliest and latest station bounds for each task. + + E_i = max(1, ceil((sum of p_k for k in A(i) + p_i) / c)) -- eq (28) + L_i = min(S*, S* + 1 - ceil((p_i + sum of p_k for k in B(i)) / c)) -- eq (29) + """ + E = {} + L = {} + for i in tasks: + pred_sum = sum(p[k] for k in A[i]) + E[i] = max(1, math.ceil((pred_sum + p[i]) / c)) + + succ_sum = sum(p[k] for k in B[i]) + L[i] = min(S_star, S_star + 1 - math.ceil((p[i] + succ_sum) / c)) + + return E, L + + +def solve_wsp(data, time_limit): + """Build and solve the WSP model using Gurobi.""" + # Extract data + tasks = [int(t) for t in data["task_processing_times"].keys()] + p = {int(t): v for t, v in data["task_processing_times"].items()} + c = data["cycle_time"] + S_star = data["num_stations"] + arcs = [(a[0], a[1]) for a in data["precedence_arcs"]] + + # Use provided E, L if available; otherwise compute them + M, R, A, B = compute_predecessors_successors(tasks, arcs) + + # Compute E_i and L_i from the formulas in the paper + E_computed, L_computed = compute_E_L(tasks, p, c, S_star, A, B) + + # Use instance-provided bounds if they are tighter + if "earliest_station" in data: + E_provided = {int(k): v for k, v in data["earliest_station"].items()} + else: + E_provided = {} + if "latest_station" in data: + L_provided = {int(k): v for k, v in data["latest_station"].items()} + else: + L_provided = {} + + E = {} + L = {} + for i in tasks: + E[i] = max(E_computed[i], E_provided.get(i, 1)) + L[i] = min(L_computed[i], L_provided.get(i, S_star)) + + # Validate bounds + for i in tasks: + if E[i] > L[i]: + # Relax to computed bounds if instance bounds are inconsistent + E[i] = E_computed[i] + L[i] = L_computed[i] + + # T(s): tasks that can be assigned to station s + T_s = defaultdict(list) + for i in tasks: + for s in range(E[i], L[i] + 1): + T_s[s].append(i) + + # Build the model + model = gp.Model("WSP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables: x[s,i] = 1 if task i assigned to station s + x = {} + for i in tasks: + for s in range(E[i], L[i] + 1): + x[s, i] = model.addVar(vtype=GRB.BINARY, name=f"x_{s}_{i}") + + # z_max: maximum idle time (continuous variable) + z_max = model.addVar(vtype=GRB.CONTINUOUS, lb=0, name="z_max") + + # Objective: minimize z_max + model.setObjective(z_max, GRB.MINIMIZE) + + # Constraint (2): Assignment - each task assigned to exactly one station + for i in tasks: + model.addConstr( + gp.quicksum(x[s, i] for s in range(E[i], L[i] + 1)) == 1, + name=f"assign_{i}" + ) + + # Constraint (3): Precedence - for each arc (i,j), station(i) <= station(j) + for (i, j) in arcs: + model.addConstr( + gp.quicksum(s * x[s, i] for s in range(E[i], L[i] + 1)) + - gp.quicksum(s * x[s, j] for s in range(E[j], L[j] + 1)) <= 0, + name=f"prec_{i}_{j}" + ) + + # Constraint (4): Cycle time / capacity constraint + for s in range(1, S_star + 1): + if T_s[s]: + model.addConstr( + gp.quicksum(p[i] * x[s, i] for i in T_s[s] if (s, i) in x) <= c, + name=f"capacity_{s}" + ) + + # Constraint (6): z_max >= c - sum_i p_i * x_{si} for each station + for s in range(1, S_star + 1): + if T_s[s]: + model.addConstr( + gp.quicksum(p[i] * x[s, i] for i in T_s[s] if (s, i) in x) + z_max >= c, + name=f"idle_{s}" + ) + else: + # If no task can be assigned to station s, idle time = c + model.addConstr(z_max >= c, name=f"idle_empty_{s}") + + # Lower bound on z_max (from the paper, Section 5.2): + # z_max >= floor((c * S* - sum p_t) / c) + total_p = sum(p[i] for i in tasks) + z_lb = math.floor((c * S_star - total_p) / c) + if z_lb > 0: + model.addConstr(z_max >= z_lb, name="z_lower_bound") + + # Optimize + model.optimize() + + # Extract solution + result = { + "objective_value": None, + "status": None, + "task_assignments": {}, + "station_workloads": {}, + "station_idle_times": {} + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + + # Extract task assignments + for i in tasks: + for s in range(E[i], L[i] + 1): + if (s, i) in x and x[s, i].X > 0.5: + result["task_assignments"][str(i)] = s + break + + # Compute station workloads and idle times + for s in range(1, S_star + 1): + workload = 0 + for i in T_s[s]: + if (s, i) in x and x[s, i].X > 0.5: + workload += p[i] + result["station_workloads"][str(s)] = workload + result["station_idle_times"][str(s)] = c - workload + + result["z_max"] = z_max.X + result["num_stations"] = S_star + result["cycle_time"] = c + else: + result["status"] = "infeasible" + result["objective_value"] = None + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the Workload Smoothing Problem (WSP) using Gurobi." + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write the solution JSON file.") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + result = solve_wsp(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 (z_max): {result['objective_value']}") + print(f"Status: {result['status']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/pinnoi1997/gurobi_feasi_result/large_feasi_result_1.json b/tasks/pinnoi1997/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pinnoi1997/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/pinnoi1997/gurobi_feasi_result/large_feasi_result_2.json b/tasks/pinnoi1997/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pinnoi1997/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/pinnoi1997/gurobi_feasi_result/large_feasi_result_3.json b/tasks/pinnoi1997/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pinnoi1997/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/pinnoi1997/gurobi_feasi_result/large_feasi_result_4.json b/tasks/pinnoi1997/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pinnoi1997/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/pinnoi1997/gurobi_feasi_result/large_feasi_result_5.json b/tasks/pinnoi1997/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pinnoi1997/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/pinnoi1997/gurobi_feasi_result/tiny_feasi_result.json b/tasks/pinnoi1997/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/pinnoi1997/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/pinnoi1997/gurobi_solution/large_solution_1.json b/tasks/pinnoi1997/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9fba80bec69e72ad221c7b50c5b7695ee2a66b11 --- /dev/null +++ b/tasks/pinnoi1997/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b881db43420bdea490c6f0628362464d9d777d5a851b8b45d36a1ab279a8cf8c +size 1486 diff --git a/tasks/pinnoi1997/gurobi_solution/large_solution_2.json b/tasks/pinnoi1997/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c542f852798072ef6f31e17706b00077fff883dc --- /dev/null +++ b/tasks/pinnoi1997/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a1b842e25c36907a0378f1d74dc445c06f105293ce246f4ca734867fb628679 +size 1480 diff --git a/tasks/pinnoi1997/gurobi_solution/large_solution_3.json b/tasks/pinnoi1997/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ea3cd47971e279c9137298022abd692f73e1957b --- /dev/null +++ b/tasks/pinnoi1997/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa5c345ca0120927dd15f0685619ab022c6420015190ad30b62dd8fad91ed64d +size 1492 diff --git a/tasks/pinnoi1997/gurobi_solution/large_solution_4.json b/tasks/pinnoi1997/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9044107ef921a6901e0be6c74ff7672a88162b78 --- /dev/null +++ b/tasks/pinnoi1997/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45f65099137c5f5d3db1b5a29b92b56e3d04589cb6c2e9b767f5668d93a5a08b +size 1484 diff --git a/tasks/pinnoi1997/gurobi_solution/large_solution_5.json b/tasks/pinnoi1997/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..475e1822e82f5205bc213139d21e68194f5e374a --- /dev/null +++ b/tasks/pinnoi1997/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c272c9e2698442ca2707ce18f59ba85cd179565b1b320f81e237b13fceb8be7 +size 1488 diff --git a/tasks/pinnoi1997/gurobi_solution/tiny_solution.json b/tasks/pinnoi1997/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..be93dad5163cb35369123e0650209baccf758a6b --- /dev/null +++ b/tasks/pinnoi1997/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22fce539f0b5a7442f62116741ba0532b4d5e815e00c9fdd385549558ee1bdce +size 411 diff --git a/tasks/pinnoi1997/gurobi_solution_log/large_log_3.jsonl b/tasks/pinnoi1997/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..799e21f2bc9a8c401a78c57da54eac16f092b814 --- /dev/null +++ b/tasks/pinnoi1997/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f5774a3154964bfcf08fb0e726d099904f0aac55b1cb1199cd2c0f315bbf46d +size 244 diff --git a/tasks/pinnoi1997/gurobi_solution_log/tiny_log.jsonl b/tasks/pinnoi1997/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..20a3310b68c09c3ed6511b9672c7e91545a0408b --- /dev/null +++ b/tasks/pinnoi1997/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a31db2394ebfca9510c96a6eddf715541896bb9f0c78ef8837276c74a43f6f0e +size 40 diff --git a/tasks/pinnoi1997/instance/large_instance_1.json b/tasks/pinnoi1997/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5551b914cf9f723854375e4f7a1a89709d02bbbc --- /dev/null +++ b/tasks/pinnoi1997/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e4d466ec2cebf45f9a2b8a11419dda8370ebefeb15b90c233d5d38ce813c711 +size 6425 diff --git a/tasks/pinnoi1997/instance/large_instance_2.json b/tasks/pinnoi1997/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c37fac41f01941a8afffb59295d62b78e4842752 --- /dev/null +++ b/tasks/pinnoi1997/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d28092bbef23007ac9e1ebc47f8f0ea2062fba9c5ee3a10350345ad3e49917e9 +size 5960 diff --git a/tasks/pinnoi1997/instance/large_instance_3.json b/tasks/pinnoi1997/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1dfb06c342250582ad3338f76bae24024003882d --- /dev/null +++ b/tasks/pinnoi1997/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:644f8fc43d49301ca212d1bc277b4fe7b848c60d13c72f1c94eccd1289c5e5b4 +size 5936 diff --git a/tasks/pinnoi1997/instance/large_instance_4.json b/tasks/pinnoi1997/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..439c14d37056f05e3eac3fac82e96a6b056431a0 --- /dev/null +++ b/tasks/pinnoi1997/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bef118b8a512ac0b4f40d4ca24afbd62f413a4c9c8112bfc83c8af964f1fc4f1 +size 5938 diff --git a/tasks/pinnoi1997/instance/large_instance_5.json b/tasks/pinnoi1997/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..265396558d29c289362cf7d7f76b321d1ec4b749 --- /dev/null +++ b/tasks/pinnoi1997/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce1ab645e206787078a41cdd3a7fe1ca4ad63a2300dcd7b671db56847b25d4d7 +size 5958 diff --git a/tasks/pinnoi1997/instance/tiny_instance.json b/tasks/pinnoi1997/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..cfb35b166e91c48f8bb2fe904ed0636abf356aa6 --- /dev/null +++ b/tasks/pinnoi1997/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8ece039eabdd2f0ee4cd5c5f97a21f71b50e79d15bf3f36e59ab1a4e7b170a9 +size 855 diff --git a/tasks/pinnoi1997/instance_schema.json b/tasks/pinnoi1997/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..25a656f209efd3bba609116d0018232c0d167771 --- /dev/null +++ b/tasks/pinnoi1997/instance_schema.json @@ -0,0 +1,12 @@ +{ + "num_tasks": " Total number of tasks to be assigned across the assembly line.", + "cycle_time": " Maximum allowable total processing time at any single station.", + "num_stations": " Number of workstations arranged in series on the assembly line.", + "total_processing_time": " Sum of processing times across all tasks.", + "station_lower_bound": " Minimum number of stations required to accommodate the total processing time within the cycle time.", + "task_processing_times": " Time required to complete each task.", + "precedence_arcs": " Pairs of tasks where the first task must be assigned to a station no later than the second task.", + "num_precedence_arcs": " Number of immediate precedence relationships between tasks.", + "earliest_station": " Earliest station to which each task may feasibly be assigned, based on cumulative predecessor processing times.", + "latest_station": " Latest station to which each task may feasibly be assigned, based on cumulative successor processing times." +} diff --git a/tasks/pinnoi1997/mathematical_formulation.md b/tasks/pinnoi1997/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..3c370e4974c10bfa668ed6594f648c0f55d55a0f --- /dev/null +++ b/tasks/pinnoi1997/mathematical_formulation.md @@ -0,0 +1,57 @@ +# Original Formulation: Workload Smoothing Problem (WSP) + +*Source: A Branch and Cut Approach for Workload Smoothing on Assembly Lines, Anulark Pinnoi and Wilbert E. Wilhelm, INFORMS Journal on Computing 9(4):335–350, 1997.* + +## Sets and Indices + +$$\begin{align*} +&T = \{1, \ldots, \tau\} && \text{set of all tasks; } \tau = |T|.\\ +&s = 1, \ldots, S_U && \text{station index.}\\ +&i, j, t \in T && \text{task indices.}\\ +&\Theta = \{(i,j): i,j \in T,\ i \text{ is an immediate predecessor of } j\} && \text{arc set of the precedence graph.}\\ +&H = (T, \Theta) && \text{precedence (directed) graph.}\\ +&M(t),\ A(t) && \text{immediate / all predecessors of task } t.\\ +&R(t),\ B(t) && \text{immediate / all successors of task } t.\\ +&T(s) && \text{set of task candidates that may be processed at station } s. +\end{align*}$$ + +## Parameters + +$$\begin{align*} +&c && \text{cycle time (maximum workload allowed per station).}\\ +&p_t && \text{processing time of task } t \text{ (integer).}\\ +&E_t && \text{earliest station to which task } t \text{ may be assigned.}\\ +&L_t && \text{latest station to which task } t \text{ may be assigned.}\\ +&S_U && \text{upper bound on the optimal number of stations.}\\ +&S_L = \left\lceil \tfrac{\sum_{t \in T} p_t}{c} \right\rceil && \text{lower bound on the optimal number of stations.}\\ +&S^* && \text{optimal (fixed) number of stations, given as input to the WSP.} +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +&x_{si} = +\begin{cases} +1 & \text{if task } i \text{ is assigned to station } s,\\ +0 & \text{otherwise,} +\end{cases} +\qquad \forall\, s \in S(i),\ i \in T.\\[4pt] +&z_{\max} \;=\; \text{the maximum station idle time (a real / continuous variable).} +\end{align*}$$ + +## Objective + +The WSP assigns tasks to the optimal number of stations $S^{*}$ while minimizing the maximum idle time on any station to balance workloads: $$\begin{align} +\text{Minimize } \quad z_{\max} \tag{WSP} +\end{align}$$ + +## Constraints + +Subject to (2)–(5) with $s = 1, \ldots, S^{*}$ in (4), and (6)–(7): $$\begin{align} +&\sum_{s=E_i}^{L_i} x_{si} = 1 && \forall\, i \in T, \tag{2}\\[4pt] +&\sum_{s=E_i}^{L_i} s\, x_{si} \;-\; \sum_{s=E_j}^{L_j} s\, x_{sj} \;\leq\; 0 && \forall\, (i,j) \in \Theta, \tag{3}\\[4pt] +&\sum_{i \in T(s)} p_i\, x_{si} \;\leq\; c && \forall\, s = 1, \ldots, S^{*}, \tag{4}\\[4pt] +&x_{si} \in \{0,1\} && \forall\, s = E_i, \ldots, L_i,\ i \in T, \tag{5}\\[4pt] +&\sum_{t} p_t\, x_{st} \;+\; z_{\max} \;\geq\; c && \forall\, s = 1, \ldots, S^{*}, \tag{6}\\[4pt] +&z_{\max} \;\geq\; 0. \tag{7} +\end{align}$$ diff --git a/tasks/pinnoi1997/problem_description.txt b/tasks/pinnoi1997/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..4c5ba99021b6058d793dd6533c6b5d49642e5d6c --- /dev/null +++ b/tasks/pinnoi1997/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +An assembly line consists of a set of tasks and a fixed number of workstations arranged in series. Each task has a known integer processing time. The tasks are related by a precedence graph that specifies immediate predecessor relationships: if one task is an immediate predecessor of another, then the predecessor must be processed at a station whose number is no greater than the station number assigned to the successor. The line operates with a fixed cycle time, which is the maximum allowable total processing time at any single station. The number of stations is given as a fixed input parameter representing the optimal (minimum feasible) number of stations for the line. + +The input data specifies the number of tasks, the processing time of each task, the cycle time, the number of stations, the set of immediate precedence arcs between tasks, and for each task the earliest and latest station to which it may feasibly be assigned. These earliest and latest station bounds are derived from the precedence structure and processing times: the earliest station for a task is determined by the cumulative processing time of the task itself together with all of its predecessors, divided by the cycle time and rounded up, while the latest station is determined by subtracting from the total number of stations the cumulative processing time of the task itself together with all of its successors, divided by the cycle time and rounded up, plus one. + +The planner must assign every task to exactly one station, choosing from among the stations between its earliest and latest feasible station inclusive. The assignment must respect all precedence relationships: for every immediate precedence arc, the station number assigned to the predecessor task must not exceed the station number assigned to the successor task. The total processing time of all tasks assigned to any single station must not exceed the cycle time. In addition, the planner must determine a single value representing the worst-case station idle time across the entire line. + +The idle time at a station is the difference between the cycle time and the total processing time of the tasks assigned to that station. The worst-case idle time value must be at least as large as the idle time at every station, meaning that for each station, the sum of the processing times of tasks assigned to it plus this worst-case value must be at least equal to the cycle time. A lower bound on this worst-case value is given by the floor of the quantity obtained by dividing the total slack across all stations (the number of stations times the cycle time minus the sum of all task processing times) by the cycle time. + +The goal is to minimize this worst-case station idle time, thereby producing the most balanced distribution of work across the stations on the line. diff --git a/tasks/pinnoi1997/solution_logger.py b/tasks/pinnoi1997/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/pinnoi1997/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/pinnoi1997/solution_schema.json b/tasks/pinnoi1997/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..547541de8047396628ede0890c5c3470716cebff --- /dev/null +++ b/tasks/pinnoi1997/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Maximum idle time across all stations on the assembly line.", + "task_assignments": " Station to which each task is assigned." +} diff --git a/tasks/potthoff2010/feasibility_check.py b/tasks/potthoff2010/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..ed88771e98fe7aedbb5c5b190b794508f876c608 --- /dev/null +++ b/tasks/potthoff2010/feasibility_check.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Fail-closed checker for the released OCRSP completion certificate.""" + +import argparse +import json +import math + +from release_contract import ( + RELEASED_VARIANT, + ReleasedInstance, + completion_cost, + validate_completion, +) + + +def rejection(category, messages): + return { + "feasible": False, + "violated_constraints": [category], + "violations": messages, + "violation_magnitudes": [], + } + + +def check_feasibility(data, solution): + if not isinstance(solution, dict): + return rejection("solution_schema", ["solution must be a JSON object"]) + required = { + "released_problem_variant", + "objective_value", + "canceled_tasks", + "duty_assignments", + } + missing = sorted(required - set(solution)) + if missing: + return rejection( + "solution_schema", [f"missing required solution fields: {missing}"] + ) + if solution["released_problem_variant"] != RELEASED_VARIANT: + return rejection( + "solution_schema", + [f"released_problem_variant must be {RELEASED_VARIANT}"], + ) + objective = solution["objective_value"] + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or not math.isfinite(float(objective)) + ): + return rejection("solution_schema", ["objective_value must be finite"]) + if not isinstance(solution["canceled_tasks"], list) or any( + not isinstance(task_id, str) for task_id in solution["canceled_tasks"] + ): + return rejection( + "solution_schema", ["canceled_tasks must be a list of identifiers"] + ) + if not isinstance(solution["duty_assignments"], dict): + return rejection("solution_schema", ["duty_assignments must be an object"]) + + try: + inst = ReleasedInstance(data) + except Exception as error: + return rejection("instance_contract", [str(error)]) + + violations = [] + violated = set() + canceled_list = solution["canceled_tasks"] + canceled = set(canceled_list) + if len(canceled) != len(canceled_list): + violations.append("canceled_tasks contains duplicates") + violated.add(4) + unknown_canceled = sorted(canceled - set(inst.tasks)) + if unknown_canceled: + violations.append(f"unknown/non-reschedulable canceled tasks: {unknown_canceled}") + violated.add(4) + + assignments = solution["duty_assignments"] + expected_duties = set(inst.duties) + actual_duties = set(assignments) + if actual_duties != expected_duties: + missing_duties = sorted(expected_duties - actual_duties) + extra_duties = sorted(actual_duties - expected_duties) + violations.append( + f"duty assignment keys are incomplete: missing={missing_duties}, " + f"unexpected={extra_duties}" + ) + violated.add(3) + + coverage = {task_id: 0 for task_id in inst.tasks} + completion_cost_sum = 0.0 + required_assignment_fields = { + "completion_index", + "cost", + "covered_tasks", + "uses_taxi", + "release_at_relief_point", + "return_station", + "return_time_minutes", + } + for duty_id in sorted(actual_duties & expected_duties): + assignment = assignments[duty_id] + if not isinstance(assignment, dict): + violations.append(f"assignment for {duty_id} must be an object") + violated.add("solution_schema") + continue + missing_fields = sorted(required_assignment_fields - set(assignment)) + if missing_fields: + violations.append( + f"assignment for {duty_id} is missing fields {missing_fields}" + ) + violated.add("solution_schema") + continue + if ( + isinstance(assignment["completion_index"], bool) + or not isinstance(assignment["completion_index"], int) + or assignment["completion_index"] < 0 + ): + violations.append(f"{duty_id}: completion_index must be nonnegative integer") + violated.add("solution_schema") + declared_cost = assignment["cost"] + if ( + isinstance(declared_cost, bool) + or not isinstance(declared_cost, (int, float)) + or not math.isfinite(float(declared_cost)) + ): + violations.append(f"{duty_id}: cost must be a finite number") + violated.add("solution_schema") + continue + + derived, error = validate_completion( + inst, + inst.duties[duty_id], + assignment["covered_tasks"], + assignment["uses_taxi"], + assignment["release_at_relief_point"], + ) + if error is not None: + violations.append(f"{duty_id}: {error}") + violated.add("completion_feasibility") + continue + if assignment["return_station"] != derived["return_station"]: + violations.append( + f"{duty_id}: return_station={assignment['return_station']} does not " + f"match derived {derived['return_station']}" + ) + violated.add("completion_feasibility") + if abs(float(assignment["return_time_minutes"]) - derived["return_time_minutes"]) > 1e-6: + violations.append( + f"{duty_id}: return_time_minutes does not match derived return time" + ) + violated.add("completion_feasibility") + + expected_cost = completion_cost( + inst, + inst.duties[duty_id], + assignment["covered_tasks"], + assignment["uses_taxi"], + assignment["release_at_relief_point"], + ) + if abs(float(declared_cost) - expected_cost) > 1e-6: + violations.append( + f"{duty_id}: cost={declared_cost} does not match derived {expected_cost}" + ) + violated.add(5) + completion_cost_sum += expected_cost + for task_id in assignment["covered_tasks"]: + if task_id in coverage: + coverage[task_id] += 1 + + uncovered = sorted( + task_id + for task_id, count in coverage.items() + if count == 0 and task_id not in canceled + ) + if uncovered: + violations.append(f"tasks neither covered nor canceled: {uncovered}") + violated.add(2) + + cancellation_cost = 0.0 + for task_id in canceled & set(inst.tasks): + task = inst.tasks[task_id] + cancellation_cost += ( + inst.params["cost_cancel_A_to_A"] + if task["task_type"] == "A_to_A" + else inst.params["cost_cancel_A_to_B"] + ) + expected_objective = completion_cost_sum + cancellation_cost + difference = abs(float(objective) - expected_objective) + tolerance = max(1e-6, 1e-9 * abs(expected_objective)) + if difference > tolerance: + violations.append( + f"objective_value={objective} does not match exact completion plus " + f"cancellation cost {expected_objective}" + ) + violated.add(5) + + return { + "feasible": not violations, + "violated_constraints": sorted(violated, key=str), + "violations": violations, + "violation_magnitudes": [], + } + + +def main(): + parser = argparse.ArgumentParser(description="Check released OCRSP certificate.") + parser.add_argument("--instance_path", required=True) + parser.add_argument("--solution_path", required=True) + parser.add_argument("--result_path", required=True) + arguments = parser.parse_args() + try: + with open(arguments.instance_path) as handle: + data = json.load(handle) + with open(arguments.solution_path) as handle: + solution = json.load(handle) + result = check_feasibility(data, solution) + except Exception as error: + result = rejection( + "malformed_solution", + [f"checker rejected malformed input: {type(error).__name__}: {error}"], + ) + with open(arguments.result_path, "w") as handle: + json.dump(result, handle, indent=2) + print(f"Feasible: {result['feasible']}") + for message in result["violations"]: + print(f" - {message}") + + +if __name__ == "__main__": + main() diff --git a/tasks/potthoff2010/gurobi_code.py b/tasks/potthoff2010/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..7b994b9128dfa7f0f7c0a5de0ff8793e688b85da --- /dev/null +++ b/tasks/potthoff2010/gurobi_code.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Solve the released finite-completion OCRSP set-covering model.""" + +import argparse +import json +import os as _os +import sys as _sys +import time + +import gurobipy as gp +from gurobipy import GRB + +from release_contract import ( + RELEASED_VARIANT, + ReleasedInstance, + completion_options, +) + + +_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): + del log_path + + +def solve(data, time_limit): + inst = ReleasedInstance(data) + libraries = { + duty_id: completion_options(inst, duty) + for duty_id, duty in sorted(inst.duties.items()) + } + + model = gp.Model("released_OCRSP") + model.Params.Threads = 1 + model.Params.TimeLimit = time_limit + model.Params.OutputFlag = 1 + + chosen = {} + for duty_id, options in libraries.items(): + for index, option in enumerate(options): + chosen[duty_id, index] = model.addVar( + vtype=GRB.BINARY, + obj=option["cost"], + name=f"x_{duty_id}_{index}", + ) + canceled = { + task_id: model.addVar( + vtype=GRB.BINARY, + obj=( + inst.params["cost_cancel_A_to_A"] + if task["task_type"] == "A_to_A" + else inst.params["cost_cancel_A_to_B"] + ), + name=f"y_{task_id}", + ) + for task_id, task in inst.tasks.items() + } + + for duty_id, options in libraries.items(): + model.addConstr( + gp.quicksum(chosen[duty_id, index] for index in range(len(options))) == 1, + name=f"assign_{duty_id}", + ) + for task_id in inst.tasks: + model.addConstr( + gp.quicksum( + chosen[duty_id, index] + for duty_id, options in libraries.items() + for index, option in enumerate(options) + if task_id in option["covered_tasks"] + ) + canceled[task_id] >= 1, + name=f"cover_{task_id}", + ) + + # The first option is always the canonical empty/fallback completion. + for duty_id, options in libraries.items(): + for index in range(len(options)): + chosen[duty_id, index].Start = int(index == 0) + for task_id in canceled: + canceled[task_id].Start = 1 + + model.ModelSense = GRB.MINIMIZE + model.optimize() + + result = { + "instance_id": data.get("instance_id", "unknown"), + "released_problem_variant": RELEASED_VARIANT, + "solver": "Gurobi_finite_completion_set_covering", + "status": "infeasible", + "objective_value": None, + "canceled_tasks": [], + "duty_assignments": {}, + } + if model.SolCount == 0: + return result + + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + result["best_bound"] = float(model.ObjBound) + result["optimality_gap"] = float(model.MIPGap) + result["canceled_tasks"] = sorted( + task_id for task_id, variable in canceled.items() if variable.X > 0.5 + ) + for duty_id, options in libraries.items(): + index = max(range(len(options)), key=lambda k: chosen[duty_id, k].X) + option = dict(options[index]) + option["completion_index"] = index + result["duty_assignments"][duty_id] = option + + cancellation_cost = sum( + inst.params["cost_cancel_A_to_A"] + if inst.tasks[task_id]["task_type"] == "A_to_A" + else inst.params["cost_cancel_A_to_B"] + for task_id in result["canceled_tasks"] + ) + result["objective_value"] = cancellation_cost + sum( + assignment["cost"] for assignment in result["duty_assignments"].values() + ) + return result + + +def main(): + parser = argparse.ArgumentParser(description="Solve the released OCRSP model.") + parser.add_argument("--instance_path", required=True) + parser.add_argument("--solution_path", required=True) + parser.add_argument("--time_limit", type=int, default=600) + parser.add_argument("--log_path", default=None) + arguments = parser.parse_args() + install_gurobi_logger(arguments.log_path) + with open(arguments.instance_path) as handle: + data = json.load(handle) + result = solve(data, arguments.time_limit) + with open(arguments.solution_path, "w") as handle: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, handle, indent=2) + print( + f"status={result['status']} objective={result['objective_value']} " + f"assignments={len(result['duty_assignments'])}" + ) + + +if __name__ == "__main__": + main() diff --git a/tasks/potthoff2010/gurobi_feasi_result/large_feasi_result_1.json b/tasks/potthoff2010/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/potthoff2010/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/potthoff2010/gurobi_feasi_result/large_feasi_result_2.json b/tasks/potthoff2010/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/potthoff2010/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/potthoff2010/gurobi_feasi_result/large_feasi_result_3.json b/tasks/potthoff2010/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/potthoff2010/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/potthoff2010/gurobi_feasi_result/large_feasi_result_4.json b/tasks/potthoff2010/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/potthoff2010/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/potthoff2010/gurobi_feasi_result/large_feasi_result_5.json b/tasks/potthoff2010/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/potthoff2010/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/potthoff2010/gurobi_feasi_result/tiny_feasi_result.json b/tasks/potthoff2010/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/potthoff2010/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/potthoff2010/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/potthoff2010/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/potthoff2010/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/potthoff2010/gurobi_solution/large_solution_1.json b/tasks/potthoff2010/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6f8fa63a3da03a60272890bfc724cccb23e8b294 --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e3968606f75f80efd3eaa42c91a89bb362e4928f92e19e659eaec2c46259044 +size 6648 diff --git a/tasks/potthoff2010/gurobi_solution/large_solution_2.json b/tasks/potthoff2010/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..2506eda18f3b1642510424c77898408abf45bf3f --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:559cf01f7771d4ed076590b66f7142f1861207e1cace939ab6dfad5c3ed4bbc2 +size 20828 diff --git a/tasks/potthoff2010/gurobi_solution/large_solution_3.json b/tasks/potthoff2010/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d573a3fd0b032b52ff629f4cb23e6da3ef8736a3 --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4635dfc461c2ba2f4e7682c563b531abbda2ee5198a4fb1a62d02960ccb5abd +size 6780 diff --git a/tasks/potthoff2010/gurobi_solution/large_solution_4.json b/tasks/potthoff2010/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..fd9a8218a562cea31a78cf381280b19277f07ada --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:897a2c085e401498e186bf709ee038d69ff4000e3f64c3afa53c4ef6387df0c6 +size 6997 diff --git a/tasks/potthoff2010/gurobi_solution/large_solution_5.json b/tasks/potthoff2010/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a2a2179431f55b8376169182370088b78250d116 --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32e2ff2dc2482b856df9f3ac6c7aa9714245f026b44838b42aadb9eaa6d35cee +size 7114 diff --git a/tasks/potthoff2010/gurobi_solution/tiny_solution.json b/tasks/potthoff2010/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..899877d76050f6a71ead773b987a865486e9aca5 --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da5f07bb441de0079e74d25303e1b8301eb94d07af31570b60c118c97cbae0be +size 2462 diff --git a/tasks/potthoff2010/gurobi_solution/tiny_solution_2.json b/tasks/potthoff2010/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..7bd8518520b020931430028eb9dc7357c186c465 --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a134f5035253e20291eb0fee5cf07a27e047637f3b6b6001e4a5dca3baa2365 +size 7460 diff --git a/tasks/potthoff2010/gurobi_solution_log/large_log_1.jsonl b/tasks/potthoff2010/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f344cfe15b80591ad38afe20df48416f70a6395c --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b802ce853b57f14f67ce9f8ceb502cad78d75c523ab63df68b1b0ea59d17831 +size 140 diff --git a/tasks/potthoff2010/gurobi_solution_log/large_log_2.jsonl b/tasks/potthoff2010/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..903fe0b657f04e5aad31f4217cf8c8fbeb8e5781 --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9a32ad2a9b96292144e8081d7cfe9b7fd92f92b44d7aec008c234ad6acb6e82 +size 48 diff --git a/tasks/potthoff2010/gurobi_solution_log/large_log_3.jsonl b/tasks/potthoff2010/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..830383a81f8a4effb7ee55b9a1513b0e628eb3c1 --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ba8518fee66720f7c28c19bcf8a1d8d823b292f9440ae1808ef7e76cf184402 +size 47 diff --git a/tasks/potthoff2010/gurobi_solution_log/large_log_4.jsonl b/tasks/potthoff2010/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c4a293542a486a86ee02bd215c493c087e970edb --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b0e84091e643b2698d362433a6b02cd8635ddb87e7aac713ad2122b33987542 +size 91 diff --git a/tasks/potthoff2010/gurobi_solution_log/large_log_5.jsonl b/tasks/potthoff2010/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..009218d82aff6229c89a5945887249006c816446 --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7eea74ffed441c380c3f8af00e5c8584faaed1e6f96ed8230af75a57cb609ab5 +size 46 diff --git a/tasks/potthoff2010/gurobi_solution_log/tiny_log.jsonl b/tasks/potthoff2010/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2f077df8018eb980eeaac9cc03c1df8d24a8bf19 --- /dev/null +++ b/tasks/potthoff2010/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f31d06cd268abb1e5d59334d1e7efadfef9ecf0e8364937b7fc5e323307e297d +size 90 diff --git a/tasks/potthoff2010/instance/large_instance_1.json b/tasks/potthoff2010/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3b515cd8ea637e36316eece16095c701a97f8932 --- /dev/null +++ b/tasks/potthoff2010/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d77fddf7b480c295889b9cbded78256af9b19599f1924c93d691dba78cf59c1 +size 118476 diff --git a/tasks/potthoff2010/instance/large_instance_2.json b/tasks/potthoff2010/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..8af2b244b3fa2d5005c4cdd2cb81bcc1fabd888a --- /dev/null +++ b/tasks/potthoff2010/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e779eca48fde718eed6b16b475716eedd24bde5cea2ca3d7c384223c77edde04 +size 339370 diff --git a/tasks/potthoff2010/instance/large_instance_3.json b/tasks/potthoff2010/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..9db3a1dcb80f90d4bcc7c1b37fd330739a43a552 --- /dev/null +++ b/tasks/potthoff2010/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fec606078bc4334b9e83d8531aec1b4caf2f326ede32ec5808dd3df0f14818db +size 104235 diff --git a/tasks/potthoff2010/instance/large_instance_4.json b/tasks/potthoff2010/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c7f09ff0537d3f7b00006f538ded556555ed41c6 --- /dev/null +++ b/tasks/potthoff2010/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:015f49a9072a53b06f016156a6bcd1124ed8cf2500f175fea47bbafb8eb478ff +size 109677 diff --git a/tasks/potthoff2010/instance/large_instance_5.json b/tasks/potthoff2010/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e6650551b1881ed9e079673fd34aed78189ef705 --- /dev/null +++ b/tasks/potthoff2010/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b4fd1b726301310d7dc42f0d776d009b1daed4b34085ec317d4f3f4b8224979 +size 108660 diff --git a/tasks/potthoff2010/instance/tiny_instance.json b/tasks/potthoff2010/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..f531d49ccbf64fa98fa10c5d10bc07f5d7908070 --- /dev/null +++ b/tasks/potthoff2010/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:837f942bc7354e0b6d02b75c93eab42b7d49a899dd295419f2235620b2071bfc +size 30281 diff --git a/tasks/potthoff2010/instance/tiny_instance_2.json b/tasks/potthoff2010/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..b8091fc1de60cae0c7bc11e200da94ed92bec1a8 --- /dev/null +++ b/tasks/potthoff2010/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:612832afd3203de24b9ddb939527191e99a4dc8215d96fd8b2e753fbc3b66595 +size 118127 diff --git a/tasks/potthoff2010/instance_schema.json b/tasks/potthoff2010/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..01252cb3e2d0d0fc59ec84e95621d8ea9b1e4d6e --- /dev/null +++ b/tasks/potthoff2010/instance_schema.json @@ -0,0 +1,144 @@ +{ + "released_problem_variant": " Discriminator for the finite public completion library and its explicit emergency relief-point release fallback.", + "network": { + "stations": [ + { + "id": " Unique identifier for the station.", + "name": " Human-readable name of the station.", + "is_relief_point": " Whether crew members can be relieved at this station.", + "is_crew_base": " Whether duties can start and end at this station.", + "has_canteen": " Whether meal breaks can be taken at this station.", + "x": " X coordinate of the station for distance computation.", + "y": " Y coordinate of the station for distance computation." + } + ], + "crew_bases": " Station IDs where duties can originate and terminate.", + "route_segments": [ + { + "from_station": " Station ID at one end of the track segment.", + "to_station": " Station ID at the other end of the track segment.", + "travel_time_minutes": " Time in minutes to traverse this segment by train.", + "distance_km": " Distance in kilometers between the two stations.", + "bidirectional": " Whether trains can travel in both directions on this segment." + } + ], + "taxi_connections": [ + { + "from_station": " Station ID at one end of the taxi connection.", + "to_station": " Station ID at the other end of the taxi connection.", + "travel_time_minutes": " Time in minutes to travel between stations by taxi.", + "bidirectional": " Whether the taxi connection can be used in both directions." + } + ] + }, + "train_lines": [ + { + "line_id": " Unique identifier for the train line.", + "type": " Service class of the line, either 'intercity' or 'regional'.", + "stations": " Ordered sequence of station IDs served by this line.", + "segment_travel_times": " Travel time in minutes for each consecutive pair of stations on the line.", + "frequency_per_hour": " Number of departures per hour on this line." + } + ], + "tasks": [ + { + "task_id": " Unique identifier for the task.", + "line_id": " Train line on which this task operates.", + "departure_station": " Station ID where the task departs.", + "arrival_station": " Station ID where the task arrives.", + "departure_time": " Scheduled departure time in HH:MM format.", + "departure_time_minutes": " Scheduled departure time in minutes from midnight.", + "arrival_time": " Scheduled arrival time in HH:MM format.", + "arrival_time_minutes": " Scheduled arrival time in minutes from midnight.", + "task_type": " Whether the task travels between two different stations ('A_to_B') or returns to the same station ('A_to_A').", + "direction": " Direction of travel along the line, either 'forward' or 'backward'.", + "rolling_stock_type": " Type of rolling stock required to operate this task." + } + ], + "active_duties": [ + { + "duty_id": " Unique identifier for the duty.", + "duty_type": " Classification of the duty as 'active'.", + "crew_base": " Station ID where the duty originates and must terminate.", + "start_time": " Scheduled duty start time in HH:MM format.", + "start_time_minutes": " Scheduled duty start time in minutes from midnight.", + "end_time": " Scheduled duty end time in HH:MM format.", + "end_time_minutes": " Scheduled duty end time in minutes from midnight.", + "tasks": " Post-disruption task IDs originally assigned to this duty that need to be rescheduled.", + "pre_disruption_tasks": " Task IDs that were completed or in progress before the disruption occurred.", + "task_details": [ + { + "task_id": " Unique identifier for the task.", + "departure_station": " Station ID where the task departs.", + "arrival_station": " Station ID where the task arrives.", + "departure_time": " Scheduled departure time in HH:MM format.", + "arrival_time": " Scheduled arrival time in HH:MM format." + } + ], + "route_knowledge": " Station IDs that this driver is licensed to operate through.", + "rolling_stock_licenses": " Rolling stock types that this driver is certified to operate.", + "has_meal_break": " Whether this duty requires a meal break.", + "meal_break": " Details of the scheduled meal break, if any." + } + ], + "reserve_duties": [ + { + "duty_id": " Unique identifier for the reserve duty.", + "duty_type": " Classification of the duty as 'reserve'.", + "crew_base": " Station ID where the reserve duty is based.", + "start_time": " Start time of the standby period in HH:MM format.", + "start_time_minutes": " Start time of the standby period in minutes from midnight.", + "end_time": " End time of the standby period in HH:MM format.", + "end_time_minutes": " End time of the standby period in minutes from midnight.", + "standby_station": " Station ID where the reserve driver is waiting.", + "tasks": " Post-disruption task IDs assigned to this reserve duty.", + "pre_disruption_tasks": " Task IDs completed before the disruption.", + "task_details": [ + { + "task_id": " Unique identifier for the task.", + "departure_station": " Station ID where the task departs.", + "arrival_station": " Station ID where the task arrives.", + "departure_time": " Scheduled departure time in HH:MM format.", + "arrival_time": " Scheduled arrival time in HH:MM format." + } + ], + "route_knowledge": " Station IDs that this reserve driver is licensed to operate through.", + "rolling_stock_licenses": " Rolling stock types that this reserve driver is certified to operate.", + "has_meal_break": " Whether this reserve duty requires a meal break.", + "meal_break": " Details of the scheduled meal break, if any." + } + ], + "disruption": { + "disruption_type": " Type of disruption affecting the network, such as 'two_sided_blockage' or 'reduced_capacity'.", + "blocked_segment": { + "from_station": " Station ID at one end of the blocked track segment.", + "to_station": " Station ID at the other end of the blocked track segment." + }, + "start_time": " Time the disruption begins in HH:MM format.", + "start_time_minutes": " Time the disruption begins in minutes from midnight.", + "end_time": " Time the disruption ends in HH:MM format.", + "end_time_minutes": " Time the disruption ends in minutes from midnight.", + "duration_hours": " Duration of the disruption in hours.", + "rescheduling_time": " Time at which crew rescheduling decisions take effect in HH:MM format.", + "rescheduling_time_minutes": " Time at which crew rescheduling decisions take effect in minutes from midnight.", + "canceled_tasks": " Task IDs that are canceled as a direct result of the disruption.", + "modified_tasks": " Task IDs whose schedules are modified due to the disruption.", + "affected_duty_ids": " Duty IDs whose original task assignments are impacted by the disruption.", + "num_affected_duties": " Number of duties affected by the disruption." + }, + "parameters": { + "cost_cancel_A_to_B": " Penalty incurred for canceling a task that travels between two different stations.", + "cost_cancel_A_to_A": " Penalty incurred for canceling a task that returns to its origin station.", + "cost_duty_changed": " Fixed penalty incurred when a duty's completion differs from its original schedule.", + "cost_task_reassigned": " Penalty per task assigned to a duty that did not originally include it.", + "cost_new_transfer": " Penalty for each new connection between consecutive tasks within a duty.", + "cost_taxi": " Penalty incurred when a taxi is used to reposition a driver between stations.", + "max_overtime_minutes": " Maximum number of minutes a duty may extend beyond its scheduled end time.", + "meal_break_min_minutes": " Minimum duration in minutes required for a meal break.", + "max_work_before_break_hours": " Maximum consecutive working hours allowed before a meal break must be taken.", + "max_work_after_break_hours": " Maximum consecutive working hours allowed after a meal break.", + "min_connection_time_minutes": " Minimum gap in minutes required between consecutive tasks on different rolling stock.", + "max_duty_duration_hours": " Maximum total duration of a duty in hours including overtime.", + "disruption_duration_hours": " Duration of the disruption period in hours." + } +} diff --git a/tasks/potthoff2010/mathematical_formulation.md b/tasks/potthoff2010/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..e3370a8965dd189b7ec5936eb5974daab6522f7f --- /dev/null +++ b/tasks/potthoff2010/mathematical_formulation.md @@ -0,0 +1,71 @@ +# Original Formulation: Operational Crew Rescheduling Problem (OCRSP) + +*Source: Column Generation with Dynamic Duty Selection for Railway Crew Rescheduling, M. Potthoff, D. Huisman, and G. Desaulniers, Transportation Science 44(4), pp. 493–505, 2010.* + +## Sets and Parameters + +$$\begin{align*} +S &: \text{set of stations (limited to relief points).}\\ +D &: \text{set of crew bases (a subset of the relief points).}\\ +N &: \text{set of tasks that have not started at the time of rescheduling.}\\ + &\quad \text{For every } i\in N:\ ds_i,dt_i \text{ are its departure station and time,}\\ + &\quad \text{and } as_i,at_i \text{ are its arrival station and time.}\\ +\Delta &= \Delta_A \cup \Delta_R:\ \text{set of unfinished original duties, where } \Delta_A\\ + &\quad \text{are the active and } \Delta_R \text{ the reserve duties. For every } \delta\in\Delta:\\ + &\quad cs_\delta:\ \text{the station where the duty is at the time of rescheduling}\\ + &\quad\quad \text{(or the arrival station of the task being performed then);}\\ + &\quad b_\delta:\ \text{the crew base where the original duty starts and ends.}\\ +K^\delta &: \text{set of all feasible completions for original duty } \delta\in\Delta.\\ + &\quad \text{For every feasible completion } k\in K^\delta:\\ + &\quad c^\delta_k:\ \text{cost of feasible completion } k \text{ for duty } \delta \text{ (zero if the}\\ + &\quad\quad \text{duty is unchanged);}\\ + &\quad a^\delta_{ik}\in\{0,1\}:\ 1 \text{ if task } i \text{ is covered (driven) by completion } k.\\ +f_i &: \text{cost for canceling task } i. +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +x^\delta_k &\in \{0,1\} \quad \forall\, \delta\in\Delta,\ \forall\, k\in K^\delta,\\ + &\quad =1 \text{ if feasible completion } k \text{ is selected for original duty } \delta.\\ +y_i &\in \{0,1\} \quad \forall\, i\in N,\\ + &\quad =1 \text{ if task } i \text{ is canceled.} +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \quad \sum_{\delta\in\Delta}\sum_{k\in K^\delta} c^\delta_k\, x^\delta_k + + \sum_{i\in N} f_i\, y_i \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{\delta\in\Delta}\sum_{k\in K^\delta} a^\delta_{ik}\, x^\delta_k + y_i &\ge 1 + && \forall\, i\in N \tag{2}\\ +\sum_{k\in K^\delta} x^\delta_k &= 1 + && \forall\, \delta\in\Delta \tag{3}\\ +x^\delta_k,\ y_i &\in \{0,1\} + && \forall\, \delta\in\Delta,\ \forall\, k\in K^\delta,\ \forall\, i\in N \tag{4} +\end{align}$$ + +Constraints (2) are set-covering constraints ensuring that every task is either covered by a selected feasible completion or canceled (over-covering is allowed, hence “$\ge$”). Constraints (3) ensure that every original duty is assigned to exactly one feasible completion. + +## Released finite-completion contract + +The public data use `released_problem_variant = relief_point_completion_v1`. +The executable solver constructs a deterministic polynomial-size subset of +$K^\delta$ consisting of the unchanged/empty completion and individually +reachable task completions, then solves (1)--(4) over that finite library. +Each emitted completion contains its ordered tasks, exact taxi flag, terminal +station/time, and an explicit emergency relief-point-release flag. The latter +is permitted only when the frozen duty horizon has no timely base-return +connection; it exposes a fallback that the former generator used implicitly. + +For this released library, $c_k^\delta$ is recomputed as the fixed duty-change +cost (unless unchanged), plus per-reassigned-task and per-new-transfer costs, +plus the taxi cost when used. No coefficient is fabricated for meal breaks, +short connections, or overtime because those coefficients are absent from the +instance. The checker independently validates the ordered completion and +recomputes both $c_k^\delta$ and objective (1). diff --git a/tasks/potthoff2010/problem_description.txt b/tasks/potthoff2010/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..0e8abc1c7a90c052a5909cf37a13609a2458f923 --- /dev/null +++ b/tasks/potthoff2010/problem_description.txt @@ -0,0 +1,32 @@ +# Problem Description + +## Public executable contract + +The released instances use the variant discriminator `relief_point_completion_v1`. +For this finite public variant, a submitted completion is an ordered list of +operated tasks. The checker verifies timing, minimum connections, route +knowledge, rolling-stock licenses, the duty horizon, taxi connections, and the +exact task coverage. Normally the driver returns to the original crew base. +Some frozen synthetic duties have no possible base-return path inside their +horizon; in precisely that case the historical generator's fallback is made +explicit as `release_at_relief_point=true`, allowing the driver to finish at +the current relief point. This is a release-specific emergency rule, not a +claim about the full pricing subproblem in the source paper. + +The executable completion cost is exactly the instance's fixed duty-change +cost, plus its per-reassigned-task, per-new-transfer, and taxi costs. The +synthetic files do not provide short-connection or overtime cost coefficients, +so those terms are not silently invented. Meal-break fields remain contextual +metadata and are not decision variables in this finite released variant. The +checker recomputes every completion cost and the full objective rather than +trusting reported values. + +A passenger railway operator runs a daily crew schedule consisting of original duties, each assigned to one train driver. A disruption occurs at a known time, after which a modified timetable and rolling stock schedule are given. The crew must be rescheduled to match the new situation. The railway network comprises a set of stations, a subset of which are designated as relief points where drivers may transfer between rolling stock units. A further subset of relief points serve as crew bases where duties begin and end. Some relief points have a canteen, which is relevant for meal breaks. The network also defines route segments connecting pairs of stations, each with a known travel time, and a set of train lines, each running along a sequence of stations at a given frequency. Taxi connections between certain pairs of stations are available, each with a specified travel time. + +Every task that has not yet started at the time of rescheduling must be either covered by some driver's revised duty or canceled. Each task has a departure station, an arrival station, a departure time, an arrival time, a rolling stock type, and a task type that is either "A to B" (departure and arrival stations differ) or "A to A" (same station). The set of unfinished original duties is partitioned into active duties, whose drivers are currently working or about to work, and reserve duties, whose drivers are on standby at a designated station. Each original duty records the crew base where it starts and ends, the driver's current station at the time of rescheduling (which is the station where the driver currently is or the arrival station of the task the driver is performing at the time of rescheduling), its planned start and end times, the sequence of tasks originally assigned to it, the driver's route knowledge (a list of stations the driver is licensed to operate through), the driver's rolling stock licenses (the set of rolling stock types the driver may operate), and whether the original duty already includes a meal break. + +The operator must choose, for every unfinished original duty, exactly one feasible completion. A feasible completion is a possibly empty sequence of tasks that, together with whatever tasks from the original duty were already performed before the rescheduling time, forms the replacement duty. A feasible completion may include tasks on which the driver rides as a passenger for repositioning; such deadhead tasks do not count as covering those tasks. Independently, the operator must decide which tasks to cancel. Each task must be either covered by at least one selected feasible completion or canceled; a task may also be covered by more than one duty, in which case one driver operates and the others deadhead as passengers. Deadheading on trains incurs no additional cost. + +A released completion must respect the timing, connection, horizon, route-knowledge, and rolling-stock rules described above. It returns to the original crew base whenever the frozen network permits this; otherwise the explicit emergency relief-point release rule applies as described in the executable-contract section. + +The goal is to minimize total cost. The total cost is the sum of two components. The first is the exact released cost of all selected completions. A completion that leaves a duty unchanged costs zero; otherwise its cost is the fixed duty-change penalty plus a penalty for each newly assigned task, each new consecutive-task transfer, and any taxi use. The second component is the cost of canceled tasks. Canceling an A-to-B task incurs the high instance penalty, while canceling an A-to-A task incurs the lower instance penalty. diff --git a/tasks/potthoff2010/release_contract.py b/tasks/potthoff2010/release_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2d6b6ac954e19229dd0839427625353cba1991 --- /dev/null +++ b/tasks/potthoff2010/release_contract.py @@ -0,0 +1,215 @@ +"""Shared executable contract for the released Potthoff et al. instances.""" + +from collections import defaultdict + + +RELEASED_VARIANT = "relief_point_completion_v1" + + +def parse_time(value): + hours, minutes = value.split(":") + return int(hours) * 60 + int(minutes) + + +class ReleasedInstance: + def __init__(self, data): + if data.get("released_problem_variant") != RELEASED_VARIANT: + raise ValueError( + "instance must declare released_problem_variant=" + + RELEASED_VARIANT + ) + self.data = data + self.params = data["parameters"] + self.rescheduling_time = data["disruption"]["rescheduling_time_minutes"] + disruption_canceled = set(data["disruption"].get("canceled_tasks", [])) + self.tasks = { + task["task_id"]: task + for task in data["tasks"] + if task["departure_time_minutes"] >= self.rescheduling_time + and task["task_id"] not in disruption_canceled + } + self.duties = { + duty["duty_id"]: duty + for duty in data.get("active_duties", []) + data.get("reserve_duties", []) + } + self.stations = {station["id"] for station in data["network"]["stations"]} + self.taxis = {} + for connection in data["network"].get("taxi_connections", []): + pair = (connection["from_station"], connection["to_station"]) + self.taxis[pair] = connection["travel_time_minutes"] + if connection.get("bidirectional", False): + self.taxis[(pair[1], pair[0])] = connection["travel_time_minutes"] + self.tasks_by_departure = defaultdict(list) + for task in self.tasks.values(): + self.tasks_by_departure[task["departure_station"]].append(task) + + def duty_state(self, duty): + if duty["duty_type"] == "reserve": + return ( + duty.get("standby_station", duty["crew_base"]), + max(self.rescheduling_time, duty["start_time_minutes"]), + ) + station = duty["crew_base"] + available = duty["start_time_minutes"] + for task in duty.get("task_details", []): + departure = parse_time(task["departure_time"]) + if departure >= self.rescheduling_time: + break + station = task["arrival_station"] + available = max(available, parse_time(task["arrival_time"])) + return station, available + + @staticmethod + def can_drive(duty, task): + route = set(duty.get("route_knowledge", [])) + licenses = set(duty.get("rolling_stock_licenses", [])) + stock = task.get("rolling_stock_type", "") + return ( + task["departure_station"] in route + and task["arrival_station"] in route + and (not stock or stock in licenses) + ) + + +def validate_completion(inst, duty, covered_tasks, declared_taxi, declared_release): + """Validate one submitted ordered completion and derive its return mode.""" + if not isinstance(covered_tasks, list) or any( + not isinstance(task_id, str) for task_id in covered_tasks + ): + return None, "covered_tasks must be a list of task identifiers" + if len(covered_tasks) != len(set(covered_tasks)): + return None, "covered_tasks contains duplicate task identifiers" + if not isinstance(declared_taxi, bool) or not isinstance(declared_release, bool): + return None, "uses_taxi and release_at_relief_point must be booleans" + + station, clock = inst.duty_state(duty) + max_end = duty["end_time_minutes"] + inst.params["max_overtime_minutes"] + min_connection = inst.params["min_connection_time_minutes"] + taxi_used = False + + for position, task_id in enumerate(covered_tasks): + task = inst.tasks.get(task_id) + if task is None: + return None, f"task {task_id} is not in the reschedulable set N" + if not inst.can_drive(duty, task): + return None, f"duty is not licensed to operate task {task_id}" + required_gap = 0 if position == 0 else min_connection + if task["departure_station"] == station: + if task["departure_time_minutes"] < clock + required_gap: + return None, f"task {task_id} starts before the duty can reach it" + else: + travel = inst.taxis.get((station, task["departure_station"])) + if travel is None or clock + travel > task["departure_time_minutes"]: + return None, f"no timely connection to task {task_id}" + taxi_used = True + if task["arrival_time_minutes"] > max_end: + return None, f"task {task_id} ends after the duty horizon" + station = task["arrival_station"] + clock = task["arrival_time_minutes"] + + base = duty["crew_base"] + release_used = False + if station != base: + travel = inst.taxis.get((station, base)) + if travel is not None and clock + travel <= max_end: + taxi_used = True + clock += travel + station = base + elif declared_release and station in inst.stations: + # Several generated instances contain duties for which no path to + # the original base exists inside the frozen horizon. The public + # release makes the generator's historical fallback explicit: + # the driver may be released at the current relief point. + release_used = True + else: + return None, "completion cannot return to base inside the duty horizon" + + if taxi_used != declared_taxi: + return None, f"uses_taxi must be {taxi_used} for the submitted route" + if release_used != declared_release: + return None, ( + "release_at_relief_point must be " + str(release_used) + + " for the submitted route" + ) + return { + "uses_taxi": taxi_used, + "release_at_relief_point": release_used, + "return_station": station, + "return_time_minutes": clock, + }, None + + +def completion_cost(inst, duty, covered_tasks, uses_taxi, release_at_relief_point): + original = [task for task in duty.get("tasks", []) if task in inst.tasks] + if covered_tasks == original and not uses_taxi and not release_at_relief_point: + return 0 + if not covered_tasks and not original and not uses_taxi and not release_at_relief_point: + return 0 + + cost = int(inst.params["cost_duty_changed"]) + original_set = set(original) + cost += int(inst.params["cost_task_reassigned"]) * sum( + task not in original_set for task in covered_tasks + ) + original_pairs = set(zip(original, original[1:])) + cost += int(inst.params["cost_new_transfer"]) * sum( + pair not in original_pairs for pair in zip(covered_tasks, covered_tasks[1:]) + ) + if uses_taxi: + cost += int(inst.params["cost_taxi"]) + return cost + + +def make_completion(inst, duty, covered_tasks): + """Construct the canonical taxi/release flags for a proposed route.""" + for uses_taxi in (False, True): + for released in (False, True): + derived, error = validate_completion( + inst, duty, list(covered_tasks), uses_taxi, released + ) + if error is None: + return { + "covered_tasks": list(covered_tasks), + "uses_taxi": derived["uses_taxi"], + "release_at_relief_point": derived["release_at_relief_point"], + "return_station": derived["return_station"], + "return_time_minutes": derived["return_time_minutes"], + "cost": completion_cost( + inst, + duty, + list(covered_tasks), + derived["uses_taxi"], + derived["release_at_relief_point"], + ), + } + return None + + +def completion_options(inst, duty): + """Build a finite, deterministic released completion library.""" + routes = [[]] + original = [task for task in duty.get("tasks", []) if task in inst.tasks] + if original: + routes.append(original) + # Single-task completions keep the library polynomial and still let the + # set-covering model rescue many high-penalty tasks. + routes.extend([[task_id] for task_id in sorted(inst.tasks)]) + + options = [] + seen = set() + for route in routes: + completion = make_completion(inst, duty, route) + if completion is None: + continue + key = ( + tuple(completion["covered_tasks"]), + completion["uses_taxi"], + completion["release_at_relief_point"], + ) + if key in seen: + continue + seen.add(key) + options.append(completion) + if not options: + raise ValueError(f"no released completion exists for duty {duty['duty_id']}") + return options diff --git a/tasks/potthoff2010/solution_logger.py b/tasks/potthoff2010/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/potthoff2010/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/potthoff2010/solution_schema.json b/tasks/potthoff2010/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8968f36cb057ac943aa55bb68f0a61b9baeaab73 --- /dev/null +++ b/tasks/potthoff2010/solution_schema.json @@ -0,0 +1,16 @@ +{ + "released_problem_variant": " Must match the executable instance contract.", + "objective_value": " Total cost of the rescheduling plan, combining the cost of the selected completions for all original duties and the penalty for all canceled tasks.", + "canceled_tasks": " Identifiers of the unfinished tasks that are canceled rather than covered by any driver.", + "duty_assignments": { + "": { + "completion_index": " Index of the feasible completion selected for this original duty among the enumerated completions.", + "cost": " Exact released completion cost: fixed change cost plus task-reassignment, new-transfer, and taxi costs (zero only for an unchanged completion).", + "covered_tasks": " Ordered identifiers of tasks operated by the duty.", + "uses_taxi": " Exact taxi-use flag derived from the route connections and return.", + "release_at_relief_point": " True only when the frozen horizon provides no timely base return and the driver is released at the final relief point.", + "return_station": " Station reached at the end of the released completion.", + "return_time_minutes": " Derived end/return time in minutes from midnight." + } + } +} diff --git a/tasks/rahimian2017/feasibility_check.py b/tasks/rahimian2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..5d0a5887c3500e9cd197897261dad85a3abe7433 --- /dev/null +++ b/tasks/rahimian2017/feasibility_check.py @@ -0,0 +1,589 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Nurse Rostering Problem (Rahimian et al., 2017). +Checks hard constraints HC1-HC10 from the mathematical formulation. +Soft constraints (SC1, SC2) are ignored. + +Tier C addition (constraint 11): Objective consistency / lower-bound check. +The reported objective_value must be at least the obj implied by the +submitted schedule, where the implied obj uses the OPTIMAL choice of +y_{dt}, z_{dt} given x_{idt} (per SC1 and SC2 these are determined by x: +v_{idt} = q*(1-x) + p*x, y_{dt} = max(0, u-sum_x), z_{dt} = max(0, sum_x-u)). +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', '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: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for NRP (Rahimian et al., 2017)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + with open(args.instance_path) as f: + instance = json.load(f) + with open(args.solution_path) as f: + sol_data = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol_data) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, sol_data) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + print(f"Result written to {args.result_path}") + print(f"Feasible: {result['feasible']}") + if not result['feasible']: + print(f"Violated constraints: {result['violated_constraints']}") + + +def check_feasibility(instance, sol_data): + # Extract schedule - handle both efficient and gurobi solution formats + if ("solution" in sol_data and isinstance(sol_data["solution"], dict) + and "schedule" in sol_data["solution"]): + schedule = sol_data["solution"]["schedule"] + cov_root = sol_data["solution"] + else: + schedule = sol_data["schedule"] + cov_root = sol_data + + # Domain check: coverage_under (y_{dt}) and coverage_over (z_{dt}) are + # integer ≥ 0 (math_model L116). They are submitted in solution_schema + # but were previously never validated. Verify each entry's domain. + coverage_violations = [] + for cov_field in ("coverage_under", "coverage_over"): + cov = cov_root.get(cov_field) + if cov is None: + continue + if not isinstance(cov, dict): + coverage_violations.append( + f"{cov_field} must be a dict; got {type(cov).__name__}") + continue + for key, val in cov.items(): + if not isinstance(val, (int, float)): + coverage_violations.append( + f"{cov_field}['{key}']={val!r} is not numeric " + f"(integer ≥ 0 required)") + continue + if val < -1e-9: + coverage_violations.append( + f"{cov_field}['{key}']={val} is negative " + f"(non-negativity violated)") + if isinstance(val, float) and abs(val - round(val)) > 1e-6: + coverage_violations.append( + f"{cov_field}['{key}']={val} is not integer " + f"(integrality violated)") + + # Parse instance data + num_days = instance["num_days"] + num_nurses = instance["num_nurses"] + num_shift_types = instance["num_shift_types"] + num_weekends = instance["num_weekends"] + + D = list(range(num_days)) + I = list(range(num_nurses)) + T = list(range(num_shift_types)) + W = list(range(1, num_weekends + 1)) + + shift_lengths = {} + for st in instance["shift_types"]: + shift_lengths[st["id"]] = st["length_minutes"] + + # Forbidden rotations: R[t] = set of shift types that cannot follow t + R = {t: set() for t in T} + for rot in instance["forbidden_shift_rotations"]: + R[rot["shift_type"]].add(rot["cannot_be_followed_by"]) + + nurse_data = {} + for nurse in instance["nurses"]: + nurse_data[nurse["id"]] = nurse + + # Build x[i][d] = assigned shift type (int) or None + x = {} + for i in I: + x[i] = {} + nurse_sched = schedule[str(i)] + for d in D: + x[i][d] = nurse_sched[str(d)] + + def works(i, d): + return x[i][d] is not None + + tol = 1e-5 + eps = 1e-5 + + all_violations = {} + + def check_violation(constraint_idx, msg, lhs, rhs, constraint_type): + if constraint_type == 'le': + va = lhs - rhs + elif constraint_type == 'ge': + va = rhs - lhs + else: + va = abs(lhs - rhs) + + if va > tol: + normalizer = max(abs(rhs), eps) + ratio = va / normalizer + record = { + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(va), + "normalizer": float(normalizer), + "ratio": float(ratio), + } + if constraint_idx not in all_violations: + all_violations[constraint_idx] = [] + all_violations[constraint_idx].append((msg, record)) + + # ========================================================================= + # Constraint 1 (HC1): At most one shift per day per nurse + # ========================================================================= + for i in I: + for d in D: + lhs = 1 if works(i, d) else 0 + check_violation(1, f"Nurse {i} assigned more than one shift on day {d}", + lhs, 1, 'le') + + # ========================================================================= + # Constraint 2 (HC2): Forbidden shift rotations + # ========================================================================= + for i in I: + for d in range(num_days - 1): + if x[i][d] is not None: + t = x[i][d] + if x[i][d + 1] is not None: + u = x[i][d + 1] + if u in R[t]: + check_violation( + 2, + f"Nurse {i}: forbidden rotation shift {t} on day {d} " + f"followed by shift {u} on day {d+1}", + 2, 1, 'le') + + # ========================================================================= + # Constraint 3 (HC3): Maximum number of shifts per type + # ========================================================================= + for i in I: + nd = nurse_data[i] + for t in T: + t_str = str(t) + if t_str in nd["max_shifts_per_type"]: + max_s = nd["max_shifts_per_type"][t_str] + count = sum(1 for d in D if x[i][d] == t) + check_violation( + 3, + f"Nurse {i}: {count} shifts of type {t} exceeds max {max_s}", + count, max_s, 'le') + + # ========================================================================= + # Constraint 4 (HC4): Maximum total minutes + # ========================================================================= + for i in I: + nd = nurse_data[i] + total_min = sum(shift_lengths[x[i][d]] for d in D if x[i][d] is not None) + check_violation( + 4, + f"Nurse {i}: total minutes {total_min} exceeds maximum {nd['max_total_minutes']}", + total_min, nd['max_total_minutes'], 'le') + + # ========================================================================= + # Constraint 5 (HC5): Minimum total minutes + # ========================================================================= + for i in I: + nd = nurse_data[i] + total_min = sum(shift_lengths[x[i][d]] for d in D if x[i][d] is not None) + check_violation( + 5, + f"Nurse {i}: total minutes {total_min} below minimum {nd['min_total_minutes']}", + total_min, nd['min_total_minutes'], 'ge') + + # ========================================================================= + # Constraint 6 (HC6): Maximum consecutive shifts + # ========================================================================= + for i in I: + nd = nurse_data[i] + c_max = nd["max_consecutive_shifts"] + for d in range(num_days - c_max): + count = sum(1 for j in range(d, d + c_max + 1) if works(i, j)) + check_violation( + 6, + f"Nurse {i}: {count} shifts in window days {d}-{d+c_max} " + f"exceeds max consecutive {c_max}", + count, c_max, 'le') + + # ========================================================================= + # Constraint 7 (HC7): Minimum consecutive shifts + # ========================================================================= + for i in I: + nd = nurse_data[i] + c_min = nd["min_consecutive_shifts"] + for c in range(1, c_min): + for d in range(num_days - c - 1): + w_d = 1 if works(i, d) else 0 + mid_sum = sum(1 for j in range(d + 1, d + c + 1) if works(i, j)) + w_end = 1 if works(i, d + c + 1) else 0 + lhs_val = w_d + (c - 1 - mid_sum) + w_end + check_violation( + 7, + f"Nurse {i}: isolated block of {mid_sum} shift(s) at days " + f"{d+1}-{d+c} violates min consecutive shifts {c_min}", + lhs_val, 0, 'ge') + + # ========================================================================= + # Constraint 8 (HC8): Minimum consecutive days off + # ========================================================================= + for i in I: + nd = nurse_data[i] + o_min = nd["min_consecutive_days_off"] + for b in range(1, o_min): + for d in range(num_days - b - 1): + off_d = 1 if not works(i, d) else 0 + mid_sum = sum(1 for j in range(d + 1, d + b + 1) if works(i, j)) + w_end = 1 if works(i, d + b + 1) else 0 + lhs_val = off_d + mid_sum + w_end + check_violation( + 8, + f"Nurse {i}: isolated block of {b} day(s) off at days " + f"{d+1}-{d+b} violates min consecutive days off {o_min}", + lhs_val, 0, 'ge') + + # ========================================================================= + # Constraint 9 (HC9): Maximum number of weekends worked + # ========================================================================= + for i in I: + nd = nurse_data[i] + weekends_worked = 0 + for w in W: + sat = 7 * w - 2 + sun = 7 * w - 1 + if sat < num_days and sun < num_days: + if works(i, sat) or works(i, sun): + weekends_worked += 1 + check_violation( + 9, + f"Nurse {i}: works {weekends_worked} weekends, " + f"exceeds max {nd['max_weekends']}", + weekends_worked, nd['max_weekends'], 'le') + + # ========================================================================= + # Constraint 10 (HC10): Requested days off + # ========================================================================= + for i in I: + nd = nurse_data[i] + for d_off in nd["day_off_requests"]: + if d_off < num_days and x[i][d_off] is not None: + check_violation( + 10, + f"Nurse {i}: assigned shift on requested day off {d_off}", + 1, 0, 'eq') + + # ========================================================================= + # Domain violations on coverage_under/coverage_over (computed earlier) + # ========================================================================= + if coverage_violations: + for msg in coverage_violations: + check_violation( + "coverage_domain", + msg, + 1.0, 0.0, "geq", + ) + + # ========================================================================= + # Constraint 11: Objective consistency (Tier C anti-exploit). + # Two-sided check on reported objective_value vs schedule-implied obj. + # Per SC1 (equality): v_{idt} = q_{idt}*(1-x_{idt}) + p_{idt}*x_{idt} + # (deterministic in x). + # Per SC2 (equality): y_{dt} - z_{dt} = u_{dt} - sum_i x_{idt}, y,z>=0. + # The cost-optimal (y,z) given x is y=max(0,u-sx), z=max(0,sx-u), and + # since w_min,w_max >= 0 this gives a true LOWER BOUND on the obj. + # (a) reported < obj_lb - tol → catches under-report (e.g. obj=0) + # (b) when submitted coverage_under/coverage_over are present (per + # solution_schema), compute obj_from_submitted = sum_v + + # sum_dt(w_min*y_sub + w_max*z_sub) and require + # |reported - obj_from_submitted| <= tol — catches over-report + # exploits (e.g. obj=sys.float_info.max) and any deviation from + # the program's own data. + # ========================================================================= + reported_obj = sol_data.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + # sum_v (deterministic from x) + sum_v = 0.0 + for r in instance.get("shift_on_requests", []): + nid = r["nurse_id"] + d = r["day"] + t = r["shift_type"] + pen = r["penalty"] + if 0 <= nid < num_nurses and 0 <= d < num_days: + if x[nid][d] != t: + sum_v += pen + for r in instance.get("shift_off_requests", []): + nid = r["nurse_id"] + d = r["day"] + t = r["shift_type"] + pen = r["penalty"] + if 0 <= nid < num_nurses and 0 <= d < num_days: + if x[nid][d] == t: + sum_v += pen + + # nurse counts per (d, t) + counts = {} + for i in I: + for d in D: + t = x[i][d] + if t is not None: + counts[(d, t)] = counts.get((d, t), 0) + 1 + + # (a) lower bound from optimal (y, z) given x + opt_cov_cost = 0.0 + for cr in instance.get("coverage_requirements", []): + d = cr["day"] + t = cr["shift_type"] + pref = cr["preferred"] + uw = cr["under_weight"] + ow = cr["over_weight"] + sx = counts.get((d, t), 0) + opt_cov_cost += uw * max(0, pref - sx) + ow * max(0, sx - pref) + obj_lb = sum_v + opt_cov_cost + + # (b) full recompute using submitted (y, z), if both provided as dicts + sub_y = cov_root.get("coverage_under") + sub_z = cov_root.get("coverage_over") + has_submitted_yz = isinstance(sub_y, dict) and isinstance(sub_z, dict) + if has_submitted_yz: + sub_cov_cost = 0.0 + for cr in instance.get("coverage_requirements", []): + d = cr["day"] + t = cr["shift_type"] + uw = cr["under_weight"] + ow = cr["over_weight"] + key = f"{d}_{t}" + yv = sub_y.get(key, 0) + zv = sub_z.get(key, 0) + try: + yv = float(yv) if yv is not None else 0.0 + except (TypeError, ValueError): + yv = 0.0 + try: + zv = float(zv) if zv is not None else 0.0 + except (TypeError, ValueError): + zv = 0.0 + if yv < 0: + yv = 0.0 + if zv < 0: + zv = 0.0 + sub_cov_cost += uw * yv + ow * zv + obj_from_submitted = sum_v + sub_cov_cost + else: + obj_from_submitted = None + + # 0.1% relative tolerance with 1.0 absolute floor (integer obj) + obj_tol = max(1.0, 1e-3 * abs(obj_lb)) + + if reported < obj_lb - obj_tol: + shortfall = obj_lb - reported + check_violation( + 11, + f"Objective consistency violated: reported objective_value=" + f"{reported} is below recomputed lower bound " + f"sum_v + sum_dt(w_min*y_opt + w_max*z_opt) = {obj_lb} " + f"(shortfall={shortfall:.3g}, tol={obj_tol:.3g})", + reported, obj_lb, 'ge') + elif obj_from_submitted is not None: + eq_tol = max(1.0, 1e-3 * abs(obj_from_submitted)) + abs_diff = abs(reported - obj_from_submitted) + if abs_diff > eq_tol: + check_violation( + 11, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recompute using submitted " + f"coverage_under/coverage_over = {obj_from_submitted} " + f"(|diff|={abs_diff:.3g}, tol={eq_tol:.3g})", + reported, obj_from_submitted, 'eq') + + # ========================================================================= + # Build output + # ========================================================================= + sorted_violated = sorted(all_violations.keys(), key=lambda x: (isinstance(x, str), x)) + feasible = len(sorted_violated) == 0 + + violations_msgs = [] + violation_magnitudes = [] + for c_idx in sorted_violated: + records = all_violations[c_idx] + count = len(records) + first_msg = records[0][0] + if count > 1: + violations_msgs.append(f"{first_msg} (and {count - 1} more)") + else: + violations_msgs.append(first_msg) + for _, rec in records: + violation_magnitudes.append(rec) + + return { + "feasible": feasible, + "violated_constraints": sorted_violated, + "violations": violations_msgs, + "violation_magnitudes": violation_magnitudes if not feasible else [], + } + + +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/rahimian2017/gurobi_code.py b/tasks/rahimian2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc075f0e7bfdccd50602a4d763a8be8a93d43dc --- /dev/null +++ b/tasks/rahimian2017/gurobi_code.py @@ -0,0 +1,400 @@ +#!/usr/bin/env python3 +""" +Gurobi IP formulation for the Nurse Rostering Problem (NRP). +Based on: Rahimian, Akartunali, and Levine (2017) +"A Hybrid Integer Programming and Variable Neighbourhood Search Algorithm + to Solve Nurse Rostering Problems" + +Implements the full IP model from Section 2 of the paper. +""" + +import argparse +import json +import os +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load a problem instance from a JSON file.""" + with open(path, 'r') as f: + data = json.load(f) + return data + + +def build_and_solve(instance, time_limit): + """ + Build and solve the NRP IP model as described in Section 2 of the paper. + """ + num_days = instance["num_days"] + num_nurses = instance["num_nurses"] + num_shift_types = instance["num_shift_types"] + num_weekends = instance["num_weekends"] + + # Sets + D = list(range(num_days)) # days 0..num_days-1 + I = list(range(num_nurses)) # nurses + T = list(range(num_shift_types)) # shift types + W = list(range(1, num_weekends + 1)) # weekends 1-indexed as per paper + + # Shift type data + shift_lengths = {} + for st in instance["shift_types"]: + shift_lengths[st["id"]] = st["length_minutes"] + + # Forbidden shift rotations: R_t = set of shift types that cannot follow t + R = {t: set() for t in T} + for rot in instance["forbidden_shift_rotations"]: + preceding = rot["shift_type"] + following = rot["cannot_be_followed_by"] + R[preceding].add(following) + + # Nurse-specific data + nurses = instance["nurses"] + max_shifts_per_type = {} # m_{it}^{max} + min_total_minutes = {} # b_i^{min} + max_total_minutes = {} # b_i^{max} + min_consecutive = {} # c_i^{min} + max_consecutive = {} # c_i^{max} + min_consecutive_off = {} # o_i^{min} + max_weekends_nurse = {} # a_i^{max} + days_off = {} # N_i + + for nurse in nurses: + i = nurse["id"] + max_shifts_per_type[i] = {} + for t_str, val in nurse["max_shifts_per_type"].items(): + max_shifts_per_type[i][int(t_str)] = val + min_total_minutes[i] = nurse["min_total_minutes"] + max_total_minutes[i] = nurse["max_total_minutes"] + min_consecutive[i] = nurse["min_consecutive_shifts"] + max_consecutive[i] = nurse["max_consecutive_shifts"] + min_consecutive_off[i] = nurse["min_consecutive_days_off"] + max_weekends_nurse[i] = nurse["max_weekends"] + days_off[i] = set(nurse["day_off_requests"]) + + # Shift on/off request penalties + # q_{idt}: penalty if shift t is NOT assigned to nurse i on day d (shift-on request) + # p_{idt}: penalty if shift t IS assigned to nurse i on day d (shift-off request) + q = {} + p = {} + for i in I: + for d in D: + for t in T: + q[i, d, t] = 0 + p[i, d, t] = 0 + + for req in instance["shift_on_requests"]: + q[req["nurse_id"], req["day"], req["shift_type"]] = req["penalty"] + + for req in instance["shift_off_requests"]: + p[req["nurse_id"], req["day"], req["shift_type"]] = req["penalty"] + + # Coverage requirements + u = {} # u_{dt}: preferred number of nurses + w_min = {} # w_{dt}^{min}: under-coverage weight + w_max = {} # w_{dt}^{max}: over-coverage weight + for cov in instance["coverage_requirements"]: + d = cov["day"] + t = cov["shift_type"] + u[d, t] = cov["preferred"] + w_min[d, t] = cov["under_weight"] + w_max[d, t] = cov["over_weight"] + + # Ensure all (d,t) pairs have coverage data; default to 0 if missing + for d in D: + for t in T: + if (d, t) not in u: + u[d, t] = 0 + w_min[d, t] = 0 + w_max[d, t] = 0 + + # ========================================================================= + # Model + # ========================================================================= + model = gp.Model("NRP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x_{idt}: binary, nurse i assigned shift t on day d + x = {} + for i in I: + for d in D: + for t in T: + x[i, d, t] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{d}_{t}") + + # k_{iw}: binary, nurse i works on weekend w + k = {} + for i in I: + for w in W: + k[i, w] = model.addVar(vtype=GRB.BINARY, name=f"k_{i}_{w}") + + # y_{dt}: under-coverage (integer >= 0) + y = {} + for d in D: + for t in T: + y[d, t] = model.addVar(vtype=GRB.INTEGER, lb=0, name=f"y_{d}_{t}") + + # z_{dt}: over-coverage (integer >= 0) + z = {} + for d in D: + for t in T: + z[d, t] = model.addVar(vtype=GRB.INTEGER, lb=0, name=f"z_{d}_{t}") + + # v_{idt}: penalty from shift on/off requests (integer >= 0) + v = {} + for i in I: + for d in D: + for t in T: + v[i, d, t] = model.addVar(vtype=GRB.INTEGER, lb=0, name=f"v_{i}_{d}_{t}") + + model.update() + + # ========================================================================= + # Objective function + # ========================================================================= + # min sum_{i,d,t} v_{idt} + sum_{d,t} w_min_{dt} * y_{dt} + sum_{d,t} w_max_{dt} * z_{dt} + obj = gp.LinExpr() + for i in I: + for d in D: + for t in T: + obj += v[i, d, t] + for d in D: + for t in T: + obj += w_min[d, t] * y[d, t] + obj += w_max[d, t] * z[d, t] + model.setObjective(obj, GRB.MINIMIZE) + + # ========================================================================= + # Constraints + # ========================================================================= + + # HC1: At most one shift per day per nurse + for i in I: + for d in D: + model.addConstr( + gp.quicksum(x[i, d, t] for t in T) <= 1, + name=f"HC1_{i}_{d}" + ) + + # HC2: Forbidden shift rotations + # x_{idt} + x_{i(d+1)u} <= 1 for all forbidden pairs + # Paper assumes last day of previous period and first day of next period are days off, + # so we only need d in {0..num_days-2} + for i in I: + for d in range(num_days - 1): + for t in T: + for u_shift in R[t]: + model.addConstr( + x[i, d, t] + x[i, d + 1, u_shift] <= 1, + name=f"HC2_{i}_{d}_{t}_{u_shift}" + ) + + # HC3: Maximum number of shifts per type + for i in I: + for t in T: + if t in max_shifts_per_type[i]: + model.addConstr( + gp.quicksum(x[i, d, t] for d in D) <= max_shifts_per_type[i][t], + name=f"HC3_{i}_{t}" + ) + + # HC4 & HC5: Min and max total minutes + for i in I: + total_minutes = gp.quicksum( + shift_lengths[t] * x[i, d, t] for d in D for t in T + ) + model.addConstr(total_minutes >= min_total_minutes[i], name=f"HC5_{i}") + model.addConstr(total_minutes <= max_total_minutes[i], name=f"HC4_{i}") + + # HC6: Maximum consecutive shifts + # sum_{j=d}^{d+c_max} sum_t x_{ijt} <= c_max + # for d in {0..num_days - c_max - 1} (0-indexed) + for i in I: + c_max = max_consecutive[i] + for d in range(num_days - c_max): + model.addConstr( + gp.quicksum( + x[i, j, t] for j in range(d, d + c_max + 1) for t in T + ) <= c_max, + name=f"HC6_{i}_{d}" + ) + + # HC7: Minimum consecutive shifts + # Paper formulation (HC7): + # sum_t x_{idt} + (c - 1 - sum_{j=d+1}^{d+c} sum_t x_{ijt}) + sum_t x_{i(d+c+1)t} >= 0 + # for c in {1..c_min-1}, d in {0..num_days-(c+2)} (0-indexed) + # + # Paper comment 3: "infinite consecutive shifts at boundaries" means the constraint + # is not violated at the start/end of the horizon. We only generate constraints + # for interior positions where d and d+c+1 are valid days. + for i in I: + c_min = min_consecutive[i] + for c in range(1, c_min): + for d in range(num_days - c - 1): + # day d is the day before the gap, d+1..d+c is the potential short sequence, + # d+c+1 is the day after + lhs = gp.LinExpr() + # sum_t x_{idt} (day before) + lhs += gp.quicksum(x[i, d, t] for t in T) + # + (c - 1 - sum_{j=d+1}^{d+c} sum_t x_{ijt}) + lhs += c - 1 + lhs -= gp.quicksum(x[i, j, t] for j in range(d + 1, d + c + 1) for t in T) + # + sum_t x_{i(d+c+1)t} + lhs += gp.quicksum(x[i, d + c + 1, t] for t in T) + model.addConstr(lhs >= 0, name=f"HC7_{i}_{c}_{d}") + + # HC8: Minimum consecutive days off + # (1 - sum_t x_{idt}) + sum_{j=d+1}^{d+b} sum_t x_{ijt} + sum_t x_{i(d+b+1)t} >= 0 + # for b in {1..o_min-1}, d in {0..num_days-(b+2)} + # Paper comment 4: infinite consecutive days off at boundaries + for i in I: + o_min = min_consecutive_off[i] + for b in range(1, o_min): + for d in range(num_days - b - 1): + lhs = gp.LinExpr() + # (1 - sum_t x_{idt}) + lhs += 1 + lhs -= gp.quicksum(x[i, d, t] for t in T) + # + sum_{j=d+1}^{d+b} sum_t x_{ijt} + lhs += gp.quicksum(x[i, j, t] for j in range(d + 1, d + b + 1) for t in T) + # + sum_t x_{i(d+b+1)t} + lhs += gp.quicksum(x[i, d + b + 1, t] for t in T) + model.addConstr(lhs >= 0, name=f"HC8_{i}_{b}_{d}") + + # HC9: Maximum weekends + # Weekend w: Saturday = day (7w-2) and Sunday = day (7w-1) in 0-indexed + # Paper uses 1-indexed days: Saturday = 7w-1, Sunday = 7w + # In 0-indexed: Saturday = 7*w - 2, Sunday = 7*w - 1 + for i in I: + for w in W: + sat = 7 * w - 2 # 0-indexed Saturday + sun = 7 * w - 1 # 0-indexed Sunday + if sat < num_days and sun < num_days: + # k_{iw} <= sum_t x_{i,sat,t} + sum_t x_{i,sun,t} <= 2*k_{iw} + weekend_shifts = gp.quicksum(x[i, sat, t] for t in T) + \ + gp.quicksum(x[i, sun, t] for t in T) + model.addConstr(k[i, w] <= weekend_shifts, name=f"HC9a_{i}_{w}") + model.addConstr(weekend_shifts <= 2 * k[i, w], name=f"HC9b_{i}_{w}") + + # sum_w k_{iw} <= a_max + model.addConstr( + gp.quicksum(k[i, w] for w in W) <= max_weekends_nurse[i], + name=f"HC9c_{i}" + ) + + # HC10: Requested days off + for i in I: + for d_off in days_off[i]: + for t in T: + model.addConstr(x[i, d_off, t] == 0, name=f"HC10_{i}_{d_off}_{t}") + + # SC1: Shift on/off requests + # q_{idt}(1 - x_{idt}) + p_{idt} * x_{idt} = v_{idt} + # => v_{idt} = q_{idt} - q_{idt}*x_{idt} + p_{idt}*x_{idt} + # => v_{idt} = q_{idt} + (p_{idt} - q_{idt})*x_{idt} + for i in I: + for d in D: + for t in T: + model.addConstr( + v[i, d, t] == q[i, d, t] + (p[i, d, t] - q[i, d, t]) * x[i, d, t], + name=f"SC1_{i}_{d}_{t}" + ) + + # SC2: Coverage + # sum_i x_{idt} - z_{dt} + y_{dt} = u_{dt} + for d in D: + for t in T: + model.addConstr( + gp.quicksum(x[i, d, t] for i in I) - z[d, t] + y[d, t] == u[d, t], + name=f"SC2_{d}_{t}" + ) + + # ========================================================================= + # Solve + # ========================================================================= + model.optimize() + + # Extract solution + objective_value = None + solution = {} + + if model.SolCount > 0: + objective_value = model.ObjVal + solution["schedule"] = {} + for i in I: + nurse_schedule = {} + for d in D: + assigned_shift = None + for t in T: + if x[i, d, t].X > 0.5: + assigned_shift = t + break + nurse_schedule[str(d)] = assigned_shift + solution["schedule"][str(i)] = nurse_schedule + + solution["coverage_under"] = {} + solution["coverage_over"] = {} + for d in D: + for t in T: + if y[d, t].X > 0.5: + solution["coverage_under"][f"{d}_{t}"] = round(y[d, t].X) + if z[d, t].X > 0.5: + solution["coverage_over"][f"{d}_{t}"] = round(z[d, t].X) + + result = { + "objective_value": objective_value, + "status": model.Status, + "mip_gap": model.MIPGap if model.SolCount > 0 else None, + "solution": solution + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi IP solver for the Nurse Rostering Problem (Rahimian et al. 2017)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path 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) + + instance = load_instance(args.instance_path) + result = build_and_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) + + print(f"Solution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + else: + print("No feasible solution found within the time limit.") + + +if __name__ == "__main__": + main() diff --git a/tasks/rahimian2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/rahimian2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahimian2017/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/rahimian2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/rahimian2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahimian2017/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/rahimian2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/rahimian2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahimian2017/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/rahimian2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/rahimian2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahimian2017/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/rahimian2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/rahimian2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahimian2017/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/rahimian2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/rahimian2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahimian2017/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/rahimian2017/gurobi_solution/large_solution_1.json b/tasks/rahimian2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0c9d3b4a78d861aa5a2b5b9471aec7d7b1ffca51 --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d9d3af6d08d448c55a1b3e9e36e6f2a9c3703ad47644350117d61a8ca199721 +size 176337 diff --git a/tasks/rahimian2017/gurobi_solution/large_solution_2.json b/tasks/rahimian2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..7fe7790bb74cb76cd5298ca3e2b2e447d87624a3 --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c270d56ae9e8846e8e92738b409c640cc60750d2bf96edf0dd5e34e13fbc5df7 +size 173767 diff --git a/tasks/rahimian2017/gurobi_solution/large_solution_3.json b/tasks/rahimian2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..4dc81b6ba24b7ef9dcde7ad72e0c6bcd1a37439e --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6aac25d28fe71ef0651c7f74aec68290d27f11ddc5f17ec749a09fd7355e1699 +size 176280 diff --git a/tasks/rahimian2017/gurobi_solution/large_solution_4.json b/tasks/rahimian2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..434e7ebc095975134bec35b35882ce6c757209cf --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba424a305608192fdc668bd37fc5ce41f9be36f9a78b97aacd15b59715e8412c +size 175160 diff --git a/tasks/rahimian2017/gurobi_solution/large_solution_5.json b/tasks/rahimian2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..2c0ea6ae1d8ef306bba88a4387837a70b9f52398 --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9267b18a160141882a46a6182dd665b1529b9c80fd891283ea8a5611f2784f6 +size 176365 diff --git a/tasks/rahimian2017/gurobi_solution/tiny_solution.json b/tasks/rahimian2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..6ceb360e9c32bba8fa58f70f398cb79d0a19a533 --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:235efb3efecfda9685018c474955b0abdc898015ae1be3943fd80daea974f382 +size 2475 diff --git a/tasks/rahimian2017/gurobi_solution_log/large_log_1.jsonl b/tasks/rahimian2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c7f0d15e1c5435fb292ea8b59b3463eb52405124 --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5fcd5de3d98e6ff53d98877b9c690c410a695503ef5ac59cde48a46c8f02780 +size 313 diff --git a/tasks/rahimian2017/gurobi_solution_log/large_log_2.jsonl b/tasks/rahimian2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..992ad2a3e791f600c90f2409495dc72000ecfd84 --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6e264de2047a0518338b89290a01adb3cae7271534b536fcc8587da63fe460a +size 45 diff --git a/tasks/rahimian2017/gurobi_solution_log/large_log_3.jsonl b/tasks/rahimian2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c73cfda09e2759bbfb203c44419ad7bf385a7d7f --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5394ec8bc3386b461f3519b8e9de145c4ff7d442a660e55ab231bad347e2cf3 +size 360 diff --git a/tasks/rahimian2017/gurobi_solution_log/large_log_4.jsonl b/tasks/rahimian2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..180e9d38f5446a506b28bdd01c96131f5e106fb8 --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95d5d66a9c50f2565ffb3ad1e7bec1b87d606ea434301b760f677a854e754cd0 +size 42 diff --git a/tasks/rahimian2017/gurobi_solution_log/large_log_5.jsonl b/tasks/rahimian2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..987b176b777c6e9a020e63afd6bbadc9b1a80a55 --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de1d84a8c4769ef48b29ec1a250f97829408613e578407753f64501ee1ca1a53 +size 89 diff --git a/tasks/rahimian2017/gurobi_solution_log/tiny_log.jsonl b/tasks/rahimian2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a04af647b775ec287b6f3e6daeefcd31d0e45a5e --- /dev/null +++ b/tasks/rahimian2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc220107eb7d7d65dcb78dc1eef4c2f5671cf85c3da309b2cd916e6c225f1713 +size 43 diff --git a/tasks/rahimian2017/instance/large_instance_1.json b/tasks/rahimian2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..732184fe8457bb37ee3b1f702b66d1ceeff0733d --- /dev/null +++ b/tasks/rahimian2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfe633fc6daf31a5796cefaa5e9e9989d63424aafd634cd749fc86d702ae0c00 +size 256101 diff --git a/tasks/rahimian2017/instance/large_instance_2.json b/tasks/rahimian2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..34d6e0fb2b63f50bf92d39f42a14011d2dbc8fe3 --- /dev/null +++ b/tasks/rahimian2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c32cb5b6588d1c3d9c1097715ae315daddda24016125ee28c51f70e934c0c328 +size 256462 diff --git a/tasks/rahimian2017/instance/large_instance_3.json b/tasks/rahimian2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..922f7328cc21cc6520d9d72c3353397cc921cdcd --- /dev/null +++ b/tasks/rahimian2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f51192c7508cdcb13908decf99c893170679db839a4dfc37ba5bb08e7d3adde +size 256362 diff --git a/tasks/rahimian2017/instance/large_instance_4.json b/tasks/rahimian2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8ca768ee2f85ed0210009303c009e96d10774bc7 --- /dev/null +++ b/tasks/rahimian2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f50649ab12dfb63fff37f76641b8f4b5750a73e433ae1ce95f1c83af493e678c +size 256397 diff --git a/tasks/rahimian2017/instance/large_instance_5.json b/tasks/rahimian2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..daaf8792a7aeb8510a7740257e3988db90869620 --- /dev/null +++ b/tasks/rahimian2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f55826a6d798c48a7a5626309ec2fceafd36b3406a3ee94df816f94735d7f6cb +size 256697 diff --git a/tasks/rahimian2017/instance/tiny_instance.json b/tasks/rahimian2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..ec7363d605d7439e7f0c918dfeb84ceb70ee0de0 --- /dev/null +++ b/tasks/rahimian2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d7465ef7d30d2add23087febb503fc4c61425eca97d34b3194758f355d81f86 +size 6346 diff --git a/tasks/rahimian2017/instance_schema.json b/tasks/rahimian2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..643809af184bbd9cf43a51b55a5b22c9e0f89b07 --- /dev/null +++ b/tasks/rahimian2017/instance_schema.json @@ -0,0 +1,58 @@ +{ + "num_days": " Total number of days in the planning horizon.", + "num_weeks": " Total number of complete weeks in the planning horizon.", + "num_nurses": " Total number of nurses available for scheduling.", + "num_shift_types": " Total number of distinct shift types that can be assigned.", + "num_weekends": " Total number of weekends in the planning horizon.", + "shift_types": [ + { + "id": " Unique identifier for this shift type.", + "name": " Descriptive name of this shift type.", + "length_minutes": " Duration of this shift type in minutes." + } + ], + "forbidden_shift_rotations": [ + { + "shift_type": " Shift type that, when assigned on a day, restricts the next day's assignment.", + "cannot_be_followed_by": " Shift type that may not be assigned on the day immediately following the preceding shift type." + } + ], + "nurses": [ + { + "id": " Unique identifier for this nurse.", + "max_shifts_per_type": " Maximum number of shifts of each type this nurse may work over the planning horizon.", + "min_total_minutes": " Minimum total working time in minutes this nurse must accumulate over the planning horizon.", + "max_total_minutes": " Maximum total working time in minutes this nurse may accumulate over the planning horizon.", + "min_consecutive_shifts": " Minimum number of consecutive working days allowed in any unbroken stretch of working days for this nurse.", + "max_consecutive_shifts": " Maximum number of consecutive working days allowed in any unbroken stretch of working days for this nurse.", + "min_consecutive_days_off": " Minimum number of consecutive days off allowed in any unbroken stretch of off-days for this nurse.", + "max_weekends": " Maximum number of weekends this nurse may work over the planning horizon.", + "day_off_requests": " Days on which this nurse must not be assigned any shift." + } + ], + "shift_on_requests": [ + { + "nurse_id": " Nurse for whom this shift-on request applies.", + "day": " Day on which the requested shift assignment is desired.", + "shift_type": " Shift type that is requested to be assigned.", + "penalty": " Penalty incurred if this nurse is not assigned the requested shift type on the specified day." + } + ], + "shift_off_requests": [ + { + "nurse_id": " Nurse for whom this shift-off request applies.", + "day": " Day on which the nurse prefers not to work the specified shift.", + "shift_type": " Shift type that the nurse prefers not to be assigned.", + "penalty": " Penalty incurred if this nurse is assigned the specified shift type on the specified day." + } + ], + "coverage_requirements": [ + { + "day": " Day to which this staffing requirement applies.", + "shift_type": " Shift type to which this staffing requirement applies.", + "preferred": " Preferred number of nurses to be assigned this shift type on this day.", + "under_weight": " Penalty weight per nurse below the preferred staffing level for this day and shift type.", + "over_weight": " Penalty weight per nurse above the preferred staffing level for this day and shift type." + } + ] +} \ No newline at end of file diff --git a/tasks/rahimian2017/mathematical_formulation.md b/tasks/rahimian2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..833a2ec8dfc33fae08ee3ec3d30f5061a2812667 --- /dev/null +++ b/tasks/rahimian2017/mathematical_formulation.md @@ -0,0 +1,98 @@ +# Original Formulation: Nurse Rostering Problem (NRP) + +*Source: A Hybrid Integer Programming and Variable Neighbourhood Search Algorithm to Solve Nurse Rostering Problems, Erfan Rahimian, Kerem Akartunalı, John Levine, 2017.* + +## Sets and Parameters + +$D$ +set of days in the planning horizon. + +$W$ +set of weekends in the planning horizon. + +$I$ +set of nurses. + +$T$ +set of shift types. + +$R_t$ +set of shift types that cannot be assigned immediately after shift type $t \in T$. + +$N_i$ +set of days that nurse $i \in I$ cannot be assigned a shift on. + +$l_t$ +length of shift type $t \in T$ in minutes. + +$m_{it}^{max}$ +maximum number of shifts of type $t \in T$ that can be assigned to nurse $i \in I$. + +$b_i^{min}, b_i^{max}$ +minimum and maximum number of minutes that nurse $i \in I$ must be assigned. + +$c_i^{min}, c_i^{max}$ +minimum and maximum number of consecutive shifts that nurse $i \in I$ must work. $c$ is the index of possible number of consecutive shifts. + +$o_i^{min}$ +minimum number of consecutive days off that nurse $i \in I$ can be assigned. $b$ is the index of possible number of consecutive days off. + +$a_i^{max}$ +maximum number of weekends that nurse $i \in I$ can work. + +$q_{idt}$ +the incurred penalty if shift type $t \in T$ is not assigned to nurse $i \in I$ on day $d \in D$. + +$p_{idt}$ +the incurred penalty if shift type $t \in T$ is assigned to nurse $i \in I$ on day $d \in D$. + +$u_{dt}$ +preferred total number of nurses to whom is assigned shift type $t \in T$ on day $d \in D$. + +$w_{dt}^{min}, w_{dt}^{max}$ +under-weight and over-weight relevant to the total coverage of shift type $t \in T$ on day $d \in D$. + +## Decision Variables + +$x_{idt}$ +$= 1$ if nurse $i \in I$ is assigned to shift type $t \in T$ on day $d \in D$, $= 0$ otherwise. + +$k_{iw}$ +$= 1$ if nurse $i \in I$ works on weekend $w \in W$, $= 0$ otherwise. + +$y_{dt}$ +total number of nurses below the preferred coverage for shift type $t \in T$ on day $d \in D$. + +$z_{dt}$ +total number of nurses above the preferred coverage for shift type $t \in T$ on day $d \in D$. + +$v_{idt}$ +total incurred penalty relevant to shift on/off requests of nurse $i \in I$ for shift type $t \in T$ on day $d \in D$. + +## Objective + +$$\begin{equation} +\min \sum_{i \in I} \sum_{d \in D} \sum_{t \in T} v_{idt} + + \sum_{d \in D} \sum_{t \in T} w_{dt}^{min} y_{dt} + + \sum_{d \in D} \sum_{t \in T} w_{dt}^{max} z_{dt} +\end{equation}$$ + +## Constraints + +$$\begin{align} +& \sum_{t \in T} x_{idt} \leq 1, && \forall i \in I,\, d \in D \tag{HC1} \\[4pt] +& x_{idt} + x_{i(d+1)u} \leq 1, && \forall i \in I,\, d \in \{1 \ldots |D|-1\},\, t \in T,\, u \in R_t \tag{HC2} \\[4pt] +& \sum_{d \in D} x_{idt} \leq m_{it}^{max}, && \forall i \in I,\, t \in T \tag{HC3} \\[4pt] +& b_i^{min} \leq \sum_{d \in D} \sum_{t \in T} l_t x_{idt} \leq b_i^{max}, && \forall i \in I \tag{HC4, HC5} \\[4pt] +& \sum_{j=d}^{d+c_i^{max}} \sum_{t \in T} x_{ijt} \leq c_i^{max}, && \forall i \in I,\, d \in \{1 \ldots |D| - c_i^{max}\} \tag{HC6} \\[4pt] +& \sum_{t \in T} x_{idt} + \left( c - 1 - \sum_{j=d+1}^{d+c} \sum_{t \in T} x_{ijt} \right) + \sum_{t \in T} x_{i(d+c+1)t} \geq 0, + && \forall i \in I,\, c \in \{1 \ldots c_i^{min} - 1\},\, d \in \{1 \ldots |D| - (c+1)\} \tag{HC7} \\[4pt] +& \left(1 - \sum_{t \in T} x_{idt}\right) + \sum_{j=d+1}^{d+b} \sum_{t \in T} x_{ijt} + \sum_{t \in T} x_{i(d+b+1)t} \geq 0, + && \forall i \in I,\, b \in \{1 \ldots o_i^{min} - 1\},\, d \in \{1 \ldots |D| - (b+1)\} \tag{HC8} \\[4pt] +& k_{iw} \leq \sum_{t \in T} x_{i(7w-1)t} + \sum_{t \in T} x_{i(7w)t} \leq 2 k_{iw}, && \forall i \in I,\, w \in W \tag{HC9} \\ +& \sum_{w \in W} k_{iw} \leq a_i^{max}, && \forall i \in I \tag{HC9} \\[4pt] +& x_{int} = 0, && \forall i \in I,\, n \in N_i,\, t \in T \tag{HC10} \\[4pt] +& q_{idt}(1 - x_{idt}) + p_{idt} x_{idt} = v_{idt}, && \forall i \in I,\, d \in D,\, t \in T \tag{SC1} \\[4pt] +& \sum_{i \in I} x_{idt} - z_{dt} + y_{dt} = u_{dt}, && \forall d \in D,\, t \in T \tag{SC2} \\[4pt] +& x_{idt},\, k_{iw} \in \{0, 1\},\quad y_{dt},\, z_{dt},\, v_{idt} \in \mathbb{Z}, && \forall i \in I,\, d \in D,\, t \in T,\, w \in W \notag +\end{align}$$ diff --git a/tasks/rahimian2017/problem_description.txt b/tasks/rahimian2017/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e6e3a1dc6185f0644c894fbdabaab9a9d943164 --- /dev/null +++ b/tasks/rahimian2017/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A hospital must create a roster that assigns nurses to shifts over a planning horizon consisting of a whole number of weeks, where all weeks start on Monday. The entities involved are a set of nurses, a set of days spanning the planning horizon, a set of shift types (such as early, late, or night shifts each with a known duration in minutes), and a set of weekends (each weekend comprising the Saturday and Sunday of its respective week). The input data specifies, for each shift type, its length in minutes and the set of other shift types that may not immediately follow it on the next day (forbidden successor shifts). For each nurse, the data provides the maximum number of shifts of each type that nurse may work over the horizon, the minimum and maximum total working time in minutes over the horizon, the minimum and maximum number of consecutive shifts the nurse may work in any unbroken stretch of working days, the minimum number of consecutive days off the nurse may take in any unbroken stretch of off-days, the maximum number of weekends the nurse may work, and a set of specific days on which the nurse must not be assigned any shift. The data also includes shift-on requests and shift-off requests: a shift-on request specifies a penalty incurred if a particular nurse is not assigned a particular shift type on a particular day, and a shift-off request specifies a penalty incurred if a particular nurse is assigned a particular shift type on a particular day. Finally, for each combination of day and shift type, the data gives a preferred number of nurses to be assigned, together with an under-coverage weight and an over-coverage weight. + +The hospital must decide, for each nurse on each day, which shift type (if any) to assign. Each nurse may work at most one shift on any given day. On any two consecutive days, a nurse may not be assigned a shift type on the first day followed by a forbidden successor shift type on the second day; for purposes of this rule, the last day of the previous planning period and the first day of the next planning period are treated as days off. Over the entire horizon, no nurse may be assigned more shifts of any given type than that nurse's per-type maximum. The total working time for each nurse, computed as the sum of the durations of all assigned shifts, must fall between that nurse's minimum and maximum total minutes. In any window of consecutive days whose length equals one more than a nurse's maximum consecutive shifts, the number of shifts assigned to that nurse must not exceed the maximum; for this rule, the day before the horizon and the day after the horizon are treated as days off. A nurse must never work an isolated block of consecutive shifts shorter than the nurse's minimum consecutive shifts requirement; formally, if a nurse is off on some day and also off on a day that is only a short gap later (where the gap length is less than the minimum), then the nurse cannot be working on all of the days in between without also working on at least one of those boundary days. The same logic applies symmetrically at the boundaries of the planning horizon, where it is assumed that the nurse has been working an infinite stretch of consecutive shifts just before the first day and just after the last day. An analogous rule governs consecutive days off: a nurse must never have an isolated block of consecutive days off shorter than the nurse's minimum consecutive days off, and at the horizon boundaries it is assumed the nurse has been off for an infinite stretch. A weekend is considered worked if the nurse is assigned any shift on either the Saturday or the Sunday of that weekend, and the total number of worked weekends for each nurse must not exceed that nurse's maximum. On each day in the nurse's set of requested days off, the nurse must not be assigned any shift. + +The penalty for each nurse-day-shift combination arising from shift-on and shift-off requests is captured as follows: if a shift-on request exists with a given penalty and the nurse is not assigned that shift, the penalty is incurred; if a shift-off request exists with a given penalty and the nurse is assigned that shift, the penalty is incurred. For staffing coverage, the number of nurses assigned to each shift type on each day may differ from the preferred number; the amount by which actual staffing falls below the preferred level and the amount by which it exceeds the preferred level are each recorded separately. The goal is to minimize the total penalty, which is the sum of all shift-on/off request penalties across all nurses, days, and shift types, plus the sum over all days and shift types of the under-coverage amount multiplied by its under-coverage weight, plus the sum over all days and shift types of the over-coverage amount multiplied by its over-coverage weight. diff --git a/tasks/rahimian2017/solution_logger.py b/tasks/rahimian2017/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/rahimian2017/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/rahimian2017/solution_schema.json b/tasks/rahimian2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..17ec75988eea47a36946d28b56ac603e23efc625 --- /dev/null +++ b/tasks/rahimian2017/solution_schema.json @@ -0,0 +1,8 @@ +{ + "objective_value": " Total penalty from unmet shift requests and staffing coverage deviations.", + "solution": { + "schedule": " Shift type assigned to each nurse on each day, or null if the nurse is not working that day.", + "coverage_under": " Number of nurses below the preferred staffing level for each day and shift type with under-coverage.", + "coverage_over": " Number of nurses above the preferred staffing level for each day and shift type with over-coverage." + } +} \ No newline at end of file diff --git a/tasks/rahmaniani2017/feasibility_check.py b/tasks/rahmaniani2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..2ceb564183f9ffc82b74784fce566a3949e41e26 --- /dev/null +++ b/tasks/rahmaniani2017/feasibility_check.py @@ -0,0 +1,599 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Uncapacitated Hub Location Problem +with Multiple Assignments (UHLPMA). + +Checks all hard constraints from both the original formulation (Eqs 2-5) +and the path-based formulation (Eqs 7-10) as listed in math_model.txt. + +Constraint numbering (top to bottom from the formulation sections): + Constraint 1 (Eq 2): sum_{i,j in H} x_{ijk} = 1, forall k in K + Constraint 2 (Eq 3): sum_j x_{ijk} + sum_{j!=i} x_{jik} <= z_i, forall i in H, k in K + Constraint 3 (Eq 4): x_{ijk} >= 0, forall i,j in H, k in K + Constraint 4 (Eq 5): z_i in {0,1}, forall i in H + Constraint 5 (Eq 7): sum_{e in E_k} x_{ek} = 1, forall k in K + Constraint 6 (Eq 8): sum_{e in E_k: i in e} x_{ek} <= z_i, forall i in H, k in K + Constraint 7 (Eq 9): x_{ek} >= 0, forall k in K, e in E_k + Constraint 8 (Eq 10): z_i in {0,1}, forall i in H + Constraint 9 (NEW): Objective-value envelope check (Tier C anti-exploit). + reported objective_value must satisfy + obj_lower <= reported <= obj_upper, where + obj_lower = sum_k W_k * min(chi, tau, delta) * d[o(k), d(k)] + + min_i f_i + obj_upper = 1e15 (loose absolute ceiling to reject + sys.float_info.max-style sentinels; + the per-instance tight upper bound + cannot accommodate the reference + Gurobi solutions, so this acts as a + sanity cap rather than a tight envelope). + The lower bound uses triangle inequality: + F_ek = W_k * (chi*d[o,i] + tau*d[i,j] + delta*d[j,d]) + >= W_k * min(chi,tau,delta) * d[o,d] + so it is a valid LB regardless of which hubs are open. + Plus min_i f_i because >=1 hub must be open for feasibility. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignments', 'objective_value', 'open_hubs') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('assignments', 'objective_value', 'open_hubs') +_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): + tol = 1e-5 + eps = 1e-5 + + # ---------------------------------------------------------------- + # Extract instance data + # ---------------------------------------------------------------- + nodes = instance["nodes"] + n = len(nodes) + H = list(range(n)) + params = instance["parameters"] + chi = params["chi"] + delta = params["delta"] + tau = params["tau"] + + commodities_raw = instance["commodities"] + + # Merge opposite commodity pairs when chi == delta (Property 3) + merge = abs(chi - delta) < 1e-9 + if merge: + merged = {} + for comm in commodities_raw: + o, d = comm["origin"], comm["destination"] + key = (min(o, d), max(o, d)) + if key in merged: + merged[key]["flow"] += comm["flow"] + else: + merged[key] = { + "origin": key[0], + "destination": key[1], + "flow": comm["flow"], + } + commodities = list(merged.values()) + else: + commodities = [ + {"origin": c["origin"], "destination": c["destination"], "flow": c["flow"]} + for c in commodities_raw + ] + + num_K = len(commodities) + + # ---------------------------------------------------------------- + # Extract solution data + # ---------------------------------------------------------------- + open_hubs = set(solution["open_hubs"]) + z = {i: (1.0 if i in open_hubs else 0.0) for i in H} + + assignments = solution.get("assignments", []) + + # Build lookup: (origin, destination) -> hub_edge + # and commodity index -> hub_edge + assign_by_od = {} + assign_by_idx = {} + for a in assignments: + od_key = (a["origin"], a["destination"]) + assign_by_od[od_key] = a["hub_edge"] + assign_by_idx[a["commodity"]] = a["hub_edge"] + + # Build expected commodity set: (origin, destination) + expected_od = set() + for c in commodities: + expected_od.add((c["origin"], c["destination"])) + + # ---------------------------------------------------------------- + # Check constraints + # ---------------------------------------------------------------- + violations = [] + violation_magnitudes = [] + violated_set = set() + + def record_violation(constraint_idx, msg, lhs, rhs, raw_excess): + violated_set.add(constraint_idx) + normalizer = max(abs(rhs), eps) + violations.append(msg) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + raw_open_hubs = solution["open_hubs"] + if ( + not raw_open_hubs + or len(set(raw_open_hubs)) != len(raw_open_hubs) + or any(isinstance(hub, bool) or not isinstance(hub, int) or hub not in H + for hub in raw_open_hubs) + ): + record_violation( + 4, + "open_hubs must be a nonempty list of unique in-range node ids", + float(len(set(raw_open_hubs))), float(len(raw_open_hubs)), 1.0, + ) + + expected_indices = set(range(num_K)) + observed_indices = [] + observed_od = [] + assignment_costs = {} + distances = instance["distances"] + for position, assignment in enumerate(assignments): + try: + commodity_index = int(assignment["commodity"]) + origin = int(assignment["origin"]) + destination = int(assignment["destination"]) + hub_edge = assignment["hub_edge"] + reported_cost = float(assignment["cost"]) + except (KeyError, TypeError, ValueError) as error: + record_violation( + 1, f"Assignment {position} is malformed: {error}", + 1.0, 0.0, 1.0, + ) + continue + observed_indices.append(commodity_index) + observed_od.append((origin, destination)) + if commodity_index not in expected_indices: + record_violation( + 1, f"Assignment uses unknown commodity {commodity_index}", + float(commodity_index), float(num_K - 1), 1.0, + ) + continue + commodity = commodities[commodity_index] + expected_pair = (commodity["origin"], commodity["destination"]) + if (origin, destination) != expected_pair: + record_violation( + 1, + f"Commodity {commodity_index} reports OD {(origin, destination)}, " + f"expected {expected_pair}", + 1.0, 0.0, 1.0, + ) + valid_edge = ( + isinstance(hub_edge, list) + and len(hub_edge) in (1, 2) + and all(isinstance(hub, int) and not isinstance(hub, bool) + and hub in H for hub in hub_edge) + and (len(hub_edge) == 1 or hub_edge[0] < hub_edge[1]) + ) + if not valid_edge: + record_violation( + 2, + f"Commodity {commodity_index} hub_edge must be one hub or a " + "strictly increasing pair of in-range hubs", + float(len(hub_edge)) if isinstance(hub_edge, list) else 0.0, + 1.0, 1.0, + ) + continue + if any(hub not in open_hubs for hub in hub_edge): + record_violation( + 2, + f"Commodity {commodity_index} uses a hub that is not open", + 1.0, 0.0, 1.0, + ) + + flow = float(commodity["flow"]) + if len(hub_edge) == 1: + first = second = hub_edge[0] + expected_cost = flow * ( + chi * distances[origin][first] + + delta * distances[second][destination] + ) + else: + first, second = hub_edge + forward = flow * ( + chi * distances[origin][first] + + tau * distances[first][second] + + delta * distances[second][destination] + ) + reverse = flow * ( + chi * distances[origin][second] + + tau * distances[second][first] + + delta * distances[first][destination] + ) + expected_cost = min(forward, reverse) + assignment_costs[commodity_index] = expected_cost + cost_difference = abs(reported_cost - expected_cost) + if not math.isfinite(reported_cost) or cost_difference > max( + 1e-5, 1e-9 * abs(expected_cost)): + record_violation( + 9, + f"Commodity {commodity_index} cost={reported_cost} does not " + f"match decision-derived cost {expected_cost}", + reported_cost, expected_cost, cost_difference, + ) + + if ( + len(assignments) != num_K + or set(observed_indices) != expected_indices + or len(observed_indices) != len(set(observed_indices)) + or len(observed_od) != len(set(observed_od)) + ): + record_violation( + 1, + "assignments must contain exactly one unique record for every " + "merged commodity", + float(len(set(observed_indices))), float(num_K), + float(abs(len(set(observed_indices)) - num_K) or 1), + ) + + # ================================================================== + # Constraint 1 (Eq 2): sum_{i,j in H} x_{ijk} = 1, forall k in K + # Each commodity must be assigned exactly once. + # ================================================================== + for k_idx, comm in enumerate(commodities): + od = (comm["origin"], comm["destination"]) + count = 1.0 if od in assign_by_od else 0.0 + lhs = count + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + record_violation( + 1, + f"Constraint 1 (Eq 2): Commodity ({od[0]},{od[1]}) " + f"has {int(count)} assignment(s), expected 1", + lhs, rhs, violation_amount, + ) + + # ================================================================== + # Constraint 2 (Eq 3): sum_j x_{ijk} + sum_{j!=i} x_{jik} <= z_i + # If hub i is used in the route for commodity k, z_i must be 1. + # ================================================================== + for comm in commodities: + od = (comm["origin"], comm["destination"]) + if od not in assign_by_od: + continue + hub_edge = assign_by_od[od] + for i in hub_edge: + lhs = 1.0 # hub i is used by this commodity + rhs = z.get(i, 0.0) + violation_amount = max(0.0, lhs - rhs) + if violation_amount > tol: + record_violation( + 2, + f"Constraint 2 (Eq 3): Hub {i} used by commodity " + f"({od[0]},{od[1]}) but hub {i} is not open (z_{i}={rhs})", + lhs, rhs, violation_amount, + ) + + # ================================================================== + # Constraint 3 (Eq 4): x_{ijk} >= 0, forall i,j in H, k in K + # Non-negativity of routing variables. With the solution format + # (assignments are binary 0/1), this is trivially satisfied. + # We verify no negative implicit values exist. + # ================================================================== + # (No violation possible: x values are implicitly 0 or 1) + + # ================================================================== + # Constraint 4 (Eq 5): z_i in {0, 1}, forall i in H + # Binary hub-opening variables. + # ================================================================== + for i in H: + z_val = z[i] + violation_amount = min(abs(z_val - 0.0), abs(z_val - 1.0)) + if violation_amount > tol: + record_violation( + 4, + f"Constraint 4 (Eq 5): z_{i} = {z_val} is not binary", + z_val, round(z_val), violation_amount, + ) + + # ================================================================== + # Constraint 5 (Eq 7): sum_{e in E_k} x_{ek} = 1, forall k in K + # Each commodity must be assigned to exactly one hub edge. + # (Path-based formulation, equivalent to Constraint 1.) + # ================================================================== + for k_idx, comm in enumerate(commodities): + od = (comm["origin"], comm["destination"]) + count = 1.0 if od in assign_by_od else 0.0 + lhs = count + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + record_violation( + 5, + f"Constraint 5 (Eq 7): Commodity ({od[0]},{od[1]}) " + f"has {int(count)} hub-edge assignment(s), expected 1", + lhs, rhs, violation_amount, + ) + + # ================================================================== + # Constraint 6 (Eq 8): sum_{e in E_k: i in e} x_{ek} <= z_i + # Routing through hub i requires z_i = 1. + # (Path-based formulation, equivalent to Constraint 2.) + # ================================================================== + for comm in commodities: + od = (comm["origin"], comm["destination"]) + if od not in assign_by_od: + continue + hub_edge = assign_by_od[od] + for i in hub_edge: + lhs = 1.0 + rhs = z.get(i, 0.0) + violation_amount = max(0.0, lhs - rhs) + if violation_amount > tol: + record_violation( + 6, + f"Constraint 6 (Eq 8): Hub {i} in edge for commodity " + f"({od[0]},{od[1]}) but hub {i} is not open (z_{i}={rhs})", + lhs, rhs, violation_amount, + ) + + # ================================================================== + # Constraint 7 (Eq 9): x_{ek} >= 0, forall k in K, e in E_k + # Non-negativity of path-based routing variables. + # ================================================================== + # (No violation possible: x values are implicitly 0 or 1) + + # ================================================================== + # Constraint 8 (Eq 10): z_i in {0, 1}, forall i in H + # Binary hub-opening variables (path-based, same as Constraint 4). + # ================================================================== + for i in H: + z_val = z[i] + violation_amount = min(abs(z_val - 0.0), abs(z_val - 1.0)) + if violation_amount > tol: + record_violation( + 8, + f"Constraint 8 (Eq 10): z_{i} = {z_val} is not binary", + z_val, round(z_val), violation_amount, + ) + + # ================================================================== + # Constraint 9: exact fixed + transportation objective from the complete + # hub/commodity witness and the already-TC-scaled distance matrix. + # ================================================================== + if set(assignment_costs) == expected_indices: + fixed_cost = sum(float(nodes[hub]["fixed_cost"]) for hub in open_hubs) + transport_cost = sum(assignment_costs.values()) + expected_objective = fixed_cost + transport_cost + reported = float(solution["objective_value"]) + difference = abs(reported - expected_objective) + objective_tolerance = max(1e-4, 1e-8 * abs(expected_objective)) + if difference > objective_tolerance: + record_violation( + 9, + f"Constraint 9 (Objective consistency): objective_value=" + f"{reported} does not match fixed + transportation cost " + f"{expected_objective} (fixed={fixed_cost}, " + f"transport={transport_cost}, |diff|={difference:.6g})", + reported, expected_objective, difference, + ) + + for field, expected_value in ( + ("num_open_hubs", float(len(open_hubs))), + ("total_fixed_cost", fixed_cost), + ("total_transport_cost", transport_cost), + ): + if field not in solution: + continue + field_value = float(solution[field]) + field_difference = abs(field_value - expected_value) + if field_difference > max(1e-4, 1e-8 * abs(expected_value)): + record_violation( + 9, + f"{field}={field_value} does not match " + f"decision-derived value {expected_value}", + field_value, expected_value, field_difference, + ) + + # ---------------------------------------------------------------- + # Build result + # ---------------------------------------------------------------- + feasible = len(violated_set) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for UHLPMA 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() + + with open(args.instance_path, "r") as f: + instance = json.load(f) + with open(args.solution_path, "r") as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/rahmaniani2017/gurobi_code.py b/tasks/rahmaniani2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d45ca1833016189eee12674d67515679cada4383 --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_code.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Uncapacitated Hub Location Problem with Multiple Assignments (UHLPMA). + +Based on the path-based (compact) formulation (Equations 6-10) from: +Contreras, Cordeau, and Laporte (2011), Operations Research 59(6), pp. 1477-1490. + +The model minimizes total fixed hub costs plus transportation costs, where commodities +are routed through one or two hubs with economies of scale on inter-hub links. +""" + +import argparse +import json +import math +import time +from itertools import combinations + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + """Load problem instance from JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def compute_distances(nodes, TC): + """Compute scaled Euclidean distances between all node pairs.""" + n = len(nodes) + dist = [[0.0] * n for _ in range(n)] + for i in range(n): + for j in range(i + 1, n): + dx = nodes[i]['x'] - nodes[j]['x'] + dy = nodes[i]['y'] - nodes[j]['y'] + d = math.sqrt(dx * dx + dy * dy) * TC + dist[i][j] = d + dist[j][i] = d + return dist + + +def solve_uhlpma(data, time_limit): + """ + Solve UHLPMA using the path-based formulation (Equations 6-10). + + Uses hub edges e ∈ E (unordered pairs or singletons of hubs) and + preprocesses to eliminate dominated hub edges per commodity. + """ + nodes = data['nodes'] + commodities = data['commodities'] + params = data['parameters'] + + n = len(nodes) + tau = params['tau'] + TC = params['TC'] + chi = params['chi'] + delta = params['delta'] + + H = list(range(n)) # All nodes are potential hubs (H = N) + + # Use distances from the instance if available, otherwise compute + if 'distances' in data: + raw_dist = data['distances'] + # Distances in the instance may already be scaled; check by comparing + # Instance-schema contract: stored distances are already scaled by TC. + dist = [[raw_dist[i][j] for j in range(n)] for i in range(n)] + else: + dist = compute_distances(nodes, TC) + + # Fixed costs + f = [nodes[i]['fixed_cost'] for i in range(n)] + + # Build commodities list + K = [] + for idx, comm in enumerate(commodities): + K.append({ + 'id': idx, + 'origin': comm['origin'], + 'destination': comm['destination'], + 'flow': comm['flow'] + }) + + # Merge opposite commodity pairs when chi == delta (Property 3) + if abs(chi - delta) < 1e-9: + merged = {} + for k in K: + o, d_node = k['origin'], k['destination'] + key = (min(o, d_node), max(o, d_node)) + if key in merged: + merged[key]['flow'] += k['flow'] + else: + merged[key] = { + 'id': len(merged), + 'origin': key[0], + 'destination': key[1], + 'flow': k['flow'] + } + K = list(merged.values()) + for idx, k in enumerate(K): + k['id'] = idx + + # Compute hub edges E: all singletons {i} and pairs {i,j} for i,j in H + # For each commodity k, compute F_{ek} and build E_k + + def compute_F_hat(o_k, d_k, W_k, i, j): + """Compute directed transportation cost F_hat_{ijk}.""" + return W_k * (chi * dist[o_k][i] + tau * dist[i][j] + delta * dist[j][d_k]) + + def compute_F_edge(o_k, d_k, W_k, i, j=None): + """Compute undirected transportation cost for hub edge e and commodity k.""" + if j is None: + # Singleton edge {i} + return compute_F_hat(o_k, d_k, W_k, i, i) + else: + # Edge {i,j}, take minimum of both directions + return min(compute_F_hat(o_k, d_k, W_k, i, j), + compute_F_hat(o_k, d_k, W_k, j, i)) + + # Build E_k for each commodity k + # E_k includes singleton edges and non-dominated pair edges + E_k_list = [] # For each commodity k: list of (edge_tuple, F_ek) + + for k in K: + o_k = k['origin'] + d_k = k['destination'] + W_k = k['flow'] + + # Compute singleton costs + singleton_costs = {} + for i in H: + singleton_costs[i] = compute_F_edge(o_k, d_k, W_k, i) + + edges_k = [] + + # Add all singleton edges + for i in H: + edges_k.append(((i,), singleton_costs[i])) + + # Property 2: if o(k) == d(k) and distances symmetric, only singleton edges + if o_k != d_k: + # Add non-dominated pair edges (Property 1) + for i, j in combinations(H, 2): + F_ej = compute_F_edge(o_k, d_k, W_k, i, j) + # Property 1: eliminate if F_ek > min(F_{e1,k}, F_{e2,k}) + if F_ej < min(singleton_costs[i], singleton_costs[j]): + edges_k.append(((i, j), F_ej)) + + E_k_list.append(edges_k) + + # Build Gurobi model + model = gp.Model("UHLPMA") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # z_i: binary, 1 if hub opened at node i + z = model.addVars(H, vtype=GRB.BINARY, name="z") + + # x_{ek}: continuous, routing variable for commodity k on hub edge e + x = {} + for k_idx, k in enumerate(K): + for e_idx, (edge, F_ek) in enumerate(E_k_list[k_idx]): + x[k_idx, e_idx] = model.addVar( + lb=0.0, ub=1.0, obj=F_ek, vtype=GRB.CONTINUOUS, + name=f"x_{k_idx}_{e_idx}" + ) + + # Objective: minimize sum f_i z_i + sum F_ek x_ek + model.setObjective( + gp.quicksum(f[i] * z[i] for i in H) + + gp.quicksum(F_ek * x[k_idx, e_idx] + for k_idx in range(len(K)) + for e_idx, (edge, F_ek) in enumerate(E_k_list[k_idx])), + GRB.MINIMIZE + ) + + # Constraint (7): sum_{e in E_k} x_{ek} = 1 for all k + for k_idx in range(len(K)): + model.addConstr( + gp.quicksum(x[k_idx, e_idx] + for e_idx in range(len(E_k_list[k_idx]))) == 1, + name=f"assign_{k_idx}" + ) + + # Constraint (8): sum_{e in E_k: i in e} x_{ek} <= z_i for all i in H, k in K + for i in H: + for k_idx in range(len(K)): + relevant = [] + for e_idx, (edge, F_ek) in enumerate(E_k_list[k_idx]): + if i in edge: + relevant.append(x[k_idx, e_idx]) + if relevant: + model.addConstr( + gp.quicksum(relevant) <= z[i], + name=f"hub_{i}_{k_idx}" + ) + + # Constraint: at least one hub must be open (constraint 17) + model.addConstr(gp.quicksum(z[i] for i in H) >= 1, name="at_least_one_hub") + + # Optimize + model.optimize() + + # Extract solution + result = {} + + if model.SolCount > 0: + result['objective_value'] = model.ObjVal + result['status'] = model.Status + result['gap'] = model.MIPGap if hasattr(model, 'MIPGap') else 0.0 + + # Open hubs + open_hubs = [i for i in H if z[i].X > 0.5] + result['open_hubs'] = open_hubs + result['num_open_hubs'] = len(open_hubs) + + # Hub fixed cost + result['total_fixed_cost'] = sum(f[i] for i in open_hubs) + result['total_transport_cost'] = result['objective_value'] - result['total_fixed_cost'] + + # Commodity assignments + assignments = [] + for k_idx, k in enumerate(K): + for e_idx, (edge, F_ek) in enumerate(E_k_list[k_idx]): + if x[k_idx, e_idx].X > 0.5: + assignments.append({ + 'commodity': k_idx, + 'origin': k['origin'], + 'destination': k['destination'], + 'hub_edge': list(edge), + 'cost': F_ek + }) + break + result['assignments'] = assignments + else: + result['objective_value'] = None + result['status'] = model.Status + result['message'] = 'No feasible solution found within time limit.' + + return result + + +def main(): + parser = argparse.ArgumentParser( + description='Solve UHLPMA using Gurobi (path-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 for the output solution JSON file.') + parser.add_argument('--time_limit', type=int, required=True, + help='Maximum solver runtime in seconds.') + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + result = solve_uhlpma(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) + + if result['objective_value'] is not None: + print(f"Objective value: {result['objective_value']:.6f}") + print(f"Open hubs: {result.get('open_hubs', [])}") + else: + print("No feasible solution found.") + + +if __name__ == '__main__': + main() diff --git a/tasks/rahmaniani2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/rahmaniani2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2017/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/rahmaniani2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/rahmaniani2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2017/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/rahmaniani2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/rahmaniani2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2017/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/rahmaniani2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/rahmaniani2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2017/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/rahmaniani2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/rahmaniani2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2017/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/rahmaniani2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/rahmaniani2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2017/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/rahmaniani2017/gurobi_solution/large_solution_1.json b/tasks/rahmaniani2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e11cbc12c9fe78de519b53d72105f9f9e069b3c7 --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4e591f4e9ffdbf1c7343392bd5bb1195d4812940396fe0fdf1875c62c425336 +size 817467 diff --git a/tasks/rahmaniani2017/gurobi_solution/large_solution_2.json b/tasks/rahmaniani2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..de7eddf3df9c779ffe9078aeff4c4eeed0671b5d --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6ef01e32c9688b9d49f4c530351b4e4705468b0f5944a87dd9cbfce2d9bf387 +size 818677 diff --git a/tasks/rahmaniani2017/gurobi_solution/large_solution_3.json b/tasks/rahmaniani2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1422dde7eea9794276fbaa829e59ff09dde850e8 --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef44008deed957321247733b14d3dce6c4713d69cc8f0c1c38d86a80cb69cc60 +size 820844 diff --git a/tasks/rahmaniani2017/gurobi_solution/large_solution_4.json b/tasks/rahmaniani2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c39dd9c196b9cac2a66302325f4439d509d29814 --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32fb7cd4bd836a941fc9314cfd4004ee1dd8055c8d6ec99cb3916674ebb6badb +size 820696 diff --git a/tasks/rahmaniani2017/gurobi_solution/large_solution_5.json b/tasks/rahmaniani2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..899953bada523aeeb56718c348e84caacb9284ef --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b576571dfb610aaf763577b0871f71c6a647c827739ed9b685309ae79457fa6 +size 807345 diff --git a/tasks/rahmaniani2017/gurobi_solution/tiny_solution.json b/tasks/rahmaniani2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..9746065ec7eb3a6ffd45ab21a1fc0ff4ecebce26 --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5350a5cce9faad8bead452a0375f07569f86c953af9453eb7e018140a99400ef +size 49643 diff --git a/tasks/rahmaniani2017/gurobi_solution_log/large_log_1.jsonl b/tasks/rahmaniani2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b9f78b62ed5bf3cc017bca30e94f4404d38defaa --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf51954b6df920f1da19189aedba5d0f7d4ce0bc7d1ca31fb1ccda56520ff881 +size 110 diff --git a/tasks/rahmaniani2017/gurobi_solution_log/large_log_2.jsonl b/tasks/rahmaniani2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0ec84dea48f1e34b541f4f3a825efbb50a4d8572 --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6e696676cac7b576b3b4519394259887647433ee0e79ffb8833b24c5d498a4b +size 110 diff --git a/tasks/rahmaniani2017/gurobi_solution_log/large_log_3.jsonl b/tasks/rahmaniani2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a5e132e85282cf24d7401fa3bb403075d8d3d623 --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9aadd1b7301681f01febe6af488f4a8426716e853657dc9d6880a7762bd975ab +size 109 diff --git a/tasks/rahmaniani2017/gurobi_solution_log/large_log_4.jsonl b/tasks/rahmaniani2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..258224d9e13db4b513225f2e854810ee64fc7cab --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b616cd60ef6a92c91277c3e820de644f2ef7c7dd20422774e42bcd258f3a1d5 +size 112 diff --git a/tasks/rahmaniani2017/gurobi_solution_log/large_log_5.jsonl b/tasks/rahmaniani2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..57478ee2244078a47eedfa2d9ab9c9a786fda887 --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0240dea3d012f55dd44a5feb26d2f169a460fc268b34b742cbb94ebaa777b48 +size 110 diff --git a/tasks/rahmaniani2017/gurobi_solution_log/tiny_log.jsonl b/tasks/rahmaniani2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..475579311204f883a2940ff77219b526bb18f3ca --- /dev/null +++ b/tasks/rahmaniani2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c7fae65d0afdc84e4e36ad70bbd47e4f596468bb5ad62bc3b5eadee40d107074 +size 109 diff --git a/tasks/rahmaniani2017/instance/large_instance_1.json b/tasks/rahmaniani2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..40c853459c24ec08973b4330043b9c24da4d1241 --- /dev/null +++ b/tasks/rahmaniani2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09c7bb466557f48f81433316f93c756e3ac2a1de85a96801dec06cd2b34976a7 +size 1206549 diff --git a/tasks/rahmaniani2017/instance/large_instance_2.json b/tasks/rahmaniani2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..63411619855ea8737946a51081bbdc0465afa6ec --- /dev/null +++ b/tasks/rahmaniani2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93b838dfb82bf6348c7be90f0ec8961f9b7b01b81c920df33fa321ac2a841a45 +size 1206805 diff --git a/tasks/rahmaniani2017/instance/large_instance_3.json b/tasks/rahmaniani2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..77672f85867f52793d0e889e4efe59b16dcff2f6 --- /dev/null +++ b/tasks/rahmaniani2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4c2f84172460778bb7c771d8a438d40f561f501ada6b3423717cab7a298137c +size 1207018 diff --git a/tasks/rahmaniani2017/instance/large_instance_4.json b/tasks/rahmaniani2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9bfda9bb281cc020d330bfbba89c340ed6af9635 --- /dev/null +++ b/tasks/rahmaniani2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4ac69e0241e261ed11647ce05411aabb896ff93fb4003d2fc45a9f4b77e055f +size 1206496 diff --git a/tasks/rahmaniani2017/instance/large_instance_5.json b/tasks/rahmaniani2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..0935cedcd7e273e56d790b89f9d04990de94b240 --- /dev/null +++ b/tasks/rahmaniani2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c861d4a0e269be12fcba6e7f8228c7109b4365748ac652c26e05b8962270daf +size 1207046 diff --git a/tasks/rahmaniani2017/instance/tiny_instance.json b/tasks/rahmaniani2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..662a9a350a7864bbbdc5602a7c27e841ccfe2f95 --- /dev/null +++ b/tasks/rahmaniani2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4015ab0b74742c80f6448552e806bf609359e22bd81e0822ee7e096c1114b01 +size 63450 diff --git a/tasks/rahmaniani2017/instance_schema.json b/tasks/rahmaniani2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..15035feb218dfe77e6ca0f32d3eab9e66e55acb9 --- /dev/null +++ b/tasks/rahmaniani2017/instance_schema.json @@ -0,0 +1,26 @@ +{ + "num_nodes": " Number of nodes in the network, all of which are candidates for hub facilities.", + "num_commodities": " Number of origin-destination commodity pairs with positive shipment flow.", + "parameters": { + "tau": " Interhub discount factor applied to the transfer leg between two hubs, reflecting economies of scale.", + "TC": " Transportation cost scaling factor applied to all Euclidean distances.", + "chi": " Collection cost parameter applied to the leg from the origin to the first hub.", + "delta": " Distribution cost parameter applied to the leg from the last hub to the destination." + }, + "nodes": [ + { + "id": " Zero-based identifier of the node.", + "x": " Horizontal coordinate of the node in the plane.", + "y": " Vertical coordinate of the node in the plane.", + "fixed_cost": " Fixed setup cost incurred when a hub is opened at this node." + } + ], + "distances": " Symmetric pairwise Euclidean distance between each pair of nodes, scaled by TC.", + "commodities": [ + { + "origin": " Node index where the shipment originates.", + "destination": " Node index where the shipment is destined.", + "flow": " Volume of goods to be shipped from the origin to the destination." + } + ] +} diff --git a/tasks/rahmaniani2017/mathematical_formulation.md b/tasks/rahmaniani2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..7860a6f0044dd6d190550f6564a0375cabfd4bab --- /dev/null +++ b/tasks/rahmaniani2017/mathematical_formulation.md @@ -0,0 +1,51 @@ +# Original Formulation: Uncapacitated Hub Location Problem with Multiple Assignments (UHLPMA) — Hamacher-style Ordered-Pair Formulation + +**Source.** Contreras, Cordeau, and Laporte (2011), *Operations Research* 59(6), 1477–1490, Section 2, equations (1)–(5). The benchmark directory is named `rahmaniani2017` but the underlying formulation is Contreras et al. (2011), which follows Hamacher, Labbé, Nickel, Sonneborn (2004). This file uses the *ordered-pair* variables $x_{ijk}$ (commodity $k$ routed via ordered hub pair $(i,j)$) rather than the path/edge-based restatement. + +## Sets and Indices + +- $G = (N, A)$ — complete digraph on nodes $N$. + +- $H \subseteq N$ — set of potential hub locations. + +- $K$ — set of commodities (origin–destination pairs with positive flow). + +- For each $k \in K$: $o(k)\in N$, $d(k)\in N$ are the origin and destination; $W_k \ge 0$ is the flow amount. + +## Parameters + +- $f_i$ — fixed set-up cost of opening a hub at $i \in H$. + +- $d_{ij} \ge 0$ — transportation distance between $i$ and $j$. + +- $\chi,\, \tau,\, \delta$ — collection, inter-hub transfer, and distribution cost parameters, with $0 < \tau < 1$ and $\tau < \chi,\ \tau < \delta$ (economies of scale between hubs). + +- $\hat F_{ijk} \;=\; W_k\bigl(\chi\,d_{o(k)\,i} + \tau\,d_{ij} + \delta\,d_{j\,d(k)}\bigr)$ — unit transportation cost of routing commodity $k$ along the path $o(k)\!\to\!i\!\to\!j\!\to\!d(k)$ via the *ordered* hub pair $(i,j)$. + +## Decision Variables + +$$\begin{align*} +& z_i \in \{0,1\} && \forall\, i \in H, \quad z_i = 1 \text{ iff a hub is opened at $i$},\\ +& x_{ijk} \ge 0 && \forall\, i,j \in H,\ k\in K, \quad \text{fraction of commodity $k$ routed via ordered hub pair $(i,j)$.} +\end{align*}$$ + +## Formulation + +$$\begin{align} +\min\quad +& \sum_{i\in H} f_i\,z_i + \;+\; \sum_{i\in H}\sum_{j\in H}\sum_{k\in K} + \hat F_{ijk}\,x_{ijk} \tag{1}\\[2pt] +\text{s.t.}\quad +& \sum_{i\in H}\sum_{j\in H} x_{ijk} \;=\; 1 + && \forall\, k\in K, \tag{2}\\ +& \sum_{j\in H} x_{ijk} \;+\; \sum_{j\in H\setminus\{i\}} x_{jik} + \;\le\; z_i + && \forall\, i\in H,\ \forall\, k\in K, \tag{3}\\ +& x_{ijk} \;\ge\; 0 + && \forall\, i,j\in H,\ \forall\, k\in K, \tag{4}\\ +& z_i \in \{0,1\} + && \forall\, i \in H. \tag{5} +\end{align}$$ + +\(1\) minimizes the sum of hub opening costs and total transportation cost. (2) requires that each commodity $k$ is routed via exactly one ordered hub pair $(i,j)$. (3) allows flow through node $i$ (either as first hub, $x_{ijk}$, or second hub, $x_{jik}$) only if a hub is opened at $i$. (4)–(5) are the variable domains. diff --git a/tasks/rahmaniani2017/problem_description.txt b/tasks/rahmaniani2017/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..59953bb34a55ac3812c834fe3413f02ba8f7315a --- /dev/null +++ b/tasks/rahmaniani2017/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A logistics network routes commodity shipments between origin-destination pairs through a hub-and-spoke system. The network consists of a set of nodes, a subset of which are candidates for hub facilities. Every pair of nodes with a positive shipment volume defines a commodity, characterized by its origin node, its destination node, and the amount of flow to be shipped. Each candidate hub node has a known fixed setup cost for opening a hub at that location. Pairwise distances between all nodes are given; these distances are symmetric and satisfy the triangle inequality. + +Every commodity must be routed from its origin to its destination through one or two open hubs. Specifically, each shipment travels from its origin to a first hub, optionally transfers to a second hub, and then continues from that second hub to its destination. The cost of shipping a commodity along a path consisting of origin, first hub, second hub, and destination equals the commodity's flow volume multiplied by the sum of three leg costs: the collection leg cost (the distance from origin to the first hub scaled by a collection cost parameter), the transfer leg cost (the distance between the first and second hubs scaled by an interhub discount factor), and the distribution leg cost (the distance from the second hub to the destination scaled by a distribution cost parameter). When a commodity is routed through a single hub, the first and second hubs coincide and the transfer leg has zero length. The interhub discount factor is strictly between zero and one and is strictly less than both the collection and distribution cost parameters, reflecting economies of scale on interhub links. In the symmetric case studied here, the collection and distribution cost parameters are both equal to one. + +The planner must decide which candidate nodes to open as hubs and, for each commodity, which ordered pair (first hub, second hub) of open hubs to use for routing (the two hubs may be the same node, meaning the commodity is routed through a single hub). There is no limit on the number of hubs that may be opened, no capacity restriction on any hub or link, and each commodity may be assigned to any such hub pair so long as both hubs in the pair are open. A commodity whose origin and destination are the same node is always routed through exactly one hub. + +Each commodity must be assigned to exactly one ordered hub pair. If a commodity is assigned to a hub pair, both hubs in that pair must be open. The goal is to minimize the total cost, defined as the sum of all fixed hub setup costs for the opened hubs plus the total transportation cost across all commodities, where each commodity's transportation cost is determined by the hub pair it is assigned to as described above. + +Observation on symmetry. Because the distances are symmetric and the collection and distribution cost parameters are equal, each commodity's routing cost through the ordered pair (i, j) equals its cost through the reverse ordered pair (j, i). Consequently, without loss of optimality, routing decisions for each commodity may be enumerated over unordered hub pairs rather than ordered ones. This observation is a property of symmetric instances, not part of the problem definition itself. diff --git a/tasks/rahmaniani2017/solution_logger.py b/tasks/rahmaniani2017/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/rahmaniani2017/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/rahmaniani2017/solution_schema.json b/tasks/rahmaniani2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..fd2c7068b9717221b759c4c64c861cd44a4ee778 --- /dev/null +++ b/tasks/rahmaniani2017/solution_schema.json @@ -0,0 +1,13 @@ +{ + "objective_value": " Total cost of opening the chosen hubs plus routing all commodities through them.", + "open_hubs": " Node ids selected to be opened as hub facilities.", + "assignments": [ + { + "commodity": " Index of the commodity being routed.", + "origin": " Origin node id of the commodity.", + "destination": " Destination node id of the commodity.", + "hub_edge": " Hub or unordered pair of hubs through which this commodity is routed (length 1 means the commodity passes through a single hub).", + "cost": " Transportation cost incurred for routing this commodity through the assigned hub edge." + } + ] +} diff --git a/tasks/rahmaniani2018/feasibility_check.py b/tasks/rahmaniani2018/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..924f03018a238d99a7861036f6c83d031418e32b --- /dev/null +++ b/tasks/rahmaniani2018/feasibility_check.py @@ -0,0 +1,1587 @@ +""" +Feasibility checker for the energy systems capacity expansion planning model +from Jacobson et al. (2023) / Rahmaniani et al. (2018). + +Checks all hard constraints from the mathematical formulation against a +candidate solution. Constraints are numbered 1-48 counting top to bottom +from the formulation section of math_model.txt. + +Constraint mapping: + 1: (12a) New gen capacity limit 2: (12b) Retirement limit + 3: (12c) Non-retirable retirement=0 4: (12d) Total capacity definition + 5: (13a) New storage energy limit 6: (13b) Storage energy ret limit + 7: (13c) Non-retirable stor energy=0 8: (13d) Storage energy definition + 9: (13e) Min duration 10: (13f) Max duration + 11: (14a) Transmission new cap limit 12: (14b) Transmission cap definition + 13: (15) Power balance 14: (16a) Capacity limit (non-UC) + 15: (16b) Storage withdrawal limit 16: (16c) Storage combined limit + 17: (16d) SOC <= energy capacity 18: (16e) Hydro level limit + 19: (16f) Charge headroom 20: (16g) Discharge floor + 21: (17a) Min output (plain) 22: (17b) Min output (hydro) + 23: (18a) Flow upper bound 24: (18b) Flow lower bound + 25: (19) NSE limit 26: (20a) SOC balance (interior) + 27: (20b) SOC balance (boundary) 28: (20c) Hydro balance (interior) + 29: (20d) Hydro balance (boundary) 30: (21a) Ramp up (non-UC, interior) + 31: (21b) Ramp down (non-UC, interior) 32: (21c) Ramp up (non-UC, boundary) + 33: (21d) Ramp down (non-UC, boundary) 34: (22a) Commit limit + 35: (22b) Start limit 36: (22c) Shut limit + 37: (22d) UC min output 38: (22e) UC max output + 39: (22f) UC transition (interior) 40: (22g) UC transition (boundary) + 41: (23a) UC ramp up (interior) 42: (23b) UC ramp down (interior) + 43: (23c) UC ramp up (boundary) 44: (23d) UC ramp down (boundary) + 45: (24a) Min up time 46: (24b) Min down time + 47: (26) RPS constraint 48: (27a) CO2 constraint + 49: Objective consistency (trusted fixed-investment recourse optimization) +""" + +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 = ('investment_decisions', 'model_variables', 'objective_value', 'transmission_decisions') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('investment_decisions', 'model_variables', 'transmission_decisions') +_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 compute_violation(lhs, rhs, op): + """ + Compute violation_amount for a constraint. + op: '<=', '>=', or '=' + Returns violation_amount (>0 means violated beyond tol). + """ + if op == '<=': + return max(0.0, lhs - rhs) + elif op == '>=': + return max(0.0, rhs - lhs) + elif op == '=': + return abs(lhs - rhs) + return 0.0 + + +def record_violation(violations_list, magnitudes_list, constraint_idx, msg, lhs, rhs, violation_amount): + """Record a violation if violation_amount > TOL.""" + if violation_amount > TOL: + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations_list.append((constraint_idx, msg)) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + +def parse_solution(sol): + """ + Parse solution into a unified format. + Returns dict with: + - 'has_investment': bool + - 'gen_inv': dict mapping generator_id -> {y_P_new, y_P_ret, y_P_total} + - 'stor_inv': dict mapping generator_id -> {y_E_new, y_E_ret, y_E_total} + - 'trans_inv': dict mapping line_id -> {y_F_new, y_F_total} + - 'has_operational': bool + - operational data dicts (if available) + """ + result = { + 'has_investment': False, + 'gen_inv': {}, + 'stor_inv': {}, + 'trans_inv': {}, + 'has_operational': False, + } + + # Gurobi solution format + if 'investment_decisions' in sol and sol['investment_decisions'] is not None: + result['has_investment'] = True + for entry in sol['investment_decisions']: + gid = entry['generator_id'] + result['gen_inv'][gid] = { + 'y_P_new': entry.get('y_P_new', 0.0), + 'y_P_ret': entry.get('y_P_ret', 0.0), + 'y_P_total': entry.get('y_P_total_MW', 0.0), + } + if 'y_E_total_MWh' in entry: + result['stor_inv'][gid] = { + 'y_E_new': entry.get('y_E_new', 0.0), + 'y_E_ret': entry.get('y_E_ret', 0.0), + 'y_E_total': entry.get('y_E_total_MWh', 0.0), + } + if 'transmission_decisions' in sol and sol['transmission_decisions'] is not None: + for entry in sol['transmission_decisions']: + lid = entry['line_id'] + result['trans_inv'][lid] = { + 'y_F_new': entry.get('y_F_new_MW', 0.0), + 'y_F_total': entry.get('total_capacity_MW', 0.0), + } + + # Efficient algorithm solution format + elif 'investment' in sol and sol['investment'] is not None: + result['has_investment'] = True + inv = sol['investment'] + for key, entry in inv.items(): + if str(key).startswith('line_'): + lid = entry['id'] + result['trans_inv'][lid] = { + 'y_F_new': entry.get('new_capacity_MW', 0.0), + 'y_F_total': entry.get('total_capacity_MW', 0.0), + } + else: + gid = entry['id'] + result['gen_inv'][gid] = { + 'y_P_new': entry.get('new_units', 0.0), + 'y_P_ret': entry.get('retired_units', 0.0), + 'y_P_total': entry.get('total_capacity_MW', 0.0), + } + if 'total_energy_capacity_MWh' in entry: + result['stor_inv'][gid] = { + 'y_E_new': entry.get('new_energy_units', 0.0), + 'y_E_ret': entry.get('retired_energy_units', 0.0), + 'y_E_total': entry.get('total_energy_capacity_MWh', 0.0), + } + + # Check for operational data (per-timestep variables) + if 'operational' in sol and sol['operational'] is not None: + result['has_operational'] = True + result['operational'] = sol['operational'] + + return result + + +def check_investment_constraints(instance, parsed_sol): + """Check constraints 1-12 (investment constraints).""" + violations = [] + magnitudes = [] + generators = instance['generators'] + gen_by_id = {g['id']: g for g in generators} + lines = instance['transmission_lines'] + line_by_id = {l['id']: l for l in lines} + + gen_inv = parsed_sol['gen_inv'] + stor_inv = parsed_sol['stor_inv'] + trans_inv = parsed_sol['trans_inv'] + + # Identify sets + G_STOR_ids = [g['id'] for g in generators if g['is_storage']] + G_NONRET_ids = [g['id'] for g in generators if not g['can_retire']] + G_NONRET_STOR_ids = [g['id'] for g in generators + if not g['can_retire'] and g['is_storage']] + + # --- Constraint 1 (12a): gamma_P * y_P_new <= max_capacity --- + for g in generators: + gid = g['id'] + if gid not in gen_inv: + continue + lhs = g['capacity_size_MW'] * gen_inv[gid]['y_P_new'] + rhs = g['max_capacity_MW'] + va = compute_violation(lhs, rhs, '<=') + record_violation(violations, magnitudes, 1, + f"Constraint 1 (12a): Generator {gid} ({g['resource_type']}): " + f"gamma*y_P_new={lhs:.4f} > max_cap={rhs:.4f}", + lhs, rhs, va) + + # --- Constraint 2 (12b): gamma_P * y_P_ret <= existing_capacity --- + for g in generators: + gid = g['id'] + if gid not in gen_inv: + continue + lhs = g['capacity_size_MW'] * gen_inv[gid]['y_P_ret'] + rhs = g['existing_capacity_MW'] + va = compute_violation(lhs, rhs, '<=') + record_violation(violations, magnitudes, 2, + f"Constraint 2 (12b): Generator {gid} ({g['resource_type']}): " + f"gamma*y_P_ret={lhs:.4f} > existing={rhs:.4f}", + lhs, rhs, va) + + # --- Constraint 3 (12c): y_P_ret = 0 for non-retirable --- + for gid in G_NONRET_ids: + if gid not in gen_inv: + continue + g = gen_by_id[gid] + lhs = gen_inv[gid]['y_P_ret'] + rhs = 0.0 + va = compute_violation(lhs, rhs, '=') + record_violation(violations, magnitudes, 3, + f"Constraint 3 (12c): Generator {gid} ({g['resource_type']}): " + f"y_P_ret={lhs:.4f} != 0 (non-retirable)", + lhs, rhs, va) + + # --- Constraint 4 (12d): y_P = existing + gamma*(new - ret) --- + for g in generators: + gid = g['id'] + if gid not in gen_inv: + continue + lhs = gen_inv[gid]['y_P_total'] + rhs = g['existing_capacity_MW'] + g['capacity_size_MW'] * ( + gen_inv[gid]['y_P_new'] - gen_inv[gid]['y_P_ret']) + va = compute_violation(lhs, rhs, '=') + record_violation(violations, magnitudes, 4, + f"Constraint 4 (12d): Generator {gid} ({g['resource_type']}): " + f"y_P_total={lhs:.4f} != computed={rhs:.4f}", + lhs, rhs, va) + + # --- Constraint 5 (13a): gamma_E * y_E_new <= max_storage_capacity --- + for gid in G_STOR_ids: + if gid not in stor_inv: + continue + g = gen_by_id[gid] + lhs = g['storage_capacity_size_MWh'] * stor_inv[gid]['y_E_new'] + rhs = g['max_storage_capacity_MWh'] + va = compute_violation(lhs, rhs, '<=') + record_violation(violations, magnitudes, 5, + f"Constraint 5 (13a): Storage {gid} ({g['resource_type']}): " + f"gamma_E*y_E_new={lhs:.4f} > max_E={rhs:.4f}", + lhs, rhs, va) + + # --- Constraint 6 (13b): gamma_E * y_E_ret <= existing_storage --- + for gid in G_STOR_ids: + if gid not in stor_inv: + continue + g = gen_by_id[gid] + lhs = g['storage_capacity_size_MWh'] * stor_inv[gid]['y_E_ret'] + rhs = g['existing_storage_capacity_MWh'] + va = compute_violation(lhs, rhs, '<=') + record_violation(violations, magnitudes, 6, + f"Constraint 6 (13b): Storage {gid} ({g['resource_type']}): " + f"gamma_E*y_E_ret={lhs:.4f} > existing_E={rhs:.4f}", + lhs, rhs, va) + + # --- Constraint 7 (13c): y_E_ret = 0 for non-retirable storage --- + for gid in G_NONRET_STOR_ids: + if gid not in stor_inv: + continue + g = gen_by_id[gid] + lhs = stor_inv[gid]['y_E_ret'] + rhs = 0.0 + va = compute_violation(lhs, rhs, '=') + record_violation(violations, magnitudes, 7, + f"Constraint 7 (13c): Storage {gid} ({g['resource_type']}): " + f"y_E_ret={lhs:.4f} != 0 (non-retirable)", + lhs, rhs, va) + + # --- Constraint 8 (13d): y_E = existing_E + gamma_E*(new_E - ret_E) --- + for gid in G_STOR_ids: + if gid not in stor_inv or gid not in gen_inv: + continue + g = gen_by_id[gid] + lhs = stor_inv[gid]['y_E_total'] + rhs = g['existing_storage_capacity_MWh'] + g['storage_capacity_size_MWh'] * ( + stor_inv[gid]['y_E_new'] - stor_inv[gid]['y_E_ret']) + va = compute_violation(lhs, rhs, '=') + record_violation(violations, magnitudes, 8, + f"Constraint 8 (13d): Storage {gid} ({g['resource_type']}): " + f"y_E_total={lhs:.4f} != computed={rhs:.4f}", + lhs, rhs, va) + + # --- Constraint 9 (13e): min_duration * y_P <= y_E --- + for gid in G_STOR_ids: + if gid not in stor_inv or gid not in gen_inv: + continue + g = gen_by_id[gid] + lhs = g['min_duration_MWh_per_MW'] * gen_inv[gid]['y_P_total'] + rhs = stor_inv[gid]['y_E_total'] + va = compute_violation(lhs, rhs, '<=') + record_violation(violations, magnitudes, 9, + f"Constraint 9 (13e): Storage {gid} ({g['resource_type']}): " + f"min_dur*y_P={lhs:.4f} > y_E={rhs:.4f}", + lhs, rhs, va) + + # --- Constraint 10 (13f): max_duration * y_P >= y_E --- + for gid in G_STOR_ids: + if gid not in stor_inv or gid not in gen_inv: + continue + g = gen_by_id[gid] + lhs = g['max_duration_MWh_per_MW'] * gen_inv[gid]['y_P_total'] + rhs = stor_inv[gid]['y_E_total'] + va = compute_violation(lhs, rhs, '>=') + record_violation(violations, magnitudes, 10, + f"Constraint 10 (13f): Storage {gid} ({g['resource_type']}): " + f"max_dur*y_P={lhs:.4f} < y_E={rhs:.4f}", + lhs, rhs, va) + + # --- Constraint 11 (14a): y_F_new <= max_new_capacity --- + for l in lines: + lid = l['id'] + if lid not in trans_inv: + continue + lhs = trans_inv[lid]['y_F_new'] + rhs = l['max_new_capacity_MW'] + va = compute_violation(lhs, rhs, '<=') + record_violation(violations, magnitudes, 11, + f"Constraint 11 (14a): Line {lid}: " + f"y_F_new={lhs:.4f} > max_new={rhs:.4f}", + lhs, rhs, va) + + # --- Constraint 12 (14b): y_F = existing + y_F_new --- + for l in lines: + lid = l['id'] + if lid not in trans_inv: + continue + lhs = trans_inv[lid]['y_F_total'] + rhs = l['existing_capacity_MW'] + trans_inv[lid]['y_F_new'] + va = compute_violation(lhs, rhs, '=') + record_violation(violations, magnitudes, 12, + f"Constraint 12 (14b): Line {lid}: " + f"y_F_total={lhs:.4f} != computed={rhs:.4f}", + lhs, rhs, va) + + return violations, magnitudes + + +def check_non_negativity(instance, parsed_sol): + """Check non-negativity of investment variables.""" + violations = [] + magnitudes = [] + generators = instance['generators'] + gen_inv = parsed_sol['gen_inv'] + stor_inv = parsed_sol['stor_inv'] + trans_inv = parsed_sol['trans_inv'] + + # y_P_new, y_P_ret, y_P >= 0 + for g in generators: + gid = g['id'] + if gid not in gen_inv: + continue + for var_name, var_val in [('y_P_new', gen_inv[gid]['y_P_new']), + ('y_P_ret', gen_inv[gid]['y_P_ret']), + ('y_P_total', gen_inv[gid]['y_P_total'])]: + if var_val < -TOL: + # Map to constraint 4 (12d) as the capacity definition + lhs = 0.0 + rhs = var_val + va = abs(var_val) + record_violation(violations, magnitudes, 4, + f"Non-negativity: Generator {gid} {var_name}={var_val:.6f} < 0", + var_val, 0.0, va) + + for gid in stor_inv: + for var_name, var_val in [('y_E_new', stor_inv[gid]['y_E_new']), + ('y_E_ret', stor_inv[gid]['y_E_ret']), + ('y_E_total', stor_inv[gid]['y_E_total'])]: + if var_val < -TOL: + lhs = var_val + rhs = 0.0 + va = abs(var_val) + record_violation(violations, magnitudes, 8, + f"Non-negativity: Storage {gid} {var_name}={var_val:.6f} < 0", + var_val, 0.0, va) + + for lid in trans_inv: + for var_name, var_val in [('y_F_new', trans_inv[lid]['y_F_new']), + ('y_F_total', trans_inv[lid]['y_F_total'])]: + if var_val < -TOL: + lhs = var_val + rhs = 0.0 + va = abs(var_val) + record_violation(violations, magnitudes, 12, + f"Non-negativity: Line {lid} {var_name}={var_val:.6f} < 0", + var_val, 0.0, va) + + return violations, magnitudes + + +def check_operational_constraints(instance, parsed_sol): + """ + Check operational constraints 13-48 if per-timestep data is available. + Returns (violations, magnitudes). + """ + violations = [] + magnitudes = [] + + if not parsed_sol['has_operational']: + return violations, magnitudes + + op = parsed_sol['operational'] + generators = instance['generators'] + gen_by_id = {g['id']: g for g in generators} + lines = instance['transmission_lines'] + line_by_id = {l['id']: l for l in lines} + nse_segments = instance['nse_segments'] + dims = instance['problem_dimensions'] + subperiods_info = instance['subperiods'] + num_zones = dims['num_zones'] + total_T = dims['total_timesteps'] + W = subperiods_info['num_subperiods'] + delta_w = subperiods_info['hours_per_subperiod'] + weights = subperiods_info['subperiod_weights'] + avail_data = instance['availability_profiles'] + demand_data = instance['demand'] + policy = instance['policy'] + + gen_inv = parsed_sol['gen_inv'] + stor_inv = parsed_sol['stor_inv'] + trans_inv = parsed_sol['trans_inv'] + + # Build sigma + sigma = {} + for g in generators: + gid_str = str(g['id']) + if gid_str in avail_data: + prof = avail_data[gid_str] + if prof['type'] == 'timeseries': + sigma[g['id']] = prof['values'] + else: + sigma[g['id']] = [prof['value']] * total_T + else: + sigma[g['id']] = [1.0] * total_T + + # Build alpha + alpha = [0.0] * total_T + for w in range(W): + for t in range(w * delta_w, (w + 1) * delta_w): + alpha[t] = weights[w] / delta_w + + # Extract operational variables + x_inj = op.get('x_inj', {}) + x_wdw = op.get('x_wdw', {}) + x_nse = op.get('x_nse', {}) + x_soc = op.get('x_soc', {}) + x_lvl = op.get('x_lvl', {}) + x_spill = op.get('x_spill', {}) + x_flow = op.get('x_flow', {}) + x_commit = op.get('x_commit', {}) + x_start = op.get('x_start', {}) + x_shut = op.get('x_shut', {}) + x_rps = op.get('x_rps', {}) + x_co2 = op.get('x_co2', {}) + + # Helper to get operational value + def get_val(d, key, default=0.0): + return d.get(str(key), d.get(key, default)) + + def get_val2(d, key1, key2, default=0.0): + k = f"{key1},{key2}" + return d.get(k, d.get((key1, key2), default)) + + def get_val3(d, key1, key2, key3, default=0.0): + k = f"{key1},{key2},{key3}" + return d.get(k, d.get((key1, key2, key3), default)) + + # Generator sets + G_UC_ids = [g['id'] for g in generators if g['is_UC']] + G_STOR_ids = [g['id'] for g in generators if g['is_storage']] + G_HYDRO_ids = [g['id'] for g in generators if g['is_hydro']] + G_nonUC_ids = [g['id'] for g in generators if not g['is_UC']] + G_PLAIN_ids = [g['id'] for g in generators + if not g['is_UC'] and not g['is_storage'] and not g['is_hydro']] + G_RPS_ids = [g['id'] for g in generators if g['is_RPS_qualifying']] + + gens_in_zone = {z: [] for z in range(1, num_zones + 1)} + stor_in_zone = {z: [] for z in range(1, num_zones + 1)} + for g in generators: + gens_in_zone[g['zone']].append(g['id']) + if g['is_storage']: + stor_in_zone[g['zone']].append(g['id']) + + I_in = {z: [] for z in range(1, num_zones + 1)} + I_out = {z: [] for z in range(1, num_zones + 1)} + for l in lines: + I_out[l['from_zone']].append(l['id']) + I_in[l['to_zone']].append(l['id']) + + def circ_prev(t, w): + t_start = w * delta_w + if t == t_start: + return t_start + delta_w - 1 + return t - 1 + + # --- Constraint 13 (15): Power balance --- + if x_inj: + for z in range(1, num_zones + 1): + for t in range(total_T): + lhs_val = 0.0 + for gid in gens_in_zone[z]: + lhs_val += get_val2(x_inj, gid, t) + for gid in stor_in_zone[z]: + lhs_val -= get_val2(x_wdw, gid, t) + for lid in I_out[z]: + lhs_val -= get_val2(x_flow, lid, t) + for lid in I_in[z]: + lhs_val += get_val2(x_flow, lid, t) + for seg in nse_segments: + s = seg['segment'] + lhs_val += get_val3(x_nse, s, z, t) + rhs_val = demand_data[str(z)][t] + va = compute_violation(lhs_val, rhs_val, '=') + record_violation(violations, magnitudes, 13, + f"Constraint 13 (15): Power balance z={z} t={t}: " + f"LHS={lhs_val:.4f} != demand={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 14 (16a): Capacity limit for non-UC generators --- + if x_inj: + for gid in G_PLAIN_ids + G_HYDRO_ids: + g = gen_by_id[gid] + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + for t in range(total_T): + lhs_val = get_val2(x_inj, gid, t) + rhs_val = sigma[gid][t] * yP + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 14, + f"Constraint 14 (16a): Gen {gid} t={t}: " + f"inj={lhs_val:.4f} > sigma*yP={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 15 (16b): Storage withdrawal limit --- + if x_wdw: + for gid in G_STOR_ids: + g = gen_by_id[gid] + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + for t in range(total_T): + lhs_val = get_val2(x_wdw, gid, t) + rhs_val = sigma[gid][t] * yP + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 15, + f"Constraint 15 (16b): Storage {gid} t={t}: " + f"wdw={lhs_val:.4f} > sigma*yP={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 16 (16c): Storage combined limit --- + if x_inj and x_wdw: + for gid in G_STOR_ids: + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + for t in range(total_T): + lhs_val = get_val2(x_inj, gid, t) + get_val2(x_wdw, gid, t) + rhs_val = yP + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 16, + f"Constraint 16 (16c): Storage {gid} t={t}: " + f"inj+wdw={lhs_val:.4f} > yP={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 17 (16d): SOC <= energy capacity --- + if x_soc: + for gid in G_STOR_ids: + yE = stor_inv.get(gid, {}).get('y_E_total', 0.0) + for t in range(total_T): + lhs_val = get_val2(x_soc, gid, t) + rhs_val = yE + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 17, + f"Constraint 17 (16d): Storage {gid} t={t}: " + f"soc={lhs_val:.4f} > yE={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 18 (16e): Hydro level limit --- + if x_lvl: + for gid in G_HYDRO_ids: + g = gen_by_id[gid] + rho = g['duration_MWh_per_MW'] + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + for t in range(total_T): + lhs_val = get_val2(x_lvl, gid, t) + rhs_val = rho * yP + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 18, + f"Constraint 18 (16e): Hydro {gid} t={t}: " + f"lvl={lhs_val:.4f} > rho*yP={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 19 (16f): Charge headroom --- + if x_wdw and x_soc: + for gid in G_STOR_ids: + g = gen_by_id[gid] + eta_plus = g['charge_efficiency'] + yE = stor_inv.get(gid, {}).get('y_E_total', 0.0) + for t in range(total_T): + lhs_val = eta_plus * get_val2(x_wdw, gid, t) + rhs_val = yE - get_val2(x_soc, gid, t) + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 19, + f"Constraint 19 (16f): Storage {gid} t={t}: " + f"eta+*wdw={lhs_val:.4f} > yE-soc={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 20 (16g): Discharge floor --- + if x_inj and x_soc: + for gid in G_STOR_ids: + g = gen_by_id[gid] + eta_minus = g['discharge_efficiency'] + for t in range(total_T): + lhs_val = get_val2(x_inj, gid, t) / eta_minus + rhs_val = get_val2(x_soc, gid, t) + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 20, + f"Constraint 20 (16g): Storage {gid} t={t}: " + f"inj/eta-={lhs_val:.4f} > soc={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 21 (17a): Min output (plain generators) --- + if x_inj: + for gid in G_PLAIN_ids: + g = gen_by_id[gid] + min_out = g.get('min_output_frac', 0.0) + if min_out <= 0: + continue + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + for t in range(total_T): + lhs_val = get_val2(x_inj, gid, t) + rhs_val = min_out * yP + va = compute_violation(lhs_val, rhs_val, '>=') + record_violation(violations, magnitudes, 21, + f"Constraint 21 (17a): Gen {gid} t={t}: " + f"inj={lhs_val:.4f} < min_out*yP={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 22 (17b): Min output (hydro) --- + if x_inj: + for gid in G_HYDRO_ids: + g = gen_by_id[gid] + min_out = g.get('min_output_frac', 0.0) + if min_out <= 0: + continue + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + for t in range(total_T): + inj = get_val2(x_inj, gid, t) + spill = get_val2(x_spill, gid, t) if x_spill else 0.0 + lhs_val = inj + spill + rhs_val = min_out * yP + va = compute_violation(lhs_val, rhs_val, '>=') + record_violation(violations, magnitudes, 22, + f"Constraint 22 (17b): Hydro {gid} t={t}: " + f"inj+spill={lhs_val:.4f} < min_out*yP={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 23 (18a): Flow upper bound --- + if x_flow: + for l in lines: + lid = l['id'] + yF = trans_inv.get(lid, {}).get('y_F_total', l['existing_capacity_MW']) + for t in range(total_T): + lhs_val = get_val2(x_flow, lid, t) + rhs_val = yF + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 23, + f"Constraint 23 (18a): Line {lid} t={t}: " + f"flow={lhs_val:.4f} > yF={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 24 (18b): Flow lower bound --- + if x_flow: + for l in lines: + lid = l['id'] + yF = trans_inv.get(lid, {}).get('y_F_total', l['existing_capacity_MW']) + for t in range(total_T): + lhs_val = -get_val2(x_flow, lid, t) + rhs_val = yF + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 24, + f"Constraint 24 (18b): Line {lid} t={t}: " + f"-flow={lhs_val:.4f} > yF={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 25 (19): NSE limit --- + if x_nse: + for seg in nse_segments: + s = seg['segment'] + max_frac = seg['max_frac'] + for z in range(1, num_zones + 1): + for t in range(total_T): + lhs_val = get_val3(x_nse, s, z, t) + rhs_val = max_frac * demand_data[str(z)][t] + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 25, + f"Constraint 25 (19): NSE s={s} z={z} t={t}: " + f"nse={lhs_val:.4f} > limit={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraints 26-27 (20a-20b): Storage SOC balance --- + if x_soc and x_inj and x_wdw: + for gid in G_STOR_ids: + g = gen_by_id[gid] + eta_plus = g['charge_efficiency'] + eta_minus = g['discharge_efficiency'] + eta_disch = g['self_discharge_rate'] + for w_idx in range(W): + t_start = w_idx * delta_w + for t in range(t_start, t_start + delta_w): + t_prev = circ_prev(t, w_idx) + soc_t = get_val2(x_soc, gid, t) + soc_prev = get_val2(x_soc, gid, t_prev) + wdw_t = get_val2(x_wdw, gid, t) + inj_t = get_val2(x_inj, gid, t) + lhs_val = soc_t - soc_prev + rhs_val = eta_plus * wdw_t - inj_t / eta_minus - eta_disch * soc_prev + va = compute_violation(lhs_val, rhs_val, '=') + cstr_idx = 27 if t == t_start else 26 + record_violation(violations, magnitudes, cstr_idx, + f"Constraint {cstr_idx} ({'20b' if t == t_start else '20a'}): " + f"SOC balance storage {gid} t={t}: " + f"LHS={lhs_val:.6f} != RHS={rhs_val:.6f}", + lhs_val, rhs_val, va) + + # --- Constraints 28-29 (20c-20d): Hydro reservoir balance --- + if x_lvl and x_inj: + for gid in G_HYDRO_ids: + g = gen_by_id[gid] + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + for w_idx in range(W): + t_start = w_idx * delta_w + for t in range(t_start, t_start + delta_w): + t_prev = circ_prev(t, w_idx) + lvl_t = get_val2(x_lvl, gid, t) + lvl_prev = get_val2(x_lvl, gid, t_prev) + inj_t = get_val2(x_inj, gid, t) + spill_t = get_val2(x_spill, gid, t) if x_spill else 0.0 + lhs_val = lvl_t - lvl_prev + rhs_val = sigma[gid][t] * yP - inj_t - spill_t + va = compute_violation(lhs_val, rhs_val, '=') + cstr_idx = 29 if t == t_start else 28 + record_violation(violations, magnitudes, cstr_idx, + f"Constraint {cstr_idx} ({'20d' if t == t_start else '20c'}): " + f"Hydro balance {gid} t={t}: " + f"LHS={lhs_val:.6f} != RHS={rhs_val:.6f}", + lhs_val, rhs_val, va) + + # --- Constraints 30-33 (21a-21d): Ramping for non-UC --- + if x_inj: + for gid in G_PLAIN_ids + G_HYDRO_ids: + g = gen_by_id[gid] + mu_up = g.get('ramp_up_frac_per_hr', 1.0) + mu_dn = g.get('ramp_dn_frac_per_hr', 1.0) + if mu_up >= 1.0 and mu_dn >= 1.0: + continue + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + for w_idx in range(W): + t_start = w_idx * delta_w + for t in range(t_start, t_start + delta_w): + t_prev = circ_prev(t, w_idx) + inj_t = get_val2(x_inj, gid, t) + inj_prev = get_val2(x_inj, gid, t_prev) + is_boundary = (t == t_start) + # Ramp up + if mu_up < 1.0: + lhs_val = inj_t - inj_prev + rhs_val = mu_up * yP + va = compute_violation(lhs_val, rhs_val, '<=') + cstr_idx = 32 if is_boundary else 30 + record_violation(violations, magnitudes, cstr_idx, + f"Constraint {cstr_idx} ({'21c' if is_boundary else '21a'}): " + f"Ramp up gen {gid} t={t}: " + f"delta={lhs_val:.4f} > limit={rhs_val:.4f}", + lhs_val, rhs_val, va) + # Ramp down + if mu_dn < 1.0: + lhs_val = inj_prev - inj_t + rhs_val = mu_dn * yP + va = compute_violation(lhs_val, rhs_val, '<=') + cstr_idx = 33 if is_boundary else 31 + record_violation(violations, magnitudes, cstr_idx, + f"Constraint {cstr_idx} ({'21d' if is_boundary else '21b'}): " + f"Ramp dn gen {gid} t={t}: " + f"delta={lhs_val:.4f} > limit={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraints 34-36 (22a-22c): UC commit/start/shut limits --- + if x_commit: + for gid in G_UC_ids: + g = gen_by_id[gid] + size_P = g['capacity_size_MW'] + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + for t in range(total_T): + # (22a) + lhs_val = size_P * get_val2(x_commit, gid, t) + rhs_val = yP + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 34, + f"Constraint 34 (22a): UC {gid} t={t}: " + f"gamma*commit={lhs_val:.4f} > yP={rhs_val:.4f}", + lhs_val, rhs_val, va) + # (22b) + lhs_val = size_P * get_val2(x_start, gid, t) + va = compute_violation(lhs_val, yP, '<=') + record_violation(violations, magnitudes, 35, + f"Constraint 35 (22b): UC {gid} t={t}: " + f"gamma*start={lhs_val:.4f} > yP={yP:.4f}", + lhs_val, yP, va) + # (22c) + lhs_val = size_P * get_val2(x_shut, gid, t) + va = compute_violation(lhs_val, yP, '<=') + record_violation(violations, magnitudes, 36, + f"Constraint 36 (22c): UC {gid} t={t}: " + f"gamma*shut={lhs_val:.4f} > yP={yP:.4f}", + lhs_val, yP, va) + + # --- Constraint 37 (22d): UC min output --- + if x_inj and x_commit: + for gid in G_UC_ids: + g = gen_by_id[gid] + min_out = g.get('min_output_frac', 0.0) + size_P = g['capacity_size_MW'] + for t in range(total_T): + lhs_val = get_val2(x_inj, gid, t) + rhs_val = min_out * size_P * get_val2(x_commit, gid, t) + va = compute_violation(lhs_val, rhs_val, '>=') + record_violation(violations, magnitudes, 37, + f"Constraint 37 (22d): UC {gid} t={t}: " + f"inj={lhs_val:.4f} < min*gamma*commit={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 38 (22e): UC max output --- + if x_inj and x_commit: + for gid in G_UC_ids: + g = gen_by_id[gid] + size_P = g['capacity_size_MW'] + for t in range(total_T): + lhs_val = get_val2(x_inj, gid, t) + rhs_val = sigma[gid][t] * size_P * get_val2(x_commit, gid, t) + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 38, + f"Constraint 38 (22e): UC {gid} t={t}: " + f"inj={lhs_val:.4f} > sigma*gamma*commit={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraints 39-40 (22f-22g): UC state transition --- + if x_commit and x_start and x_shut: + for gid in G_UC_ids: + for w_idx in range(W): + t_start_w = w_idx * delta_w + for t in range(t_start_w, t_start_w + delta_w): + t_prev = circ_prev(t, w_idx) + lhs_val = (get_val2(x_commit, gid, t) + - get_val2(x_commit, gid, t_prev)) + rhs_val = (get_val2(x_start, gid, t) + - get_val2(x_shut, gid, t)) + va = compute_violation(lhs_val, rhs_val, '=') + is_boundary = (t == t_start_w) + cstr_idx = 40 if is_boundary else 39 + record_violation(violations, magnitudes, cstr_idx, + f"Constraint {cstr_idx} ({'22g' if is_boundary else '22f'}): " + f"UC transition {gid} t={t}: " + f"LHS={lhs_val:.6f} != RHS={rhs_val:.6f}", + lhs_val, rhs_val, va) + + # --- Constraints 41-44 (23a-23d): UC ramping --- + if x_inj and x_commit and x_start and x_shut: + for gid in G_UC_ids: + g = gen_by_id[gid] + size_P = g['capacity_size_MW'] + min_out = g.get('min_output_frac', 0.0) + mu_up = g.get('ramp_up_frac_per_hr', 1.0) + mu_dn = g.get('ramp_dn_frac_per_hr', 1.0) + for w_idx in range(W): + t_start_w = w_idx * delta_w + for t in range(t_start_w, t_start_w + delta_w): + t_prev = circ_prev(t, w_idx) + inj_t = get_val2(x_inj, gid, t) + inj_prev = get_val2(x_inj, gid, t_prev) + commit_t = get_val2(x_commit, gid, t) + start_t = get_val2(x_start, gid, t) + shut_t = get_val2(x_shut, gid, t) + sig_t = sigma[gid][t] + is_boundary = (t == t_start_w) + # (23a/23c) Ramp up + lhs_val = inj_t - inj_prev + rhs_val = (size_P * mu_up * (commit_t - start_t) + + size_P * min(sig_t, max(min_out, mu_up)) * start_t + - size_P * min_out * shut_t) + va = compute_violation(lhs_val, rhs_val, '<=') + cstr_idx = 43 if is_boundary else 41 + record_violation(violations, magnitudes, cstr_idx, + f"Constraint {cstr_idx} ({'23c' if is_boundary else '23a'}): " + f"UC ramp up {gid} t={t}: " + f"delta={lhs_val:.4f} > limit={rhs_val:.4f}", + lhs_val, rhs_val, va) + # (23b/23d) Ramp down + lhs_val = inj_prev - inj_t + rhs_val = (size_P * mu_dn * (commit_t - start_t) + + size_P * min(sig_t, max(min_out, mu_dn)) * shut_t + - size_P * min_out * start_t) + va = compute_violation(lhs_val, rhs_val, '<=') + cstr_idx = 44 if is_boundary else 42 + record_violation(violations, magnitudes, cstr_idx, + f"Constraint {cstr_idx} ({'23d' if is_boundary else '23b'}): " + f"UC ramp dn {gid} t={t}: " + f"delta={lhs_val:.4f} > limit={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 45 (24a): Min up time --- + if x_commit and x_start: + for gid in G_UC_ids: + g = gen_by_id[gid] + tau_up = g.get('min_up_time_hr', 0) + if tau_up <= 0: + continue + for w_idx in range(W): + t_start_w = w_idx * delta_w + for t in range(t_start_w, t_start_w + delta_w): + idx_in_sub = t - t_start_w + starts_sum = 0.0 + for k in range(tau_up): + tk = t_start_w + ((idx_in_sub - k) % delta_w) + starts_sum += get_val2(x_start, gid, tk) + lhs_val = get_val2(x_commit, gid, t) + rhs_val = starts_sum + va = compute_violation(lhs_val, rhs_val, '>=') + record_violation(violations, magnitudes, 45, + f"Constraint 45 (24a): Min up time UC {gid} t={t}: " + f"commit={lhs_val:.4f} < sum_starts={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 46 (24b): Min down time --- + if x_commit and x_shut: + for gid in G_UC_ids: + g = gen_by_id[gid] + size_P = g['capacity_size_MW'] + tau_dn = g.get('min_down_time_hr', 0) + if tau_dn <= 0: + continue + yP = gen_inv.get(gid, {}).get('y_P_total', 0.0) + max_units = yP / size_P if size_P > 0 else 0.0 + for w_idx in range(W): + t_start_w = w_idx * delta_w + for t in range(t_start_w, t_start_w + delta_w): + idx_in_sub = t - t_start_w + shuts_sum = 0.0 + for k in range(tau_dn): + tk = t_start_w + ((idx_in_sub - k) % delta_w) + shuts_sum += get_val2(x_shut, gid, tk) + lhs_val = get_val2(x_commit, gid, t) + shuts_sum + rhs_val = max_units + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 46, + f"Constraint 46 (24b): Min down time UC {gid} t={t}: " + f"commit+shuts={lhs_val:.4f} > yP/gamma={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 47 (26): RPS constraint --- + if x_inj and policy.get('RPS_enabled', False): + rps_share = policy['RPS_share'] + total_rps_gen = 0.0 + total_rps_slack = 0.0 + total_demand_val = 0.0 + for w_idx in range(W): + t_start_w = w_idx * delta_w + for t in range(t_start_w, t_start_w + delta_w): + for gid in G_RPS_ids: + total_rps_gen += alpha[t] * get_val2(x_inj, gid, t) + for z in range(1, num_zones + 1): + total_demand_val += alpha[t] * demand_data[str(z)][t] + total_rps_slack += get_val(x_rps, w_idx) if x_rps else 0.0 + lhs_val = total_rps_gen + total_rps_slack + rhs_val = rps_share * total_demand_val + va = compute_violation(lhs_val, rhs_val, '>=') + record_violation(violations, magnitudes, 47, + f"Constraint 47 (26): RPS: " + f"rps_gen+slack={lhs_val:.4f} < required={rhs_val:.4f}", + lhs_val, rhs_val, va) + + # --- Constraint 48 (27a): CO2 constraint --- + if x_inj and policy.get('CO2_cap_enabled', False): + co2_cap_rate = policy['CO2_cap_tons_per_MWh'] + total_demand_val = 0.0 + for w_idx in range(W): + t_start_w = w_idx * delta_w + for t in range(t_start_w, t_start_w + delta_w): + for z in range(1, num_zones + 1): + total_demand_val += alpha[t] * demand_data[str(z)][t] + co2_cap = co2_cap_rate * total_demand_val + + total_co2 = 0.0 + total_co2_slack = 0.0 + for w_idx in range(W): + t_start_w = w_idx * delta_w + for t in range(t_start_w, t_start_w + delta_w): + for g in generators: + gid = g['id'] + co2_rate = g['co2_tons_per_MWh'] + if co2_rate > 0: + total_co2 += alpha[t] * co2_rate * get_val2(x_inj, gid, t) + for gid in G_STOR_ids: + g2 = gen_by_id[gid] + co2_rate = g2['co2_tons_per_MWh'] + if co2_rate > 0: + total_co2 += alpha[t] * co2_rate * get_val2(x_wdw, gid, t) + total_co2_slack += get_val(x_co2, w_idx) if x_co2 else 0.0 + lhs_val = total_co2 - total_co2_slack + rhs_val = co2_cap + va = compute_violation(lhs_val, rhs_val, '<=') + record_violation(violations, magnitudes, 48, + f"Constraint 48 (27a): CO2: " + f"emissions-slack={lhs_val:.4f} > cap={rhs_val:.4f}", + lhs_val, rhs_val, va) + + return violations, magnitudes + + +def check_objective_consistency_legacy_envelope(instance, parsed_sol, solution): + """ + Constraint 49 (Tier C anti-exploit, envelope check on objective_value). + + The solution carries only first-stage investment variables (y_P, y_E, y_F + and the new/ret pieces). Operational variables (x_inj, x_wdw, x_nse, + x_start, x_commit, x_rps, x_co2) are NOT in the solution schema, so a + full obj recompute is impossible. Instead we bracket the reported + objective with an envelope derivable from the first-stage variables and + the instance data. + + Lower bound (rejects obj=0 / "do-nothing" / "claim-zero-cost" exploits): + obj_lower = c^FIXED (= eq. 29 of the paper, computed exactly) + The other components (c^VAR, c^NSE, c^START, c^RPS, c^CO2) are sums + of non-negative variables times non-negative coefficients, so all >= 0. + + Upper bound (rejects obj=MAX_FLOAT / arbitrarily-huge exploits): + c^VAR <= sum_t alpha_t * sum_g c_g^VAR * y_g^P + (since x_inj, x_wdw <= sigma * y_P <= y_P (16a/16b), and + for storage x_inj + x_wdw <= y_P (16c), so the c_g^VAR + cost on the storage pair sums to at most c_g^VAR * y_P) + c^NSE <= sum_t alpha_t * sum_{s,z} c_{s,z}^NSE * max_frac_s * d_{z,t} + (eq. 19 bounds x_nse per segment) + c^START <= sum_t alpha_t * sum_{g in UC} c_g^START * y_g^P / gamma_g + (x_start <= y_P/gamma per (22b)) + c^RPS <= c^RPS_cost * RPS_share * total_weighted_demand + (slack at most equals the RPS requirement) + c^CO2 <= c^CO2_cost * sum_t alpha_t * sum_g co2_rate * y_g^P + (slack absorbs emissions at most equal to gross emissions) + + Tolerance: max(1e-3 absolute, 1e-3 relative). For numbers on the order + of 1e9, this is roughly 1e6 tolerance --- tight enough to catch any + LLM-style fabrication, loose enough not to trip on Gurobi's MIP gap or + floating-point noise. + """ + violations = [] + magnitudes = [] + + if not parsed_sol['has_investment']: + return violations, magnitudes + + reported_obj = solution.get("objective_value") + if reported_obj is None: + return violations, magnitudes + try: + reported = float(reported_obj) + except (TypeError, ValueError): + return violations, magnitudes + if not math.isfinite(reported): + # Non-finite reported obj is unambiguously bogus -> reject as + # exceeding any sensible envelope. + violations.append((49, f"Constraint 49 (obj consistency): reported " + f"objective_value={reported_obj} is not finite.")) + magnitudes.append({ + "constraint": 49, "lhs": float('inf'), "rhs": 0.0, + "raw_excess": float('inf'), "normalizer": EPS, "ratio": float('inf'), + }) + return violations, magnitudes + + generators = instance['generators'] + lines = instance['transmission_lines'] + nse_segments = instance['nse_segments'] + dims = instance['problem_dimensions'] + subperiods_info = instance['subperiods'] + policy = instance['policy'] + demand_data = instance['demand'] + num_zones = dims['num_zones'] + total_T = dims['total_timesteps'] + W = subperiods_info['num_subperiods'] + delta_w = subperiods_info['hours_per_subperiod'] + weights = subperiods_info['subperiod_weights'] + + gen_inv = parsed_sol['gen_inv'] + stor_inv = parsed_sol['stor_inv'] + trans_inv = parsed_sol['trans_inv'] + + # alpha_t weights for annualisation + alpha = [0.0] * total_T + for w_idx in range(W): + for h in range(delta_w): + alpha[w_idx * delta_w + h] = weights[w_idx] / delta_w + sum_alpha = sum(alpha) + + def _f(x, default=0.0): + try: + v = float(x) + return v if math.isfinite(v) else default + except (TypeError, ValueError): + return default + + # ----- Lower bound: c^FIXED exactly (eq. 29) -------------------------- + c_fixed = 0.0 + for g in generators: + gid = g['id'] + inv_p = gen_inv.get(gid, {}) + yPn = _f(inv_p.get('y_P_new', 0.0)) + yPt = _f(inv_p.get('y_P_total', 0.0)) + # c_g^{P,INV} * gamma * y_P_NEW + c_fixed += _f(g.get('inv_cost_per_MW_yr', 0.0)) \ + * _f(g.get('capacity_size_MW', 0.0)) * yPn + # c_g^{P,FOM} * y_P + c_fixed += _f(g.get('fom_cost_per_MW_yr', 0.0)) * yPt + if g.get('is_storage'): + inv_e = stor_inv.get(gid, {}) + yEn = _f(inv_e.get('y_E_new', 0.0)) + yEt = _f(inv_e.get('y_E_total', 0.0)) + # c_g^{E,INV} * gamma_E * y_E_NEW + c_fixed += _f(g.get('inv_cost_energy_per_MWh_yr', 0.0)) \ + * _f(g.get('storage_capacity_size_MWh', 0.0)) * yEn + # c_g^{E,FOM} * y_E + c_fixed += _f(g.get('fom_cost_energy_per_MWh_yr', 0.0)) * yEt + if g.get('is_hydro'): + rho = _f(g.get('duration_MWh_per_MW', 0.0)) + # c_g^{E,INV} * rho * y_P_NEW (hydro energy-side investment) + c_fixed += _f(g.get('inv_cost_energy_per_MWh_yr', 0.0)) * rho * yPn + # c_g^{E,FOM} * rho * y_P (hydro energy-side FOM) + c_fixed += _f(g.get('fom_cost_energy_per_MWh_yr', 0.0)) * rho * yPt + for l in lines: + lid = l['id'] + t_inv = trans_inv.get(lid, {}) + yFn = _f(t_inv.get('y_F_new', 0.0)) + c_fixed += _f(l.get('inv_cost_per_MW_yr', 0.0)) * yFn + + obj_lower = c_fixed + + # ----- Upper bound: c^FIXED + per-component upper bounds -------------- + # c^VAR upper bound: alpha_t * c_g^VAR * y_P per (g,t). For storage, c^VAR + # is charged on both x_inj and x_wdw but x_inj + x_wdw <= y_P (16c) so the + # bound is still c_g^VAR * y_P per timestep. + c_var_upper = 0.0 + for g in generators: + gid = g['id'] + yPt = _f(gen_inv.get(gid, {}).get('y_P_total', 0.0)) + cv = _f(g.get('var_cost_per_MWh', 0.0)) + c_var_upper += sum_alpha * cv * yPt + + # c^NSE upper bound from (19): x_nse_{s,z,t} <= max_frac_s * d_{z,t}. + c_nse_upper = 0.0 + for seg in nse_segments: + cs = _f(seg.get('cost_per_MWh', 0.0)) + mfs = _f(seg.get('max_frac', 0.0)) + for z in range(1, num_zones + 1): + d_list = demand_data.get(str(z), []) + for t in range(total_T): + d_zt = _f(d_list[t]) if t < len(d_list) else 0.0 + c_nse_upper += alpha[t] * cs * mfs * d_zt + + # c^START upper bound: x_start <= y_P / gamma per (22b). + c_start_upper = 0.0 + for g in generators: + if not g.get('is_UC'): + continue + gid = g['id'] + yPt = _f(gen_inv.get(gid, {}).get('y_P_total', 0.0)) + cs = _f(g.get('start_cost_per_unit', 0.0)) + gamma = _f(g.get('capacity_size_MW', 1.0), default=1.0) + if gamma > 0.0: + c_start_upper += sum_alpha * cs * (yPt / gamma) + + # c^RPS upper bound: x_w^RPS slack at most equals the RPS requirement. + c_rps_upper = 0.0 + if policy.get('RPS_enabled', False): + rps_cost = _f(policy.get('RPS_noncompliance_cost_per_MWh', 0.0)) + rps_share = _f(policy.get('RPS_share', 0.0)) + twd = 0.0 + for z in range(1, num_zones + 1): + d_list = demand_data.get(str(z), []) + for t in range(total_T): + d_zt = _f(d_list[t]) if t < len(d_list) else 0.0 + twd += alpha[t] * d_zt + c_rps_upper = rps_cost * rps_share * twd + + # c^CO2 upper bound: x_w^CO2 slack at most equals gross emissions. + c_co2_upper = 0.0 + if policy.get('CO2_cap_enabled', False): + co2_cost = _f(policy.get('CO2_noncompliance_cost_per_ton', 0.0)) + for g in generators: + gid = g['id'] + yPt = _f(gen_inv.get(gid, {}).get('y_P_total', 0.0)) + co2r = _f(g.get('co2_tons_per_MWh', 0.0)) + c_co2_upper += sum_alpha * co2_cost * co2r * yPt + + obj_upper = c_fixed + c_var_upper + c_nse_upper + c_start_upper + c_rps_upper + c_co2_upper + + # Tolerances: 0.1% relative with a small absolute floor. + tol_lo = max(1e-3, 1e-3 * abs(obj_lower)) + tol_hi = max(1e-3, 1e-3 * abs(obj_upper)) + + shortfall = obj_lower - reported + overshoot = reported - obj_upper + + if shortfall > tol_lo: + record_violation( + violations, magnitudes, 49, + f"Constraint 49 (Objective consistency): reported objective_value=" + f"{reported:.6f} is below lower bound c^FIXED={obj_lower:.6f} " + f"(shortfall={shortfall:.6g}, tol={tol_lo:.6g})", + obj_lower, reported, shortfall, + ) + + if overshoot > tol_hi: + record_violation( + violations, magnitudes, 49, + f"Constraint 49 (Objective consistency): reported objective_value=" + f"{reported:.6f} exceeds upper bound={obj_upper:.6f} " + f"(c^FIXED={c_fixed:.4f}, c^VAR_max={c_var_upper:.4f}, " + f"c^NSE_max={c_nse_upper:.4f}, c^START_max={c_start_upper:.4f}, " + f"c^RPS_max={c_rps_upper:.4f}, c^CO2_max={c_co2_upper:.4f}); " + f"overshoot={overshoot:.6g}, tol={tol_hi:.6g}", + reported, obj_upper, overshoot, + ) + + return violations, magnitudes + + +def check_first_stage_coverage(instance, solution): + """Require one complete, finite record for every first-stage entity.""" + messages = [] + generator_entries = solution.get("investment_decisions") + line_entries = solution.get("transmission_decisions") + if not isinstance(generator_entries, list) or not isinstance(line_entries, list): + return [(0, "First-stage decisions must be JSON lists")], [] + + expected_generators = {g["id"]: g for g in instance["generators"]} + expected_lines = {line["id"]: line for line in instance["transmission_lines"]} + + generator_ids = [ + entry.get("generator_id") for entry in generator_entries + if isinstance(entry, dict) + ] + line_ids = [ + entry.get("line_id") for entry in line_entries + if isinstance(entry, dict) + ] + if len(generator_ids) != len(generator_entries): + messages.append("Every investment_decisions entry must be an object") + if len(line_ids) != len(line_entries): + messages.append("Every transmission_decisions entry must be an object") + if len(generator_ids) != len(set(generator_ids)): + messages.append("Generator investment records contain duplicate IDs") + if len(line_ids) != len(set(line_ids)): + messages.append("Transmission investment records contain duplicate IDs") + if set(generator_ids) != set(expected_generators): + messages.append( + "Generator investment records do not exactly cover the instance IDs" + ) + if set(line_ids) != set(expected_lines): + messages.append( + "Transmission investment records do not exactly cover the instance IDs" + ) + + for entry in generator_entries: + if not isinstance(entry, dict) or entry.get("generator_id") not in expected_generators: + continue + generator = expected_generators[entry["generator_id"]] + fields = ["y_P_new", "y_P_ret", "y_P_total_MW"] + if generator["is_storage"]: + fields.extend(["y_E_new", "y_E_ret", "y_E_total_MWh"]) + for field in fields: + value = entry.get(field) + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(float(value)) + ): + messages.append( + f"Generator {entry['generator_id']} has invalid or missing {field}" + ) + + for entry in line_entries: + if not isinstance(entry, dict) or entry.get("line_id") not in expected_lines: + continue + for field in ("y_F_new_MW", "total_capacity_MW"): + value = entry.get(field) + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(float(value)) + ): + messages.append( + f"Line {entry['line_id']} has invalid or missing {field}" + ) + + return [(0, message) for message in messages], [] + + +def check_objective_consistency(instance, parsed_sol, solution, instance_path): + """Validate complete operations and bind the scalar to their exact cost.""" + reported = float(solution["objective_value"]) + expected, errors, _ = validate_complete_witness( + instance_path, solution, Path(__file__).resolve().parent + ) + links = {} + entries = {entry["generator_id"]: entry for entry in solution["investment_decisions"]} + for index, generator in enumerate(instance["generators"]): + entry = entries[generator["id"]] + links[f"yPnew_{index}"] = float(entry["y_P_new"]) + links[f"yPret_{index}"] = float(entry["y_P_ret"]) + if generator["is_storage"]: + links[f"yEnew_{index}"] = float(entry["y_E_new"]) + links[f"yEret_{index}"] = float(entry["y_E_ret"]) + line_entries = {entry["line_id"]: entry for entry in solution["transmission_decisions"]} + for index, line in enumerate(instance["transmission_lines"]): + links[f"yFnew_{index}"] = float(line_entries[line["id"]]["y_F_new_MW"]) + errors.extend(require_linked_variables(solution, links)) + if errors or expected is None: + return [(49, "Constraint 49 (complete witness): " + "; ".join(errors[:20]))], [] + # Published MIP incumbents can retain a few parts per million of recourse + # suboptimality even after the first-stage integers are fixed. Five ppm + # covers that numerical residue while remaining far below eval mutations. + tolerance = max(1e-3, 5e-6 * max(1.0, abs(expected))) + difference = abs(reported - expected) + if difference <= tolerance: + return [], [] + return [( + 49, + f"Constraint 49 (objective consistency): reported objective_value=" + f"{reported:.6f} does not equal trusted fixed-investment cost=" + f"{expected:.6f} (difference={difference:.6g}, tol={tolerance:.6g})", + )], [{ + "constraint": 49, + "lhs": reported, + "rhs": expected, + "raw_excess": difference, + "normalizer": max(abs(expected), EPS), + "ratio": difference / max(abs(expected), EPS), + }] + + +def check_feasibility(instance, solution, instance_path=None): + """In-memory feasibility check entrypoint (used by the diff-test harness). + Returns the same dict shape that main() writes to disk.""" + parsed = parse_solution(solution) + + if not parsed['has_investment']: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["No investment solution provided (null or missing)"], + "violation_magnitudes": [], + } + + all_violations = [] + all_magnitudes = [] + + v, m = check_first_stage_coverage(instance, solution) + all_violations.extend(v); all_magnitudes.extend(m) + if all_violations: + return { + "feasible": False, + "violated_constraints": [0], + "violations": [message for _, message in all_violations], + "violation_magnitudes": all_magnitudes, + } + + v, m = check_investment_constraints(instance, parsed) + all_violations.extend(v); all_magnitudes.extend(m) + v, m = check_non_negativity(instance, parsed) + all_violations.extend(v); all_magnitudes.extend(m) + v, m = check_operational_constraints(instance, parsed) + all_violations.extend(v); all_magnitudes.extend(m) + if instance_path is None: + v, m = [(49, "instance_path is required for solverless validation")], [] + else: + v, m = check_objective_consistency(instance, parsed, solution, instance_path) + all_violations.extend(v); all_magnitudes.extend(m) + + violated_indices = sorted(set(idx for idx, _ in all_violations)) + violation_messages = [] + for idx in violated_indices: + msgs = [msg for i, msg in all_violations if i == idx] + if len(msgs) <= 3: + violation_messages.extend(msgs) + else: + violation_messages.append(msgs[0]) + violation_messages.append(f"... and {len(msgs) - 1} more violations of constraint {idx}") + + return { + "feasible": len(violated_indices) == 0, + "violated_constraints": violated_indices, + "violations": violation_messages, + "violation_magnitudes": all_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for energy systems planning model") + parser.add_argument('--instance_path', required=True, + help='Path to instance JSON file') + parser.add_argument('--solution_path', required=True, + help='Path to candidate solution JSON file') + parser.add_argument('--result_path', required=True, + help='Path to write feasibility result JSON file') + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution, args.instance_path) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"Solution is FEASIBLE.") + else: + print( + "Solution is INFEASIBLE. Violated constraints: " + f"{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/rahmaniani2018/gurobi_code.py b/tasks/rahmaniani2018/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c000505ed4bbc77ed917f4cd76775017d76198f8 --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_code.py @@ -0,0 +1,894 @@ +""" +Monolithic MILP energy systems capacity expansion planning model using Gurobi. + +Implements the model from Jacobson et al. (2023) as described in +Rahmaniani et al. (2018). Minimizes total system cost subject to +investment, operational, and policy constraints. +""" + +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_and_solve(instance, time_limit, fixed_solution=None, quiet=False): + # ---------------------------------------------------------------- + # Unpack instance data + # ---------------------------------------------------------------- + dims = instance["problem_dimensions"] + algo = instance["algorithm_parameters"] + policy = instance["policy"] + subperiods = instance["subperiods"] + generators = instance["generators"] + trans_lines = instance["transmission_lines"] + demand_data = instance["demand"] + nse_segments = instance["nse_segments"] + avail_data = instance["availability_profiles"] + + num_zones = dims["num_zones"] + total_T = dims["total_timesteps"] + formulation = algo["formulation"] # "MILP" or "LP" + + num_subperiods = subperiods["num_subperiods"] + hours_per_subperiod = subperiods["hours_per_subperiod"] + subperiod_weights = subperiods["subperiod_weights"] # beta_w + + # Build subperiod structure: list of (w, [t indices within subperiod]) + # Subperiods are sequential blocks of hours_per_subperiod timesteps. + subperiod_timesteps = [] # subperiod_timesteps[w] = list of global t indices + for w in range(num_subperiods): + start = w * hours_per_subperiod + end = start + hours_per_subperiod + subperiod_timesteps.append(list(range(start, end))) + + # alpha_t = beta_w / delta_w + alpha = {} + for w in range(num_subperiods): + beta_w = subperiod_weights[w] + delta_w = hours_per_subperiod + a = beta_w / delta_w + for t in subperiod_timesteps[w]: + alpha[t] = a + + # Generator sets + G_all = list(range(len(generators))) + G_UC = [i for i in G_all if generators[i]["is_UC"]] + G_nonUC = [i for i in G_all if not generators[i]["is_UC"]] + G_STOR = [i for i in G_all if generators[i]["is_storage"]] + G_HYDRO = [i for i in G_all if generators[i]["is_hydro"]] + G_RPS = [i for i in G_all if generators[i]["is_RPS_qualifying"]] + + # Zone sets + zones = list(range(1, num_zones + 1)) + + # Generators by zone + gens_in_zone = {z: [] for z in zones} + for i in G_all: + gens_in_zone[generators[i]["zone"]].append(i) + + # Availability profiles: build sigma[i][t] + sigma = {} + for i in G_all: + gid = str(generators[i]["id"]) + if gid in avail_data: + prof = avail_data[gid] + if prof["type"] == "timeseries": + sigma[i] = prof["values"] + else: + sigma[i] = [prof["value"]] * total_T + else: + sigma[i] = [1.0] * total_T + + # Demand: demand[z][t] + demand = {} + for z in zones: + demand[z] = demand_data[str(z)] + + # Transmission lines indexed 0..L-1 + L_all = list(range(len(trans_lines))) + + # NSE segments indexed 0..S-1 + S_all = list(range(len(nse_segments))) + + # ---------------------------------------------------------------- + # Build Gurobi model + # ---------------------------------------------------------------- + model = gp.Model("energy_planning") + model.setParam("Threads", 1) + + # Solver parameters + if time_limit is not None: + model.setParam("TimeLimit", time_limit) + model.setParam("MIPFocus", 1) + model.setParam("NoRelHeurTime", min(60.0, time_limit * 0.05)) + model.setParam("MIPGap", 1e-4) + if formulation == "LP": + model.setParam("Method", 2) # barrier + model.setParam("Crossover", 0) # crossover off + + # Variable type for investment + inv_vtype = GRB.INTEGER if formulation == "MILP" else GRB.CONTINUOUS + + # ---------------------------------------------------------------- + # Decision Variables + # ---------------------------------------------------------------- + + # --- Investment variables (per generator) --- + y_P_new = {} # new power capacity (units) + y_P_ret = {} # retired power capacity (units) + y_P = {} # total installed power capacity (MW) + for i in G_all: + g = generators[i] + max_new_units = g["max_capacity_MW"] / g["capacity_size_MW"] if g["capacity_size_MW"] > 0 else 0 + max_ret_units = g["existing_capacity_MW"] / g["capacity_size_MW"] if g["capacity_size_MW"] > 0 else 0 + y_P_new[i] = model.addVar(lb=0, ub=max_new_units, vtype=inv_vtype, name=f"yPnew_{i}") + y_P_ret[i] = model.addVar(lb=0, ub=max_ret_units, vtype=inv_vtype, name=f"yPret_{i}") + y_P[i] = model.addVar(lb=0, name=f"yP_{i}") + + # --- Storage energy investment variables --- + y_E_new = {} + y_E_ret = {} + y_E = {} + for i in G_STOR: + g = generators[i] + max_new_e = g["max_storage_capacity_MWh"] / g["storage_capacity_size_MWh"] if g["storage_capacity_size_MWh"] > 0 else 0 + max_ret_e = g["existing_storage_capacity_MWh"] / g["storage_capacity_size_MWh"] if g["storage_capacity_size_MWh"] > 0 else 0 + y_E_new[i] = model.addVar(lb=0, ub=max_new_e, vtype=inv_vtype, name=f"yEnew_{i}") + y_E_ret[i] = model.addVar(lb=0, ub=max_ret_e, vtype=inv_vtype, name=f"yEret_{i}") + y_E[i] = model.addVar(lb=0, name=f"yE_{i}") + + # --- Transmission investment --- + y_F_new = {} + for l in L_all: + tl = trans_lines[l] + y_F_new[l] = model.addVar(lb=0, ub=tl["max_new_capacity_MW"], vtype=inv_vtype, name=f"yFnew_{l}") + + # --- Operational variables --- + # Power injection (generation) for all generators + x_inj = {} + for i in G_all: + for t in range(total_T): + x_inj[i, t] = model.addVar(lb=0, name=f"xinj_{i}_{t}") + + # Storage charge (withdrawal from grid) + x_wdw = {} + for i in G_STOR: + for t in range(total_T): + x_wdw[i, t] = model.addVar(lb=0, name=f"xwdw_{i}_{t}") + + # Storage state of charge + x_soc = {} + for i in G_STOR: + for t in range(total_T): + x_soc[i, t] = model.addVar(lb=0, name=f"xsoc_{i}_{t}") + + # Hydro reservoir level + x_hydro_level = {} + for i in G_HYDRO: + for t in range(total_T): + x_hydro_level[i, t] = model.addVar(lb=0, name=f"xhydro_{i}_{t}") + + # Transmission flow (bidirectional: positive = from_zone -> to_zone) + x_flow = {} + for l in L_all: + for t in range(total_T): + x_flow[l, t] = model.addVar(lb=-GRB.INFINITY, name=f"xflow_{l}_{t}") + + # NSE (non-served energy) per segment, zone, timestep + x_nse = {} + for s in S_all: + for z in zones: + for t in range(total_T): + x_nse[s, z, t] = model.addVar(lb=0, name=f"xnse_{s}_{z}_{t}") + + # UC variables (commit, start, shut) - continuous relaxation + x_commit = {} + x_start = {} + x_shut = {} + for i in G_UC: + for t in range(total_T): + x_commit[i, t] = model.addVar(lb=0, name=f"xcommit_{i}_{t}") + x_start[i, t] = model.addVar(lb=0, name=f"xstart_{i}_{t}") + x_shut[i, t] = model.addVar(lb=0, name=f"xshut_{i}_{t}") + + # Policy slack variables + x_RPS = {} + x_CO2 = {} + for w in range(num_subperiods): + x_RPS[w] = model.addVar(lb=0, name=f"xRPS_{w}") + x_CO2[w] = model.addVar(lb=0, name=f"xCO2_{w}") + + model.update() + + # Checker mode: investment decisions are the submitted first-stage witness. + # Fix them and optimize only the omitted operational recourse variables. + if fixed_solution is not None: + # The original global-MIP run reserves up to 60 seconds for a no-relaxation + # heuristic. All integer first-stage variables are fixed here, so that + # phase is pure overhead for checker recourse. + model.setParam("NoRelHeurTime", 0) + fixed_generators = { + entry["generator_id"]: entry + for entry in fixed_solution.get("investment_decisions", []) + } + fixed_lines = { + entry["line_id"]: entry + for entry in fixed_solution.get("transmission_decisions", []) + } + expected_generator_ids = {g["id"] for g in generators} + expected_line_ids = {line["id"] for line in trans_lines} + if set(fixed_generators) != expected_generator_ids: + raise ValueError("fixed solution must cover every generator exactly once") + if set(fixed_lines) != expected_line_ids: + raise ValueError("fixed solution must cover every transmission line exactly once") + + for i, generator in enumerate(generators): + entry = fixed_generators[generator["id"]] + y_P_new[i].LB = y_P_new[i].UB = float(entry["y_P_new"]) + y_P_ret[i].LB = y_P_ret[i].UB = float(entry["y_P_ret"]) + if i in y_E_new: + y_E_new[i].LB = y_E_new[i].UB = float(entry["y_E_new"]) + y_E_ret[i].LB = y_E_ret[i].UB = float(entry["y_E_ret"]) + for l, line in enumerate(trans_lines): + value = float(fixed_lines[line["id"]]["y_F_new_MW"]) + y_F_new[l].LB = y_F_new[l].UB = value + + if quiet: + model.setParam("OutputFlag", 0) + + # ---------------------------------------------------------------- + # Objective Function + # ---------------------------------------------------------------- + + # c^FIXED + c_fixed = gp.LinExpr() + for i in G_all: + g = generators[i] + gamma_P = g["capacity_size_MW"] + # Investment cost for new power capacity + c_fixed += g["inv_cost_per_MW_yr"] * gamma_P * y_P_new[i] + # FOM cost on total installed capacity + c_fixed += g["fom_cost_per_MW_yr"] * y_P[i] + + for i in G_STOR: + g = generators[i] + gamma_E = g["storage_capacity_size_MWh"] + c_fixed += g["inv_cost_energy_per_MWh_yr"] * gamma_E * y_E_new[i] + c_fixed += g.get("fom_cost_energy_per_MWh_yr", 0) * y_E[i] + + for i in G_HYDRO: + g = generators[i] + rho = g["duration_MWh_per_MW"] + # Hydro energy investment and FOM (assumed 0 per notes, but include if present) + hydro_e_inv = g.get("inv_cost_energy_per_MWh_yr", 0) + hydro_e_fom = g.get("fom_cost_energy_per_MWh_yr", 0) + c_fixed += hydro_e_inv * rho * g["capacity_size_MW"] * y_P_new[i] + c_fixed += hydro_e_fom * rho * y_P[i] + + for l in L_all: + tl = trans_lines[l] + c_fixed += tl["inv_cost_per_MW_yr"] * y_F_new[l] + + # c^VAR + c_var = gp.LinExpr() + for i in G_all: + g = generators[i] + vc = g["var_cost_per_MWh"] + if vc > 0: + for t in range(total_T): + c_var += vc * alpha[t] * x_inj[i, t] + for i in G_STOR: + g = generators[i] + vc = g["var_cost_per_MWh"] + if vc > 0: + for t in range(total_T): + c_var += vc * alpha[t] * x_wdw[i, t] + + # c^NSE + c_nse = gp.LinExpr() + for s in S_all: + cost_s = nse_segments[s]["cost_per_MWh"] + for z in zones: + for t in range(total_T): + c_nse += cost_s * alpha[t] * x_nse[s, z, t] + + # c^START + c_start = gp.LinExpr() + for i in G_UC: + g = generators[i] + sc = g["start_cost_per_unit"] + if sc > 0: + for t in range(total_T): + c_start += sc * alpha[t] * x_start[i, t] + + # c^RPS + c^CO2 + c_policy = gp.LinExpr() + rps_cost = policy["RPS_noncompliance_cost_per_MWh"] + co2_cost = policy["CO2_noncompliance_cost_per_ton"] + for w in range(num_subperiods): + c_policy += rps_cost * x_RPS[w] + c_policy += co2_cost * x_CO2[w] + + model.setObjective(c_fixed + c_var + c_nse + c_start + c_policy, GRB.MINIMIZE) + + # ---------------------------------------------------------------- + # Investment Constraints + # ---------------------------------------------------------------- + + # (12a) New capacity limit + for i in G_all: + g = generators[i] + model.addConstr( + g["capacity_size_MW"] * y_P_new[i] <= g["max_capacity_MW"], + name=f"inv_new_cap_{i}" + ) + + # (12b) Retirement limit + for i in G_all: + g = generators[i] + model.addConstr( + g["capacity_size_MW"] * y_P_ret[i] <= g["existing_capacity_MW"], + name=f"inv_ret_cap_{i}" + ) + + # (12c) Cannot retire if can_retire is False + for i in G_all: + if not generators[i]["can_retire"]: + model.addConstr(y_P_ret[i] == 0, name=f"inv_no_ret_{i}") + + # (12d) Total installed capacity + for i in G_all: + g = generators[i] + model.addConstr( + y_P[i] == g["existing_capacity_MW"] + g["capacity_size_MW"] * (y_P_new[i] - y_P_ret[i]), + name=f"inv_total_cap_{i}" + ) + + # (13a-13f) Storage energy capacity + for i in G_STOR: + g = generators[i] + gamma_E = g["storage_capacity_size_MWh"] + # (13a) New energy limit + model.addConstr( + gamma_E * y_E_new[i] <= g["max_storage_capacity_MWh"], + name=f"stor_new_ecap_{i}" + ) + # (13b) Retirement energy limit + model.addConstr( + gamma_E * y_E_ret[i] <= g["existing_storage_capacity_MWh"], + name=f"stor_ret_ecap_{i}" + ) + # (13c) Cannot retire energy if can_retire is False + if not g["can_retire"]: + model.addConstr(y_E_ret[i] == 0, name=f"stor_no_eret_{i}") + # (13d) Total energy capacity + model.addConstr( + y_E[i] == g["existing_storage_capacity_MWh"] + gamma_E * (y_E_new[i] - y_E_ret[i]), + name=f"stor_total_ecap_{i}" + ) + # (13e) Min duration: y_E >= min_duration * y_P + model.addConstr( + y_E[i] >= g["min_duration_MWh_per_MW"] * y_P[i], + name=f"stor_min_dur_{i}" + ) + # (13f) Max duration: y_E <= max_duration * y_P + model.addConstr( + y_E[i] <= g["max_duration_MWh_per_MW"] * y_P[i], + name=f"stor_max_dur_{i}" + ) + + # (14a-14b) Transmission capacity (total = existing + new) + # We don't need an explicit y_F total variable; we use it inline. + # The flow constraints will use existing + y_F_new. + + # ---------------------------------------------------------------- + # Operational Constraints + # ---------------------------------------------------------------- + + # Build net flow into each zone for each timestep + # flow_into_zone[z][t] = sum of flows into zone z at time t + # For line l: from_zone -> to_zone with flow x_flow[l,t] + # Positive flow: from_zone -> to_zone (adds to to_zone, subtracts from from_zone) + + # (15) Power balance: for each zone z, timestep t + for z in zones: + for t in range(total_T): + lhs = gp.LinExpr() + # Generation injection from generators in zone z + for i in gens_in_zone[z]: + lhs += x_inj[i, t] + # Subtract storage charging in zone z + for i in gens_in_zone[z]: + if generators[i]["is_storage"]: + lhs -= x_wdw[i, t] + # Transmission: net flow into zone z + for l in L_all: + tl = trans_lines[l] + if tl["to_zone"] == z: + lhs += x_flow[l, t] + if tl["from_zone"] == z: + lhs -= x_flow[l, t] + # NSE + for s in S_all: + lhs += x_nse[s, z, t] + # Must equal demand + model.addConstr(lhs == demand[z][t], name=f"balance_{z}_{t}") + + # (16a-16g) Capacity limits + for i in G_all: + g = generators[i] + is_uc = g["is_UC"] + is_stor = g["is_storage"] + is_hydro = g["is_hydro"] + + for t in range(total_T): + if is_uc: + # (16b) UC: x_inj <= sigma * capacity_size * x_commit + model.addConstr( + x_inj[i, t] <= sigma[i][t] * g["capacity_size_MW"] * x_commit[i, t], + name=f"cap_uc_{i}_{t}" + ) + elif is_stor: + # (16c) Storage discharge: x_inj <= sigma * y_P + model.addConstr( + x_inj[i, t] <= sigma[i][t] * y_P[i], + name=f"cap_stor_dis_{i}_{t}" + ) + # (16d) Storage charge: x_wdw <= sigma * y_P + model.addConstr( + x_wdw[i, t] <= sigma[i][t] * y_P[i], + name=f"cap_stor_chg_{i}_{t}" + ) + elif is_hydro: + # (16e) Hydro: x_inj <= sigma * y_P + model.addConstr( + x_inj[i, t] <= sigma[i][t] * y_P[i], + name=f"cap_hydro_{i}_{t}" + ) + else: + # (16a) Non-UC, non-storage, non-hydro (VRE, etc.): x_inj <= sigma * y_P + model.addConstr( + x_inj[i, t] <= sigma[i][t] * y_P[i], + name=f"cap_gen_{i}_{t}" + ) + + # (16f) Storage SOC limit: x_soc <= y_E + for i in G_STOR: + for t in range(total_T): + model.addConstr(x_soc[i, t] <= y_E[i], name=f"soc_limit_{i}_{t}") + + # (16g) Hydro level limit: x_hydro_level <= rho * y_P + for i in G_HYDRO: + g = generators[i] + rho = g["duration_MWh_per_MW"] + for t in range(total_T): + model.addConstr( + x_hydro_level[i, t] <= rho * y_P[i], + name=f"hydro_level_limit_{i}_{t}" + ) + + # (17a-17b) Minimum output + for i in G_all: + g = generators[i] + min_frac = g.get("min_output_frac", 0.0) + if min_frac <= 0: + continue + is_uc = g["is_UC"] + for t in range(total_T): + if is_uc: + # (17b) UC: x_inj >= min_frac * capacity_size * x_commit + model.addConstr( + x_inj[i, t] >= min_frac * g["capacity_size_MW"] * x_commit[i, t], + name=f"minout_uc_{i}_{t}" + ) + else: + # (17a) Non-UC: x_inj >= min_frac * sigma * y_P + model.addConstr( + x_inj[i, t] >= min_frac * sigma[i][t] * y_P[i], + name=f"minout_{i}_{t}" + ) + + # (18a-18b) Transmission flow limits + for l in L_all: + tl = trans_lines[l] + for t in range(total_T): + # (18a) x_flow <= existing + y_F_new + model.addConstr( + x_flow[l, t] <= tl["existing_capacity_MW"] + y_F_new[l], + name=f"flow_ub_{l}_{t}" + ) + # (18b) x_flow >= -(existing + y_F_new) + model.addConstr( + x_flow[l, t] >= -(tl["existing_capacity_MW"] + y_F_new[l]), + name=f"flow_lb_{l}_{t}" + ) + + # (19) NSE limits: x_nse[s,z,t] <= max_frac_s * demand[z][t] + for s in S_all: + seg = nse_segments[s] + for z in zones: + for t in range(total_T): + model.addConstr( + x_nse[s, z, t] <= seg["max_frac"] * demand[z][t], + name=f"nse_limit_{s}_{z}_{t}" + ) + + # (20a-20d) Storage SOC dynamics (circular within subperiod) + for i in G_STOR: + g = generators[i] + eta_c = g["charge_efficiency"] + eta_d = g["discharge_efficiency"] + self_dis = g["self_discharge_rate"] + for w in range(num_subperiods): + ts = subperiod_timesteps[w] + T_w = len(ts) + for idx in range(T_w): + t = ts[idx] + t_prev = ts[(idx - 1) % T_w] # circular: wraps to last hour + # (20a) SOC[t] = (1-self_discharge)*SOC[t-1] + eta_c*charge[t] - (1/eta_d)*discharge[t] + model.addConstr( + x_soc[i, t] == (1 - self_dis) * x_soc[i, t_prev] + + eta_c * x_wdw[i, t] + - (1.0 / eta_d) * x_inj[i, t], + name=f"soc_dyn_{i}_{t}" + ) + + # (20c-20d) Hydro level dynamics (circular within subperiod) + # Inferred: sigma[i][t] serves as normalized inflow + for i in G_HYDRO: + g = generators[i] + rho = g["duration_MWh_per_MW"] + for w in range(num_subperiods): + ts = subperiod_timesteps[w] + T_w = len(ts) + for idx in range(T_w): + t = ts[idx] + t_prev = ts[(idx - 1) % T_w] + # level[t] = level[t-1] + inflow[t] - generation[t] + # inflow = sigma[i][t] * rho * y_P[i] (normalized inflow * reservoir capacity) + # Actually, inflow should be scaled: sigma as fraction of capacity per hour + # From paper: inflow_{g,t} = sigma^{inflow}_{g,t} * rho_g * y^P_g + # But that would mean inflow ~ capacity which is huge. More likely: + # inflow per hour is sigma[i][t] * y_P[i] (matching generation scale) + # and reservoir = rho * y_P, so sigma ~ inflow/capacity. + # Let's use: level[t] = level[t-1] + sigma[i][t] * y_P[i] - x_inj[i,t] + model.addConstr( + x_hydro_level[i, t] == x_hydro_level[i, t_prev] + + sigma[i][t] * y_P[i] + - x_inj[i, t], + name=f"hydro_dyn_{i}_{t}" + ) + + # (21a-21d) Ramping for non-UC generators (circular within subperiod) + for i in G_nonUC: + g = generators[i] + if g["is_storage"]: + continue # storage handled by SOC dynamics, not ramping + ramp_up = g.get("ramp_up_frac_per_hr", 1.0) + ramp_dn = g.get("ramp_dn_frac_per_hr", 1.0) + if ramp_up >= 1.0 and ramp_dn >= 1.0: + continue # no binding ramp constraints + for w in range(num_subperiods): + ts = subperiod_timesteps[w] + T_w = len(ts) + for idx in range(T_w): + t = ts[idx] + t_prev = ts[(idx - 1) % T_w] + # (21a) Ramp up: x_inj[t] - x_inj[t-1] <= ramp_up * y_P + if ramp_up < 1.0: + model.addConstr( + x_inj[i, t] - x_inj[i, t_prev] <= ramp_up * y_P[i], + name=f"ramp_up_{i}_{t}" + ) + # (21b) Ramp down: x_inj[t-1] - x_inj[t] <= ramp_dn * y_P + if ramp_dn < 1.0: + model.addConstr( + x_inj[i, t_prev] - x_inj[i, t] <= ramp_dn * y_P[i], + name=f"ramp_dn_{i}_{t}" + ) + + # (22a-22g) Unit commitment constraints + for i in G_UC: + g = generators[i] + cap_size = g["capacity_size_MW"] + + for w in range(num_subperiods): + ts = subperiod_timesteps[w] + T_w = len(ts) + for idx in range(T_w): + t = ts[idx] + t_prev = ts[(idx - 1) % T_w] + + # (22a) Commitment state transition: commit[t] = commit[t-1] + start[t] - shut[t] + model.addConstr( + x_commit[i, t] == x_commit[i, t_prev] + x_start[i, t] - x_shut[i, t], + name=f"uc_trans_{i}_{t}" + ) + + # (22b) commit <= max_units = max_capacity / capacity_size + max_units = g["max_capacity_MW"] / cap_size if cap_size > 0 else 0 + for t in range(total_T): + # Actually commit is bounded by installed capacity / cap_size + # commit[t] <= y_P / cap_size + model.addConstr( + x_commit[i, t] * cap_size <= y_P[i], + name=f"uc_max_commit_{i}_{t}" + ) + + # (23a-23d) Ramping for UC generators (circular within subperiod) + for i in G_UC: + g = generators[i] + cap_size = g["capacity_size_MW"] + ramp_up = g.get("ramp_up_frac_per_hr", 1.0) + ramp_dn = g.get("ramp_dn_frac_per_hr", 1.0) + min_frac = g.get("min_output_frac", 0.0) + + for w in range(num_subperiods): + ts = subperiod_timesteps[w] + T_w = len(ts) + for idx in range(T_w): + t = ts[idx] + t_prev = ts[(idx - 1) % T_w] + + # (23a) Ramp up: x_inj[t] - x_inj[t-1] <= ramp_up * cap_size * commit[t-1] + # + min(sigma*cap_size, ramp_up*cap_size + min_frac*cap_size) * start[t] + # Simplified: ramp up limited by committed units + # x_inj[t] - x_inj[t-1] <= ramp_up * cap_size * commit[t-1] + # + max(min_frac, ramp_up) * cap_size * start[t] + model.addConstr( + x_inj[i, t] - x_inj[i, t_prev] <= + ramp_up * cap_size * x_commit[i, t_prev] + + max(min_frac, ramp_up) * cap_size * x_start[i, t], + name=f"uc_ramp_up_{i}_{t}" + ) + + # (23b) Ramp down: x_inj[t-1] - x_inj[t] <= ramp_dn * cap_size * commit[t] + # + max(min_frac, ramp_dn) * cap_size * shut[t] + model.addConstr( + x_inj[i, t_prev] - x_inj[i, t] <= + ramp_dn * cap_size * x_commit[i, t] + + max(min_frac, ramp_dn) * cap_size * x_shut[i, t], + name=f"uc_ramp_dn_{i}_{t}" + ) + + # (24a-24b) Minimum up/down time (circular within subperiod) + for i in G_UC: + g = generators[i] + min_up = g.get("min_up_time_hr", 0) + min_dn = g.get("min_down_time_hr", 0) + + if min_up <= 1 and min_dn <= 1: + continue + + for w in range(num_subperiods): + ts = subperiod_timesteps[w] + T_w = len(ts) + + for idx in range(T_w): + t = ts[idx] + + # (24a) Min up time: commit[t] >= sum of start[t'] for t' in [t-min_up+1, t] + if min_up > 1: + start_sum = gp.LinExpr() + for k in range(min_up): + idx_k = (idx - k) % T_w + t_k = ts[idx_k] + start_sum += x_start[i, t_k] + model.addConstr( + x_commit[i, t] >= start_sum, + name=f"min_up_{i}_{t}" + ) + + # (24b) Min down time: (y_P/cap_size) - commit[t] >= sum of shut[t'] for t' in [t-min_dn+1, t] + if min_dn > 1: + shut_sum = gp.LinExpr() + for k in range(min_dn): + idx_k = (idx - k) % T_w + t_k = ts[idx_k] + shut_sum += x_shut[i, t_k] + cap_size = g["capacity_size_MW"] + if cap_size > 0: + model.addConstr( + y_P[i] / cap_size - x_commit[i, t] >= shut_sum, + name=f"min_dn_{i}_{t}" + ) + + # ---------------------------------------------------------------- + # Policy Constraints + # ---------------------------------------------------------------- + + # Compute total weighted demand for CO2 cap + total_weighted_demand = 0.0 + for z in zones: + for t in range(total_T): + total_weighted_demand += alpha[t] * demand[z][t] + + # (26) RPS constraint (if enabled) + if policy["RPS_enabled"]: + rps_share = policy["RPS_share"] + for w in range(num_subperiods): + ts = subperiod_timesteps[w] + # Sum of RPS-qualifying generation in subperiod w + rps_gen = gp.LinExpr() + for i in G_RPS: + for t in ts: + rps_gen += alpha[t] * x_inj[i, t] + # Total demand in subperiod w + total_demand_w = gp.LinExpr() + for z in zones: + for t in ts: + total_demand_w += alpha[t] * demand[z][t] + # rps_gen + x_RPS[w] >= rps_share * total_demand_w + model.addConstr( + rps_gen + x_RPS[w] >= rps_share * total_demand_w, + name=f"rps_{w}" + ) + + # (27-28) CO2 constraint (if enabled) + if policy["CO2_cap_enabled"]: + co2_cap_rate = policy["CO2_cap_tons_per_MWh"] + for w in range(num_subperiods): + ts = subperiod_timesteps[w] + # Total CO2 emissions in subperiod w + co2_emit = gp.LinExpr() + for i in G_all: + g = generators[i] + co2_rate = g["co2_tons_per_MWh"] + if co2_rate > 0: + for t in ts: + co2_emit += co2_rate * alpha[t] * x_inj[i, t] + # Total demand in subperiod w + demand_w_val = sum(alpha[t] * demand[z][t] for z in zones for t in ts) + # CO2 cap = co2_cap_rate * demand_w (eq 28 uses total demand but applied per subperiod) + # Actually eq 28: cap = 0.05 * total_weighted_demand (global cap) + # But constraint 27 is per subperiod with slack. + # Let's apply proportionally: + co2_cap_w = co2_cap_rate * demand_w_val + model.addConstr( + co2_emit - x_CO2[w] <= co2_cap_w, + name=f"co2_{w}" + ) + + # ---------------------------------------------------------------- + # Solve + # ---------------------------------------------------------------- + if not quiet: + print("Starting optimization...") + start_time = time.time() + model.optimize() + solve_time = time.time() - start_time + + # ---------------------------------------------------------------- + # Extract solution + # ---------------------------------------------------------------- + result = { + "status": model.Status, + "status_name": { + 1: "LOADED", 2: "OPTIMAL", 3: "INFEASIBLE", 4: "INF_OR_UNBD", + 5: "UNBOUNDED", 6: "CUTOFF", 7: "ITERATION_LIMIT", + 8: "NODE_LIMIT", 9: "TIME_LIMIT", 10: "SOLUTION_LIMIT", + 11: "INTERRUPTED", 12: "NUMERIC", 13: "SUBOPTIMAL", + 14: "INPROGRESS", 15: "USER_OBJ_LIMIT", 16: "WORK_LIMIT", + 17: "MEM_LIMIT" + }.get(model.Status, "UNKNOWN"), + "solve_time_seconds": solve_time, + "num_variables": model.NumVars, + "num_constraints": model.NumConstrs, + "num_nonzeros": model.NumNZs, + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound if hasattr(model, "ObjBound") else model.ObjVal + result["mip_gap"] = model.MIPGap if formulation == "MILP" else 0.0 + + # Investment decisions + inv_decisions = [] + for i in G_all: + g = generators[i] + entry = { + "generator_id": g["id"], + "resource_type": g["resource_type"], + "zone": g["zone"], + "y_P_new": y_P_new[i].X, + "y_P_ret": y_P_ret[i].X, + "y_P_total_MW": y_P[i].X, + } + if g["is_storage"]: + entry["y_E_new"] = y_E_new[i].X + entry["y_E_ret"] = y_E_ret[i].X + entry["y_E_total_MWh"] = y_E[i].X + inv_decisions.append(entry) + result["investment_decisions"] = inv_decisions + + # Transmission decisions + trans_decisions = [] + for l in L_all: + tl = trans_lines[l] + trans_decisions.append({ + "line_id": tl["id"], + "y_F_new_MW": y_F_new[l].X, + "total_capacity_MW": tl["existing_capacity_MW"] + y_F_new[l].X, + }) + result["transmission_decisions"] = trans_decisions + + # Cost breakdown + result["cost_breakdown"] = { + "fixed": c_fixed.getValue(), + "variable": c_var.getValue(), + "nse": c_nse.getValue(), + "startup": c_start.getValue(), + "policy": c_policy.getValue(), + } + + # Generation summary per subperiod + gen_summary = [] + for w in range(num_subperiods): + ts = subperiod_timesteps[w] + total_gen = sum(alpha[t] * x_inj[i, t].X for i in G_all for t in ts) + total_dem = sum(alpha[t] * demand[z][t] for z in zones for t in ts) + total_nse_val = sum( + alpha[t] * x_nse[s, z, t].X + for s in S_all for z in zones for t in ts + ) + gen_summary.append({ + "subperiod": w, + "weighted_generation_MWh": total_gen, + "weighted_demand_MWh": total_dem, + "weighted_nse_MWh": total_nse_val, + }) + result["generation_summary"] = gen_summary + else: + result["objective_value"] = None + result["best_bound"] = model.ObjBound if hasattr(model, "ObjBound") else None + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Monolithic MILP energy systems planning model using Gurobi" + ) + parser.add_argument("--instance_path", required=True, help="Path to instance JSON file") + parser.add_argument("--solution_path", required=True, help="Path to output solution JSON file") + parser.add_argument("--time_limit", type=int, default=172800, 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) + + instance = load_instance(args.instance_path) + result = build_and_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) + + print(f"\nSolution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']:.2f}") + print(f"Status: {result['status_name']}") + print(f"Solve time: {result['solve_time_seconds']:.2f}s") + + +if __name__ == "__main__": + main() diff --git a/tasks/rahmaniani2018/gurobi_feasi_result/large_feasi_result_1.json b/tasks/rahmaniani2018/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2018/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/rahmaniani2018/gurobi_feasi_result/large_feasi_result_2.json b/tasks/rahmaniani2018/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2018/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/rahmaniani2018/gurobi_feasi_result/large_feasi_result_3.json b/tasks/rahmaniani2018/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2018/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/rahmaniani2018/gurobi_feasi_result/large_feasi_result_4.json b/tasks/rahmaniani2018/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2018/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/rahmaniani2018/gurobi_feasi_result/large_feasi_result_5.json b/tasks/rahmaniani2018/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2018/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/rahmaniani2018/gurobi_feasi_result/tiny_feasi_result.json b/tasks/rahmaniani2018/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2018/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/rahmaniani2018/gurobi_solution/large_solution_1.json b/tasks/rahmaniani2018/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9eb74639e8a310f1cfed613c0c7f0edde4206eeb --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fc3c578c1b5dc2bfe9402b53fd51e1461fff417720880eb0d53f1e9e292b8b9 +size 619261 diff --git a/tasks/rahmaniani2018/gurobi_solution/large_solution_2.json b/tasks/rahmaniani2018/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..33ca4962e3659ab44a7a45d423f5bf7779aa8cad --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ed9bd12afd31eef254f6d5c23d840846490a12c602ba5f888a45a3657779c74 +size 745757 diff --git a/tasks/rahmaniani2018/gurobi_solution/large_solution_3.json b/tasks/rahmaniani2018/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ae8c9a5d2d0d1e0fa5d8f6f731dee1ea4b972cec --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:427e28bee98e608a2a8afaed5cdbe3d8caa280ce00ca736e33c6e0ce1cdd9dc9 +size 666038 diff --git a/tasks/rahmaniani2018/gurobi_solution/large_solution_4.json b/tasks/rahmaniani2018/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e20286b9ae929320622f621c8b3345b86e24fee8 --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60e9876254d123b6f9f80e6a87d594cc967e376913ef454db616ace44ec24ab9 +size 637266 diff --git a/tasks/rahmaniani2018/gurobi_solution/large_solution_5.json b/tasks/rahmaniani2018/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..6b2b02b80f4c9c7fff6914cf7d6d430221633a70 --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:687ecc18f0d0e17b9b28a8809744b5fe44cdab36d0d30ea972a7fcb03078d21a +size 674260 diff --git a/tasks/rahmaniani2018/gurobi_solution/tiny_solution.json b/tasks/rahmaniani2018/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..69b4c6fe1c7aaf4f114e5dd4ed6c8f077ba8d73f --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6adffa287210ab568b8ade0ebaed4a09be89490a9facaef0fa063bbaf57ca195 +size 527076 diff --git a/tasks/rahmaniani2018/gurobi_solution_log/large_log_1.jsonl b/tasks/rahmaniani2018/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d0fd1c434b012f76ca3cfcbcf161704eca68ebea --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec8793515a0fc3142d400c8cc58d028e8f568c3371937631794176c28131e802 +size 2934 diff --git a/tasks/rahmaniani2018/gurobi_solution_log/large_log_2.jsonl b/tasks/rahmaniani2018/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a34f1c2385ac25e4a9f7bfe13259df63d113cc70 --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9da15224d66e505026c24faa40d50ad0111d5b25568963eebf5a2cfd8524c66 +size 935 diff --git a/tasks/rahmaniani2018/gurobi_solution_log/large_log_3.jsonl b/tasks/rahmaniani2018/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4393bf837e9d0a5f85f3e322d9ae3e001b0cd935 --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06bd56cdfca0f11d779e2c92e74b83fb16c6b9f8ef3dc1832cec0a3c2c9b062b +size 498 diff --git a/tasks/rahmaniani2018/gurobi_solution_log/large_log_4.jsonl b/tasks/rahmaniani2018/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b901ff633721d30439faf83c6cebac4206c106a3 --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5b19db9045401d1d68169cadeab1357040dfe80ef4e4233a6783f6e02f377de +size 1536 diff --git a/tasks/rahmaniani2018/gurobi_solution_log/large_log_5.jsonl b/tasks/rahmaniani2018/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f8efdb2c3bed486f6ace8f8068bda652704a4d07 --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab28a868a9d1a551e2dfb2d93ee7fcbd3f70f7597ce9161acedccf75acbdbfe4 +size 2579 diff --git a/tasks/rahmaniani2018/gurobi_solution_log/tiny_log.jsonl b/tasks/rahmaniani2018/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..84a169937ccdd67e151e6da3bbda81da92c11511 --- /dev/null +++ b/tasks/rahmaniani2018/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dcad2e788381bd62fd3214493b3e5d9ca97b99097488893b1b3458b9fcd8dba2 +size 110 diff --git a/tasks/rahmaniani2018/instance/large_instance_1.json b/tasks/rahmaniani2018/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..91917e12b09b30e085abd67434ff0a1a2eb1e707 --- /dev/null +++ b/tasks/rahmaniani2018/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2b221e12d5fa016d9b049b22feebd9b776679c74c84dd2014b0aec8a26fa71d +size 5429711 diff --git a/tasks/rahmaniani2018/instance/large_instance_2.json b/tasks/rahmaniani2018/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ca2555d1cd50cdfe432828c3e4f7fb5f9943c86a --- /dev/null +++ b/tasks/rahmaniani2018/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:517d7c15c0012d2476934c78e77f647327e408397a309c4e97b95e6913467aed +size 5427306 diff --git a/tasks/rahmaniani2018/instance/large_instance_3.json b/tasks/rahmaniani2018/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..f57d4029bd816c92a9522282b29e68890c1ac8ab --- /dev/null +++ b/tasks/rahmaniani2018/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73a0e4f78eabc435debc14cd145ddac1e9bf6f73555740bf7a21d1bdbaea3e9c +size 5428574 diff --git a/tasks/rahmaniani2018/instance/large_instance_4.json b/tasks/rahmaniani2018/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..eeb8cae2dbf4f962740f6861097ca7b2423cf016 --- /dev/null +++ b/tasks/rahmaniani2018/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:941110a0327a7838702cbc1d9cb3a29fb34e980b2776a48b10f249b1a4730b50 +size 5428053 diff --git a/tasks/rahmaniani2018/instance/large_instance_5.json b/tasks/rahmaniani2018/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..db3dd350f374bda12cfcf0da2a51a75ad1dfff5a --- /dev/null +++ b/tasks/rahmaniani2018/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:351432c0a34b4d614a5586d66f431800afb39792f3ef831b49a7fb3932ca4a0f +size 5424253 diff --git a/tasks/rahmaniani2018/instance/tiny_instance.json b/tasks/rahmaniani2018/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..7584ee8872baefd3b696af1909edd312b05f27d6 --- /dev/null +++ b/tasks/rahmaniani2018/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5dd1b43b5f42b21c7d32d55c444455a4c3e891203dfb32cb09f12db9405fcfce +size 181971 diff --git a/tasks/rahmaniani2018/instance_schema.json b/tasks/rahmaniani2018/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..6398392ff95d719cc2e704a4f2010e49c0a722dc --- /dev/null +++ b/tasks/rahmaniani2018/instance_schema.json @@ -0,0 +1,92 @@ +{ + "problem_dimensions": { + "num_zones": " Number of spatial zones in the power system network.", + "num_weeks": " Number of representative weeks modeled in the planning year.", + "hours_per_week": " Number of hourly time steps within each representative week.", + "total_timesteps": " Total number of hourly time steps across all weeks (num_weeks * hours_per_week).", + "num_generators": " Total number of resource clusters (generators, storage, and hydro) across all zones.", + "num_UC_generators": " Number of resource clusters subject to unit commitment (thermal plants with discrete startup/shutdown).", + "num_storage_resources": " Number of battery storage resource clusters across all zones.", + "num_hydro_resources": " Number of reservoir-based hydropower resource clusters across all zones.", + "num_transmission_lines": " Number of interregional transmission lines connecting zones.", + "num_demand_segments": " Number of non-served energy penalty cost segments for demand curtailment." + }, + "policy": { + "RPS_enabled": " Whether the renewable portfolio standard policy is active.", + "RPS_share": " Required fraction of total weighted demand that must come from RPS-qualifying resources.", + "CO2_cap_enabled": " Whether the CO2 emissions cap policy is active.", + "CO2_cap_tons_per_MWh": " CO2 emissions cap expressed as tons per MWh of total weighted demand, null if policy is inactive.", + "RPS_noncompliance_cost_per_MWh": " Penalty cost per MWh of shortfall below the RPS requirement.", + "CO2_noncompliance_cost_per_ton": " Penalty cost per ton of CO2 exceeding the emissions cap." + }, + "subperiods": { + "num_subperiods": " Number of representative weekly subperiods in the planning year.", + "hours_per_subperiod": " Number of hourly time steps within each subperiod.", + "subperiod_weights": " Number of weeks each subperiod represents when annualizing costs and quantities.", + "circular_indexing": " Whether the first and last hours of each subperiod are linked circularly for state-of-charge, reservoir, and ramping constraints." + }, + "generators": [ + { + "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., onshore_wind, solar_pv, ng_cc, battery_4hr, hydro).", + "category": " Resource category: VRE, THERMAL, STORAGE, or HYDRO.", + "is_UC": " Whether this resource is subject to unit commitment constraints.", + "is_storage": " Whether this resource is a battery storage resource.", + "is_hydro": " Whether this resource is a reservoir-based hydropower resource.", + "is_RPS_qualifying": " Whether generation from this resource counts toward the renewable portfolio standard.", + "can_retire": " Whether existing capacity of this resource may be retired.", + "capacity_size_MW": " Power capacity per discrete unit in MW, used for integer investment and unit commitment sizing.", + "existing_capacity_MW": " Currently installed power capacity in MW before any new investment or retirement.", + "max_capacity_MW": " Maximum total power capacity in MW that this resource cluster may reach after investment.", + "inv_cost_per_MW_yr": " Annualized investment cost per MW of new power capacity.", + "fom_cost_per_MW_yr": " Annual fixed operations and maintenance cost per MW of total installed power capacity.", + "var_cost_per_MWh": " Variable operating cost per MWh of generation or storage withdrawal.", + "co2_tons_per_MWh": " CO2 emissions intensity in tons per MWh of generation.", + "min_output_frac": " Minimum generation as a fraction of committed capacity (UC resources) or installed capacity (non-UC resources).", + "ramp_up_frac_per_hr": " Maximum hourly increase in generation as a fraction of capacity (present for non-storage resources).", + "ramp_dn_frac_per_hr": " Maximum hourly decrease in generation as a fraction of capacity (present for non-storage resources).", + "min_up_time_hr": " Minimum number of consecutive hours a unit must remain online after starting up (UC resources only).", + "min_down_time_hr": " Minimum number of consecutive hours a unit must remain offline after shutting down (UC resources only).", + "start_cost_per_unit": " Cost incurred each time one unit of this resource is started up (UC resources only).", + "storage_capacity_size_MWh": " Energy storage capacity per discrete unit in MWh (storage resources only).", + "existing_storage_capacity_MWh": " Currently installed energy storage capacity in MWh (storage resources only).", + "max_storage_capacity_MWh": " Maximum total energy storage capacity in MWh after investment (storage resources only).", + "charge_efficiency": " Fraction of withdrawn energy that is stored when charging (storage resources only).", + "discharge_efficiency": " Fraction of stored energy that is injected when discharging (storage resources only).", + "self_discharge_rate": " Fraction of stored energy lost per hour due to self-discharge (storage resources only).", + "min_duration_MWh_per_MW": " Minimum ratio of energy capacity to power capacity in MWh per MW (storage resources only).", + "max_duration_MWh_per_MW": " Maximum ratio of energy capacity to power capacity in MWh per MW (storage resources only).", + "inv_cost_energy_per_MWh_yr": " Annualized investment cost per MWh of new energy storage capacity (storage resources only).", + "fom_cost_energy_per_MWh_yr": " Annual fixed operations and maintenance cost per MWh of total energy storage capacity (storage resources only).", + "duration_MWh_per_MW": " Fixed ratio of reservoir energy capacity to power capacity in MWh per MW (hydro resources only)." + } + ], + "transmission_lines": [ + { + "id": " Unique identifier for this transmission line.", + "from_zone": " Zone at the sending end of the transmission line.", + "to_zone": " Zone at the receiving end of the transmission line.", + "existing_capacity_MW": " Currently installed transmission capacity in MW.", + "max_new_capacity_MW": " Maximum additional transmission capacity in MW that may be built.", + "inv_cost_per_MW_yr": " Annualized investment cost per MW of new transmission capacity." + } + ], + "demand": { + "{zone_id}": " Hourly electricity demand in MWh for each zone, keyed by zone ID as a string." + }, + "nse_segments": [ + { + "segment": " Index of this non-served energy cost segment.", + "cost_per_MWh": " Penalty cost per MWh of demand curtailment in this segment.", + "max_frac": " Maximum fraction of zonal hourly demand that may go unserved in this segment." + } + ], + "availability_profiles": { + "{generator_id}": { + "type": " Profile type: 'constant' for a fixed availability fraction or 'timeseries' for hourly-varying values.", + "value": " Fixed availability fraction for all hours (present when type is 'constant').", + "values": " Hourly availability fraction giving the maximum dispatchable share of installed capacity (present when type is 'timeseries')." + } + } +} diff --git a/tasks/rahmaniani2018/mathematical_formulation.md b/tasks/rahmaniani2018/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..4e312dd2ec44d7509b417cd3bfdc9b4a9de8ee11 --- /dev/null +++ b/tasks/rahmaniani2018/mathematical_formulation.md @@ -0,0 +1,81 @@ +# 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, 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}}$. + +**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{\epsilon}^{\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 \epsilon_g^{\text{CO2}} x_{g,t}^{\text{inj}} + + \sum_{g\in G^{\text{STOR}}} \alpha_t \epsilon_g^{\text{CO2}} x_{g,t}^{\text{wdw}}\big) - x_w^{CO2}\Big) + \leq \overline{\epsilon}^{\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/rahmaniani2018/problem_description.txt b/tasks/rahmaniani2018/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..4622ee4339fe879d97db366164d82064259212f4 --- /dev/null +++ b/tasks/rahmaniani2018/problem_description.txt @@ -0,0 +1,23 @@ +# Problem Description + +An electricity system planner must determine the least-cost strategy for expanding, retiring, and operating generation, storage, and transmission resources across a network of spatial zones over a single planning year. The system contains a set of resource clusters (generators, storage units, and hydropower plants), each located in a specific zone, connected by a set of interregional transmission lines. The planning year is divided into weekly subperiods, each containing 168 hourly time steps. Each subperiod carries a weight reflecting how many weeks of the year it represents, and each hour within a subperiod receives a weight equal to the subperiod weight divided by 168. Resources fall into several overlapping categories: those subject to unit commitment (thermal plants whose individual units must be started up and shut down), storage resources (batteries), hydropower resources (reservoir-based hydro), resources qualifying for a renewable portfolio standard, and resources that cannot be retired. + +The input data specifies, for every resource cluster: existing installed power capacity in MW, existing energy storage capacity in MWh (for storage resources), the capacity size per unit in MW (relevant for unit commitment resources; set to one for all others), maximum allowable new capacity in MW, investment cost per MW-year, fixed operations and maintenance cost per MW-year, time-varying variable operating cost per MWh, CO2 emission factor in tons per MWh, a time-varying availability fraction between zero and one giving the maximum fraction of installed capacity dispatchable in each hour, a minimum output fraction, maximum ramp-up and ramp-down rates as fractions of capacity per hour, minimum up-time and minimum down-time in hours (for unit commitment resources), and startup cost per unit (for unit commitment resources). For storage resources the data additionally specifies existing and maximum energy capacity in MWh, energy capacity size per unit in MWh (set to one for all resources not subject to unit commitment), energy investment cost per MWh-year, energy fixed O&M cost per MWh-year, charging efficiency, discharging efficiency, self-discharge rate per hour, and minimum and maximum duration ratios (MWh per MW) linking energy capacity to power capacity. For hydropower resources the data specifies a fixed duration ratio (MWh per MW) and an hourly normalized inflow profile as a fraction of power capacity. For each transmission line the data gives existing capacity in MW, maximum new capacity in MW, and investment cost per MW-year. For each zone and each hour the data gives net electricity demand in MWh. Multiple non-served-energy segments are defined, each with a cost per MWh that may vary by zone and a maximum fraction of zonal demand that may go unserved. A policy scenario specifies whether a renewable portfolio standard is active (with a required share of total demand and a noncompliance penalty cost per MWh) and whether a CO2 emissions cap is active (with a cap defined as five percent of total weighted demand, in tons, and a noncompliance penalty cost per ton). + +The planner must decide, for each resource cluster, how many new units of power capacity to build and how many existing units to retire (in whole-unit increments of the cluster's capacity size), and likewise for storage energy capacity. For each transmission line the planner must choose the new capacity to add; this expansion capacity variable is modeled as an integer-valued number of MW in the MILP formulation. These investment and retirement decisions determine the total installed power capacity, energy capacity, and transmission capacity for each resource and line. Operationally, for every resource and every hour, the planner must decide the generation (injection) in MWh, and for storage resources also the withdrawal (charging) in MWh. For each transmission line and hour the planner must set the power flow in MWh, which may be positive or negative to represent flow in either direction. For each non-served-energy segment, zone, and hour the planner must set the amount of curtailed demand. For unit commitment resources the planner must determine, for each hour, the number of committed units, the number of units started up, and the number shut down. For storage resources the planner must track the state of charge in MWh at each hour. For hydropower resources the planner must track the reservoir level in MWh and any spillage in MWh at each hour. For each subperiod the planner must also set noncompliance slack amounts for the renewable portfolio standard and the CO2 cap, if those policies are active. + +The total installed power capacity for each resource equals its existing capacity plus the capacity size times the difference between newly built units and retired units. The product of the capacity size and the number of new units built must not exceed the maximum allowable new capacity, and the product of the capacity size and the number of retired units must not exceed the existing capacity. Resources designated as non-retirable may not be retired. The same structure applies to storage energy capacity: the total energy capacity equals existing energy capacity plus the energy capacity size times the difference between new and retired energy units, with analogous upper bounds on new builds and retirements. Additionally, the energy capacity of a storage resource must lie between the minimum duration ratio times the power capacity and the maximum duration ratio times the power capacity. For transmission lines, new capacity must not exceed the maximum allowable expansion, and total line capacity equals existing capacity plus new capacity. + +In every zone and every hour, the power balance must hold: the sum of generation from all resources in that zone, minus withdrawals by storage resources in that zone, minus flows on lines leaving that zone, plus flows on lines entering that zone, plus all non-served energy in that zone, must equal the zone's demand. For resources not subject to unit commitment, generation in any hour must not exceed the availability fraction times the installed power capacity. For storage resources, withdrawals must not exceed the availability fraction times the power capacity, the sum of generation and withdrawal must not exceed the power capacity, charging (the product of charging efficiency and withdrawal) must not exceed the remaining room in the battery (energy capacity minus current state of charge), and generation divided by discharging efficiency must not exceed the current state of charge. The state of charge must not exceed the energy capacity. For hydropower resources the reservoir level must not exceed the duration ratio times the power capacity. + +For resources not subject to unit commitment, storage, or hydro classification, generation in each hour must be at least the minimum output fraction times the installed power capacity. For hydropower resources, generation plus spillage must be at least the minimum output fraction times the installed power capacity. The flow on each transmission line in each hour must have absolute value no greater than the line's total capacity. Non-served energy in each segment, zone, and hour must not exceed that segment's maximum fraction of the zone's demand in that hour. + +Within each subperiod, storage state of charge evolves from one hour to the next: the change in state of charge equals the charging efficiency times the withdrawal, minus the generation divided by the discharging efficiency, minus the self-discharge rate times the previous hour's state of charge. The first and last hours of each subperiod are linked circularly, so that the state of charge wraps around within each week. Hydropower reservoir levels follow an analogous balance: the change in reservoir level equals the normalized inflow fraction times the power capacity, minus generation, minus spillage, with the same circular linkage between the first and last hours of each subperiod. + +For resources not subject to unit commitment, the hour-to-hour increase in generation must not exceed the ramp-up rate times the installed power capacity, and the hour-to-hour decrease must not exceed the ramp-down rate times the installed capacity. These ramp limits also apply at the subperiod boundary using circular indexing, so the change from the last hour to the first hour of each subperiod is likewise bounded. + +For unit commitment resources, the number of committed units times the capacity size must not exceed the installed power capacity, and the same bound applies individually to the number of started-up units and the number of shut-down units. Generation from a unit commitment resource must be at least the number of committed units times the minimum output fraction times the capacity size, and at most the number of committed units times the availability fraction times the capacity size. The change in committed units from one hour to the next equals the number of startups minus shutdowns in that hour, with circular linkage at subperiod boundaries. Ramp limits for unit commitment resources are tighter: the increase in generation is bounded by the capacity size times the ramp-up rate times the number of units that were committed but not just started, plus the capacity size times the lesser of the availability fraction and the larger of the minimum output fraction and the ramp-up rate, applied to the number of units just started, minus the capacity size times the minimum output fraction times the number of units just shut down. The decrease in generation is bounded by the capacity size times the ramp-down rate times the number of units that were committed but not just started, plus the capacity size times the lesser of the availability fraction and the larger of the minimum output fraction and the ramp-down rate, applied to the number of units just shut down, minus the capacity size times the minimum output fraction times the number of units just started. These ramp limits also apply at the circular subperiod boundaries. A committed unit must remain online for at least the minimum up-time: the number of committed units at any hour must be at least the sum of startups over the preceding hours equal in number to the minimum up-time, using circular indexing within the subperiod. Similarly, the number of committed units plus the number of shutdowns over the preceding hours equal in number to the minimum down-time must not exceed the total number of available units (installed capacity divided by capacity size). + +When the renewable portfolio standard policy is active, the sum over all subperiods of the weighted generation from qualifying resources plus the noncompliance slack must be at least the required share times total weighted demand across all zones and subperiods. When the CO2 cap policy is active, the sum over all subperiods of the weighted CO2 emissions from all generation and storage withdrawals minus the noncompliance slack must not exceed the emissions cap, which is five percent of total weighted demand. + +The goal is to minimize the total annual system cost. This cost is the sum of six components: fixed costs, which include generation investment cost (investment cost per MW-year times capacity size times new units built, for all resources, plus a parallel term for hydro resources using the energy investment cost times the duration ratio times new units built), storage energy investment cost (energy investment cost per MWh-year times energy capacity size times new energy units built), transmission investment cost (investment cost per MW-year times new line capacity), generation fixed O&M (fixed O&M cost per MW-year times total power capacity, with a parallel hydro term using the energy fixed O&M cost times the duration ratio times power capacity), and storage energy fixed O&M (energy fixed O&M cost per MWh-year times total energy capacity); variable operating costs, which are the sum over all hours and resources of the hourly weight times the variable cost per MWh times generation, plus the same for storage withdrawals; non-served energy costs, which are the sum over all hours, zones, and segments of the hourly weight times the segment-and-zone cost per MWh times the curtailed demand; startup costs, which are the sum over all hours and unit commitment resources of the hourly weight times the startup cost times the number of startups; renewable portfolio standard noncompliance cost, the penalty cost per MWh times the noncompliance slack summed over all subperiods; and CO2 cap noncompliance cost, the penalty cost per ton times the noncompliance slack summed over all subperiods. diff --git a/tasks/rahmaniani2018/solution_logger.py b/tasks/rahmaniani2018/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/rahmaniani2018/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/rahmaniani2018/solution_schema.json b/tasks/rahmaniani2018/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9c8bbdd517069651e3722f827c56a4f9cf5623d3 --- /dev/null +++ b/tasks/rahmaniani2018/solution_schema.json @@ -0,0 +1,24 @@ +{ + "objective_value": " Total annual system cost represented by the complete submitted witness.", + "model_variables": " Sparse complete investment and hourly-operation solution. Omitted model variables are exactly zero.", + "investment_decisions": [ + { + "generator_id": " Identifier of the generator cluster this entry refers to.", + "resource_type": " Technology label of the generator cluster (e.g. onshore_wind, ng_cc, battery_4hr, hydro).", + "zone": " Zone in which the generator cluster is located.", + "y_P_new": " Number of new power-capacity units built for this generator cluster, in whole-unit increments of its capacity size.", + "y_P_ret": " Number of existing power-capacity units retired for this generator cluster, in whole-unit increments of its capacity size.", + "y_P_total_MW": " Total installed power capacity of this generator cluster in MW after additions and retirements.", + "y_E_new": " Number of new energy-capacity units built for this storage cluster, in whole-unit increments of its energy capacity size.", + "y_E_ret": " Number of existing energy-capacity units retired for this storage cluster, in whole-unit increments of its energy capacity size.", + "y_E_total_MWh": " Total installed energy storage capacity of this storage cluster in MWh after additions and retirements." + } + ], + "transmission_decisions": [ + { + "line_id": " Identifier of the transmission line this entry refers to.", + "y_F_new_MW": " New transmission capacity added to this line in MW.", + "total_capacity_MW": " Total line capacity in MW equal to existing capacity plus new capacity." + } + ] +} diff --git a/tasks/rahmaniani2018/solverless_models/351432c0a34b4d614a5586d66f431800afb39792f3ef831b49a7fb3932ca4a0f.npz b/tasks/rahmaniani2018/solverless_models/351432c0a34b4d614a5586d66f431800afb39792f3ef831b49a7fb3932ca4a0f.npz new file mode 100644 index 0000000000000000000000000000000000000000..61de6d9fa62001f2be009592484722fd87af00c3 --- /dev/null +++ b/tasks/rahmaniani2018/solverless_models/351432c0a34b4d614a5586d66f431800afb39792f3ef831b49a7fb3932ca4a0f.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:822a482fe094ea5d3d0bce97e87dfd0b20b90fbd6cbe32ba1d1c022ca7807b7b +size 1477977 diff --git a/tasks/rahmaniani2018/solverless_models/517d7c15c0012d2476934c78e77f647327e408397a309c4e97b95e6913467aed.npz b/tasks/rahmaniani2018/solverless_models/517d7c15c0012d2476934c78e77f647327e408397a309c4e97b95e6913467aed.npz new file mode 100644 index 0000000000000000000000000000000000000000..c548bf2c11190312ed2885bea8113edbc9fbc5ea --- /dev/null +++ b/tasks/rahmaniani2018/solverless_models/517d7c15c0012d2476934c78e77f647327e408397a309c4e97b95e6913467aed.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1214e700b44b3f5ef39e0b37db662d8ae9d5d073e0b86501f6851568946747a8 +size 1462534 diff --git a/tasks/rahmaniani2018/solverless_models/5dd1b43b5f42b21c7d32d55c444455a4c3e891203dfb32cb09f12db9405fcfce.npz b/tasks/rahmaniani2018/solverless_models/5dd1b43b5f42b21c7d32d55c444455a4c3e891203dfb32cb09f12db9405fcfce.npz new file mode 100644 index 0000000000000000000000000000000000000000..1d2bd3f258ec772e168d06433b20f1ac4d1089db --- /dev/null +++ b/tasks/rahmaniani2018/solverless_models/5dd1b43b5f42b21c7d32d55c444455a4c3e891203dfb32cb09f12db9405fcfce.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10ea6e86da9c52b6df8a3ceb2f21b29fb4c449b0b19e966a8e13afb47e91e301 +size 1296189 diff --git a/tasks/rahmaniani2018/solverless_models/73a0e4f78eabc435debc14cd145ddac1e9bf6f73555740bf7a21d1bdbaea3e9c.npz b/tasks/rahmaniani2018/solverless_models/73a0e4f78eabc435debc14cd145ddac1e9bf6f73555740bf7a21d1bdbaea3e9c.npz new file mode 100644 index 0000000000000000000000000000000000000000..8e6f9006a89c837334b17670c20096c7230494c5 --- /dev/null +++ b/tasks/rahmaniani2018/solverless_models/73a0e4f78eabc435debc14cd145ddac1e9bf6f73555740bf7a21d1bdbaea3e9c.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50fb3ba44db037c5c443a5d686343caf442e815df63b3f466b486b84d983d063 +size 1477647 diff --git a/tasks/rahmaniani2018/solverless_models/941110a0327a7838702cbc1d9cb3a29fb34e980b2776a48b10f249b1a4730b50.npz b/tasks/rahmaniani2018/solverless_models/941110a0327a7838702cbc1d9cb3a29fb34e980b2776a48b10f249b1a4730b50.npz new file mode 100644 index 0000000000000000000000000000000000000000..238fad6680e1cb8efbe4aa99ca0dc375ca0dab76 --- /dev/null +++ b/tasks/rahmaniani2018/solverless_models/941110a0327a7838702cbc1d9cb3a29fb34e980b2776a48b10f249b1a4730b50.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38ea16e130210c2938e62932694d31a8cbc0a205a00fd6ced76d28e860a8e727 +size 1492278 diff --git a/tasks/rahmaniani2018/solverless_models/a2b221e12d5fa016d9b049b22feebd9b776679c74c84dd2014b0aec8a26fa71d.npz b/tasks/rahmaniani2018/solverless_models/a2b221e12d5fa016d9b049b22feebd9b776679c74c84dd2014b0aec8a26fa71d.npz new file mode 100644 index 0000000000000000000000000000000000000000..686b8d22dc36f8e41736b13b4c3d90c30e04ccce --- /dev/null +++ b/tasks/rahmaniani2018/solverless_models/a2b221e12d5fa016d9b049b22feebd9b776679c74c84dd2014b0aec8a26fa71d.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:71db204c225a10536e94533f341fd20e00eb071b6240d24852bb006c5d5371d8 +size 1477883 diff --git a/tasks/rahmaniani2018/solverless_witness.py b/tasks/rahmaniani2018/solverless_witness.py new file mode 100644 index 0000000000000000000000000000000000000000..6e8d1c0a2a83a5aa314a7405d6b50f6d5dacaf8c --- /dev/null +++ b/tasks/rahmaniani2018/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/rahmaniani2020/feasibility_check.py b/tasks/rahmaniani2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..23669128f16410d9488d1fe6e1dc02af1f782261 --- /dev/null +++ b/tasks/rahmaniani2020/feasibility_check.py @@ -0,0 +1,457 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Stochastic Capacitated Facility Location (SFL) problem. +Rahmaniani et al. (2020), Appendix D.2, Equations (D.4)-(D.7). + +Constraint numbering (top to bottom in formulation section): + Constraint 1: (D.5) sum_i x_{ij}^s >= d_j^s for all j in M, s in S [demand satisfaction, >=] + Constraint 2: (D.6) sum_j x_{ij}^s <= u_i * y_i for all i in N, s in S [capacity, <=] + Constraint 3: (D.7) sum_i u_i * y_i >= max_s sum_j d_j^s [complete recourse, >=] + Constraint 4: (D.4) Objective consistency: reported objective_value must equal + f^T y + sum_s p_s * min_x { sum_{i,j} c_{ij} x_{ij}^s : D.5, D.6, x>=0 } + (Tier C defense against fabricated objective values.) + +Since solutions only contain y (facility opening decisions) and not x (flow variables), +constraints 1 and 2 are checked by solving an LP per scenario to determine if feasible +x exists given y. If demand cannot be fully met, constraint 1 (D.5) is reported violated. +Constraint 2 (D.6) is verified explicitly on the LP-optimal x. +Constraint 3 (D.7) is checked directly from y. + +Constraint 4 recomputes the true objective by solving a cost-minimization transportation +LP per scenario (the recourse problem) and comparing the expected total cost against the +reported objective_value. +""" + +import json +import argparse +import numpy as np +from scipy.optimize import linprog + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'y') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + 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(data, sol): + tol = 1e-5 + eps = 1e-5 + + N = data["num_facilities"] + M = data["num_customers"] + S = data["num_scenarios"] + cap = data["facilities"]["capacities"] + demands = data["scenarios"]["demands"] + y = sol["y"] + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ------------------------------------------------------------------ + # Constraint 3 (D.7): sum_i u_i * y_i >= max_s sum_j d_j^s + # Type: >= constraint. Violation = RHS - LHS when RHS > LHS. + # ------------------------------------------------------------------ + D_max = max(sum(demands[s][j] for j in range(M)) for s in range(S)) + lhs_3 = sum(cap[i] * y[i] for i in range(N)) + rhs_3 = float(D_max) + viol_3 = rhs_3 - lhs_3 + if viol_3 > tol: + violated_constraints.add(3) + violations.append( + f"Constraint 3 (D.7) violated: sum(u_i*y_i)={lhs_3:.6f} < " + f"max_s(sum_j d_j^s)={rhs_3:.6f}" + ) + normalizer = max(abs(rhs_3), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs_3, + "rhs": rhs_3, + "raw_excess": viol_3, + "normalizer": normalizer, + "ratio": viol_3 / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraints 1 (D.5) and 2 (D.6): checked via LP per scenario. + # + # For each scenario s we solve: + # min sum_j slack_j + # s.t. sum_i x_{ij} + slack_j >= d_j^s for all j (D.5 relaxed) + # sum_j x_{ij} <= u_i*y_i for all i (D.6 enforced) + # x >= 0, slack >= 0 + # + # If total slack > 0, constraint 1 (D.5) is violated for that scenario. + # Constraint 2 (D.6) is then verified explicitly on the found x. + # ------------------------------------------------------------------ + feasibility_ok_per_scenario = [True] * S + for s in range(S): + d_s = demands[s] + n_x = N * M + n_slack = M + n_vars = n_x + n_slack + + # Objective: minimize total demand shortfall + c_obj = np.zeros(n_vars) + c_obj[n_x:] = 1.0 + + A_ub_rows = [] + b_ub_vals = [] + + # D.5 (>=): sum_i x_{ij} + slack_j >= d_j^s + # => -sum_i x_{ij} - slack_j <= -d_j^s + for j in range(M): + row = np.zeros(n_vars) + for i in range(N): + row[i * M + j] = -1.0 + row[n_x + j] = -1.0 + A_ub_rows.append(row) + b_ub_vals.append(-float(d_s[j])) + + # D.6 (<=): sum_j x_{ij} <= u_i * y_i + for i in range(N): + row = np.zeros(n_vars) + for j in range(M): + row[i * M + j] = 1.0 + A_ub_rows.append(row) + b_ub_vals.append(float(cap[i] * y[i])) + + A_ub = np.array(A_ub_rows) + b_ub = np.array(b_ub_vals) + bounds = [(0, None)] * n_vars + + res = linprog(c_obj, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method="highs") + + if not res.success: + # Should not happen with slack variables, but handle defensively + violated_constraints.add(1) + violations.append( + f"Constraint 1 (D.5) violated: LP solver failed for scenario {s}" + ) + feasibility_ok_per_scenario[s] = False + continue + + # Check D.5 violations via slack values + if res.fun > tol: + violated_constraints.add(1) + feasibility_ok_per_scenario[s] = False + slack = res.x[n_x:] + shortfall_details = [] + for j in range(M): + if slack[j] > tol: + # LHS = sum_i x_{ij}^s = d_j^s - slack_j (actual flow) + lhs_val = float(d_s[j]) - slack[j] + rhs_val = float(d_s[j]) + viol_amt = slack[j] + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": viol_amt, + "normalizer": normalizer, + "ratio": viol_amt / normalizer, + }) + shortfall_details.append(f"customer {j} short by {slack[j]:.6f}") + violations.append( + f"Constraint 1 (D.5) violated in scenario {s}: " + f"total shortfall={res.fun:.6f} ({'; '.join(shortfall_details)})" + ) + + # Explicitly verify D.6 on the LP-optimal x + x_vals = res.x[:n_x].reshape(N, M) + for i in range(N): + flow_i = float(np.sum(x_vals[i, :])) + cap_rhs = float(cap[i] * y[i]) + viol_6 = flow_i - cap_rhs # <= constraint: violation when LHS > RHS + if viol_6 > tol: + violated_constraints.add(2) + normalizer = max(abs(cap_rhs), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": flow_i, + "rhs": cap_rhs, + "raw_excess": viol_6, + "normalizer": normalizer, + "ratio": viol_6 / normalizer, + }) + violations.append( + f"Constraint 2 (D.6) violated: facility {i}, scenario {s}, " + f"flow={flow_i:.6f} > capacity={cap_rhs:.6f}" + ) + + # ------------------------------------------------------------------ + # Constraint 4: Objective consistency (Tier C anti-exploit defense). + # + # Recompute the optimal objective for the given y by solving the recourse + # problem (a transportation LP) per scenario, then compare to the reported + # objective_value. The full-recompute formula: + # + # true_obj = sum_i f_i * y_i + # + sum_s p_s * min_{x>=0} { sum_{i,j} c_{ij} x_{ij}^s + # : sum_i x_{ij}^s >= d_j^s (D.5), + # sum_j x_{ij}^s <= u_i*y_i (D.6) } + # + # Skip the check if any structural constraint (1, 2, or 3) already + # marks the solution infeasible -- in that case the obj is undefined, + # and the existing violations already cause feasible=False. + # ------------------------------------------------------------------ + structural_violation = bool(violated_constraints & {1, 2, 3}) + reported_obj_raw = sol.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 structural_violation: + fixed_costs = data["facilities"]["fixed_costs"] + routing_costs = data["routing_costs"] + probs = data["scenarios"]["probabilities"] + + setup_cost = float(sum(fixed_costs[i] * y[i] for i in range(N))) + + # Build the cost vector for the routing LP (same A_ub structure as above + # but without slack variables, since structural feasibility is already + # confirmed for every scenario). + n_x = N * M + c_route = np.empty(n_x) + for i in range(N): + for j in range(M): + c_route[i * M + j] = float(routing_costs[i][j]) + + # D.6 capacity rows are scenario-independent (depend only on y). + cap_rows = np.zeros((N, n_x)) + cap_rhs_arr = np.empty(N) + for i in range(N): + for j in range(M): + cap_rows[i, i * M + j] = 1.0 + cap_rhs_arr[i] = float(cap[i] * y[i]) + + # D.5 demand rows depend on scenario; build template once. + demand_template = np.zeros((M, n_x)) + for j in range(M): + for i in range(N): + demand_template[j, i * M + j] = -1.0 + + recompute_failed_for_scenario = False + expected_recourse = 0.0 + for s in range(S): + d_s = demands[s] + demand_rhs = np.array([-float(d_s[j]) for j in range(M)]) + A_ub_s = np.vstack([demand_template, cap_rows]) + b_ub_s = np.concatenate([demand_rhs, cap_rhs_arr]) + res = linprog( + c_route, + A_ub=A_ub_s, + b_ub=b_ub_s, + bounds=[(0, None)] * n_x, + method="highs", + ) + if not res.success or res.fun is None: + recompute_failed_for_scenario = True + break + expected_recourse += float(probs[s]) * float(res.fun) + + if not recompute_failed_for_scenario: + true_obj = setup_cost + expected_recourse + abs_diff = abs(reported_obj - true_obj) + # 0.1% relative tolerance with 1.0 absolute floor (obj is on the + # order of 1e3 to 1e5 cost units; floating-point recompute noise + # is well under 1). + tol_obj = max(1.0, 1e-3 * abs(true_obj)) + if abs_diff > tol_obj: + violated_constraints.add(4) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(reported_obj), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": normalizer, + "ratio": float(abs_diff) / normalizer, + }) + violations.append( + f"Constraint 4 (D.4) violated: reported objective_value=" + f"{reported_obj} differs from recomputed setup+E[recourse]=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={tol_obj:.6g})" + ) + + # ------------------------------------------------------------------ + # Build result + # ------------------------------------------------------------------ + vc_sorted = sorted(violated_constraints) + return { + "feasible": len(vc_sorted) == 0, + "violated_constraints": vc_sorted, + "violations": violations, + "violation_magnitudes": violation_magnitudes if violation_magnitudes else [], + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for SFL (Rahmaniani et al. 2020)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file.") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result.") + args = parser.parse_args() + + with open(args.instance_path) as f: + data = 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(data, sol) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(json.dumps(result, 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/rahmaniani2020/gurobi_code.py b/tasks/rahmaniani2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..b378c795281baf06f7615a641ca20f7df5dad5ca --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_code.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +""" +Direct Gurobi MIP formulation of the Stochastic Capacitated Facility Location (SFL) +problem from Rahmaniani et al. (2020), Appendix D.2, Equations (D.4)-(D.7). + + SFL := min sum_i f_i y_i + sum_s sum_i sum_j p_s c_{ij} x_{ij}^s + s.t. sum_i x_{ij}^s >= d_j^s for all j in M, s in S (D.5) + sum_j x_{ij}^s <= u_i y_i for all i in N, s in S (D.6) + sum_i u_i y_i >= max_s sum_j d_j^s (D.7) + y_i in {0,1}, x_{ij}^s >= 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="Solve SFL via direct Gurobi MIP (Rahmaniani et al. 2020)" + ) + 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.") + 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 fh: + data = json.load(fh) + + num_facilities = data["num_facilities"] # |N| + num_customers = data["num_customers"] # |M| + num_scenarios = data["num_scenarios"] # |S| + + f_cost = data["facilities"]["fixed_costs"] # f_i + cap = data["facilities"]["capacities"] # u_i + c = data["routing_costs"] # c[i][j] + + prob = data["scenarios"]["probabilities"] # p_s + demand = data["scenarios"]["demands"] # demand[s][j] = d_j^s + + N = range(num_facilities) + M = range(num_customers) + S = range(num_scenarios) + + # max total demand across scenarios (for complete recourse constraint D.7) + D_max = max(sum(demand[s][j] for j in M) for s in S) + + # ------------------------------------------------------------------ # + # Build Gurobi model + # ------------------------------------------------------------------ # + model = gp.Model("SFL") + model.setParam("TimeLimit", args.time_limit) + model.setParam("Threads", 1) # single-thread as in the paper + + # Decision variables + y = model.addVars(num_facilities, vtype=GRB.BINARY, name="y") + x = model.addVars(num_facilities, num_customers, num_scenarios, + lb=0.0, name="x") + + # Objective (D.4) + model.setObjective( + gp.quicksum(f_cost[i] * y[i] for i in N) + + gp.quicksum( + prob[s] * c[i][j] * x[i, j, s] + for s in S for i in N for j in M + ), + GRB.MINIMIZE, + ) + + # Demand satisfaction (D.5): sum_i x_{ij}^s >= d_j^s + for j in M: + for s in S: + model.addConstr( + gp.quicksum(x[i, j, s] for i in N) >= demand[s][j], + name=f"demand_{j}_{s}", + ) + + # Capacity (D.6): sum_j x_{ij}^s <= u_i y_i + for i in N: + for s in S: + model.addConstr( + gp.quicksum(x[i, j, s] for j in M) <= cap[i] * y[i], + name=f"capacity_{i}_{s}", + ) + + # Complete recourse (D.7): sum_i u_i y_i >= max_s sum_j d_j^s + model.addConstr( + gp.quicksum(cap[i] * y[i] for i in N) >= D_max, + name="recourse", + ) + + # ------------------------------------------------------------------ # + # Optimize + # ------------------------------------------------------------------ # + model.optimize() + + # ------------------------------------------------------------------ # + # Extract and save solution + # ------------------------------------------------------------------ # + result = {} + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["y"] = [int(round(y[i].X)) for i in N] + result["status"] = model.Status + result["mip_gap"] = model.MIPGap if model.Status != GRB.OPTIMAL else 0.0 + else: + result["objective_value"] = None + result["status"] = model.Status + + with open(args.solution_path, "w") as fh: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, fh, indent=2) + + print(f"Solution written to {args.solution_path}") + if model.SolCount > 0: + print(f"Objective value: {result['objective_value']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/rahmaniani2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/rahmaniani2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2020/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/rahmaniani2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/rahmaniani2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2020/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/rahmaniani2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/rahmaniani2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2020/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/rahmaniani2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/rahmaniani2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2020/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