Minwei Kong commited on
Commit
d85e4dd
·
verified ·
1 Parent(s): fddb194

Nest task folders under tasks/ (part 7)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/eiselt2009/mathematical_formulation.md +59 -0
  2. tasks/eiselt2009/problem_description.txt +11 -0
  3. tasks/eiselt2009/solution_logger.py +61 -0
  4. tasks/eiselt2009/solution_schema.json +4 -0
  5. tasks/elci2022/feasibility_check.py +666 -0
  6. tasks/elci2022/gurobi_code.py +291 -0
  7. tasks/elci2022/gurobi_feasi_result/large_feasi_result_1.json +3 -0
  8. tasks/elci2022/gurobi_feasi_result/large_feasi_result_2.json +3 -0
  9. tasks/elci2022/gurobi_feasi_result/large_feasi_result_3.json +3 -0
  10. tasks/elci2022/gurobi_feasi_result/large_feasi_result_4.json +3 -0
  11. tasks/elci2022/gurobi_feasi_result/large_feasi_result_5.json +3 -0
  12. tasks/elci2022/gurobi_feasi_result/tiny_feasi_result.json +3 -0
  13. tasks/elci2022/gurobi_solution/large_solution_1.json +3 -0
  14. tasks/elci2022/gurobi_solution/large_solution_2.json +3 -0
  15. tasks/elci2022/gurobi_solution/large_solution_3.json +3 -0
  16. tasks/elci2022/gurobi_solution/large_solution_4.json +3 -0
  17. tasks/elci2022/gurobi_solution/large_solution_5.json +3 -0
  18. tasks/elci2022/gurobi_solution/tiny_solution.json +3 -0
  19. tasks/elci2022/gurobi_solution_log/large_log_1.jsonl +3 -0
  20. tasks/elci2022/gurobi_solution_log/large_log_2.jsonl +3 -0
  21. tasks/elci2022/gurobi_solution_log/large_log_3.jsonl +3 -0
  22. tasks/elci2022/gurobi_solution_log/large_log_4.jsonl +3 -0
  23. tasks/elci2022/gurobi_solution_log/large_log_5.jsonl +3 -0
  24. tasks/elci2022/gurobi_solution_log/tiny_log.jsonl +3 -0
  25. tasks/elci2022/instance/large_instance_1.json +3 -0
  26. tasks/elci2022/instance/large_instance_2.json +3 -0
  27. tasks/elci2022/instance/large_instance_3.json +3 -0
  28. tasks/elci2022/instance/large_instance_4.json +3 -0
  29. tasks/elci2022/instance/large_instance_5.json +3 -0
  30. tasks/elci2022/instance/tiny_instance.json +3 -0
  31. tasks/elci2022/instance_schema.json +15 -0
  32. tasks/elci2022/mathematical_formulation.md +56 -0
  33. tasks/elci2022/problem_description.txt +7 -0
  34. tasks/elci2022/solution_logger.py +61 -0
  35. tasks/elci2022/solution_schema.json +13 -0
  36. tasks/engineer2012/feasibility_check.py +963 -0
  37. tasks/engineer2012/gurobi_code.py +904 -0
  38. tasks/engineer2012/gurobi_feasi_result/large_feasi_result_1.json +3 -0
  39. tasks/engineer2012/gurobi_feasi_result/large_feasi_result_2.json +3 -0
  40. tasks/engineer2012/gurobi_feasi_result/large_feasi_result_3.json +3 -0
  41. tasks/engineer2012/gurobi_feasi_result/large_feasi_result_4.json +3 -0
  42. tasks/engineer2012/gurobi_feasi_result/large_feasi_result_5.json +3 -0
  43. tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result.json +3 -0
  44. tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result_2.json +3 -0
  45. tasks/engineer2012/gurobi_solution/large_solution_1.json +3 -0
  46. tasks/engineer2012/gurobi_solution/large_solution_2.json +3 -0
  47. tasks/engineer2012/gurobi_solution/large_solution_3.json +3 -0
  48. tasks/engineer2012/gurobi_solution/large_solution_4.json +3 -0
  49. tasks/engineer2012/gurobi_solution/large_solution_5.json +3 -0
  50. tasks/engineer2012/gurobi_solution/tiny_solution.json +3 -0
tasks/eiselt2009/mathematical_formulation.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sets and Parameters
2
+
3
+ - $N$: set of all nodes (origins, destinations, potential hub locations); indices $i, j \in N$.
4
+
5
+ - $\mathrm{Own}$: set of candidate hub nodes for the entering airline (“us”); indices $k, \ell \in \mathrm{Own}$.
6
+
7
+ - $\mathrm{Comp}$: set of hub nodes of existing (competing) airlines; $|\mathrm{Comp}| = r$.
8
+
9
+ - $s$: airline index; $s = o$ denotes the entering airline, $s = 1,2,\ldots$ denote incumbent airlines.
10
+
11
+ - $h_{ij}$: known non-elastic demand for air traffic from origin $i$ to destination $j$.
12
+
13
+ - $p$: number of hubs to be located by the entering airline (exogenously given).
14
+
15
+ - $A_{k\ell s}$: basic attractiveness of the hub pair $(k, \ell)$ operated by airline $s$.
16
+
17
+ - $\beta, \lambda$: attraction-decay exponents for travel time and travel cost, respectively.
18
+
19
+ - $\gamma \in [0,1]$: relative weight of travel time vs. travel cost.
20
+
21
+ - $\alpha \leq 1$: discount factor for interhub fare (economies of scale).
22
+
23
+ - $t_{ijk\ell s}$: total travel time for route $(i,j,k,\ell)$ by airline $s$.
24
+
25
+ - $c_{ijk\ell s}$: total fare for route $(i,j,k,\ell)$ by airline $s$.
26
+
27
+ # Derived Quantities
28
+
29
+ Utility (attraction) of route $(i,j,k,\ell)$ by airline $s$ (Equation (1)): $$\begin{equation}
30
+ u_{ijk\ell s} \;=\; \frac{A_{k\ell s}}{\gamma\, t_{ijk\ell s}^{\beta} \;+\; (1-\gamma)\, c_{ijk\ell s}^{\lambda}} \tag{1}
31
+ \end{equation}$$
32
+
33
+ Probability that a customer traveling from $i$ to $j$ uses route $(k,\ell)$ via the entering airline $o$ (Equation (2)): $$\begin{equation}
34
+ p_{ijk\ell o} \;=\; \frac{u_{ijk\ell o}}{\displaystyle \sum_{m, n \in \mathrm{Own}} u_{ijmno} \;+\; \sum_{s \neq o} \sum_{m, n \in \mathrm{Comp}} u_{ijmns}} \tag{2}
35
+ \end{equation}$$
36
+
37
+ # Decision Variables
38
+
39
+ $$\begin{align*}
40
+ y_k &\in \{0,1\} && \forall\, k \in \mathrm{Own} \quad (\text{1 if hub is located at $k$ by entering airline}) \\
41
+ w_{k\ell} &\in \{0,1\} && \forall\, k, \ell \in \mathrm{Own} \quad (\text{1 if hubs are located at \emph{both} $k$ and $\ell$})
42
+ \end{align*}$$
43
+
44
+ # Objective (nonlinear sum-of-ratios form, Equation (3))
45
+
46
+ $$\begin{align}
47
+ \mathrm{P}: \quad \max\; z
48
+ &= \sum_{i,j} \sum_{k, \ell \in \mathrm{Own}} h_{ij} \, p_{ijk\ell o} \notag \\
49
+ &= \sum_{i,j} h_{ij}\, \frac{\displaystyle\sum_{k, \ell \in \mathrm{Own}} w_{k\ell}\, u_{ijk\ell o}}{\displaystyle\sum_{m, n \in \mathrm{Own}} w_{mn}\, u_{ijmno} \;+\; \sum_{s \neq o} \sum_{m, n \in \mathrm{Comp}} u_{ijmns}} \tag{3}
50
+ \end{align}$$
51
+
52
+ # Constraints
53
+
54
+ $$\begin{align}
55
+ w_{k\ell} &\leq y_k && \forall\, k, \ell \in \mathrm{Own} \tag{4} \\
56
+ w_{k\ell} &\leq y_\ell && \forall\, k, \ell \in \mathrm{Own} \tag{5} \\
57
+ \sum_{k} y_k &= p \tag{6} \\
58
+ y_k,\; w_{k\ell} &\in \{0,1\} && \forall\, k, \ell \in \mathrm{Own} \tag{7}
59
+ \end{align}$$
tasks/eiselt2009/problem_description.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Problem Description
2
+
3
+ A region is served by an air transportation network in which several nodes represent cities that are simultaneously origins, destinations, and candidate hub locations. One or more incumbent airlines already operate hub-and-spoke networks in this region, each with a fixed set of hub airports. A new entrant airline wishes to enter this market by opening exactly a prescribed number of hubs, chosen from the full set of nodes, so as to capture as large a share of total passenger traffic as possible.
4
+
5
+ The input data consists of the following. There is a set of nodes, each with spatial coordinates and a fixed waiting time representing the dwell or layover delay passengers experience at that airport. A demand matrix gives the known, non-elastic number of passengers wishing to travel from every origin to every destination. A distance matrix gives the pairwise distances between all nodes. A set of nodes is designated as the fixed hub locations of the competing airlines, and the number of hubs the entrant must open is given. Several global parameters govern customer behavior: an interhub fare discount factor that reduces the fare charged on the hub-to-hub leg of a trip to reflect economies of scale; a time-versus-cost weight that ranges from zero to one and controls how much customers value travel time relative to fare; an attraction decay exponent for travel time; an attraction decay exponent for fare; and a cost scalar that converts distances into fares. In addition, each combination of hub pair and airline has a given attractiveness value that reflects the quality of the airline, the convenience of the hub airports, and whether the route passes through a single hub or two distinct hubs.
6
+
7
+ Every trip from an origin to a destination may be routed through a pair of hubs, where the two hubs may be the same node (a single-hub route) or different nodes (a two-hub route). For each airline and each ordered hub pair, the total travel time on a route equals the sum of the travel time from the origin to the first hub, the travel time between the two hubs, the travel time from the second hub to the destination, and the fixed waiting times at the origin airport, the first hub, and the second hub. Travel times on each leg are proportional to the distance between the endpoints. The total fare on a route equals the fare from the origin to the first hub, plus the interhub fare discount factor times the fare between the two hubs, plus the fare from the second hub to the destination, where each leg fare is proportional to the distance of that leg scaled by the cost scalar. For each airline, each ordered origin-destination pair (with the origin i and destination j held fixed), and each unordered pair of two distinct hubs {k, l}, only one of the two corresponding two-hub routes is considered open: namely, whichever of the route i -> k -> l -> j and the route i -> l -> k -> j yields the higher customer utility. The origin and destination are never swapped; only the visiting order of the two intermediate hubs is reversed (so the comparison is between two four-node paths that share the same first node i and the same last node j and differ only in the relative order of the two hub nodes in between).
8
+
9
+ The utility that customers perceive for a particular route operated by a particular airline is the attractiveness of that hub pair divided by the sum of two terms: the time-versus-cost weight times the total travel time raised to the time decay exponent, plus the quantity (one minus the time-versus-cost weight) multiplied by (the total fare raised to the fare decay exponent). In particular, the exponentiation by the fare decay exponent applies only to the total fare and not to the product of the weight complement and the fare, and the "one minus" applies only to the time-versus-cost weight and not to the entire product; equivalently, denoting the time-versus-cost weight by gamma, the total time by t, the total fare by c, the time decay exponent by beta, and the fare decay exponent by lambda, the denominator equals gamma * t^beta + (1 - gamma) * c^lambda. The probability that a passenger traveling from a given origin to a given destination chooses a particular route offered by the entrant airline equals the utility of that route divided by the sum of the utilities of all routes offered by all airlines, including all routes the entrant offers through its opened hub pairs and all routes every incumbent airline offers through its fixed hub pairs. The expected number of passengers captured by the entrant on a given route is the demand for that origin-destination pair multiplied by this probability.
10
+
11
+ The entrant must select exactly the prescribed number of nodes at which to open hubs. A hub pair is considered active for the entrant only if both nodes in the pair have been selected as hubs. The goal is to maximize the total expected number of passengers captured by the entrant across all origin-destination pairs and all of the entrant's active hub-pair routes, where capture on each origin-destination pair is the demand times the fraction of total utility contributed by the entrant's active routes.
tasks/eiselt2009/solution_logger.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convergence logger for optimization algorithms.
3
+
4
+ Records incumbent solutions with timestamps to a JSONL file.
5
+ This module is provided to LLM-generated programs — they only need to call
6
+ `log(objective_value)` whenever a better feasible solution is found.
7
+
8
+ Usage in generated code:
9
+ from solution_logger import SolutionLogger
10
+ logger = SolutionLogger(log_path, sense="minimize") # or "maximize"
11
+ # ... inside algorithm loop:
12
+ logger.log(objective_value)
13
+ """
14
+
15
+ import json
16
+ import time
17
+
18
+
19
+ class SolutionLogger:
20
+ def __init__(self, log_path, sense="minimize"):
21
+ """
22
+ Args:
23
+ log_path: Path to the JSONL output file.
24
+ sense: "minimize" or "maximize".
25
+ """
26
+ self.log_path = log_path
27
+ self.sense = sense
28
+ self.start_time = time.time()
29
+ self.best_obj = None
30
+ self.min_interval = 0.1 # seconds, avoid excessive writes
31
+
32
+ self._last_log_time = 0.0
33
+ # Clear the file
34
+ with open(self.log_path, "w") as f:
35
+ pass
36
+
37
+ def log(self, objective_value):
38
+ """Record a new incumbent if it improves on the best known."""
39
+ if objective_value is None:
40
+ return
41
+
42
+ # Check if this is an improvement
43
+ if self.best_obj is not None:
44
+ if self.sense == "minimize" and objective_value >= self.best_obj:
45
+ return
46
+ if self.sense == "maximize" and objective_value <= self.best_obj:
47
+ return
48
+
49
+ elapsed = time.time() - self.start_time
50
+
51
+ # Throttle writes
52
+ if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval:
53
+ self.best_obj = objective_value
54
+ return
55
+
56
+ self.best_obj = objective_value
57
+ self._last_log_time = elapsed
58
+
59
+ with open(self.log_path, "a") as f:
60
+ f.write(json.dumps({"time": round(elapsed, 3),
61
+ "objective_value": objective_value}) + "\n")
tasks/eiselt2009/solution_schema.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "objective_value": "<float> Total captured passenger demand across all origin-destination pairs for the entering airline.",
3
+ "hub_locations": "<list[int], length p> Node indices selected as hub locations for the entering airline."
4
+ }
tasks/elci2022/feasibility_check.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Feasibility checker for the Stochastic Planning & Scheduling problem
4
+ (Elci & Hooker, 2020) - Minimum Makespan variant.
5
+
6
+ Checks constraints from the deterministic equivalent MILP (Eq. 22),
7
+ numbered 1-9 from top to bottom:
8
+
9
+ Constraint 1 (22b): sum_i x_{ij} = 1 for all j in J
10
+ Constraint 2 (22c): beta_omega >= beta_{i,omega} for all i in I, omega in Omega
11
+ Constraint 3 (22d): x_{ij} in {0,1} for all i in I, j in J
12
+ Constraint 4 (22e): beta_omega >= sum_t (t + p^omega_ij) z^omega_ijt
13
+ for all i in I, j in J, omega in Omega
14
+ Constraint 5 (22f): z^omega_ijt <= x_{ij} for all i,j,t,omega
15
+ Constraint 6 (22g): sum_i sum_t z^omega_ijt = 1 for all j in J, omega in Omega
16
+ Constraint 7 (22h): sum_j sum_{t' in T^omega_tij} c_{ij} z^omega_ijt' <= K_i
17
+ for all i in I, t in T, omega in Omega
18
+ Constraint 8 (22i): z^omega_ijt = 0 for t < r_j for all i,omega,j,t
19
+ Constraint 9 (22j): z^omega_ijt in {0,1} for all i,j,t,omega
20
+
21
+ Constraint 10 (objective consistency, Tier-C defense): the reported
22
+ objective_value must equal the recomputed expected makespan
23
+ sum_omega pi_omega * beta_omega, where beta_omega = max_j finish_j in
24
+ scenario omega. Every variable needed for this recompute (the per-
25
+ scenario finish times) is present in the solution's `schedule`, so a
26
+ FULL two-sided recompute is possible.
27
+
28
+ The original Constraint 4 (22e) objective check is ONE-SIDED -- it only
29
+ flags reported < computed. Constraint 10 adds the symmetric direction
30
+ (reported > computed), rejecting fabricated/inflated objective values
31
+ that the structural constraint checks alone would otherwise accept.
32
+ """
33
+
34
+ import argparse
35
+ import json
36
+
37
+ # FRONTIEROR_RELEASE_CONTRACT_V2
38
+ _FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignment', 'objective_value', 'schedule')
39
+ _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('schedule',)
40
+ _FRONTIEROR_DERIVED_FIELD_RULES = ()
41
+ _FRONTIEROR_CONDITIONAL_FIELD_RULES = ()
42
+
43
+
44
+ def _frontieror_validate_solution_contract(solution):
45
+ """Return a structured rejection when the public solution contract is absent."""
46
+ violations = []
47
+ if not isinstance(solution, dict):
48
+ violations.append("solution must be a JSON object")
49
+ else:
50
+ missing = [
51
+ field
52
+ for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS
53
+ if field not in solution or solution[field] is None
54
+ ]
55
+ if missing:
56
+ violations.append(
57
+ "missing required solution field(s): " + ", ".join(missing)
58
+ )
59
+
60
+ for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES:
61
+ if solution.get(discriminator) != expected_value:
62
+ continue
63
+ conditional_missing = [
64
+ field
65
+ for field in fields
66
+ if field not in solution or solution[field] is None
67
+ ]
68
+ if conditional_missing:
69
+ violations.append(
70
+ "missing conditionally required solution field(s): "
71
+ + ", ".join(conditional_missing)
72
+ )
73
+
74
+ empty = [
75
+ field
76
+ for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS
77
+ if field in solution and solution[field] in (None, [], {})
78
+ ]
79
+ if empty:
80
+ violations.append(
81
+ "empty required decision witness field(s): " + ", ".join(empty)
82
+ )
83
+
84
+ for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES:
85
+ try:
86
+ reported = float(solution[target])
87
+ if operation == "length":
88
+ expected = float(len(solution[source]))
89
+ elif operation == "mapping_value":
90
+ expected = float(solution[source][source_key])
91
+ else:
92
+ raise ValueError("unknown derived-field operation")
93
+ except (KeyError, TypeError, ValueError, OverflowError):
94
+ violations.append(
95
+ f"cannot derive {target} from decision witness field {source}"
96
+ )
97
+ continue
98
+ if (
99
+ reported != reported
100
+ or expected != expected
101
+ or reported in (float("inf"), float("-inf"))
102
+ or expected in (float("inf"), float("-inf"))
103
+ or abs(reported - expected) > 1e-6
104
+ ):
105
+ violations.append(
106
+ f"{target}={reported} does not match the decision-derived "
107
+ f"value {expected}"
108
+ )
109
+
110
+ if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS:
111
+ objective = solution.get("objective_value")
112
+ if (
113
+ isinstance(objective, bool)
114
+ or not isinstance(objective, (int, float))
115
+ or objective != objective
116
+ or objective in (float("inf"), float("-inf"))
117
+ ):
118
+ violations.append("objective_value must be a finite JSON number")
119
+
120
+ if not violations:
121
+ return None
122
+ return {
123
+ "feasible": False,
124
+ "violated_constraints": ["solution_schema"],
125
+ "violations": violations,
126
+ "violation_magnitudes": [],
127
+ }
128
+
129
+
130
+ def _frontieror_write_unexpected_rejection(error):
131
+ """Turn malformed candidate/checker exceptions into a normal rejection."""
132
+ import json as _frontieror_json
133
+ import sys as _frontieror_sys
134
+
135
+ result_path = None
136
+ for index, argument in enumerate(_frontieror_sys.argv):
137
+ if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv):
138
+ result_path = _frontieror_sys.argv[index + 1]
139
+ break
140
+ if argument.startswith("--result_path="):
141
+ result_path = argument.split("=", 1)[1]
142
+ break
143
+ if not result_path:
144
+ return False
145
+ try:
146
+ with open(result_path, "w") as result_handle:
147
+ _frontieror_json.dump(
148
+ {
149
+ "feasible": False,
150
+ "violated_constraints": ["malformed_solution"],
151
+ "violations": [
152
+ "checker rejected malformed candidate: "
153
+ + type(error).__name__
154
+ + ": "
155
+ + str(error)[:500]
156
+ ],
157
+ "violation_magnitudes": [],
158
+ },
159
+ result_handle,
160
+ indent=2,
161
+ )
162
+ except Exception:
163
+ return False
164
+ return True
165
+
166
+
167
+
168
+ def check_feasibility(instance_path, solution_path, result_path):
169
+ tol = 1e-5
170
+ eps = 1e-5
171
+
172
+ with open(instance_path) as f:
173
+ inst = json.load(f)
174
+ with open(solution_path) as f:
175
+ sol = json.load(f)
176
+ _frontieror_contract_result = _frontieror_validate_solution_contract(sol)
177
+ if _frontieror_contract_result is not None:
178
+ with open(result_path, "w") as _frontieror_result_handle:
179
+ json.dump(
180
+ _frontieror_contract_result,
181
+ _frontieror_result_handle,
182
+ indent=2,
183
+ )
184
+ return _frontieror_contract_result
185
+
186
+ n = inst["n"]
187
+ m = inst["m"]
188
+ S = inst["num_scenarios"]
189
+ K = inst["facility_capacity_limits"] # K[i]
190
+ c = inst["capacity_requirements"] # c[i][j]
191
+ r = inst["release_times"] # r[j]
192
+ scenarios = inst["scenarios"]
193
+ pi_prob = [sc["probability"] for sc in scenarios]
194
+ p = [sc["processing_times"] for sc in scenarios] # p[omega][i][j]
195
+
196
+ assignment = sol.get("assignment", {})
197
+ schedule = sol.get("schedule", None)
198
+ objective_value = sol.get("objective_value", None)
199
+
200
+ violations = []
201
+ violation_magnitudes = []
202
+ violated_constraints = set()
203
+
204
+ # Parse assignment: job j -> facility i
205
+ assign = {}
206
+ for j_str, i_val in assignment.items():
207
+ assign[int(j_str)] = int(i_val)
208
+
209
+ # Build x[i][j] matrix from assignment
210
+ x = [[0] * n for _ in range(m)]
211
+ for j_val, i_val in assign.items():
212
+ if 0 <= i_val < m and 0 <= j_val < n:
213
+ x[i_val][j_val] = 1
214
+
215
+ # ------------------------------------------------------------------
216
+ # Constraint 1 (22b): sum_i x_{ij} = 1 for all j in J
217
+ # ------------------------------------------------------------------
218
+ for j in range(n):
219
+ lhs = sum(x[i][j] for i in range(m))
220
+ rhs_val = 1.0
221
+ violation_amount = abs(lhs - rhs_val)
222
+ if violation_amount > tol:
223
+ violated_constraints.add(1)
224
+ violations.append(
225
+ f"Constraint 1 (22b): Job {j} assigned to {lhs} facilities (expected 1)"
226
+ )
227
+ normalizer = max(abs(rhs_val), eps)
228
+ violation_magnitudes.append({
229
+ "constraint": 1,
230
+ "lhs": float(lhs),
231
+ "rhs": float(rhs_val),
232
+ "raw_excess": float(violation_amount),
233
+ "normalizer": float(normalizer),
234
+ "ratio": float(violation_amount / normalizer),
235
+ })
236
+
237
+ # ------------------------------------------------------------------
238
+ # Constraint 3 (22d): x_{ij} in {0,1} for all i, j
239
+ # Check that assignment values are valid (binary, valid facility index)
240
+ # ------------------------------------------------------------------
241
+ for j in range(n):
242
+ if j in assign:
243
+ fac = assign[j]
244
+ if fac < 0 or fac >= m:
245
+ violated_constraints.add(3)
246
+ violation_amount = 1.0
247
+ violations.append(
248
+ f"Constraint 3 (22d): Job {j} assigned to invalid facility {fac} "
249
+ f"(valid range 0..{m-1})"
250
+ )
251
+ violation_magnitudes.append({
252
+ "constraint": 3,
253
+ "lhs": float(fac),
254
+ "rhs": 0.0,
255
+ "raw_excess": float(violation_amount),
256
+ "normalizer": max(float(m - 1), eps),
257
+ "ratio": float(violation_amount / max(float(m - 1), eps)),
258
+ })
259
+
260
+ # ------------------------------------------------------------------
261
+ # Constraints 2, 4-9 require schedule data (z variables)
262
+ # ------------------------------------------------------------------
263
+ if schedule is not None:
264
+ # Parse schedule: sched[omega][j] = {facility, start, finish}
265
+ sched = {}
266
+ for omega_str, jobs in schedule.items():
267
+ omega = int(omega_str)
268
+ sched[omega] = {}
269
+ for j_str, info in jobs.items():
270
+ j_val = int(j_str)
271
+ sched[omega][j_val] = {
272
+ "facility": int(info["facility"]),
273
+ "start": float(info["start"]),
274
+ "finish": float(info["finish"]),
275
+ }
276
+
277
+ for omega in range(S):
278
+ if omega not in sched:
279
+ continue
280
+
281
+ # Compute per-facility makespan (beta_{i,omega}) and scenario makespan (beta_omega)
282
+ beta_iw = [0.0] * m
283
+ for j_val in range(n):
284
+ if j_val not in sched[omega]:
285
+ continue
286
+ info = sched[omega][j_val]
287
+ fac = info["facility"]
288
+ beta_iw[fac] = max(beta_iw[fac], info["finish"])
289
+
290
+ beta_omega = max(beta_iw) if any(
291
+ j_val in sched[omega] for j_val in range(n)
292
+ ) else 0.0
293
+
294
+ # ----------------------------------------------------------
295
+ # Constraint 2 (22c): beta_omega >= beta_{i,omega}
296
+ # This is a >= constraint: LHS = beta_omega, RHS = beta_{i,omega}
297
+ # Violated if beta_{i,omega} > beta_omega
298
+ # ----------------------------------------------------------
299
+ for i in range(m):
300
+ violation_amount = max(0.0, beta_iw[i] - beta_omega)
301
+ if violation_amount > tol:
302
+ violated_constraints.add(2)
303
+ violations.append(
304
+ f"Constraint 2 (22c): Scenario {omega}, facility {i}: "
305
+ f"beta_omega={beta_omega:.4f} < beta_{{i,omega}}={beta_iw[i]:.4f}"
306
+ )
307
+ normalizer = max(abs(beta_iw[i]), eps)
308
+ violation_magnitudes.append({
309
+ "constraint": 2,
310
+ "lhs": float(beta_omega),
311
+ "rhs": float(beta_iw[i]),
312
+ "raw_excess": float(violation_amount),
313
+ "normalizer": float(normalizer),
314
+ "ratio": float(violation_amount / normalizer),
315
+ })
316
+
317
+ # ----------------------------------------------------------
318
+ # Constraint 4 (22e): beta_omega >= finish_j for all i, j
319
+ # For the assigned facility, finish_j = start_j + p[omega][fac][j].
320
+ # Also verify finish time consistency with processing times.
321
+ # ----------------------------------------------------------
322
+ for j_val in range(n):
323
+ if j_val not in sched[omega]:
324
+ continue
325
+ info = sched[omega][j_val]
326
+ fac = info["facility"]
327
+ start_j = info["start"]
328
+ finish_j = info["finish"]
329
+
330
+ # Verify finish = start + processing time
331
+ if 0 <= fac < m:
332
+ expected_finish = start_j + p[omega][fac][j_val]
333
+ diff = abs(finish_j - expected_finish)
334
+ if diff > tol:
335
+ violated_constraints.add(4)
336
+ violations.append(
337
+ f"Constraint 4 (22e): Scenario {omega}, job {j_val}: "
338
+ f"finish={finish_j} != start({start_j}) + "
339
+ f"p[{omega}][{fac}][{j_val}]({p[omega][fac][j_val]}) = {expected_finish}"
340
+ )
341
+ normalizer = max(abs(expected_finish), eps)
342
+ violation_magnitudes.append({
343
+ "constraint": 4,
344
+ "lhs": float(finish_j),
345
+ "rhs": float(expected_finish),
346
+ "raw_excess": float(diff),
347
+ "normalizer": float(normalizer),
348
+ "ratio": float(diff / normalizer),
349
+ })
350
+
351
+ # beta_omega >= finish_j
352
+ violation_amount = max(0.0, finish_j - beta_omega)
353
+ if violation_amount > tol:
354
+ violated_constraints.add(4)
355
+ violations.append(
356
+ f"Constraint 4 (22e): Scenario {omega}, job {j_val}: "
357
+ f"beta_omega={beta_omega:.4f} < finish={finish_j}"
358
+ )
359
+ normalizer = max(abs(finish_j), eps)
360
+ violation_magnitudes.append({
361
+ "constraint": 4,
362
+ "lhs": float(beta_omega),
363
+ "rhs": float(finish_j),
364
+ "raw_excess": float(violation_amount),
365
+ "normalizer": float(normalizer),
366
+ "ratio": float(violation_amount / normalizer),
367
+ })
368
+
369
+ # Check objective consistency: objective_value should equal
370
+ # sum pi_omega * beta_omega (computed from schedule)
371
+ # This is an additional check for constraint 4 validity.
372
+ if objective_value is not None and S > 0:
373
+ computed_obj = 0.0
374
+ all_scenarios_present = True
375
+ for om in range(S):
376
+ if om in sched and sched[om]:
377
+ mk = max(sched[om][jj]["finish"] for jj in sched[om])
378
+ computed_obj += pi_prob[om] * mk
379
+ else:
380
+ all_scenarios_present = False
381
+
382
+ if all_scenarios_present:
383
+ violation_amount = max(0.0, computed_obj - objective_value)
384
+ if violation_amount > tol:
385
+ violated_constraints.add(4)
386
+ violations.append(
387
+ f"Constraint 4 (22e): Reported objective {objective_value} "
388
+ f"< computed makespan objective {computed_obj:.4f}"
389
+ )
390
+ normalizer = max(abs(computed_obj), eps)
391
+ violation_magnitudes.append({
392
+ "constraint": 4,
393
+ "lhs": float(objective_value),
394
+ "rhs": float(computed_obj),
395
+ "raw_excess": float(violation_amount),
396
+ "normalizer": float(normalizer),
397
+ "ratio": float(violation_amount / normalizer),
398
+ })
399
+
400
+ # ----------------------------------------------------------
401
+ # Constraint 5 (22f): z^omega_ijt <= x_{ij}
402
+ # Job scheduled on a facility must be assigned there.
403
+ # ----------------------------------------------------------
404
+ for j_val in range(n):
405
+ if j_val not in sched[omega]:
406
+ continue
407
+ sched_fac = sched[omega][j_val]["facility"]
408
+ assigned_fac = assign.get(j_val, -1)
409
+ if sched_fac != assigned_fac:
410
+ violated_constraints.add(5)
411
+ violations.append(
412
+ f"Constraint 5 (22f): Scenario {omega}, job {j_val}: "
413
+ f"scheduled on facility {sched_fac} but assigned to facility {assigned_fac}"
414
+ )
415
+ rhs_val = 0.0 # x_{sched_fac, j} = 0
416
+ violation_magnitudes.append({
417
+ "constraint": 5,
418
+ "lhs": 1.0,
419
+ "rhs": float(rhs_val),
420
+ "raw_excess": 1.0,
421
+ "normalizer": max(abs(rhs_val), eps),
422
+ "ratio": float(1.0 / max(abs(rhs_val), eps)),
423
+ })
424
+
425
+ # ----------------------------------------------------------
426
+ # Constraint 6 (22g): sum_i sum_t z^omega_ijt = 1 for all j, omega
427
+ # Each job must be scheduled exactly once per scenario.
428
+ # ----------------------------------------------------------
429
+ for j_val in range(n):
430
+ count = 1 if j_val in sched[omega] else 0
431
+ rhs_val = 1.0
432
+ violation_amount = abs(count - rhs_val)
433
+ if violation_amount > tol:
434
+ violated_constraints.add(6)
435
+ violations.append(
436
+ f"Constraint 6 (22g): Scenario {omega}, job {j_val}: "
437
+ f"scheduled {count} times (expected 1)"
438
+ )
439
+ normalizer = max(abs(rhs_val), eps)
440
+ violation_magnitudes.append({
441
+ "constraint": 6,
442
+ "lhs": float(count),
443
+ "rhs": float(rhs_val),
444
+ "raw_excess": float(violation_amount),
445
+ "normalizer": float(normalizer),
446
+ "ratio": float(violation_amount / normalizer),
447
+ })
448
+
449
+ # ----------------------------------------------------------
450
+ # Constraint 7 (22h): Cumulative resource capacity
451
+ # At each time t, for facility i:
452
+ # sum of c_{ij} for jobs j active at t <= K_i
453
+ # Job j active at t if start_j <= t < start_j + p[omega][i][j]
454
+ # ----------------------------------------------------------
455
+ facility_jobs = {i: [] for i in range(m)}
456
+ for j_val in range(n):
457
+ if j_val in sched[omega]:
458
+ fac = sched[omega][j_val]["facility"]
459
+ facility_jobs[fac].append(j_val)
460
+
461
+ for i in range(m):
462
+ if not facility_jobs[i]:
463
+ continue
464
+
465
+ # Collect event times (start and finish of each job on this facility)
466
+ events = set()
467
+ for j_val in facility_jobs[i]:
468
+ info = sched[omega][j_val]
469
+ events.add(int(info["start"]))
470
+ events.add(int(info["finish"]))
471
+
472
+ # Check resource usage at each event time and just before each event
473
+ times_to_check = set()
474
+ for ev in events:
475
+ times_to_check.add(ev)
476
+ if ev > 0:
477
+ times_to_check.add(ev - 1)
478
+
479
+ worst_violation = 0.0
480
+ worst_t = None
481
+ worst_lhs = 0.0
482
+
483
+ for t in sorted(times_to_check):
484
+ resource_used = 0.0
485
+ for j_val in facility_jobs[i]:
486
+ info = sched[omega][j_val]
487
+ s_j = info["start"]
488
+ f_j = info["finish"]
489
+ if s_j <= t < f_j:
490
+ resource_used += c[i][j_val]
491
+
492
+ violation_amount = max(0.0, resource_used - K[i])
493
+ if violation_amount > worst_violation:
494
+ worst_violation = violation_amount
495
+ worst_t = t
496
+ worst_lhs = resource_used
497
+
498
+ if worst_violation > tol:
499
+ violated_constraints.add(7)
500
+ violations.append(
501
+ f"Constraint 7 (22h): Scenario {omega}, facility {i}, "
502
+ f"time {worst_t}: resource usage {worst_lhs} > capacity {K[i]}"
503
+ )
504
+ normalizer = max(abs(float(K[i])), eps)
505
+ violation_magnitudes.append({
506
+ "constraint": 7,
507
+ "lhs": float(worst_lhs),
508
+ "rhs": float(K[i]),
509
+ "raw_excess": float(worst_violation),
510
+ "normalizer": float(normalizer),
511
+ "ratio": float(worst_violation / normalizer),
512
+ })
513
+
514
+ # ----------------------------------------------------------
515
+ # Constraint 8 (22i): z^omega_ijt = 0 for t < r_j
516
+ # Equivalently: start_j >= r_j (release time)
517
+ # This is a >= constraint.
518
+ # ----------------------------------------------------------
519
+ for j_val in range(n):
520
+ if j_val not in sched[omega]:
521
+ continue
522
+ start_j = sched[omega][j_val]["start"]
523
+ rhs_val = float(r[j_val])
524
+ violation_amount = max(0.0, rhs_val - start_j)
525
+ if violation_amount > tol:
526
+ violated_constraints.add(8)
527
+ violations.append(
528
+ f"Constraint 8 (22i): Scenario {omega}, job {j_val}: "
529
+ f"start={start_j} < release time={r[j_val]}"
530
+ )
531
+ normalizer = max(abs(rhs_val), eps)
532
+ violation_magnitudes.append({
533
+ "constraint": 8,
534
+ "lhs": float(start_j),
535
+ "rhs": float(rhs_val),
536
+ "raw_excess": float(violation_amount),
537
+ "normalizer": float(normalizer),
538
+ "ratio": float(violation_amount / normalizer),
539
+ })
540
+
541
+ # ----------------------------------------------------------
542
+ # NOTE: The original two-stage stochastic program (1)-(3) uses
543
+ # CONTINUOUS start-time variables s_j. The integer start_time
544
+ # check (formerly "Constraint 9 (22j): z^omega_ijt in {0,1}")
545
+ # only applies to the time-indexed deterministic-equivalent
546
+ # reformulation (22), where z^omega_ijt binary requires starts
547
+ # to land on integer time indices. LLM-evolved algorithms that
548
+ # solve the original continuous-time problem produce valid
549
+ # non-integer starts, which this checker must accept.
550
+ # Accordingly, the integer-start check is INTENTIONALLY OMITTED.
551
+ # ----------------------------------------------------------
552
+
553
+ # ------------------------------------------------------------------
554
+ # Constraint 10 (objective consistency, full two-sided recompute):
555
+ # The reported objective_value must equal the expected makespan
556
+ # sum_{omega} pi_omega * beta_omega,
557
+ # where beta_omega = max_j finish_j in scenario omega.
558
+ # All variables required for this recompute (the per-scenario job
559
+ # finish times) are present in the solution's `schedule`, so a FULL
560
+ # recompute is possible -- no second-stage LP needs to be re-solved.
561
+ #
562
+ # The original Constraint 4 (22e) objective check above is
563
+ # ONE-SIDED: it only flags reported < computed. This Constraint 10
564
+ # check is the symmetric Tier-C defense -- it rejects ANY
565
+ # disagreement (within tolerance) between the reported objective and
566
+ # the recomputed one, in particular reported > computed, i.e.
567
+ # fabricated / inflated objective values (e.g. sys.float_info.max)
568
+ # that the structural constraint checks alone would accept.
569
+ # ------------------------------------------------------------------
570
+ if schedule is not None and objective_value is not None and S > 0:
571
+ obj_sched = {}
572
+ try:
573
+ for omega_str, jobs in schedule.items():
574
+ om = int(omega_str)
575
+ obj_sched[om] = {}
576
+ for j_str, info in jobs.items():
577
+ obj_sched[om][int(j_str)] = float(info["finish"])
578
+ except (TypeError, ValueError, KeyError):
579
+ obj_sched = None
580
+
581
+ if obj_sched is not None:
582
+ computed_obj = 0.0
583
+ all_scenarios_present = True
584
+ for om in range(S):
585
+ if om in obj_sched and obj_sched[om]:
586
+ computed_obj += pi_prob[om] * max(obj_sched[om].values())
587
+ else:
588
+ all_scenarios_present = False
589
+
590
+ if all_scenarios_present:
591
+ try:
592
+ reported = float(objective_value)
593
+ except (TypeError, ValueError):
594
+ reported = None
595
+ if reported is not None:
596
+ abs_diff = abs(reported - computed_obj)
597
+ # 0.1% relative tolerance with a 1e-3 absolute floor
598
+ obj_tol = max(1e-3, 1e-3 * abs(computed_obj))
599
+ if abs_diff > obj_tol:
600
+ violated_constraints.add(10)
601
+ violations.append(
602
+ f"Constraint 10 (objective consistency): reported "
603
+ f"objective_value={reported} differs from recomputed "
604
+ f"expected makespan sum_omega(pi_omega*beta_omega)="
605
+ f"{computed_obj:.4f} (|diff|={abs_diff:.4g}, "
606
+ f"tol={obj_tol:.4g})"
607
+ )
608
+ normalizer = max(abs(computed_obj), eps)
609
+ violation_magnitudes.append({
610
+ "constraint": 10,
611
+ "lhs": float(reported),
612
+ "rhs": float(computed_obj),
613
+ "raw_excess": float(abs_diff),
614
+ "normalizer": float(normalizer),
615
+ "ratio": float(abs_diff / normalizer),
616
+ })
617
+
618
+ # ------------------------------------------------------------------
619
+ # Build output
620
+ # ------------------------------------------------------------------
621
+ feasible = len(violated_constraints) == 0
622
+ result = {
623
+ "feasible": feasible,
624
+ "violated_constraints": sorted(violated_constraints),
625
+ "violations": violations,
626
+ "violation_magnitudes": violation_magnitudes,
627
+ }
628
+
629
+ with open(result_path, "w") as f:
630
+ json.dump(result, f, indent=2)
631
+
632
+ return result
633
+
634
+
635
+ if __name__ == "__main__":
636
+ try:
637
+ parser = argparse.ArgumentParser(
638
+ description="Feasibility checker for stochastic planning & scheduling "
639
+ "(Elci & Hooker 2020, Eq. 22)."
640
+ )
641
+ parser.add_argument(
642
+ "--instance_path", required=True,
643
+ help="Path to the JSON instance file."
644
+ )
645
+ parser.add_argument(
646
+ "--solution_path", required=True,
647
+ help="Path to the JSON solution file."
648
+ )
649
+ parser.add_argument(
650
+ "--result_path", required=True,
651
+ help="Path to write the JSON feasibility result."
652
+ )
653
+ args = parser.parse_args()
654
+
655
+ result = check_feasibility(args.instance_path, args.solution_path, args.result_path)
656
+ status = "FEASIBLE" if result["feasible"] else "INFEASIBLE"
657
+ print(f"Result: {status}")
658
+ if not result["feasible"]:
659
+ print(f"Violated constraints: {result['violated_constraints']}")
660
+ for v in result["violations"]:
661
+ print(f" - {v}")
662
+ except Exception as _frontieror_unexpected_error:
663
+ if not _frontieror_write_unexpected_rejection(
664
+ _frontieror_unexpected_error
665
+ ):
666
+ raise
tasks/elci2022/gurobi_code.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Deterministic Equivalent MILP for Stochastic Planning and Scheduling
3
+ Paper: "Stochastic Planning and Scheduling with Logic-Based Benders Decomposition"
4
+ Elci & Hooker (2020)
5
+ Model: Eq. (22) – Minimum Makespan variant
6
+
7
+ Usage:
8
+ python gurobi_code.py --instance_path instance_1.json \
9
+ --solution_path gurobi_solution_1.json \
10
+ --time_limit 3600
11
+ """
12
+
13
+ import argparse
14
+ import json
15
+ import gurobipy as gp
16
+ from gurobipy import GRB
17
+ import os as _os, sys as _sys
18
+ import time
19
+ # Walk up from this file's directory to find repo root (containing scripts/).
20
+ _GUROBI_CODE_START_TIME = time.time()
21
+ _repo = _os.path.dirname(_os.path.abspath(__file__))
22
+ while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')):
23
+ _repo = _os.path.dirname(_repo)
24
+ if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')):
25
+ _sys.path.insert(0, _repo)
26
+ try:
27
+ from scripts.utils.gurobi_log_helper import install_gurobi_logger
28
+ except ImportError:
29
+ def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable
30
+ pass
31
+
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Helpers
35
+ # ---------------------------------------------------------------------------
36
+
37
+ def compute_time_horizon(n, m, S, r, p):
38
+ """
39
+ Upper bound on the scheduling horizon.
40
+ NOT SPECIFIED IN PAPER exactly.
41
+ INFERRED ASSUMPTION: T_max = max_j(r_j) + sum_j(max_{i,omega}(p^omega_ij)).
42
+ This is a valid upper bound because even if all jobs run sequentially
43
+ starting from the latest release time, the makespan cannot exceed this value.
44
+ """
45
+ max_release = max(r)
46
+ # For each job, the largest processing time across all facilities and scenarios
47
+ max_proc_per_job = [
48
+ max(p[omega][i][j] for i in range(m) for omega in range(S))
49
+ for j in range(n)
50
+ ]
51
+ return max_release + sum(max_proc_per_job)
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Main solver
56
+ # ---------------------------------------------------------------------------
57
+
58
+ def solve(instance_path, solution_path, time_limit):
59
+ # ---- Load instance ----
60
+ with open(instance_path) as f:
61
+ inst = json.load(f)
62
+
63
+ n = inst["n"] # number of jobs
64
+ m = inst["m"] # number of facilities
65
+ S = inst["num_scenarios"]
66
+ K = inst["facility_capacity_limits"] # K[i]
67
+ c = inst["capacity_requirements"] # c[i][j]
68
+ r = inst["release_times"] # r[j]
69
+ scenarios = inst["scenarios"]
70
+ pi = [sc["probability"] for sc in scenarios]
71
+ p = [sc["processing_times"] for sc in scenarios] # p[omega][i][j]
72
+
73
+ T_max = compute_time_horizon(n, m, S, r, p)
74
+
75
+ # ---- Build model ----
76
+ model = gp.Model("DetEquivMILP")
77
+ model.setParam("Threads", 1)
78
+ model.setParam("TimeLimit", time_limit)
79
+ model.setParam("MIPFocus", 1)
80
+ model.setParam("NoRelHeurTime", min(60.0, time_limit * 0.05))
81
+
82
+ # ----------------------------------------------------------------
83
+ # Variables
84
+ # ----------------------------------------------------------------
85
+
86
+ # x[i,j] in {0,1}: 1 if job j assigned to facility i (Eq. 22d)
87
+ x = {}
88
+ for i in range(m):
89
+ for j in range(n):
90
+ x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}")
91
+
92
+ # beta[omega] >= 0: scenario-level makespan surrogate (Eq. 22a)
93
+ beta = {
94
+ omega: model.addVar(lb=0.0, name=f"beta_{omega}")
95
+ for omega in range(S)
96
+ }
97
+
98
+ # beta_iw[i,omega] >= 0: facility–scenario makespan surrogate (Eq. 22c)
99
+ beta_iw = {
100
+ (i, omega): model.addVar(lb=0.0, name=f"biw_{i}_{omega}")
101
+ for i in range(m) for omega in range(S)
102
+ }
103
+
104
+ # z[omega,i,j,t] in {0,1}: 1 if job j starts at time t on facility i, scenario omega
105
+ # Only create for valid (omega, i, j, t): r[j] <= t <= T_max - p[omega][i][j]
106
+ z = {}
107
+ for omega in range(S):
108
+ for i in range(m):
109
+ for j in range(n):
110
+ p_ij = p[omega][i][j]
111
+ t_end = T_max - p_ij
112
+ for t in range(r[j], max(r[j], t_end) + 1):
113
+ z[omega, i, j, t] = model.addVar(
114
+ vtype=GRB.BINARY, name=f"z_{omega}_{i}_{j}_{t}"
115
+ )
116
+
117
+ # ----------------------------------------------------------------
118
+ # Objective (Eq. 22a): minimize sum_omega pi_omega * beta_omega
119
+ # ----------------------------------------------------------------
120
+ model.setObjective(
121
+ gp.quicksum(pi[omega] * beta[omega] for omega in range(S)),
122
+ GRB.MINIMIZE
123
+ )
124
+
125
+ # ----------------------------------------------------------------
126
+ # Constraint (22b): each job assigned to exactly one facility
127
+ # ----------------------------------------------------------------
128
+ for j in range(n):
129
+ model.addConstr(
130
+ gp.quicksum(x[i, j] for i in range(m)) == 1,
131
+ name=f"assign_{j}"
132
+ )
133
+
134
+ # ----------------------------------------------------------------
135
+ # Constraint (22c): beta_omega >= beta_iw[i,omega]
136
+ # ----------------------------------------------------------------
137
+ for omega in range(S):
138
+ for i in range(m):
139
+ model.addConstr(
140
+ beta[omega] >= beta_iw[i, omega],
141
+ name=f"betadecomp_{omega}_{i}"
142
+ )
143
+
144
+ # ----------------------------------------------------------------
145
+ # Constraint (22e): beta_iw[i,omega] >= finish time of job j on facility i
146
+ # beta_iw[i,omega] >= sum_t (t + p_ij) * z_ijt for all i, j, omega
147
+ # Note: z_ijt = 0 when job j is NOT assigned to facility i (from constraint f),
148
+ # so this properly bounds the facility makespan.
149
+ # ----------------------------------------------------------------
150
+ for omega in range(S):
151
+ for i in range(m):
152
+ for j in range(n):
153
+ p_ij = p[omega][i][j]
154
+ valid = [
155
+ (t, z[omega, i, j, t])
156
+ for t in range(r[j], T_max - p_ij + 1)
157
+ if (omega, i, j, t) in z
158
+ ]
159
+ if valid:
160
+ model.addConstr(
161
+ beta_iw[i, omega] >= gp.quicksum(
162
+ (t + p_ij) * zv for t, zv in valid
163
+ ),
164
+ name=f"mksp_{omega}_{i}_{j}"
165
+ )
166
+
167
+ # ----------------------------------------------------------------
168
+ # Constraint (22f): z_ijt <= x_ij
169
+ # ----------------------------------------------------------------
170
+ for (omega, i, j, t), zv in z.items():
171
+ model.addConstr(zv <= x[i, j], name=f"link_{omega}_{i}_{j}_{t}")
172
+
173
+ # ----------------------------------------------------------------
174
+ # Constraint (22g): each job scheduled in exactly one (facility, time) slot
175
+ # per scenario
176
+ # ----------------------------------------------------------------
177
+ for omega in range(S):
178
+ for j in range(n):
179
+ model.addConstr(
180
+ gp.quicksum(
181
+ z[omega, i, j, t]
182
+ for i in range(m)
183
+ for t in range(r[j], T_max - p[omega][i][j] + 1)
184
+ if (omega, i, j, t) in z
185
+ ) == 1,
186
+ name=f"sched_{omega}_{j}"
187
+ )
188
+
189
+ # ----------------------------------------------------------------
190
+ # Constraint (22h): cumulative resource capacity at each time point.
191
+ #
192
+ # Paper states: T^omega_tij = {t' | 0 <= t' <= t - p^omega_ij}
193
+ # However, applying the standard cumulative constraint interpretation,
194
+ # job j (started at t') is ACTIVE at time t if t' <= t < t' + p_ij,
195
+ # i.e., t - p_ij + 1 <= t' <= t.
196
+ #
197
+ # INFERRED ASSUMPTION: We use the standard cumulative formulation where
198
+ # job j is active at time t iff its start time t' satisfies
199
+ # max(r_j, t - p_ij + 1) <= t' <= t. This is the correct formulation
200
+ # for a cumulative resource constraint and matches the CP subproblem (11).
201
+ # ----------------------------------------------------------------
202
+ for omega in range(S):
203
+ for i in range(m):
204
+ for t in range(T_max + 1):
205
+ parts = []
206
+ for j in range(n):
207
+ p_ij = p[omega][i][j]
208
+ t_lo = max(r[j], t - p_ij + 1)
209
+ t_hi = t
210
+ for t_prime in range(t_lo, t_hi + 1):
211
+ if (omega, i, j, t_prime) in z:
212
+ parts.append(c[i][j] * z[omega, i, j, t_prime])
213
+ if parts:
214
+ model.addConstr(
215
+ gp.quicksum(parts) <= K[i],
216
+ name=f"cap_{omega}_{i}_{t}"
217
+ )
218
+
219
+ # ----------------------------------------------------------------
220
+ # Solve
221
+ # ----------------------------------------------------------------
222
+ model.optimize()
223
+
224
+ # ----------------------------------------------------------------
225
+ # Extract and write solution
226
+ # ----------------------------------------------------------------
227
+ result = {
228
+ "objective_value": None,
229
+ "status": "no_solution",
230
+ }
231
+
232
+ if model.SolCount > 0:
233
+ result["objective_value"] = model.ObjVal
234
+ result["status"] = "optimal" if model.status == GRB.OPTIMAL else "time_limit"
235
+
236
+ assignment = {}
237
+ for j in range(n):
238
+ for i in range(m):
239
+ if x[i, j].X > 0.5:
240
+ assignment[str(j)] = i
241
+ result["assignment"] = assignment
242
+
243
+ schedule = {}
244
+ for omega in range(S):
245
+ schedule[str(omega)] = {}
246
+ for j in range(n):
247
+ for i in range(m):
248
+ for t in range(r[j], T_max + 1):
249
+ if (omega, i, j, t) in z and z[omega, i, j, t].X > 0.5:
250
+ schedule[str(omega)][str(j)] = {
251
+ "facility": i,
252
+ "start": t,
253
+ "finish": t + p[omega][i][j],
254
+ }
255
+ result["schedule"] = schedule
256
+
257
+ with open(solution_path, "w") as f:
258
+ result["runtime"] = time.time() - _GUROBI_CODE_START_TIME
259
+ json.dump(result, f, indent=2)
260
+
261
+ print(f"Objective value : {result['objective_value']}")
262
+ print(f"Status : {result['status']}")
263
+ return result
264
+
265
+
266
+ # ---------------------------------------------------------------------------
267
+ # Entry point
268
+ # ---------------------------------------------------------------------------
269
+
270
+ if __name__ == "__main__":
271
+ parser = argparse.ArgumentParser(
272
+ description="Solve stochastic planning & scheduling via deterministic "
273
+ "equivalent MILP (Eq. 22, Elci & Hooker 2020)."
274
+ )
275
+ parser.add_argument(
276
+ "--instance_path", required=True,
277
+ help="Path to the JSON instance file."
278
+ )
279
+ parser.add_argument(
280
+ "--solution_path", required=True,
281
+ help="Path where the solution JSON will be written."
282
+ )
283
+ parser.add_argument(
284
+ "--time_limit", type=int, required=True,
285
+ help="Maximum solver time in seconds."
286
+ )
287
+ parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions")
288
+ args = parser.parse_args()
289
+ install_gurobi_logger(args.log_path)
290
+
291
+ solve(args.instance_path, args.solution_path, args.time_limit)
tasks/elci2022/gurobi_feasi_result/large_feasi_result_1.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/elci2022/gurobi_feasi_result/large_feasi_result_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/elci2022/gurobi_feasi_result/large_feasi_result_3.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/elci2022/gurobi_feasi_result/large_feasi_result_4.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/elci2022/gurobi_feasi_result/large_feasi_result_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/elci2022/gurobi_feasi_result/tiny_feasi_result.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/elci2022/gurobi_solution/large_solution_1.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f70745cb57b7d02ed05c87aad42295f7c8516e0f5412169c3462303c16c43f8
3
+ size 40056
tasks/elci2022/gurobi_solution/large_solution_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbd8235274dba4659ae444b6419cb80741435cbe92a8fde670d6deb48d0393cc
3
+ size 40053
tasks/elci2022/gurobi_solution/large_solution_3.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:269902e0ef7a3d8f241288c9e055d86fb1be73fb3b1ce3dec439fd963b7905d5
3
+ size 40061
tasks/elci2022/gurobi_solution/large_solution_4.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4555930fc66b0fb4bd97bfd6eab5cfdcd5557e5831b8d27ed5434f34df9009ce
3
+ size 40024
tasks/elci2022/gurobi_solution/large_solution_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e010ffd21711d842287d61bfb50a96a79d4bd9890054b9f6be2c36b9e50290ba
3
+ size 40043
tasks/elci2022/gurobi_solution/tiny_solution.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea965457fce80fa668a3f42f4a6feb56909b2ef8ac26b3b5e1190077300cb1c1
3
+ size 1119
tasks/elci2022/gurobi_solution_log/large_log_1.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a93d25ea627e70f82697dd7c0f8ff951932e1872211956c637c3044703207067
3
+ size 1030
tasks/elci2022/gurobi_solution_log/large_log_2.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2deb923dd27265ff47af622924e53badc5f5dd9a94277b60708a0c5e8a70f5af
3
+ size 641
tasks/elci2022/gurobi_solution_log/large_log_3.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bda7818edcd8ab0f3ec0217c8c96338400dbf428408be0de443f2603129bbc9a
3
+ size 1283
tasks/elci2022/gurobi_solution_log/large_log_4.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de1acabe4be8094a13ce08f2492c14d487ec1273e622a320af5d36b862582c3d
3
+ size 865
tasks/elci2022/gurobi_solution_log/large_log_5.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d9ce387a5ef3f58508837ccba76c42e04826ec41e5555ca9f1c4c27f62c2b09
3
+ size 603
tasks/elci2022/gurobi_solution_log/tiny_log.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92946e707c5d1ae5135b4eb5a6685627e1be8ae41bbfb03ae1367d5bf6c6f5cb
3
+ size 83
tasks/elci2022/instance/large_instance_1.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e231d8b82dd401795c880f16ce6ec7879aea35572fa1ce1fd5e8a183ad97ccf4
3
+ size 9326
tasks/elci2022/instance/large_instance_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:059cfa17376ab67646861911c9fa2a0c7d541d58bcd20a48010f525a06bb3b5e
3
+ size 9419
tasks/elci2022/instance/large_instance_3.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:671001a8628b0b96dd08dd7bd6b3cc30c3ac470f192cfa124eb64d9c3e64a5e8
3
+ size 9017
tasks/elci2022/instance/large_instance_4.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ed0d66f7862cc6a5f0a0955860511028bccdfc9209292aee7aaefdf9814fe17
3
+ size 9253
tasks/elci2022/instance/large_instance_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1739ec2a8f6eda87083ab63cd62be3169eb89578e40906e53484a718421d2193
3
+ size 8671
tasks/elci2022/instance/tiny_instance.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b183b9a4b3bd8a148d0462bf29cf5e10dd1bbba27f99fbd7a9400510cca41799
3
+ size 1187
tasks/elci2022/instance_schema.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "n": "<int> Number of jobs to be processed.",
3
+ "m": "<int> Number of facilities available for processing jobs.",
4
+ "num_scenarios": "<int> Number of uncertain processing-time scenarios considered.",
5
+ "facility_capacity_limits": "<list[int], length m> Maximum resource capacity of each facility at any point in time.",
6
+ "capacity_requirements": "<list[list[int]], shape [m][n]> Resource consumption rate of each job when processed on each facility.",
7
+ "release_times": "<list[int], length n> Earliest time at which each job may begin processing.",
8
+ "mean_processing_times": "<list[list[int]], shape [m][n]> Nominal processing time of each job on each facility before scenario-based perturbation.",
9
+ "scenarios": [
10
+ {
11
+ "probability": "<float> Likelihood of this scenario occurring.",
12
+ "processing_times": "<list[list[int]], shape [m][n]> Realized processing time of each job on each facility under this scenario."
13
+ }
14
+ ]
15
+ }
tasks/elci2022/mathematical_formulation.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Original Formulation: Two-Stage Stochastic Planning and Scheduling
2
+
3
+ *Source: Stochastic Planning and Scheduling with Logic-Based Benders Decomposition, Özgün Elçi and J. N. Hooker, 2020/2022.*
4
+
5
+ ## Sets and Parameters
6
+
7
+ - $J$: set of jobs, indexed by $j$.
8
+
9
+ - $I$: set of facilities, indexed by $i$.
10
+
11
+ - $\Omega$: finite set of scenarios, indexed by $\omega$; $\pi_\omega \ge 0$ is the probability of scenario $\omega$, with $\sum_{\omega \in \Omega} \pi_\omega = 1$.
12
+
13
+ - $p^{\omega}_{ij}$: processing time of job $j$ on facility $i$ in scenario $\omega$.
14
+
15
+ - $r_j$: release time of job $j$.
16
+
17
+ - $d_j$: deadline of job $j$; each job must be processed within $[r_j, d_j]$.
18
+
19
+ - $c_{ij}$: resource consumption of job $j$ on facility $i$ (cumulative scheduling).
20
+
21
+ - $K_i$: maximum total resource consumption on facility $i$ at any instant.
22
+
23
+ - $g(\mathbf{x})$: first-stage cost as a function of the assignment.
24
+
25
+ - $h(\mathbf{s},\mathbf{x},\omega)$: second-stage objective.
26
+
27
+ ## Decision Variables
28
+
29
+ - **First-stage (binary)**: $x_j \in I$ for all $j \in J$, i.e. $x_j$ denotes the facility to which job $j$ is assigned. Equivalently, $x_{ij} \in \{0,1\}$ with $x_{ij} = 1$ iff job $j$ is assigned to facility $i$. For each $\mathbf{x}$, let $J_i(\mathbf{x}) = \{j \in J : x_j = i\}$ denote the set of jobs assigned to facility $i$.
30
+
31
+ - **Second-stage (continuous)**: $s_j \ge 0$ for all $j \in J$, the start time of job $j$; $s_j$ is determined after the scenario $\omega$ is revealed.
32
+
33
+ ## Objective
34
+
35
+ $$\begin{align}
36
+ \min_{\mathbf{x}} \quad & g(\mathbf{x}) + \sum_{\omega \in \Omega} \pi_\omega\, Q(\mathbf{x}, \omega)
37
+ \;:\; x_j \in I,\ \forall j \in J, \tag{3}
38
+ \end{align}$$ where the second-stage value is $$\begin{align}
39
+ Q(\mathbf{x}, \omega) = \min_{\mathbf{s}} \quad & h(\mathbf{s}, \mathbf{x}, \omega) \tag{2}
40
+ \end{align}$$ *(With (1): $\min_{\mathbf{x}\in X}\{f(\mathbf{x}) + \mathbb{E}_{\omega}[Q(\mathbf{x},\omega)]\}$.)*
41
+
42
+ ## Constraints of the Second Stage (for each scenario $\omega \in \Omega$)
43
+
44
+ $$\begin{align}
45
+ s_j \in [\, r_j,\; d_j - p^{\omega}_{x_j,j} \,],
46
+ & \quad \forall j \in J, \tag{TW}\\
47
+ \sum_{\substack{j \in J_i(\mathbf{x}) \\ 0 \le t \le s_j + p^{\omega}_{x_j,j}}} c_{ij} \le K_i,
48
+ & \quad \forall i \in I,\; \forall t \ge 0. \tag{CUM}
49
+ \end{align}$$ Here (TW) are the time-window constraints ensuring each job finishes before its deadline under its (scenario-dependent) processing time. The cumulative resource constraint (CUM) states that, at every point in time $t$, the total resource consumption of jobs being processed on facility $i$ must not exceed $K_i$. Each assignment $\mathbf{x}$ induces, for every $(\omega, i)$, a cumulative scheduling problem over the jobs in $J_i(\mathbf{x})$ with continuous start-time variables $s_j$.
50
+
51
+ ## First-Stage Constraints
52
+
53
+ $$\begin{align}
54
+ \sum_{i \in I} x_{ij} &= 1, & \forall j \in J, \notag\\
55
+ x_{ij} &\in \{0,1\}, & \forall i \in I,\; j \in J. \notag
56
+ \end{align}$$
tasks/elci2022/problem_description.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Problem Description
2
+
3
+ A company operates a set of facilities and must process a set of jobs under uncertainty. Processing times are uncertain and modeled through a finite set of scenarios, each with a known probability. The input data specifies, for each facility, a resource capacity limit. For each combination of job and facility, the data provides a resource consumption rate and a scenario-dependent processing time. Each job also has a release time before which it cannot begin processing. Jobs have no deadlines.
4
+
5
+ The company must make two types of decisions. First, before the uncertain processing times are revealed, each job must be assigned to exactly one facility. Second, after a scenario is realized, the jobs assigned to each facility must be scheduled by choosing a start time for each job. A job's start time must be no earlier than its release time. Multiple jobs may run simultaneously on the same facility, but at every point in time the total resource consumption of all jobs whose processing intervals overlap that time point must not exceed the facility's resource capacity. Specifically, a job assigned to a given facility occupies resources from its start time until its start time plus its processing time on that facility under the realized scenario, and during this entire interval the job's resource consumption counts toward the facility's capacity limit.
6
+
7
+ The goal is to minimize the expected makespan across all scenarios. The makespan under a given scenario is the latest completion time among all jobs, where a job's completion time equals its start time plus its processing time on its assigned facility under that scenario. The expected makespan is the probability-weighted sum of the scenario makespans. There is no first-stage assignment cost, so the entire objective consists of this expected makespan.
tasks/elci2022/solution_logger.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convergence logger for optimization algorithms.
3
+
4
+ Records incumbent solutions with timestamps to a JSONL file.
5
+ This module is provided to LLM-generated programs — they only need to call
6
+ `log(objective_value)` whenever a better feasible solution is found.
7
+
8
+ Usage in generated code:
9
+ from solution_logger import SolutionLogger
10
+ logger = SolutionLogger(log_path, sense="minimize") # or "maximize"
11
+ # ... inside algorithm loop:
12
+ logger.log(objective_value)
13
+ """
14
+
15
+ import json
16
+ import time
17
+
18
+
19
+ class SolutionLogger:
20
+ def __init__(self, log_path, sense="minimize"):
21
+ """
22
+ Args:
23
+ log_path: Path to the JSONL output file.
24
+ sense: "minimize" or "maximize".
25
+ """
26
+ self.log_path = log_path
27
+ self.sense = sense
28
+ self.start_time = time.time()
29
+ self.best_obj = None
30
+ self.min_interval = 0.1 # seconds, avoid excessive writes
31
+
32
+ self._last_log_time = 0.0
33
+ # Clear the file
34
+ with open(self.log_path, "w") as f:
35
+ pass
36
+
37
+ def log(self, objective_value):
38
+ """Record a new incumbent if it improves on the best known."""
39
+ if objective_value is None:
40
+ return
41
+
42
+ # Check if this is an improvement
43
+ if self.best_obj is not None:
44
+ if self.sense == "minimize" and objective_value >= self.best_obj:
45
+ return
46
+ if self.sense == "maximize" and objective_value <= self.best_obj:
47
+ return
48
+
49
+ elapsed = time.time() - self.start_time
50
+
51
+ # Throttle writes
52
+ if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval:
53
+ self.best_obj = objective_value
54
+ return
55
+
56
+ self.best_obj = objective_value
57
+ self._last_log_time = elapsed
58
+
59
+ with open(self.log_path, "a") as f:
60
+ f.write(json.dumps({"time": round(elapsed, 3),
61
+ "objective_value": objective_value}) + "\n")
tasks/elci2022/solution_schema.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "objective_value": "<float> Expected makespan across all scenarios, weighted by scenario probabilities.",
3
+ "assignment": "<dict, key: '{job}'> Facility to which each job is assigned before uncertainty is revealed.",
4
+ "schedule": {
5
+ "{scenario}": {
6
+ "{job}": {
7
+ "facility": "<int> Facility on which this job is processed in this scenario.",
8
+ "start": "<int> Time at which this job begins processing in this scenario.",
9
+ "finish": "<int> Time at which this job completes processing in this scenario."
10
+ }
11
+ }
12
+ }
13
+ }
tasks/engineer2012/feasibility_check.py ADDED
@@ -0,0 +1,963 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Feasibility Checker for Single-Product Maritime Inventory Routing.
4
+
5
+ Checks hard constraints from the mathematical formulation in Engineer et al. (2012):
6
+ "A Branch-Price-and-Cut Algorithm for Single-Product Maritime Inventory Routing"
7
+
8
+ Constraints checked (numbered as in the paper formulation):
9
+ (1) Inventory balance at supply ports
10
+ (2) Inventory balance at demand ports
11
+ (3) Storage capacity bounds: 0 <= I_{j,t} <= Q_{j,t}
12
+ (4) Convexity: each vessel executes exactly one voyage (sum lambda = 1)
13
+ (5) Non-negativity: lambda >= 0
14
+ (6) Integrality of load/discharge decisions (z in {0,1})
15
+ (7) Flow conservation (path from source to sink)
16
+ (8) Load/discharge only if node is visited
17
+ (9) Load/discharge quantity bounds: F_min * z <= |f| <= F_max * z
18
+ (10) Vessel inventory tracking along path
19
+ (11) Vessel inventory capacity: 0 <= F_n <= U_n
20
+ (12) Arc integrality
21
+ (13) Load/discharge decision integrality (z in {0,1})
22
+
23
+ Usage:
24
+ python feasibility_check.py --instance_path instance_1.json \
25
+ --solution_path efficient_solution_1.json \
26
+ --result_path efficient_feasi_result_1.json
27
+ """
28
+
29
+ import argparse
30
+ import ast
31
+ import json
32
+ import math
33
+ import sys
34
+ from collections import defaultdict
35
+
36
+ # FRONTIEROR_RELEASE_CONTRACT_V2
37
+ _FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('cost_breakdown', 'objective_value', 'port_inventories', 'vessel_operations', 'vessel_routes')
38
+ _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('cost_breakdown', 'objective_value', 'port_inventories', 'vessel_routes')
39
+ _FRONTIEROR_DERIVED_FIELD_RULES = ()
40
+ _FRONTIEROR_CONDITIONAL_FIELD_RULES = ()
41
+
42
+
43
+ def _frontieror_validate_solution_contract(solution):
44
+ """Return a structured rejection when the public solution contract is absent."""
45
+ violations = []
46
+ if not isinstance(solution, dict):
47
+ violations.append("solution must be a JSON object")
48
+ else:
49
+ missing = [
50
+ field
51
+ for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS
52
+ if field not in solution or solution[field] is None
53
+ ]
54
+ if missing:
55
+ violations.append(
56
+ "missing required solution field(s): " + ", ".join(missing)
57
+ )
58
+
59
+ for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES:
60
+ if solution.get(discriminator) != expected_value:
61
+ continue
62
+ conditional_missing = [
63
+ field
64
+ for field in fields
65
+ if field not in solution or solution[field] is None
66
+ ]
67
+ if conditional_missing:
68
+ violations.append(
69
+ "missing conditionally required solution field(s): "
70
+ + ", ".join(conditional_missing)
71
+ )
72
+
73
+ empty = [
74
+ field
75
+ for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS
76
+ if field in solution and solution[field] in (None, [], {})
77
+ ]
78
+ if empty:
79
+ violations.append(
80
+ "empty required decision witness field(s): " + ", ".join(empty)
81
+ )
82
+
83
+ for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES:
84
+ try:
85
+ if operation == "assignment_key_set":
86
+ reported_set = set(solution[target])
87
+ expected_set = {entry[source_key] for entry in solution[source]}
88
+ if reported_set != expected_set:
89
+ violations.append(
90
+ f"{target}={sorted(reported_set)} does not match the "
91
+ f"decision-derived value {sorted(expected_set)}"
92
+ )
93
+ continue
94
+
95
+ reported = float(solution[target])
96
+ if operation == "length":
97
+ expected = float(len(solution[source]))
98
+ elif operation == "mapping_value":
99
+ expected = float(solution[source][source_key])
100
+ else:
101
+ raise ValueError("unknown derived-field operation")
102
+ except (KeyError, TypeError, ValueError, OverflowError):
103
+ violations.append(
104
+ f"cannot derive {target} from decision witness field {source}"
105
+ )
106
+ continue
107
+ if (
108
+ reported != reported
109
+ or expected != expected
110
+ or reported in (float("inf"), float("-inf"))
111
+ or expected in (float("inf"), float("-inf"))
112
+ or abs(reported - expected) > 1e-6
113
+ ):
114
+ violations.append(
115
+ f"{target}={reported} does not match the decision-derived "
116
+ f"value {expected}"
117
+ )
118
+
119
+ if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS:
120
+ objective = solution.get("objective_value")
121
+ if (
122
+ isinstance(objective, bool)
123
+ or not isinstance(objective, (int, float))
124
+ or objective != objective
125
+ or objective in (float("inf"), float("-inf"))
126
+ ):
127
+ violations.append("objective_value must be a finite JSON number")
128
+
129
+ if not violations:
130
+ return None
131
+ return {
132
+ "feasible": False,
133
+ "violated_constraints": ["solution_schema"],
134
+ "violations": violations,
135
+ "violation_magnitudes": [],
136
+ }
137
+
138
+
139
+ def _frontieror_write_unexpected_rejection(error):
140
+ """Turn malformed candidate/checker exceptions into a normal rejection."""
141
+ import json as _frontieror_json
142
+ import sys as _frontieror_sys
143
+
144
+ result_path = None
145
+ for index, argument in enumerate(_frontieror_sys.argv):
146
+ if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv):
147
+ result_path = _frontieror_sys.argv[index + 1]
148
+ break
149
+ if argument.startswith("--result_path="):
150
+ result_path = argument.split("=", 1)[1]
151
+ break
152
+ if not result_path:
153
+ return False
154
+ try:
155
+ with open(result_path, "w") as result_handle:
156
+ _frontieror_json.dump(
157
+ {
158
+ "feasible": False,
159
+ "violated_constraints": ["malformed_solution"],
160
+ "violations": [
161
+ "checker rejected malformed candidate: "
162
+ + type(error).__name__
163
+ + ": "
164
+ + str(error)[:500]
165
+ ],
166
+ "violation_magnitudes": [],
167
+ },
168
+ result_handle,
169
+ indent=2,
170
+ )
171
+ except Exception:
172
+ return False
173
+ return True
174
+
175
+
176
+
177
+ def load_json(path):
178
+ with open(path, 'r') as f:
179
+ return json.load(f)
180
+
181
+
182
+ def parse_instance(data):
183
+ """Parse instance data into a structured format."""
184
+ T = data["planning_horizon"]
185
+ vessels = {}
186
+ for v in data["vessels"]:
187
+ vessels[v["id"]] = {
188
+ "id": v["id"],
189
+ "capacity": v["capacity"],
190
+ "avail_start": v["availability_start"],
191
+ "avail_end": v["availability_end"],
192
+ "initial_load": v.get("initial_load", 0),
193
+ "transport_cost_per_day": v["transport_cost_per_day"],
194
+ "demurrage_cost_per_day": v["demurrage_cost_per_day"],
195
+ }
196
+
197
+ supply_ports = {}
198
+ for sp in data["supply_ports"]:
199
+ supply_ports[sp["port_id"]] = {
200
+ "port_id": sp["port_id"],
201
+ "type": "supply",
202
+ "initial_inventory": sp["initial_inventory"],
203
+ "rates": sp["production_rate"],
204
+ "storage_capacity": sp["storage_capacity"],
205
+ "F_min": sp["F_min"],
206
+ "F_max": sp["F_max"],
207
+ "unit_cost": sp["unit_procurement_cost"],
208
+ }
209
+
210
+ demand_ports = {}
211
+ for dp in data["demand_ports"]:
212
+ demand_ports[dp["port_id"]] = {
213
+ "port_id": dp["port_id"],
214
+ "type": "demand",
215
+ "initial_inventory": dp["initial_inventory"],
216
+ "rates": dp["consumption_rate"],
217
+ "storage_capacity": dp["storage_capacity"],
218
+ "F_min": dp["F_min"],
219
+ "F_max": dp["F_max"],
220
+ "unit_cost": dp["unit_supply_revenue"],
221
+ }
222
+
223
+ travel_times = {}
224
+ for key, val in data["travel_times"].items():
225
+ a, b = key.split("->")
226
+ travel_times[(a, b)] = val
227
+
228
+ draft_limits = {}
229
+ for key, val in data.get("draft_limits", {}).items():
230
+ a, b = key.split("->")
231
+ draft_limits[(a, b)] = val
232
+
233
+ return T, vessels, supply_ports, demand_ports, travel_times, draft_limits
234
+
235
+
236
+ def parse_solution(sol_data, vessels_info):
237
+ """Parse the serialized operation witness for every vessel."""
238
+ vessel_visits = {}
239
+ operations = sol_data["vessel_operations"]
240
+ for vid in vessels_info:
241
+ visits = []
242
+ for op in operations.get(vid, []):
243
+ visits.append({
244
+ "port": op["port"],
245
+ "time": int(op["time"]),
246
+ "load_discharge": float(op["quantity"]),
247
+ "type": op["type"],
248
+ })
249
+ visits.sort(key=lambda visit: visit["time"])
250
+ vessel_visits[vid] = visits
251
+ return vessel_visits
252
+
253
+
254
+ def parse_route_node(serialized):
255
+ """Parse the tuple representation emitted by gurobi_code.py."""
256
+ node = ast.literal_eval(serialized)
257
+ if not isinstance(node, tuple) or len(node) != 2:
258
+ raise ValueError(f"invalid route node {serialized!r}")
259
+ return node
260
+
261
+
262
+ def check_feasibility(instance_data, solution_data):
263
+ """Check all hard constraints and return violations."""
264
+ tol = 1e-5
265
+ eps = 1e-5
266
+
267
+ T, vessels, supply_ports, demand_ports, travel_times, draft_limits = \
268
+ parse_instance(instance_data)
269
+
270
+ vessel_visits = parse_solution(solution_data, vessels)
271
+
272
+ all_ports = {}
273
+ all_ports.update(supply_ports)
274
+ all_ports.update(demand_ports)
275
+
276
+ violations = []
277
+ violation_magnitudes = []
278
+
279
+ def add_violation(constraint_idx, message, lhs, rhs, violation_amount):
280
+ normalizer = max(abs(rhs), eps)
281
+ ratio = violation_amount / normalizer
282
+ violations.append((constraint_idx, message))
283
+ violation_magnitudes.append({
284
+ "constraint": constraint_idx,
285
+ "lhs": lhs,
286
+ "rhs": rhs,
287
+ "raw_excess": violation_amount,
288
+ "normalizer": normalizer,
289
+ "ratio": ratio,
290
+ })
291
+
292
+ # =====================================================================
293
+ # Constraints (7), (8), (10), and (12): validate the complete serialized
294
+ # source-to-sink path, arc timing, operation support, and commodity flow.
295
+ # Route entries are unordered in the JSON, so first reconstruct the path.
296
+ # =====================================================================
297
+ expected_vessels = set(vessels)
298
+ route_witness = solution_data["vessel_routes"]
299
+ operation_witness = solution_data["vessel_operations"]
300
+ if set(route_witness) != expected_vessels:
301
+ add_violation(
302
+ 7,
303
+ "vessel_routes keys do not exactly cover the instance vessels",
304
+ float(len(route_witness)), float(len(expected_vessels)), 1.0,
305
+ )
306
+ if set(operation_witness) != expected_vessels:
307
+ add_violation(
308
+ 8,
309
+ "vessel_operations keys do not exactly cover the instance vessels",
310
+ float(len(operation_witness)), float(len(expected_vessels)), 1.0,
311
+ )
312
+
313
+ transport_cost = 0.0
314
+ demurrage_cost = 0.0
315
+ for vid, vessel in vessels.items():
316
+ source = ("src", vid)
317
+ sink = ("snk", vid)
318
+ serialized_arcs = route_witness.get(vid, [])
319
+ parsed_arcs = []
320
+ route_nodes = set()
321
+
322
+ for arc_position, arc in enumerate(serialized_arcs):
323
+ try:
324
+ tail = parse_route_node(arc["tail"])
325
+ head = parse_route_node(arc["head"])
326
+ arc_type = arc["type"]
327
+ reported_cost = float(arc["cost"])
328
+ product_flow = float(arc["product_flow"])
329
+ if not all(math.isfinite(value) for value in
330
+ (reported_cost, product_flow)):
331
+ raise ValueError("arc cost/product_flow is not finite")
332
+ except (KeyError, TypeError, ValueError, SyntaxError) as error:
333
+ add_violation(
334
+ 12,
335
+ f"Vessel {vid} route arc {arc_position} is malformed: {error}",
336
+ 1.0, 0.0, 1.0,
337
+ )
338
+ continue
339
+
340
+ def is_port_time(node):
341
+ return (
342
+ node[0] in all_ports
343
+ and isinstance(node[1], int)
344
+ and not isinstance(node[1], bool)
345
+ and vessel["avail_start"] <= node[1] <= vessel["avail_end"]
346
+ )
347
+
348
+ canonical_cost = None
349
+ valid_arc = True
350
+ if arc_type == "source":
351
+ valid_arc = (
352
+ tail == source
353
+ and is_port_time(head)
354
+ and head[1] == vessel["avail_start"]
355
+ )
356
+ canonical_cost = 0.0
357
+ elif arc_type == "sink":
358
+ valid_arc = is_port_time(tail) and head == sink
359
+ canonical_cost = 0.0
360
+ elif arc_type == "demurrage":
361
+ valid_arc = (
362
+ is_port_time(tail)
363
+ and is_port_time(head)
364
+ and tail[0] == head[0]
365
+ and head[1] == tail[1] + 1
366
+ )
367
+ canonical_cost = float(vessel["demurrage_cost_per_day"])
368
+ elif arc_type == "travel":
369
+ travel_time = travel_times.get((tail[0], head[0]))
370
+ valid_arc = (
371
+ is_port_time(tail)
372
+ and is_port_time(head)
373
+ and tail[0] != head[0]
374
+ and travel_time is not None
375
+ and head[1] == tail[1] + travel_time
376
+ )
377
+ if travel_time is not None:
378
+ canonical_cost = (
379
+ float(vessel["transport_cost_per_day"])
380
+ * float(travel_time)
381
+ )
382
+ else:
383
+ valid_arc = False
384
+
385
+ if not valid_arc or canonical_cost is None:
386
+ add_violation(
387
+ 7,
388
+ f"Vessel {vid} contains an invalid {arc_type!r} arc "
389
+ f"{tail!r} -> {head!r}",
390
+ 1.0, 0.0, 1.0,
391
+ )
392
+ continue
393
+ if abs(reported_cost - canonical_cost) > tol:
394
+ add_violation(
395
+ 7,
396
+ f"Vessel {vid} arc {tail!r}->{head!r} reports cost "
397
+ f"{reported_cost}, expected {canonical_cost}",
398
+ reported_cost, canonical_cost,
399
+ abs(reported_cost - canonical_cost),
400
+ )
401
+ if product_flow < -tol:
402
+ add_violation(
403
+ 10,
404
+ f"Vessel {vid} has negative product flow on "
405
+ f"{tail!r}->{head!r}",
406
+ product_flow, 0.0, -product_flow,
407
+ )
408
+
409
+ endpoint_limits = []
410
+ for node in (tail, head):
411
+ if is_port_time(node):
412
+ endpoint_limits.append(min(
413
+ vessel["capacity"],
414
+ draft_limits.get((vid, node[0]), vessel["capacity"]),
415
+ ))
416
+ flow_limit = min(endpoint_limits, default=vessel["capacity"])
417
+ if product_flow > flow_limit + tol:
418
+ add_violation(
419
+ 11,
420
+ f"Vessel {vid} product flow {product_flow} exceeds arc "
421
+ f"capacity {flow_limit} on {tail!r}->{head!r}",
422
+ product_flow, flow_limit, product_flow - flow_limit,
423
+ )
424
+
425
+ parsed_arcs.append({
426
+ "tail": tail,
427
+ "head": head,
428
+ "type": arc_type,
429
+ "flow": product_flow,
430
+ })
431
+ route_nodes.update((tail, head))
432
+ if arc_type == "travel":
433
+ transport_cost += canonical_cost
434
+ elif arc_type == "demurrage":
435
+ demurrage_cost += canonical_cost
436
+
437
+ outgoing = defaultdict(list)
438
+ incoming = defaultdict(list)
439
+ for arc in parsed_arcs:
440
+ outgoing[arc["tail"]].append(arc)
441
+ incoming[arc["head"]].append(arc)
442
+ structural_error = False
443
+ for node in route_nodes | {source, sink}:
444
+ expected_in = 0 if node == source else 1
445
+ expected_out = 0 if node == sink else 1
446
+ if len(incoming[node]) != expected_in or len(outgoing[node]) != expected_out:
447
+ structural_error = True
448
+ add_violation(
449
+ 7,
450
+ f"Vessel {vid} route degree is invalid at {node!r}: "
451
+ f"in={len(incoming[node])}, out={len(outgoing[node])}",
452
+ float(len(incoming[node]) + len(outgoing[node])),
453
+ float(expected_in + expected_out), 1.0,
454
+ )
455
+
456
+ if not structural_error:
457
+ traversed = []
458
+ current = source
459
+ while current != sink and len(traversed) <= len(parsed_arcs):
460
+ arc = outgoing[current][0]
461
+ traversed.append(arc)
462
+ current = arc["head"]
463
+ if current != sink or len(traversed) != len(parsed_arcs):
464
+ add_violation(
465
+ 7,
466
+ f"Vessel {vid} selected arcs do not form one complete "
467
+ "source-to-sink path",
468
+ float(len(traversed)), float(len(parsed_arcs)), 1.0,
469
+ )
470
+
471
+ operation_by_node = {}
472
+ for visit in vessel_visits[vid]:
473
+ node = (visit["port"], visit["time"])
474
+ if node in operation_by_node:
475
+ continue # Constraint 6 records the duplicate below.
476
+ operation_by_node[node] = visit["load_discharge"]
477
+ expected_type = (
478
+ "load" if visit["port"] in supply_ports else "discharge"
479
+ )
480
+ if visit["type"] != expected_type:
481
+ add_violation(
482
+ 8,
483
+ f"Vessel {vid} operation at {node!r} has type "
484
+ f"{visit['type']!r}, expected {expected_type!r}",
485
+ 1.0, 0.0, 1.0,
486
+ )
487
+ if node not in outgoing:
488
+ add_violation(
489
+ 8,
490
+ f"Vessel {vid} operation at {node!r} is not supported by "
491
+ "a selected route visit",
492
+ 1.0, 0.0, 1.0,
493
+ )
494
+
495
+ if len(outgoing[source]) == 1:
496
+ source_flow = outgoing[source][0]["flow"]
497
+ if abs(source_flow - vessel["initial_load"]) > tol:
498
+ add_violation(
499
+ 10,
500
+ f"Vessel {vid} source flow {source_flow} does not match "
501
+ f"initial load {vessel['initial_load']}",
502
+ source_flow, vessel["initial_load"],
503
+ abs(source_flow - vessel["initial_load"]),
504
+ )
505
+ for node in route_nodes - {source, sink}:
506
+ if len(incoming[node]) != 1 or len(outgoing[node]) != 1:
507
+ continue
508
+ incoming_flow = incoming[node][0]["flow"]
509
+ outgoing_flow = outgoing[node][0]["flow"]
510
+ operation = operation_by_node.get(node, 0.0)
511
+ flow_difference = abs(incoming_flow + operation - outgoing_flow)
512
+ if flow_difference > 1e-3:
513
+ add_violation(
514
+ 10,
515
+ f"Vessel {vid} commodity flow is inconsistent at "
516
+ f"{node!r}: incoming {incoming_flow} + operation "
517
+ f"{operation} != outgoing {outgoing_flow}",
518
+ incoming_flow + operation, outgoing_flow, flow_difference,
519
+ )
520
+
521
+ # =====================================================================
522
+ # Compute net load/discharge at each (port, time) across all vessels
523
+ # f_total[port_id][t] = sum over vessels of f_{j,t}^{v,r}
524
+ # For supply ports: f > 0 means loading (removing from port inventory)
525
+ # For demand ports: f < 0 means discharging (adding to port inventory)
526
+ # In the model: I_{j,t} = I_{j,t-1} + b_{j,t} - sum_v f_{j,t}
527
+ # =====================================================================
528
+ f_total = defaultdict(lambda: defaultdict(float))
529
+ for vid, visits in vessel_visits.items():
530
+ for visit in visits:
531
+ f_total[visit["port"]][visit["time"]] += visit["load_discharge"]
532
+
533
+ # =====================================================================
534
+ # Compute port inventories
535
+ # =====================================================================
536
+ port_inventory = {} # port_inventory[port_id][t] for t=0..T
537
+ for pid, port in all_ports.items():
538
+ inv = [0.0] * (T + 1)
539
+ inv[0] = port["initial_inventory"]
540
+ for t in range(1, T + 1):
541
+ if port["type"] == "supply":
542
+ # Constraint (1): I_{j,t} = I_{j,t-1} + b_{j,t} - sum_v f_{j,t}
543
+ inv[t] = inv[t - 1] + port["rates"][t - 1] - f_total[pid][t]
544
+ else:
545
+ # Constraint (2): I_{j,t} = I_{j,t-1} - b_{j,t} - sum_v f_{j,t}
546
+ # For demand: f < 0 for discharge, so -f > 0 adds to inventory
547
+ inv[t] = inv[t - 1] - port["rates"][t - 1] - f_total[pid][t]
548
+ port_inventory[pid] = inv
549
+
550
+ # The reported inventory trajectory is a derived witness and must cover
551
+ # every port/time exactly; otherwise a candidate could alter operations
552
+ # while leaving an unrelated inventory summary in the JSON.
553
+ reported_inventories = solution_data["port_inventories"]
554
+ if set(reported_inventories) != set(all_ports):
555
+ add_violation(
556
+ 1,
557
+ "port_inventories keys do not exactly cover all instance ports",
558
+ float(len(reported_inventories)), float(len(all_ports)), 1.0,
559
+ )
560
+ for pid in all_ports:
561
+ entries = reported_inventories.get(pid, [])
562
+ by_time = {}
563
+ for entry in entries:
564
+ time_value = int(entry["time"])
565
+ if time_value in by_time:
566
+ add_violation(
567
+ 1,
568
+ f"Port {pid} reports inventory twice at t={time_value}",
569
+ 2.0, 1.0, 1.0,
570
+ )
571
+ by_time[time_value] = float(entry["inventory"])
572
+ expected_times = set(range(1, T + 1))
573
+ if set(by_time) != expected_times:
574
+ add_violation(
575
+ 1,
576
+ f"Port {pid} inventory times do not exactly cover 1..{T}",
577
+ float(len(by_time)), float(T), 1.0,
578
+ )
579
+ for time_value in expected_times & set(by_time):
580
+ difference = abs(
581
+ by_time[time_value] - port_inventory[pid][time_value]
582
+ )
583
+ if difference > 1e-3:
584
+ add_violation(
585
+ 1,
586
+ f"Port {pid} reported inventory {by_time[time_value]} at "
587
+ f"t={time_value}, expected {port_inventory[pid][time_value]}",
588
+ by_time[time_value], port_inventory[pid][time_value],
589
+ difference,
590
+ )
591
+
592
+ # =====================================================================
593
+ # Constraint (1): Inventory balance at supply ports
594
+ # I_{j,t} = I_{j,t-1} + b_{j,t} - sum_v f_{j,t}
595
+ # This is an equality constraint. We check it by verifying the computed
596
+ # inventory is consistent (it's computed directly, so the balance holds
597
+ # by construction). The real check is whether the inventory stays within
598
+ # bounds (Constraint 3). However, we still verify the balance equation
599
+ # holds as an equality for supply ports.
600
+ # =====================================================================
601
+ for pid, port in supply_ports.items():
602
+ for t in range(1, T + 1):
603
+ I_prev = port_inventory[pid][t - 1]
604
+ b_jt = port["rates"][t - 1]
605
+ f_sum = f_total[pid][t]
606
+ lhs = port_inventory[pid][t]
607
+ rhs_val = I_prev + b_jt - f_sum
608
+ diff = abs(lhs - rhs_val)
609
+ if diff > tol:
610
+ add_violation(
611
+ 1,
612
+ f"Supply port {pid} inventory balance violated at t={t}: "
613
+ f"I[t]={lhs:.4f} != I[t-1]+b-f = {rhs_val:.4f}",
614
+ lhs, rhs_val, diff
615
+ )
616
+
617
+ # =====================================================================
618
+ # Constraint (2): Inventory balance at demand ports
619
+ # I_{j,t} = I_{j,t-1} - b_{j,t} - sum_v f_{j,t}
620
+ # =====================================================================
621
+ for pid, port in demand_ports.items():
622
+ for t in range(1, T + 1):
623
+ I_prev = port_inventory[pid][t - 1]
624
+ b_jt = port["rates"][t - 1]
625
+ f_sum = f_total[pid][t]
626
+ lhs = port_inventory[pid][t]
627
+ rhs_val = I_prev - b_jt - f_sum
628
+ diff = abs(lhs - rhs_val)
629
+ if diff > tol:
630
+ add_violation(
631
+ 2,
632
+ f"Demand port {pid} inventory balance violated at t={t}: "
633
+ f"I[t]={lhs:.4f} != I[t-1]-b-f = {rhs_val:.4f}",
634
+ lhs, rhs_val, diff
635
+ )
636
+
637
+ # =====================================================================
638
+ # Constraint (3): Storage capacity bounds: 0 <= I_{j,t} <= Q_{j,t}
639
+ # This is two inequalities: I_{j,t} >= 0 and I_{j,t} <= Q_{j,t}
640
+ # =====================================================================
641
+ for pid, port in all_ports.items():
642
+ for t in range(1, T + 1):
643
+ inv = port_inventory[pid][t]
644
+ Q_jt = port["storage_capacity"][t - 1]
645
+
646
+ # Lower bound: I_{j,t} >= 0 => LHS = -I_{j,t}, RHS = 0 (<=)
647
+ # Or equivalently: 0 <= I_{j,t}, violation if I_{j,t} < 0
648
+ if inv < -tol:
649
+ violation_amount = -inv # how much below 0
650
+ add_violation(
651
+ 3,
652
+ f"Port {pid} inventory below 0 at t={t}: "
653
+ f"I={inv:.4f} < 0",
654
+ inv, 0.0, violation_amount
655
+ )
656
+
657
+ # Upper bound: I_{j,t} <= Q_{j,t}
658
+ if inv > Q_jt + tol:
659
+ violation_amount = inv - Q_jt
660
+ add_violation(
661
+ 3,
662
+ f"Port {pid} inventory exceeds capacity at t={t}: "
663
+ f"I={inv:.4f} > Q={Q_jt:.4f}",
664
+ inv, Q_jt, violation_amount
665
+ )
666
+
667
+ # =====================================================================
668
+ # Constraint (4): Convexity - each vessel has exactly one voyage
669
+ # sum_{r in R_v} lambda^{v,r} = 1
670
+ # In the realized solution, each vessel has exactly one schedule.
671
+ # This is satisfied by construction since the solution specifies
672
+ # one schedule per vessel. We just verify each vessel is present.
673
+ # =====================================================================
674
+ for vid in vessels:
675
+ # Each vessel should appear in the solution (even if idle)
676
+ if vid not in vessel_visits:
677
+ add_violation(
678
+ 4,
679
+ f"Vessel {vid} has no voyage assigned (convexity constraint)",
680
+ 0.0, 1.0, 1.0
681
+ )
682
+
683
+ # =====================================================================
684
+ # Constraint (5): Non-negativity: lambda >= 0
685
+ # Trivially satisfied since the solution represents a realized (integral)
686
+ # voyage selection with lambda = 1 for the chosen voyage.
687
+ # No check needed.
688
+ # =====================================================================
689
+
690
+ # =====================================================================
691
+ # Constraint (6): Integrality on load/discharge decisions
692
+ # sum_r z_{j,t}^{v,r} lambda^{v,r} in {0,1}
693
+ # In realized solution, each vessel visits each (port, time) at most once.
694
+ # Check: no vessel visits the same (port, time) more than once.
695
+ # =====================================================================
696
+ for vid, visits in vessel_visits.items():
697
+ pt_count = defaultdict(int)
698
+ for visit in visits:
699
+ key = (visit["port"], visit["time"])
700
+ pt_count[key] += 1
701
+ for (port, time), count in pt_count.items():
702
+ if count > 1:
703
+ add_violation(
704
+ 6,
705
+ f"Vessel {vid} visits ({port}, t={time}) {count} times "
706
+ f"(integrality requires at most 1)",
707
+ float(count), 1.0, float(count - 1)
708
+ )
709
+
710
+ # =====================================================================
711
+ # Constraint (9): Load/discharge quantity bounds
712
+ # F_n^{min} * z_n <= f_n <= F_n^{max} * z_n
713
+ # For supply: F_min <= f <= F_max (f > 0 for loading)
714
+ # For demand: -F_max <= f <= -F_min (f < 0 for discharging)
715
+ # So |f| must be in [F_min, F_max] when the port is visited (z=1)
716
+ # =====================================================================
717
+ for vid, visits in vessel_visits.items():
718
+ for visit in visits:
719
+ pid = visit["port"]
720
+ t = visit["time"]
721
+ f_val = visit["load_discharge"]
722
+ port = all_ports[pid]
723
+ F_min = port["F_min"]
724
+ F_max = port["F_max"]
725
+ abs_f = abs(f_val)
726
+
727
+ if port["type"] == "supply":
728
+ # f >= F_min when visiting
729
+ if f_val < F_min - tol:
730
+ violation_amount = F_min - f_val
731
+ add_violation(
732
+ 9,
733
+ f"Vessel {vid} at supply port {pid} t={t}: "
734
+ f"load={f_val:.4f} < F_min={F_min}",
735
+ f_val, F_min, violation_amount
736
+ )
737
+ # f <= F_max when visiting
738
+ if f_val > F_max + tol:
739
+ violation_amount = f_val - F_max
740
+ add_violation(
741
+ 9,
742
+ f"Vessel {vid} at supply port {pid} t={t}: "
743
+ f"load={f_val:.4f} > F_max={F_max}",
744
+ f_val, F_max, violation_amount
745
+ )
746
+ else:
747
+ # Demand port: f <= 0, |f| >= F_min, |f| <= F_max
748
+ if f_val > tol:
749
+ violation_amount = f_val
750
+ add_violation(
751
+ 9,
752
+ f"Vessel {vid} at demand port {pid} t={t}: "
753
+ f"load_discharge={f_val:.4f} > 0 (should be <= 0)",
754
+ f_val, 0.0, violation_amount
755
+ )
756
+ if abs_f < F_min - tol:
757
+ violation_amount = F_min - abs_f
758
+ add_violation(
759
+ 9,
760
+ f"Vessel {vid} at demand port {pid} t={t}: "
761
+ f"|discharge|={abs_f:.4f} < F_min={F_min}",
762
+ abs_f, F_min, violation_amount
763
+ )
764
+ if abs_f > F_max + tol:
765
+ violation_amount = abs_f - F_max
766
+ add_violation(
767
+ 9,
768
+ f"Vessel {vid} at demand port {pid} t={t}: "
769
+ f"|discharge|={abs_f:.4f} > F_max={F_max}",
770
+ abs_f, F_max, violation_amount
771
+ )
772
+
773
+ # =====================================================================
774
+ # Constraint (11): Vessel inventory capacity: 0 <= F_n <= U_n
775
+ # Track vessel load along its path. U_n = min(Q_v, draft_limit(v,j))
776
+ # The vessel starts with initial_load and accumulates f values.
777
+ #
778
+ # Per math_model.txt constraint (11): F_n is the vessel inventory
779
+ # ENTERING node n (before loading/discharging at n). This is defined
780
+ # by constraint (10): F_n = sum_{e=(n',n)} x_e (F_{n'} + f_{n'}).
781
+ # Equivalently, from the LP subproblem constraint (14):
782
+ # 0 <= sum_{i=0}^{k-1} f_{n_i} <= U_{n_k} for k=1,...,K
783
+ # which bounds the cumulative load BEFORE operations at node n_k.
784
+ # =====================================================================
785
+ for vid, visits in vessel_visits.items():
786
+ if not visits:
787
+ continue
788
+ vessel = vessels[vid]
789
+ Q_v = vessel["capacity"]
790
+ load = vessel["initial_load"]
791
+ for i, visit in enumerate(visits):
792
+ pid = visit["port"]
793
+ t = visit["time"]
794
+ f_val = visit["load_discharge"]
795
+
796
+ # Draft limit: U_n bounds the inventory ENTERING the node
797
+ dl = draft_limits.get((vid, pid), Q_v)
798
+ U_n = min(Q_v, dl)
799
+
800
+ # Check 0 <= load <= U_n BEFORE loading/discharging at this node
801
+ if load < -tol:
802
+ violation_amount = -load
803
+ add_violation(
804
+ 11,
805
+ f"Vessel {vid} has negative load={load:.4f} entering "
806
+ f"{pid} at t={t}",
807
+ load, 0.0, violation_amount
808
+ )
809
+ if load > U_n + tol:
810
+ violation_amount = load - U_n
811
+ add_violation(
812
+ 11,
813
+ f"Vessel {vid} load={load:.4f} exceeds capacity "
814
+ f"U_n={U_n:.4f} entering {pid} at t={t}",
815
+ load, U_n, violation_amount
816
+ )
817
+
818
+ # Update load AFTER checking the constraint
819
+ load += f_val
820
+
821
+ # =====================================================================
822
+ # Objective and cost summary: every component is derivable from the route
823
+ # and operation witnesses, so bind both cost_breakdown and objective_value
824
+ # to those decisions instead of trusting candidate-reported numbers.
825
+ # =====================================================================
826
+ procurement_cost = sum(
827
+ supply_ports[visit["port"]]["unit_cost"]
828
+ * visit["load_discharge"]
829
+ for visits in vessel_visits.values()
830
+ for visit in visits
831
+ if visit["port"] in supply_ports
832
+ )
833
+ supply_revenue = sum(
834
+ demand_ports[visit["port"]]["unit_cost"]
835
+ * (-visit["load_discharge"])
836
+ for visits in vessel_visits.values()
837
+ for visit in visits
838
+ if visit["port"] in demand_ports
839
+ )
840
+ expected_costs = {
841
+ "transport_cost": transport_cost,
842
+ "demurrage_cost": demurrage_cost,
843
+ "procurement_cost": procurement_cost,
844
+ "supply_revenue": supply_revenue,
845
+ }
846
+ expected_costs["total_cost"] = (
847
+ transport_cost + demurrage_cost + procurement_cost - supply_revenue
848
+ )
849
+ cost_breakdown = solution_data["cost_breakdown"]
850
+ if set(cost_breakdown) != set(expected_costs):
851
+ add_violation(
852
+ 14,
853
+ "cost_breakdown fields do not exactly match the five documented "
854
+ "cost components",
855
+ float(len(cost_breakdown)), float(len(expected_costs)), 1.0,
856
+ )
857
+ for component, expected_value in expected_costs.items():
858
+ if component not in cost_breakdown:
859
+ continue
860
+ reported_value = float(cost_breakdown[component])
861
+ difference = abs(reported_value - expected_value)
862
+ component_tolerance = max(1e-3, 1e-7 * abs(expected_value))
863
+ if not math.isfinite(reported_value) or difference > component_tolerance:
864
+ add_violation(
865
+ 14,
866
+ f"cost_breakdown.{component}={reported_value} does not match "
867
+ f"the decision-derived value {expected_value}",
868
+ reported_value, expected_value, difference,
869
+ )
870
+
871
+ reported_objective = float(solution_data["objective_value"])
872
+ objective_difference = abs(
873
+ reported_objective - expected_costs["total_cost"]
874
+ )
875
+ objective_tolerance = max(
876
+ 1e-3, 1e-7 * abs(expected_costs["total_cost"])
877
+ )
878
+ if objective_difference > objective_tolerance:
879
+ add_violation(
880
+ 14,
881
+ f"objective_value={reported_objective} does not match the "
882
+ f"decision-derived total {expected_costs['total_cost']}",
883
+ reported_objective, expected_costs["total_cost"],
884
+ objective_difference,
885
+ )
886
+
887
+ # =====================================================================
888
+ # Compile results
889
+ # =====================================================================
890
+ violated_set = sorted(set(c for c, _ in violations))
891
+ violation_messages = []
892
+ # Aggregate messages per constraint
893
+ msgs_by_constraint = defaultdict(list)
894
+ for c, msg in violations:
895
+ msgs_by_constraint[c].append(msg)
896
+ for c in violated_set:
897
+ msgs = msgs_by_constraint[c]
898
+ if len(msgs) <= 3:
899
+ violation_messages.extend(msgs)
900
+ else:
901
+ violation_messages.extend(msgs[:2])
902
+ violation_messages.append(
903
+ f"... and {len(msgs) - 2} more violation(s) for constraint {c}"
904
+ )
905
+
906
+ feasible = len(violated_set) == 0
907
+
908
+ result = {
909
+ "feasible": feasible,
910
+ "violated_constraints": violated_set,
911
+ "violations": violation_messages,
912
+ "violation_magnitudes": violation_magnitudes if not feasible else [],
913
+ }
914
+
915
+ return result
916
+
917
+
918
+ def main():
919
+ parser = argparse.ArgumentParser(
920
+ description="Feasibility checker for Maritime Inventory Routing")
921
+ parser.add_argument("--instance_path", required=True,
922
+ help="Path to JSON instance file")
923
+ parser.add_argument("--solution_path", required=True,
924
+ help="Path to JSON solution file")
925
+ parser.add_argument("--result_path", required=True,
926
+ help="Path to write JSON feasibility result")
927
+ args = parser.parse_args()
928
+
929
+ instance_data = load_json(args.instance_path)
930
+ solution_data = load_json(args.solution_path)
931
+ _frontieror_contract_result = _frontieror_validate_solution_contract(solution_data)
932
+ if _frontieror_contract_result is not None:
933
+ with open(args.result_path, "w") as _frontieror_result_handle:
934
+ json.dump(
935
+ _frontieror_contract_result,
936
+ _frontieror_result_handle,
937
+ indent=2,
938
+ )
939
+ return
940
+
941
+ result = check_feasibility(instance_data, solution_data)
942
+
943
+ with open(args.result_path, 'w') as f:
944
+ json.dump(result, f, indent=2)
945
+
946
+ status = "FEASIBLE" if result["feasible"] else "INFEASIBLE"
947
+ print(f"{status}: {args.solution_path}")
948
+ if not result["feasible"]:
949
+ print(f" Violated constraints: {result['violated_constraints']}")
950
+ for msg in result["violations"][:5]:
951
+ print(f" - {msg}")
952
+
953
+ return 0
954
+
955
+
956
+ if __name__ == "__main__":
957
+ try:
958
+ sys.exit(main())
959
+ except Exception as _frontieror_unexpected_error:
960
+ if not _frontieror_write_unexpected_rejection(
961
+ _frontieror_unexpected_error
962
+ ):
963
+ raise
tasks/engineer2012/gurobi_code.py ADDED
@@ -0,0 +1,904 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Compact Arc-Flow MIP Formulation for the Maritime Inventory Routing Problem.
4
+
5
+ Based on:
6
+ Engineer, Furman, Nemhauser, Savelsbergh, Song (2012),
7
+ "A Branch-Price-and-Cut Algorithm for Single-Product Maritime Inventory
8
+ Routing"
9
+
10
+ Since the column-generation formulation in the paper cannot be directly solved
11
+ by Gurobi (the set R_v of voyages is exponentially large), we implement a
12
+ compact arc-flow formulation on a time-expanded network, as referenced in
13
+ Song and Furman (2012).
14
+
15
+ The formulation uses a commodity-flow approach for vessel inventory tracking:
16
+ - w[v,e]: continuous flow of product on arc e for vessel v
17
+ - This avoids the nonlinear constraint (10) from the paper and the need
18
+ for big-M linearization, yielding a much tighter LP relaxation.
19
+
20
+ Usage:
21
+ python gurobi_code.py --instance_path path/to/instance.json \\
22
+ --solution_path gurobi_solution.json \\
23
+ --time_limit 3600
24
+ """
25
+
26
+ import argparse
27
+ import json
28
+ import math
29
+ import sys
30
+ import time
31
+
32
+ import gurobipy as gp
33
+ from gurobipy import GRB
34
+ import os as _os, sys as _sys
35
+ # Walk up from this file's directory to find repo root (containing scripts/).
36
+ _GUROBI_CODE_START_TIME = time.time()
37
+ _repo = _os.path.dirname(_os.path.abspath(__file__))
38
+ while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')):
39
+ _repo = _os.path.dirname(_repo)
40
+ if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')):
41
+ _sys.path.insert(0, _repo)
42
+ try:
43
+ from scripts.utils.gurobi_log_helper import install_gurobi_logger
44
+ except ImportError:
45
+ def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable
46
+ pass
47
+ # =============================================================================
48
+ # Data Loading
49
+ # =============================================================================
50
+
51
+ def load_instance(path):
52
+ """Load instance data from a JSON file."""
53
+ with open(path, "r") as fh:
54
+ data = json.load(fh)
55
+ return data
56
+
57
+
58
+ # =============================================================================
59
+ # Helpers
60
+ # =============================================================================
61
+
62
+ def _node_str(node):
63
+ """Convert a node to a string suitable for constraint naming."""
64
+ if isinstance(node, tuple):
65
+ return f"{node[0]}_{node[1]}"
66
+ return str(node)
67
+
68
+
69
+ # =============================================================================
70
+ # Network Construction
71
+ # =============================================================================
72
+
73
+ def build_time_expanded_network(data):
74
+ """
75
+ Build a time-expanded network for each vessel.
76
+
77
+ For each vessel v, construct:
78
+ - Nodes: (j, t) for each port j and each time t in
79
+ [avail_start, avail_end], plus source 'src_v' and sink 'snk_v'
80
+ - Travel arcs: ((j1,t1), (j2,t2)) with t2 = t1 + travel_time(j1, j2)
81
+ - Demurrage arcs: ((j,t), (j,t+1)) for waiting at a port
82
+ - Source arcs: from src_v to supply port nodes at avail_start
83
+ - Sink arcs: from any port-time node to snk_v
84
+
85
+ INFERRED ASSUMPTION: Vessels start "at sea" and can reach any supply port
86
+ at their availability_start time.
87
+
88
+ Returns:
89
+ networks: dict keyed by vessel id
90
+ all_ports: list of port ids
91
+ port_type: dict port_id -> "supply" or "demand"
92
+ travel_time_dict: dict (p1,p2) -> int
93
+ draft_limit_dict: dict (v_id, p_id) -> float
94
+ """
95
+ T = data["planning_horizon"]
96
+ all_ports = []
97
+ port_type = {}
98
+ for sp in data["supply_ports"]:
99
+ all_ports.append(sp["port_id"])
100
+ port_type[sp["port_id"]] = "supply"
101
+ for dp in data["demand_ports"]:
102
+ all_ports.append(dp["port_id"])
103
+ port_type[dp["port_id"]] = "demand"
104
+
105
+ travel_time_dict = {}
106
+ for key, val in data["travel_times"].items():
107
+ p1, p2 = key.split("->")
108
+ travel_time_dict[(p1, p2)] = val
109
+
110
+ draft_limit_dict = {}
111
+ for key, val in data["draft_limits"].items():
112
+ v_id, p_id = key.split("->")
113
+ draft_limit_dict[(v_id, p_id)] = val
114
+
115
+ networks = {}
116
+
117
+ for vessel in data["vessels"]:
118
+ v_id = vessel["id"]
119
+ avail_start = vessel["availability_start"]
120
+ avail_end = vessel["availability_end"]
121
+ load_window_end = vessel["loading_window_end"]
122
+ cap = vessel["capacity"]
123
+
124
+ src_node = ("src", v_id)
125
+ snk_node = ("snk", v_id)
126
+
127
+ nodes = set()
128
+ arcs = [] # list of (tail, head, arc_type, cost)
129
+
130
+ # Port-time nodes
131
+ for j in all_ports:
132
+ for t in range(avail_start, avail_end + 1):
133
+ nodes.add((j, t))
134
+
135
+ # Travel arcs
136
+ for j1 in all_ports:
137
+ for j2 in all_ports:
138
+ if j1 == j2:
139
+ continue
140
+ if (j1, j2) not in travel_time_dict:
141
+ continue
142
+ tt = travel_time_dict[(j1, j2)]
143
+ arc_cost = vessel["transport_cost_per_day"] * tt
144
+ for t1 in range(avail_start, avail_end + 1):
145
+ t2 = t1 + tt
146
+ if t2 > avail_end:
147
+ break
148
+ arcs.append(((j1, t1), (j2, t2), "travel", arc_cost))
149
+
150
+ # Demurrage arcs
151
+ dem_cost = vessel["demurrage_cost_per_day"]
152
+ for j in all_ports:
153
+ for t in range(avail_start, avail_end):
154
+ arcs.append(((j, t), (j, t + 1), "demurrage", dem_cost))
155
+
156
+ # Source arcs: connect to supply ports at avail_start
157
+ # INFERRED ASSUMPTION: vessels can appear at any supply port at
158
+ # availability_start. We also allow connections to demand ports
159
+ # for generality (the cost structure will discourage starting at
160
+ # demand ports without cargo).
161
+ for j in all_ports:
162
+ arcs.append((src_node, (j, avail_start), "source", 0.0))
163
+
164
+ # Sink arcs: from every port-time node
165
+ for j in all_ports:
166
+ for t in range(avail_start, avail_end + 1):
167
+ arcs.append(((j, t), snk_node, "sink", 0.0))
168
+
169
+ nodes.add(src_node)
170
+ nodes.add(snk_node)
171
+
172
+ # U_n: max product on vessel at node n
173
+ U_n = {}
174
+ for j in all_ports:
175
+ dl = draft_limit_dict.get((v_id, j), cap)
176
+ u = min(cap, dl)
177
+ for t in range(avail_start, avail_end + 1):
178
+ U_n[(j, t)] = u
179
+ U_n[src_node] = cap
180
+ # INFERRED ASSUMPTION: vessel may end the horizon with remaining
181
+ # inventory. We do NOT force emptiness at avail_end.
182
+ U_n[snk_node] = cap
183
+
184
+ networks[v_id] = {
185
+ "nodes": nodes,
186
+ "arcs": arcs,
187
+ "src": src_node,
188
+ "snk": snk_node,
189
+ "U_n": U_n,
190
+ "capacity": cap,
191
+ "avail_start": avail_start,
192
+ "avail_end": avail_end,
193
+ "load_window_end": load_window_end,
194
+ }
195
+
196
+ return networks, all_ports, port_type, travel_time_dict, draft_limit_dict
197
+
198
+
199
+ # =============================================================================
200
+ # Preprocessing (Eqs. 16, 17)
201
+ # =============================================================================
202
+
203
+ def preprocess_bounds(data, networks, all_ports, port_type):
204
+ """
205
+ Tighten F_max at supply nodes (Eq. 16) and F_min at demand nodes (Eq. 17).
206
+
207
+ Sign convention:
208
+ Supply: f >= 0 (loading) -> F_min >= 0, F_max >= 0
209
+ Demand: f <= 0 (discharge) -> F_min <= 0, F_max <= 0
210
+ """
211
+ port_data = {}
212
+ for sp in data["supply_ports"]:
213
+ port_data[sp["port_id"]] = sp
214
+ for dp in data["demand_ports"]:
215
+ port_data[dp["port_id"]] = dp
216
+
217
+ F_min_node = {}
218
+ F_max_node = {}
219
+
220
+ for vessel in data["vessels"]:
221
+ v_id = vessel["id"]
222
+ cap = vessel["capacity"]
223
+ net = networks[v_id]
224
+ a_s = net["avail_start"]
225
+ a_e = net["avail_end"]
226
+
227
+ for j in all_ports:
228
+ pd = port_data[j]
229
+ I0 = pd["initial_inventory"]
230
+
231
+ if port_type[j] == "supply":
232
+ prod = pd["production_rate"]
233
+ stor = pd["storage_capacity"]
234
+ Fj_min = pd["F_min"]
235
+ Fj_max = pd["F_max"]
236
+
237
+ for t in range(a_s, a_e + 1):
238
+ sum_p_t = sum(prod[tp - 1] for tp in range(1, t + 1)
239
+ if tp - 1 < len(prod))
240
+ sum_p_tm1 = sum(prod[tp - 1] for tp in range(1, t)
241
+ if tp - 1 < len(prod))
242
+ Q_tm1 = stor[t - 2] if t >= 2 and t - 2 < len(stor) \
243
+ else stor[0]
244
+ b_t = prod[t - 1] if t - 1 < len(prod) else 0
245
+ dl = net["U_n"].get((j, t), cap)
246
+
247
+ excess = I0 + sum_p_tm1 - Q_tm1
248
+ n_prior = math.ceil(max(0, excess) / Fj_max) if Fj_max > 0 else 0
249
+ t4 = I0 + sum_p_t - n_prior * Fj_min
250
+
251
+ t_max = min(Fj_max, dl, Q_tm1 + b_t, max(0, t4))
252
+ t_max = max(t_max, 0)
253
+
254
+ F_max_node[(v_id, j, t)] = t_max
255
+ F_min_node[(v_id, j, t)] = Fj_min
256
+
257
+ else: # demand
258
+ cons = pd["consumption_rate"]
259
+ stor = pd["storage_capacity"]
260
+ Fj_min_d = pd["F_min"]
261
+ Fj_max_d = pd["F_max"]
262
+
263
+ for t in range(a_s, a_e + 1):
264
+ sum_c_t = sum(cons[tp - 1] for tp in range(1, t + 1)
265
+ if tp - 1 < len(cons))
266
+ sum_c_tm1 = sum(cons[tp - 1] for tp in range(1, t)
267
+ if tp - 1 < len(cons))
268
+ Q_t = stor[t - 1] if t - 1 < len(stor) else stor[-1]
269
+ b_t = cons[t - 1] if t - 1 < len(cons) else 0
270
+ dl = net["U_n"].get((j, t), cap)
271
+
272
+ deficit = -I0 + sum_c_tm1
273
+ n_prior = math.ceil(max(0, deficit) / Fj_max_d) \
274
+ if Fj_max_d > 0 else 0
275
+ avail_space = Q_t - I0 + sum_c_t - n_prior * Fj_min_d
276
+ t4 = -max(0, avail_space)
277
+
278
+ t_min = max(-Fj_max_d, -dl, -(Q_t + b_t), t4)
279
+ t_min = min(t_min, 0)
280
+
281
+ F_min_node[(v_id, j, t)] = t_min
282
+ F_max_node[(v_id, j, t)] = -Fj_min_d
283
+
284
+ return F_min_node, F_max_node
285
+
286
+
287
+ # =============================================================================
288
+ # MIP Model
289
+ # =============================================================================
290
+
291
+ def build_model(data, networks, all_ports, port_type, F_min_node, F_max_node):
292
+ """
293
+ Build the compact arc-flow MIP using a commodity-flow formulation.
294
+
295
+ Variables:
296
+ x[v, arc_idx] in {0,1}: arc selection for vessel v
297
+ z[v, j, t] in {0,1}: load/discharge indicator
298
+ f[v, j, t] continuous: quantity loaded (>0) or discharged (<0)
299
+ w[v, arc_idx] >= 0: product flow on arc for vessel v
300
+ I[j, t] >= 0: port inventory
301
+
302
+ The key insight: instead of tracking vessel inventory at nodes with big-M
303
+ constraints (which yields a very weak LP relaxation), we track the
304
+ commodity flow on each arc:
305
+ - w[v,e] represents the amount of product on vessel v traversing arc e
306
+ - Coupling: w[v,e] <= cap * x[v,e]
307
+ - Node balance: incoming_w + f[v,j,t] = outgoing_w (product conservation)
308
+ This gives a tight LP relaxation and allows Gurobi to find solutions fast.
309
+ """
310
+ T = data["planning_horizon"]
311
+ model = gp.Model("MaritimeIRP")
312
+ model.setParam("Threads", 1)
313
+
314
+ port_data = {}
315
+ for sp in data["supply_ports"]:
316
+ port_data[sp["port_id"]] = sp
317
+ for dp in data["demand_ports"]:
318
+ port_data[dp["port_id"]] = dp
319
+
320
+ supply_ports = [sp["port_id"] for sp in data["supply_ports"]]
321
+ demand_ports = [dp["port_id"] for dp in data["demand_ports"]]
322
+
323
+ # -----------------------------------------------------------------
324
+ # Build arc index structures
325
+ # -----------------------------------------------------------------
326
+ out_arcs = {} # (v_id, node) -> list of arc indices
327
+ in_arcs = {} # (v_id, node) -> list of arc indices
328
+ arc_info = {} # (v_id, arc_idx) -> (tail, head, atype, cost)
329
+
330
+ for vessel in data["vessels"]:
331
+ v_id = vessel["id"]
332
+ for idx, (tail, head, atype, cost) in enumerate(networks[v_id]["arcs"]):
333
+ arc_info[(v_id, idx)] = (tail, head, atype, cost)
334
+ out_arcs.setdefault((v_id, tail), []).append(idx)
335
+ in_arcs.setdefault((v_id, head), []).append(idx)
336
+
337
+ # =================================================================
338
+ # Variables
339
+ # =================================================================
340
+ print(" Creating variables...")
341
+
342
+ # x[v, arc_idx]: binary arc selection
343
+ x = {}
344
+ for vessel in data["vessels"]:
345
+ v_id = vessel["id"]
346
+ net = networks[v_id]
347
+ for idx in range(len(net["arcs"])):
348
+ _, _, atype, cost = arc_info[(v_id, idx)]
349
+ x[(v_id, idx)] = model.addVar(
350
+ vtype=GRB.BINARY, obj=cost, name=f"x_{v_id}_{idx}"
351
+ )
352
+
353
+ # w[v, arc_idx]: product flow on arc (continuous)
354
+ w = {}
355
+ for vessel in data["vessels"]:
356
+ v_id = vessel["id"]
357
+ net = networks[v_id]
358
+ cap = vessel["capacity"]
359
+ for idx in range(len(net["arcs"])):
360
+ w[(v_id, idx)] = model.addVar(
361
+ lb=0.0, ub=cap, vtype=GRB.CONTINUOUS,
362
+ name=f"w_{v_id}_{idx}"
363
+ )
364
+
365
+ # z[v, j, t]: binary load/discharge decision
366
+ z = {}
367
+ for vessel in data["vessels"]:
368
+ v_id = vessel["id"]
369
+ net = networks[v_id]
370
+ for j in all_ports:
371
+ for t in range(net["avail_start"], net["avail_end"] + 1):
372
+ z[(v_id, j, t)] = model.addVar(
373
+ vtype=GRB.BINARY, name=f"z_{v_id}_{j}_{t}"
374
+ )
375
+
376
+ # f[v, j, t]: load/discharge quantity (continuous)
377
+ f = {}
378
+ for vessel in data["vessels"]:
379
+ v_id = vessel["id"]
380
+ net = networks[v_id]
381
+ for j in all_ports:
382
+ for t in range(net["avail_start"], net["avail_end"] + 1):
383
+ fmin = F_min_node.get((v_id, j, t), 0)
384
+ fmax = F_max_node.get((v_id, j, t), 0)
385
+ if port_type[j] == "supply":
386
+ lb, ub = 0.0, max(fmax, 0.0)
387
+ unit_cost = port_data[j]["unit_procurement_cost"]
388
+ else:
389
+ lb, ub = min(fmin, 0.0), 0.0
390
+ # f <= 0 at demand; unit_supply_revenue * f effectively
391
+ # subtracts revenue from the objective
392
+ unit_cost = port_data[j]["unit_supply_revenue"]
393
+
394
+ f[(v_id, j, t)] = model.addVar(
395
+ lb=lb, ub=ub, vtype=GRB.CONTINUOUS,
396
+ obj=unit_cost, name=f"f_{v_id}_{j}_{t}"
397
+ )
398
+
399
+ # I[j, t]: port inventory
400
+ I_var = {}
401
+ for j in all_ports:
402
+ pd = port_data[j]
403
+ stor = pd["storage_capacity"]
404
+ for t in range(1, T + 1):
405
+ Q_jt = stor[t - 1] if t - 1 < len(stor) else stor[-1]
406
+ I_var[(j, t)] = model.addVar(
407
+ lb=0.0, ub=Q_jt, vtype=GRB.CONTINUOUS,
408
+ name=f"I_{j}_{t}"
409
+ )
410
+
411
+ model.update()
412
+
413
+ # =================================================================
414
+ # Constraints
415
+ # =================================================================
416
+ print(" Adding constraints...")
417
+
418
+ # -----------------------------------------------------------------
419
+ # (C1) Flow conservation: path from source to sink for each vessel
420
+ # -----------------------------------------------------------------
421
+ for vessel in data["vessels"]:
422
+ v_id = vessel["id"]
423
+ net = networks[v_id]
424
+ src = net["src"]
425
+ snk = net["snk"]
426
+ for node in net["nodes"]:
427
+ o_list = out_arcs.get((v_id, node), [])
428
+ i_list = in_arcs.get((v_id, node), [])
429
+ out_sum = gp.quicksum(x[(v_id, i)] for i in o_list)
430
+ in_sum = gp.quicksum(x[(v_id, i)] for i in i_list)
431
+ if node == src:
432
+ rhs = 1
433
+ elif node == snk:
434
+ rhs = -1
435
+ else:
436
+ rhs = 0
437
+ model.addConstr(
438
+ out_sum - in_sum == rhs,
439
+ name=f"flow_{v_id}_{_node_str(node)}"
440
+ )
441
+
442
+ # -----------------------------------------------------------------
443
+ # (C2) Commodity flow coupling: w <= U_n * x
444
+ # The product flow w on arc (tail -> head) represents the cargo
445
+ # in transit. This equals:
446
+ # - EXIT inventory from tail (after loading at tail)
447
+ # - ENTRY inventory at head (before loading at head)
448
+ # Draft limits must be enforced at BOTH endpoints:
449
+ # w <= U_n(head) * x (entry bound at destination)
450
+ # w <= U_n(tail) * x (exit bound at origin)
451
+ # Combined: w <= min(U_n(head), U_n(tail)) * x
452
+ # -----------------------------------------------------------------
453
+ for vessel in data["vessels"]:
454
+ v_id = vessel["id"]
455
+ cap = vessel["capacity"]
456
+ net = networks[v_id]
457
+ for idx in range(len(net["arcs"])):
458
+ tail, head, atype, _ = arc_info[(v_id, idx)]
459
+ if isinstance(head, tuple):
460
+ u_head = net["U_n"].get(head, cap)
461
+ else:
462
+ u_head = cap
463
+ if isinstance(tail, tuple):
464
+ u_tail = net["U_n"].get(tail, cap)
465
+ else:
466
+ u_tail = cap
467
+ u = min(u_head, u_tail)
468
+ model.addConstr(
469
+ w[(v_id, idx)] <= u * x[(v_id, idx)],
470
+ name=f"wcap_{v_id}_{idx}"
471
+ )
472
+
473
+ # -----------------------------------------------------------------
474
+ # (C3) Commodity flow conservation at each port-time node:
475
+ # sum(incoming w) + f[v,j,t] = sum(outgoing w)
476
+ #
477
+ # For supply: f >= 0, so incoming_w + f = outgoing_w means vessel
478
+ # picks up product (outgoing > incoming).
479
+ # For demand: f <= 0, so incoming_w + f = outgoing_w means vessel
480
+ # drops off product (outgoing < incoming).
481
+ #
482
+ # At source node: initial_load + outgoing_w = 0 (if initial_load=0
483
+ # this means vessel starts empty).
484
+ # At sink node: incoming_w = 0 is NOT enforced (vessel can end with
485
+ # product). We let the variable be free.
486
+ # -----------------------------------------------------------------
487
+ for vessel in data["vessels"]:
488
+ v_id = vessel["id"]
489
+ net = networks[v_id]
490
+ init_load = vessel["initial_load"]
491
+ src = net["src"]
492
+ snk = net["snk"]
493
+
494
+ # Source: outgoing product flow = initial_load
495
+ src_out = out_arcs.get((v_id, src), [])
496
+ model.addConstr(
497
+ gp.quicksum(w[(v_id, i)] for i in src_out) == init_load,
498
+ name=f"wbal_src_{v_id}"
499
+ )
500
+
501
+ # Port-time nodes
502
+ for j in all_ports:
503
+ for t in range(net["avail_start"], net["avail_end"] + 1):
504
+ node = (j, t)
505
+ i_list = in_arcs.get((v_id, node), [])
506
+ o_list = out_arcs.get((v_id, node), [])
507
+ in_w = gp.quicksum(w[(v_id, i)] for i in i_list)
508
+ out_w = gp.quicksum(w[(v_id, i)] for i in o_list)
509
+ model.addConstr(
510
+ in_w + f[(v_id, j, t)] == out_w,
511
+ name=f"wbal_{v_id}_{j}_{t}"
512
+ )
513
+
514
+ # Sink: no explicit constraint needed -- incoming w can be any
515
+ # non-negative value (product remaining on vessel).
516
+
517
+ # -----------------------------------------------------------------
518
+ # (C4) Load/discharge only if node is visited (Eq. 8):
519
+ # z[v,j,t] <= sum of outgoing arcs from (j,t)
520
+ # -----------------------------------------------------------------
521
+ for vessel in data["vessels"]:
522
+ v_id = vessel["id"]
523
+ net = networks[v_id]
524
+ for j in all_ports:
525
+ for t in range(net["avail_start"], net["avail_end"] + 1):
526
+ node = (j, t)
527
+ o_list = out_arcs.get((v_id, node), [])
528
+ if not o_list:
529
+ model.addConstr(z[(v_id, j, t)] == 0,
530
+ name=f"vis_{v_id}_{j}_{t}")
531
+ else:
532
+ model.addConstr(
533
+ z[(v_id, j, t)] <= gp.quicksum(
534
+ x[(v_id, i)] for i in o_list),
535
+ name=f"vis_{v_id}_{j}_{t}")
536
+
537
+ # -----------------------------------------------------------------
538
+ # (C5) Load/discharge quantity bounds (Eq. 9):
539
+ # F_min * z <= f <= F_max * z
540
+ # -----------------------------------------------------------------
541
+ for vessel in data["vessels"]:
542
+ v_id = vessel["id"]
543
+ net = networks[v_id]
544
+ for j in all_ports:
545
+ for t in range(net["avail_start"], net["avail_end"] + 1):
546
+ fmin_val = F_min_node.get((v_id, j, t), 0)
547
+ fmax_val = F_max_node.get((v_id, j, t), 0)
548
+ model.addConstr(
549
+ f[(v_id, j, t)] >= fmin_val * z[(v_id, j, t)],
550
+ name=f"flo_{v_id}_{j}_{t}")
551
+ model.addConstr(
552
+ f[(v_id, j, t)] <= fmax_val * z[(v_id, j, t)],
553
+ name=f"fhi_{v_id}_{j}_{t}")
554
+
555
+ # -----------------------------------------------------------------
556
+ # (C6) Port inventory balance (Eqs. 1, 2):
557
+ # Supply: I[j,t] = I[j,t-1] + b[j,t] - sum_v f[v,j,t]
558
+ # Demand: I[j,t] = I[j,t-1] - b[j,t] - sum_v f[v,j,t]
559
+ # -----------------------------------------------------------------
560
+ for j in all_ports:
561
+ pd = port_data[j]
562
+ I0 = pd["initial_inventory"]
563
+
564
+ if port_type[j] == "supply":
565
+ rates = pd["production_rate"]
566
+ for t in range(1, T + 1):
567
+ b_jt = rates[t - 1] if t - 1 < len(rates) else 0
568
+ I_prev = I0 if t == 1 else I_var[(j, t - 1)]
569
+ total_f = gp.quicksum(
570
+ f[(v["id"], j, t)]
571
+ for v in data["vessels"]
572
+ if (v["id"], j, t) in f
573
+ )
574
+ model.addConstr(
575
+ I_var[(j, t)] == I_prev + b_jt - total_f,
576
+ name=f"inv_{j}_{t}")
577
+ else:
578
+ rates = pd["consumption_rate"]
579
+ for t in range(1, T + 1):
580
+ b_jt = rates[t - 1] if t - 1 < len(rates) else 0
581
+ I_prev = I0 if t == 1 else I_var[(j, t - 1)]
582
+ total_f = gp.quicksum(
583
+ f[(v["id"], j, t)]
584
+ for v in data["vessels"]
585
+ if (v["id"], j, t) in f
586
+ )
587
+ model.addConstr(
588
+ I_var[(j, t)] == I_prev - b_jt - total_f,
589
+ name=f"inv_{j}_{t}")
590
+
591
+ # Port storage bounds: already set via variable bounds on I_var.
592
+
593
+ # -----------------------------------------------------------------
594
+ # (C7) Loading window:
595
+ # INFERRED ASSUMPTION: The loading_window_end field indicates the
596
+ # latest time a vessel's FIRST loading can start. We do NOT enforce
597
+ # a hard ban on loading at supply ports after loading_window_end,
598
+ # because doing so can make the problem infeasible when supply ports
599
+ # keep producing after all loading windows have closed.
600
+ # Instead, we treat the availability window [avail_start, avail_end]
601
+ # as the only hard time constraint on the vessel. The loading
602
+ # window is interpreted as a soft scheduling preference encoded in
603
+ # the time-expanded network structure (vessels are unlikely to
604
+ # revisit supply ports after their initial transatlantic crossing
605
+ # due to travel time costs).
606
+ # -----------------------------------------------------------------
607
+
608
+ # -----------------------------------------------------------------
609
+ # (C8) Force load/discharge before relocating (symmetry breaking):
610
+ # For a travel arc from (j,t), the vessel must have loaded/discharged
611
+ # at port j at some point during its stay. Simplified: either z=1
612
+ # at (j,t), or the vessel arrived via a demurrage arc (was already
613
+ # at j, so loaded earlier).
614
+ # -----------------------------------------------------------------
615
+ for vessel in data["vessels"]:
616
+ v_id = vessel["id"]
617
+ net = networks[v_id]
618
+ for idx, (tail, head, atype, cost) in enumerate(net["arcs"]):
619
+ if atype == "travel" and isinstance(tail, tuple):
620
+ j, t = tail
621
+ i_list = in_arcs.get((v_id, (j, t)), [])
622
+ dem_in = [ai for ai in i_list
623
+ if arc_info[(v_id, ai)][2] == "demurrage"]
624
+ if dem_in:
625
+ model.addConstr(
626
+ x[(v_id, idx)] <= z[(v_id, j, t)] + gp.quicksum(
627
+ x[(v_id, ai)] for ai in dem_in),
628
+ name=f"fld_{v_id}_{idx}")
629
+ else:
630
+ model.addConstr(
631
+ x[(v_id, idx)] <= z[(v_id, j, t)],
632
+ name=f"fld_{v_id}_{idx}")
633
+
634
+ model.update()
635
+ print(f" Model: {model.NumVars} variables, {model.NumConstrs} constraints")
636
+
637
+ return model, x, w, z, f, I_var
638
+
639
+
640
+ # =============================================================================
641
+ # Solution Extraction
642
+ # =============================================================================
643
+
644
+ def extract_solution(model, data, networks, all_ports, port_type,
645
+ x, w, z, f, I_var):
646
+ """Extract solution from the optimized Gurobi model."""
647
+ T = data["planning_horizon"]
648
+
649
+ solution = {
650
+ "objective_value": None,
651
+ "solver_status": None,
652
+ "mip_gap": None,
653
+ "solve_time": model.Runtime,
654
+ "vessel_routes": {},
655
+ "port_inventories": {},
656
+ "vessel_operations": {},
657
+ }
658
+
659
+ if model.SolCount == 0:
660
+ solution["solver_status"] = "no_feasible_solution"
661
+ return solution
662
+
663
+ solution["objective_value"] = model.ObjVal
664
+ solution["mip_gap"] = model.MIPGap
665
+ if model.Status == GRB.OPTIMAL:
666
+ solution["solver_status"] = "optimal"
667
+ elif model.Status == GRB.TIME_LIMIT:
668
+ solution["solver_status"] = "time_limit"
669
+ else:
670
+ solution["solver_status"] = f"status_{model.Status}"
671
+
672
+ for vessel in data["vessels"]:
673
+ v_id = vessel["id"]
674
+ net = networks[v_id]
675
+ route_arcs = []
676
+ operations = []
677
+
678
+ for idx, (tail, head, atype, cost) in enumerate(net["arcs"]):
679
+ if x[(v_id, idx)].X > 0.5:
680
+ w_val = w[(v_id, idx)].X
681
+ route_arcs.append({
682
+ "tail": str(tail),
683
+ "head": str(head),
684
+ "type": atype,
685
+ "cost": cost,
686
+ "product_flow": round(w_val, 4),
687
+ })
688
+
689
+ for j in all_ports:
690
+ for t in range(net["avail_start"], net["avail_end"] + 1):
691
+ if (v_id, j, t) in z and z[(v_id, j, t)].X > 0.5:
692
+ f_val = f[(v_id, j, t)].X
693
+ operations.append({
694
+ "port": j,
695
+ "time": t,
696
+ "quantity": round(f_val, 4),
697
+ "type": ("load" if port_type[j] == "supply"
698
+ else "discharge"),
699
+ })
700
+
701
+ solution["vessel_routes"][v_id] = route_arcs
702
+ solution["vessel_operations"][v_id] = operations
703
+
704
+ for j in all_ports:
705
+ inv = []
706
+ for t in range(1, T + 1):
707
+ if (j, t) in I_var:
708
+ inv.append({
709
+ "time": t,
710
+ "inventory": round(I_var[(j, t)].X, 4),
711
+ })
712
+ solution["port_inventories"][j] = inv
713
+
714
+ return solution
715
+
716
+
717
+ def compute_cost_breakdown(model, data, networks, all_ports, port_type,
718
+ x, f):
719
+ """Compute a detailed cost breakdown."""
720
+ if model.SolCount == 0:
721
+ return {}
722
+
723
+ port_data = {}
724
+ for sp in data["supply_ports"]:
725
+ port_data[sp["port_id"]] = sp
726
+ for dp in data["demand_ports"]:
727
+ port_data[dp["port_id"]] = dp
728
+
729
+ transport_cost = 0.0
730
+ demurrage_cost = 0.0
731
+ procurement_cost = 0.0
732
+ supply_revenue = 0.0
733
+
734
+ for vessel in data["vessels"]:
735
+ v_id = vessel["id"]
736
+ net = networks[v_id]
737
+ for idx, (tail, head, atype, cost) in enumerate(net["arcs"]):
738
+ if x[(v_id, idx)].X > 0.5:
739
+ if atype == "travel":
740
+ transport_cost += cost
741
+ elif atype == "demurrage":
742
+ demurrage_cost += cost
743
+
744
+ for j in all_ports:
745
+ for t in range(net["avail_start"], net["avail_end"] + 1):
746
+ if (v_id, j, t) in f:
747
+ fv = f[(v_id, j, t)].X
748
+ if abs(fv) > 1e-6:
749
+ if port_type[j] == "supply":
750
+ procurement_cost += (
751
+ port_data[j]["unit_procurement_cost"] * fv)
752
+ else:
753
+ supply_revenue += (
754
+ port_data[j]["unit_supply_revenue"] * (-fv))
755
+
756
+ return {
757
+ "transport_cost": round(transport_cost, 4),
758
+ "demurrage_cost": round(demurrage_cost, 4),
759
+ "procurement_cost": round(procurement_cost, 4),
760
+ "supply_revenue": round(supply_revenue, 4),
761
+ "total_cost": round(
762
+ transport_cost + demurrage_cost + procurement_cost
763
+ - supply_revenue, 4),
764
+ }
765
+
766
+
767
+ # =============================================================================
768
+ # Main
769
+ # =============================================================================
770
+
771
+ def main():
772
+ parser = argparse.ArgumentParser(
773
+ description="Compact arc-flow MIP for Maritime Inventory Routing "
774
+ "(Engineer et al. 2012)")
775
+ parser.add_argument("--instance_path", type=str, required=True,
776
+ help="Path to instance JSON file.")
777
+ parser.add_argument("--solution_path", type=str, required=True,
778
+ help="Path to write solution JSON file.")
779
+ parser.add_argument("--time_limit", type=int, default=3600,
780
+ help="Gurobi time limit in seconds (default 3600).")
781
+ parser.add_argument("--mip_gap", type=float, default=1e-4,
782
+ help="Gurobi MIPGap tolerance (default 1e-4).")
783
+ parser.add_argument("--threads", type=int, default=1,
784
+ help="Threads for Gurobi (default: 1).")
785
+ parser.add_argument("--verbose", action="store_true",
786
+ help="Enable verbose Gurobi output.")
787
+ parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions")
788
+ args = parser.parse_args()
789
+ install_gurobi_logger(args.log_path)
790
+
791
+ print("=" * 70)
792
+ print("Maritime Inventory Routing Problem - Compact Arc-Flow MIP")
793
+ print("Based on Engineer et al. (2012)")
794
+ print("=" * 70)
795
+
796
+ # Load instance
797
+ print(f"\nLoading instance: {args.instance_path}")
798
+ data = load_instance(args.instance_path)
799
+ print(f" Horizon={data['planning_horizon']}, "
800
+ f"vessels={data['num_vessels']}, "
801
+ f"supply={data['num_supply_ports']}, "
802
+ f"demand={data['num_demand_ports']}")
803
+
804
+ # Build networks
805
+ print("\nBuilding time-expanded networks...")
806
+ networks, all_ports, port_type, tt_dict, dl_dict = \
807
+ build_time_expanded_network(data)
808
+ for v_id, net in networks.items():
809
+ print(f" {v_id}: {len(net['nodes'])} nodes, {len(net['arcs'])} arcs, "
810
+ f"avail=[{net['avail_start']},{net['avail_end']}], "
811
+ f"load_end={net['load_window_end']}")
812
+
813
+ # Preprocess
814
+ print("\nPreprocessing bounds (Eqs. 16, 17)...")
815
+ F_min_node, F_max_node = preprocess_bounds(
816
+ data, networks, all_ports, port_type)
817
+
818
+ # Build model
819
+ print("\nBuilding MIP model...")
820
+ model, x, w, z, f, I_var = build_model(
821
+ data, networks, all_ports, port_type, F_min_node, F_max_node)
822
+
823
+ # Gurobi parameters
824
+ model.setParam("TimeLimit", args.time_limit)
825
+ if args.mip_gap > 0:
826
+ model.setParam("MIPGap", args.mip_gap)
827
+ if args.threads > 0:
828
+ model.setParam("Threads", args.threads)
829
+ if not args.verbose:
830
+ model.setParam("OutputFlag", 1)
831
+ # Find any feasible incumbent quickly — maritime inventory routing has a
832
+ # tight LP relaxation and gurobi can spend the full budget proving infeas/
833
+ # closing gap without producing an incumbent. MIPFocus=1 + NoRelHeurTime
834
+ # bias the search toward feasibility.
835
+ model.setParam("MIPFocus", 1)
836
+ model.setParam("NoRelHeurTime", min(60.0, args.time_limit * 0.05))
837
+
838
+ # Optimize
839
+ print("\nOptimizing...")
840
+ print("=" * 70)
841
+ t0 = time.time()
842
+ model.optimize()
843
+ solve_time = time.time() - t0
844
+ print("=" * 70)
845
+
846
+ # Report
847
+ print(f"\nSolve time: {solve_time:.2f}s")
848
+ print(f"Gurobi status: {model.Status}")
849
+
850
+ if model.SolCount > 0:
851
+ print(f"Objective value: {model.ObjVal:.4f}")
852
+ print(f"MIP gap: {model.MIPGap:.6f}")
853
+ if model.Status == GRB.OPTIMAL:
854
+ print("Solution is OPTIMAL.")
855
+ else:
856
+ print("Feasible solution found (not proven optimal).")
857
+
858
+ breakdown = compute_cost_breakdown(
859
+ model, data, networks, all_ports, port_type, x, f)
860
+ print("\nCost Breakdown:")
861
+ for k, v in breakdown.items():
862
+ print(f" {k}: {v}")
863
+
864
+ print("\nVessel Operations:")
865
+ for vessel in data["vessels"]:
866
+ v_id = vessel["id"]
867
+ net = networks[v_id]
868
+ ops = []
869
+ for j in all_ports:
870
+ for t in range(net["avail_start"], net["avail_end"] + 1):
871
+ if (v_id, j, t) in z and z[(v_id, j, t)].X > 0.5:
872
+ fv = f[(v_id, j, t)].X
873
+ ptype = "load" if port_type[j] == "supply" else "disch"
874
+ ops.append((t, j, ptype, fv))
875
+ if ops:
876
+ ops.sort()
877
+ print(f" {v_id}:")
878
+ for (t, j, pt, fv) in ops:
879
+ print(f" t={t:3d} {pt:6s} at {j}: {fv:+.2f}")
880
+ else:
881
+ print(f" {v_id}: idle")
882
+ else:
883
+ print("No feasible solution found.")
884
+
885
+ # Save solution
886
+ solution = extract_solution(
887
+ model, data, networks, all_ports, port_type, x, w, z, f, I_var)
888
+ solution["solve_time"] = round(solve_time, 2)
889
+ solution["instance_path"] = args.instance_path
890
+ if model.SolCount > 0:
891
+ solution["cost_breakdown"] = compute_cost_breakdown(
892
+ model, data, networks, all_ports, port_type, x, f)
893
+
894
+ print(f"\nSaving solution to: {args.solution_path}")
895
+ with open(args.solution_path, "w") as fout:
896
+ solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME
897
+ json.dump(solution, fout, indent=2)
898
+
899
+ print("Done.")
900
+ return 0
901
+
902
+
903
+ if __name__ == "__main__":
904
+ sys.exit(main())
tasks/engineer2012/gurobi_feasi_result/large_feasi_result_1.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/engineer2012/gurobi_feasi_result/large_feasi_result_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/engineer2012/gurobi_feasi_result/large_feasi_result_3.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/engineer2012/gurobi_feasi_result/large_feasi_result_4.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/engineer2012/gurobi_feasi_result/large_feasi_result_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd
3
+ size 102
tasks/engineer2012/gurobi_solution/large_solution_1.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a582e5cede88d69e7b19423b23ef1ac5cc02f6957c6b8ecca8c265ee94e06815
3
+ size 24839
tasks/engineer2012/gurobi_solution/large_solution_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80c1a27714c8af22bf15103c8774eb5066a6a297ca64be9ecbc867e0953cc25f
3
+ size 25138
tasks/engineer2012/gurobi_solution/large_solution_3.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:770da4332ff59a08bddd2b91ab324fda6b3946624f6d081f68b70a319bed10bf
3
+ size 25084
tasks/engineer2012/gurobi_solution/large_solution_4.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a8020b2cedfadcc0ada75afada6298b472c7491768032048079893c3e7bdfc1
3
+ size 26581
tasks/engineer2012/gurobi_solution/large_solution_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c47256caaad836d340c422c84f8af123699eee899b01539efc5c72c1936f048
3
+ size 24313
tasks/engineer2012/gurobi_solution/tiny_solution.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8b7724e6733d2b8e6e0cd3e3075682bbe96b4886502a60ae02ab07c8b6017fc
3
+ size 14128