Minwei Kong commited on
Commit
b25ec8f
·
verified ·
1 Parent(s): dd580fb

Nest task folders under tasks/ (part 11)

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/rahmaniani2020/gurobi_feasi_result/large_feasi_result_5.json +3 -0
  2. tasks/rahmaniani2020/gurobi_feasi_result/tiny_feasi_result.json +3 -0
  3. tasks/rahmaniani2020/gurobi_solution/large_solution_1.json +3 -0
  4. tasks/rahmaniani2020/gurobi_solution/large_solution_2.json +3 -0
  5. tasks/rahmaniani2020/gurobi_solution/large_solution_3.json +3 -0
  6. tasks/rahmaniani2020/gurobi_solution/large_solution_4.json +3 -0
  7. tasks/rahmaniani2020/gurobi_solution/large_solution_5.json +3 -0
  8. tasks/rahmaniani2020/gurobi_solution/tiny_solution.json +3 -0
  9. tasks/rahmaniani2020/gurobi_solution_log/large_log_1.jsonl +3 -0
  10. tasks/rahmaniani2020/gurobi_solution_log/large_log_2.jsonl +3 -0
  11. tasks/rahmaniani2020/gurobi_solution_log/large_log_3.jsonl +3 -0
  12. tasks/rahmaniani2020/gurobi_solution_log/large_log_4.jsonl +3 -0
  13. tasks/rahmaniani2020/gurobi_solution_log/large_log_5.jsonl +3 -0
  14. tasks/rahmaniani2020/gurobi_solution_log/tiny_log.jsonl +3 -0
  15. tasks/rahmaniani2020/instance/large_instance_1.json +3 -0
  16. tasks/rahmaniani2020/instance/large_instance_2.json +3 -0
  17. tasks/rahmaniani2020/instance/large_instance_3.json +3 -0
  18. tasks/rahmaniani2020/instance/large_instance_4.json +3 -0
  19. tasks/rahmaniani2020/instance/large_instance_5.json +3 -0
  20. tasks/rahmaniani2020/instance/tiny_instance.json +3 -0
  21. tasks/rahmaniani2020/instance_schema.json +23 -0
  22. tasks/rahmaniani2020/mathematical_formulation.md +36 -0
  23. tasks/rahmaniani2020/problem_description.txt +7 -0
  24. tasks/rahmaniani2020/solution_logger.py +61 -0
  25. tasks/rahmaniani2020/solution_schema.json +4 -0
  26. tasks/rahmaniani2022/feasibility_check.py +798 -0
  27. tasks/rahmaniani2022/gurobi_code.py +991 -0
  28. tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_1.json +3 -0
  29. tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_2.json +3 -0
  30. tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_3.json +3 -0
  31. tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_4.json +3 -0
  32. tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_5.json +3 -0
  33. tasks/rahmaniani2022/gurobi_feasi_result/tiny_feasi_result.json +3 -0
  34. tasks/rahmaniani2022/gurobi_solution/large_solution_1.json +3 -0
  35. tasks/rahmaniani2022/gurobi_solution/large_solution_2.json +3 -0
  36. tasks/rahmaniani2022/gurobi_solution/large_solution_3.json +3 -0
  37. tasks/rahmaniani2022/gurobi_solution/large_solution_4.json +3 -0
  38. tasks/rahmaniani2022/gurobi_solution/large_solution_5.json +3 -0
  39. tasks/rahmaniani2022/gurobi_solution/tiny_solution.json +3 -0
  40. tasks/rahmaniani2022/gurobi_solution_log/large_log_1.jsonl +3 -0
  41. tasks/rahmaniani2022/gurobi_solution_log/large_log_2.jsonl +3 -0
  42. tasks/rahmaniani2022/gurobi_solution_log/large_log_3.jsonl +3 -0
  43. tasks/rahmaniani2022/gurobi_solution_log/large_log_4.jsonl +3 -0
  44. tasks/rahmaniani2022/gurobi_solution_log/large_log_5.jsonl +3 -0
  45. tasks/rahmaniani2022/gurobi_solution_log/tiny_log.jsonl +3 -0
  46. tasks/rahmaniani2022/instance/large_instance_1.json +3 -0
  47. tasks/rahmaniani2022/instance/large_instance_2.json +3 -0
  48. tasks/rahmaniani2022/instance/large_instance_3.json +3 -0
  49. tasks/rahmaniani2022/instance/large_instance_4.json +3 -0
  50. tasks/rahmaniani2022/instance/large_instance_5.json +3 -0
tasks/rahmaniani2020/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/rahmaniani2020/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/rahmaniani2020/gurobi_solution/large_solution_1.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2899181e20d5b29da0f415e50e3de842d25d9e2cb141cc0a7f43a99ddeea18d1
3
+ size 461
tasks/rahmaniani2020/gurobi_solution/large_solution_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66a080aceacd2d2512178f80b2e44e603f5b94cdd843a72cd467dae015b4d1bc
3
+ size 460
tasks/rahmaniani2020/gurobi_solution/large_solution_3.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:422563568e3cd3a9ac29c27df84e2acb1f9298631fb57e7a9bdb9cd12d9a5923
3
+ size 460
tasks/rahmaniani2020/gurobi_solution/large_solution_4.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4f0f7cc4ed11a2c708f25b6711011e9af315ff34e63181296927e784f2ead0f
3
+ size 461
tasks/rahmaniani2020/gurobi_solution/large_solution_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d71f2994c86df64392a1ec954fc4052cfe2bd89ad0c2d3b5d9b134d75004c8d5
3
+ size 478
tasks/rahmaniani2020/gurobi_solution/tiny_solution.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2312c9290e19260087b313c0aae58476f2d0d8589b7ef9c35626b02aa6e2604a
3
+ size 169
tasks/rahmaniani2020/gurobi_solution_log/large_log_1.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12173a542f13c917bb2e08ef35cb0ae1d1b81cef349d13c8dfd5c40a370109f4
3
+ size 445
tasks/rahmaniani2020/gurobi_solution_log/large_log_2.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8b6e7c6911443a86679667e23bd69adb718caec723006897c123228de4a1858
3
+ size 386
tasks/rahmaniani2020/gurobi_solution_log/large_log_3.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab569304953cfb5d77489c1d74d1294a1d84597c17b841f3203b2d54b94ce15c
3
+ size 278
tasks/rahmaniani2020/gurobi_solution_log/large_log_4.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a0721e4ebe22c4ca6ba3b1d220a46f94492efee2cd84ec3dd9eaa20fbe85a0a
3
+ size 564
tasks/rahmaniani2020/gurobi_solution_log/large_log_5.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41cd9a23d8987b16ca5911ad364dd321fe0cb39703ac143e1447fecced244a28
3
+ size 782
tasks/rahmaniani2020/gurobi_solution_log/tiny_log.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:074260615dedff252a18829ff34a4b1d935c8fc540695f97d6d53f3f0ff44b00
3
+ size 54
tasks/rahmaniani2020/instance/large_instance_1.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa25c299fc4f7f0da766af3bee6708f4db358c250ec9247e2718ee27daeb7e54
3
+ size 492587
tasks/rahmaniani2020/instance/large_instance_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a57bc62ab3143cd1d1599d985a920ab2e1ce31f47baa63907ed99377f4c75f07
3
+ size 492603
tasks/rahmaniani2020/instance/large_instance_3.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1379028350c6595f958dfe5f4449da46fb85ac09309c4bbc1aecf6b3ac5e704
3
+ size 492656
tasks/rahmaniani2020/instance/large_instance_4.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc27975038f5568bece09e3859e39a0b33c0674aab1ccdcf53d875f53d63fbb1
3
+ size 492701
tasks/rahmaniani2020/instance/large_instance_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f216f98c67ef1df6b30557a5cb54d05640bd95badfe37aba5f87347fbef2bb51
3
+ size 492675
tasks/rahmaniani2020/instance/tiny_instance.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:239d1c6b63423d60477b7663440f801c464454037c11a3c448977714869d7069
3
+ size 5591
tasks/rahmaniani2020/instance_schema.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "num_facilities": "<int> Number of potential facility locations that may be opened.",
3
+ "num_customers": "<int> Number of customers whose demands must be served.",
4
+ "num_scenarios": "<int> Number of demand scenarios representing uncertainty.",
5
+ "total_capacity": "<int> Combined service capacity across all potential facilities.",
6
+ "max_total_demand": "<int> Highest aggregate customer demand among all scenarios.",
7
+ "facilities": {
8
+ "x_coordinates": "<list[float], length num_facilities> Horizontal coordinate of each potential facility on the service region grid.",
9
+ "y_coordinates": "<list[float], length num_facilities> Vertical coordinate of each potential facility on the service region grid.",
10
+ "fixed_costs": "<list[int], length num_facilities> One-time cost incurred for opening each facility.",
11
+ "capacities": "<list[int], length num_facilities> Maximum total flow each facility can ship to customers if opened."
12
+ },
13
+ "customers": {
14
+ "x_coordinates": "<list[float], length num_customers> Horizontal coordinate of each customer on the service region grid.",
15
+ "y_coordinates": "<list[float], length num_customers> Vertical coordinate of each customer on the service region grid."
16
+ },
17
+ "routing_costs": "<list[list[float]], shape [num_facilities][num_customers]> Per-unit cost of shipping goods from each facility to each customer.",
18
+ "scenarios": {
19
+ "num_scenarios": "<int> Number of demand scenarios representing uncertainty.",
20
+ "probabilities": "<list[float], length num_scenarios> Likelihood of each demand scenario occurring.",
21
+ "demands": "<list[list[int]], shape [num_scenarios][num_customers]> Quantity of goods each customer requires under each scenario."
22
+ }
23
+ }
tasks/rahmaniani2020/mathematical_formulation.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Original Formulation: Benders Dual Decomposition – Generic MILP and Stochastic Capacitated Facility Location (SFL)
2
+
3
+ Rahmaniani, Ahmed, Crainic, Gendreau, Rei. “The Benders Dual Decomposition Method,” *Operations Research*, 2020.
4
+
5
+ ## Generic MILP (Problem (1), Section 1)
6
+
7
+ The paper develops the Benders Dual Decomposition (BDD) method for a generic mixed-integer linear program of the form $$\begin{align}
8
+ \min_{y,x}\ & f^\top y + c^\top x \tag{1a} \\
9
+ \text{s.t.}\ & B y \ge b, \tag{1b} \\
10
+ & W x + T y \ge h, \tag{1c} \\
11
+ & y \in \mathbb{Z}_+^n, \quad x \in \mathbb{R}_+^m, \tag{1d}
12
+ \end{align}$$ where $f\in\mathbb{R}^n$, $B\in\mathbb{R}^{k\times n}$, $b\in\mathbb{R}^k$, $c\in\mathbb{R}^m$, $W\in\mathbb{R}^{\ell\times m}$, $h\in\mathbb{R}^\ell$, $T\in\mathbb{R}^{\ell\times n}$. The problem is feasible and bounded.
13
+
14
+ ## Test Problem: Stochastic Capacitated Facility Location (SFL) (Appendix D.2)
15
+
16
+ **Sets and indices:** $N$ set of potential facility sites (indexed by $i$); $M$ set of customers (indexed by $j$); $S$ set of scenarios (indexed by $s$).
17
+
18
+ **Parameters:** $f_i$ fixed cost of opening facility $i$; $u_i$ capacity of facility $i$; $c_{ij}$ routing cost per unit of flow from $i$ to $j$; $p_s$ probability of scenario $s$; $d_j^s$ demand of customer $j$ in scenario $s$.
19
+
20
+ **Decision variables:** $y_i\in\{0,1\}$ equals $1$ iff facility $i$ is opened (first stage); $x_{ij}^s\ge 0$ is the flow from facility $i$ to customer $j$ under scenario $s$ (second stage).
21
+
22
+ **Formulation (D.4)–(D.7):** $$\begin{align}
23
+ \text{SFL}:\quad \min\ & \sum_{i\in N} f_i\, y_i
24
+ + \sum_{s\in S} p_s \sum_{i\in N}\sum_{j\in M} c_{ij}\, x_{ij}^s \tag{D.4}\\
25
+ \text{s.t.}\ & \sum_{i\in N} x_{ij}^s \ge d_j^s,
26
+ && \forall\, j\in M,\ s\in S \tag{D.5}\\
27
+ & \sum_{j\in M} x_{ij}^s \le u_i\, y_i,
28
+ && \forall\, i\in N,\ s\in S \tag{D.6}\\
29
+ & \sum_{i\in N} u_i\, y_i \ge \max_{s\in S}\sum_{j\in M} d_j^s \tag{D.7}\\
30
+ & y_i \in \{0,1\},\ \ x_{ij}^s \ge 0,
31
+ && \forall\, i\in N,\ j\in M,\ s\in S. \notag
32
+ \end{align}$$
33
+
34
+ **Interpretation.** Objective (D.4) combines first-stage facility opening costs with expected second-stage routing costs. Constraint (D.5) enforces demand satisfaction in every scenario; (D.6) bounds flows out of each facility by its capacity (and forces no flow from closed facilities); (D.7) is the complete-recourse property, ensuring that the total opened capacity covers the worst-case total demand.
35
+
36
+ Matching SFL to the generic form (1): the first-stage decisions are $y$ with $f = (f_i)_{i\in N}$ and constraint (D.7) taking the role of $By\ge b$; the second-stage recourse $x=(x_{ij}^s)$ and constraints (D.5)–(D.6) correspond to $Wx+Ty\ge h$.
tasks/rahmaniani2020/problem_description.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Problem Description
2
+
3
+ A company must decide which facilities to open among a set of potential locations in order to serve a set of customers whose demands are uncertain. The uncertainty is represented by a finite set of scenarios, each occurring with a known probability. The input data specifies, for each potential facility, a fixed cost of opening, a service capacity, and geographic coordinates. For each customer, the data specifies geographic coordinates. For each facility-customer pair, a per-unit routing cost is given. For each scenario, a probability of occurrence is provided along with the demand of every customer under that scenario.
4
+
5
+ The company must choose which facilities to open and, for every scenario, how much flow to ship from each open facility to each customer. The goal is to minimize the sum of two cost components: the total fixed costs of opening the selected facilities, plus the expected routing cost, where the expected routing cost is the probability-weighted sum over all scenarios of the per-unit routing costs times the flows shipped in that scenario.
6
+
7
+ The following rules govern these decisions. In every scenario, each customer's total inbound flow from all facilities must be at least as large as that customer's demand under that scenario. In every scenario, each facility's total outbound flow to all customers must not exceed that facility's capacity if the facility is open, and must be zero if the facility is not open. Finally, the total capacity of all opened facilities must be at least as large as the maximum, taken over all scenarios, of the total demand of all customers in that scenario; this ensures that the opened facilities can collectively satisfy all customer demands regardless of which scenario is realized.
tasks/rahmaniani2020/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/rahmaniani2020/solution_schema.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "objective_value": "<float> Total expected cost, combining facility opening costs and expected routing costs across scenarios.",
3
+ "y": "<list[int], length num_facilities> Whether each facility is opened (1 = opened, 0 = not opened)."
4
+ }
tasks/rahmaniani2022/feasibility_check.py ADDED
@@ -0,0 +1,798 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Feasibility checker (Tier C variant) for the Energy Systems Planning problem.
4
+
5
+ From: Jacobson et al. (2023) - "A computationally efficient Benders
6
+ decomposition for energy systems planning problems with detailed
7
+ operations and time-coupling constraints"
8
+
9
+ Constraints 1-12 validate the submitted investment witness. Constraint 49
10
+ substitutes the complete investment-and-operation vector into trusted offline
11
+ model coefficients without invoking an optimizer.
12
+
13
+ Constraint 49 (objective consistency): trusted fixed-investment recourse solve.
14
+ """
15
+
16
+ import argparse
17
+ import json
18
+ import math
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
23
+ from solverless_witness import require_linked_variables, validate_complete_witness
24
+
25
+ # FRONTIEROR_RELEASE_CONTRACT_V2
26
+ _FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('investments', 'model_variables', 'objective_value', 'storage_energy_investments', 'transmission_investments')
27
+ _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('investments', 'model_variables')
28
+ _FRONTIEROR_DERIVED_FIELD_RULES = ()
29
+ _FRONTIEROR_CONDITIONAL_FIELD_RULES = ()
30
+
31
+
32
+ def _frontieror_validate_solution_contract(solution):
33
+ """Return a structured rejection when the public solution contract is absent."""
34
+ violations = []
35
+ if not isinstance(solution, dict):
36
+ violations.append("solution must be a JSON object")
37
+ else:
38
+ missing = [
39
+ field
40
+ for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS
41
+ if field not in solution or solution[field] is None
42
+ ]
43
+ if missing:
44
+ violations.append(
45
+ "missing required solution field(s): " + ", ".join(missing)
46
+ )
47
+
48
+ for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES:
49
+ if solution.get(discriminator) != expected_value:
50
+ continue
51
+ conditional_missing = [
52
+ field
53
+ for field in fields
54
+ if field not in solution or solution[field] is None
55
+ ]
56
+ if conditional_missing:
57
+ violations.append(
58
+ "missing conditionally required solution field(s): "
59
+ + ", ".join(conditional_missing)
60
+ )
61
+
62
+ empty = [
63
+ field
64
+ for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS
65
+ if field in solution and solution[field] in (None, [], {})
66
+ ]
67
+ if empty:
68
+ violations.append(
69
+ "empty required decision witness field(s): " + ", ".join(empty)
70
+ )
71
+
72
+ for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES:
73
+ try:
74
+ if operation == "assignment_key_set":
75
+ reported_set = set(solution[target])
76
+ expected_set = {entry[source_key] for entry in solution[source]}
77
+ if reported_set != expected_set:
78
+ violations.append(
79
+ f"{target}={sorted(reported_set)} does not match the "
80
+ f"decision-derived value {sorted(expected_set)}"
81
+ )
82
+ continue
83
+
84
+ reported = float(solution[target])
85
+ if operation == "length":
86
+ expected = float(len(solution[source]))
87
+ elif operation == "mapping_value":
88
+ expected = float(solution[source][source_key])
89
+ else:
90
+ raise ValueError("unknown derived-field operation")
91
+ except (KeyError, TypeError, ValueError, OverflowError):
92
+ violations.append(
93
+ f"cannot derive {target} from decision witness field {source}"
94
+ )
95
+ continue
96
+ if (
97
+ reported != reported
98
+ or expected != expected
99
+ or reported in (float("inf"), float("-inf"))
100
+ or expected in (float("inf"), float("-inf"))
101
+ or abs(reported - expected) > 1e-6
102
+ ):
103
+ violations.append(
104
+ f"{target}={reported} does not match the decision-derived "
105
+ f"value {expected}"
106
+ )
107
+
108
+ if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS:
109
+ objective = solution.get("objective_value")
110
+ if (
111
+ isinstance(objective, bool)
112
+ or not isinstance(objective, (int, float))
113
+ or objective != objective
114
+ or objective in (float("inf"), float("-inf"))
115
+ ):
116
+ violations.append("objective_value must be a finite JSON number")
117
+
118
+ if not violations:
119
+ return None
120
+ return {
121
+ "feasible": False,
122
+ "violated_constraints": ["solution_schema"],
123
+ "violations": violations,
124
+ "violation_magnitudes": [],
125
+ }
126
+
127
+
128
+ def _frontieror_write_unexpected_rejection(error):
129
+ """Turn malformed candidate/checker exceptions into a normal rejection."""
130
+ import json as _frontieror_json
131
+ import sys as _frontieror_sys
132
+
133
+ result_path = None
134
+ for index, argument in enumerate(_frontieror_sys.argv):
135
+ if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv):
136
+ result_path = _frontieror_sys.argv[index + 1]
137
+ break
138
+ if argument.startswith("--result_path="):
139
+ result_path = argument.split("=", 1)[1]
140
+ break
141
+ if not result_path:
142
+ return False
143
+ try:
144
+ with open(result_path, "w") as result_handle:
145
+ _frontieror_json.dump(
146
+ {
147
+ "feasible": False,
148
+ "violated_constraints": ["malformed_solution"],
149
+ "violations": [
150
+ "checker rejected malformed candidate: "
151
+ + type(error).__name__
152
+ + ": "
153
+ + str(error)[:500]
154
+ ],
155
+ "violation_magnitudes": [],
156
+ },
157
+ result_handle,
158
+ indent=2,
159
+ )
160
+ except Exception:
161
+ return False
162
+ return True
163
+
164
+
165
+ def check_feasibility(instance, solution, instance_path=None):
166
+ """Run all checks and return the same dict shape as the original main()
167
+ writes to result_path. Exposed as a function so the diff-test harness
168
+ can call it directly (parallel to other paper's _new.py files)."""
169
+ inst = instance
170
+ sol = solution
171
+
172
+ tol = 1e-5
173
+ eps = 1e-5
174
+
175
+ violated_constraints = set()
176
+ violation_details = {} # constraint_idx -> list of message strings
177
+ violation_magnitudes = [] # list of dicts
178
+
179
+ def record_violation(constraint_idx, lhs, rhs, raw_excess, msg):
180
+ violated_constraints.add(constraint_idx)
181
+ if constraint_idx not in violation_details:
182
+ violation_details[constraint_idx] = []
183
+ violation_details[constraint_idx].append(msg)
184
+ normalizer = max(abs(rhs), eps)
185
+ violation_magnitudes.append({
186
+ "constraint": constraint_idx,
187
+ "lhs": lhs,
188
+ "rhs": rhs,
189
+ "raw_excess": raw_excess,
190
+ "normalizer": normalizer,
191
+ "ratio": raw_excess / normalizer
192
+ })
193
+
194
+ def check_leq(constraint_idx, lhs, rhs, msg):
195
+ excess = lhs - rhs
196
+ if excess > tol:
197
+ record_violation(constraint_idx, lhs, rhs, excess, msg)
198
+
199
+ def check_geq(constraint_idx, lhs, rhs, msg):
200
+ excess = rhs - lhs
201
+ if excess > tol:
202
+ record_violation(constraint_idx, lhs, rhs, excess, msg)
203
+
204
+ def check_eq(constraint_idx, lhs, rhs, msg):
205
+ excess = abs(lhs - rhs)
206
+ if excess > tol:
207
+ record_violation(constraint_idx, lhs, rhs, excess, msg)
208
+
209
+ # =========================================================================
210
+ # Check if solution has investment data
211
+ # =========================================================================
212
+ has_investments = "investments" in sol
213
+
214
+ if not has_investments:
215
+ return {
216
+ "feasible": False,
217
+ "violated_constraints": ["solution_schema"],
218
+ "violations": ["No investment solution provided (null or missing)"],
219
+ "violation_magnitudes": []
220
+ }
221
+
222
+ # =========================================================================
223
+ # Extract instance data
224
+ # =========================================================================
225
+ generators = inst["generators"]
226
+ gen_params = inst["generator_parameters"]
227
+ existing_cap = inst["existing_capacity"]
228
+ trans_lines = inst["transmission_lines"]
229
+ release_convention = inst["released_investment_convention"]
230
+
231
+ num_gen = len(generators)
232
+ G = list(range(num_gen))
233
+ G_UC = [g for g in G if generators[g]["is_UC"]]
234
+ G_STOR = [g for g in G if generators[g]["is_storage"]]
235
+ G_HYDRO = [g for g in G if generators[g]["is_hydro"]]
236
+ G_NONRET = set(g for g in G if not generators[g]["can_retire"])
237
+ G_UC_set = set(G_UC)
238
+ G_STOR_set = set(G_STOR)
239
+ L = list(range(len(trans_lines)))
240
+
241
+ # Released convention: physical UC blocks and integer 1-MW non-UC blocks.
242
+ gamma_P = {}
243
+ for g in G:
244
+ if g in G_UC_set:
245
+ gamma_P[g] = generators[g]["capacity_size_MW"]
246
+ else:
247
+ gamma_P[g] = float(release_convention["non_uc_power_increment_MW"])
248
+
249
+ # gamma_E: energy_capacity_size_MWh for UC storage, 1.0 otherwise
250
+ gamma_E = {}
251
+ for g in G_STOR:
252
+ if g in G_UC_set:
253
+ rtype = generators[g]["resource_type"]
254
+ gamma_E[g] = gen_params[rtype]["energy_capacity_size_MWh"]
255
+ else:
256
+ gamma_E[g] = float(
257
+ release_convention["non_uc_storage_energy_increment_MWh"]
258
+ )
259
+
260
+ # Existing power capacity
261
+ y_P_0 = {}
262
+ for g in G:
263
+ y_P_0[g] = existing_cap.get(str(g), 0.0)
264
+
265
+ # Existing energy capacity for storage
266
+ y_E_0 = {}
267
+ for g in G_STOR:
268
+ rtype = generators[g]["resource_type"]
269
+ bp = gen_params[rtype]
270
+ phys_cap_size = bp.get("capacity_size_MW", 1.0)
271
+ e_size = bp.get("energy_capacity_size_MWh", 1.0)
272
+ if phys_cap_size > 0:
273
+ y_E_0[g] = (y_P_0[g] / phys_cap_size) * e_size
274
+ else:
275
+ y_E_0[g] = 0.0
276
+
277
+ # Max capacities
278
+ y_P_max = {}
279
+ for g in G:
280
+ rtype = generators[g]["resource_type"]
281
+ y_P_max[g] = gen_params[rtype]["max_capacity_MW"]
282
+
283
+ y_E_max = {}
284
+ for g in G_STOR:
285
+ rtype = generators[g]["resource_type"]
286
+ y_E_max[g] = gen_params[rtype]["max_energy_capacity_MWh"]
287
+
288
+ # Storage duration limits
289
+ rho_min_stor = {}
290
+ rho_max_stor = {}
291
+ for g in G_STOR:
292
+ rtype = generators[g]["resource_type"]
293
+ rho_min_stor[g] = gen_params[rtype]["min_duration_MWh_per_MW"]
294
+ rho_max_stor[g] = gen_params[rtype]["max_duration_MWh_per_MW"]
295
+
296
+ # =========================================================================
297
+ # Extract solution investment variables
298
+ # =========================================================================
299
+ inv = sol.get("investments", {})
300
+ stor_inv = sol.get("storage_energy_investments", {})
301
+ trans_inv = sol.get("transmission_investments", {})
302
+
303
+ # Power capacity variables
304
+ y_P_new = {}
305
+ y_P_ret = {}
306
+ y_P = {}
307
+ for g in G:
308
+ gs = str(g)
309
+ if gs in inv:
310
+ y_P_new[g] = inv[gs]["new_units"]
311
+ y_P_ret[g] = abs(inv[gs]["retired_units"])
312
+ y_P[g] = inv[gs]["total_capacity_MW"]
313
+ else:
314
+ y_P_new[g] = 0.0
315
+ y_P_ret[g] = 0.0
316
+ y_P[g] = y_P_0[g]
317
+
318
+ # Storage energy capacity variables
319
+ y_E_new = {}
320
+ y_E = {}
321
+ for g in G_STOR:
322
+ gs = str(g)
323
+ if gs in stor_inv:
324
+ y_E_new[g] = stor_inv[gs]["new_units"]
325
+ y_E[g] = stor_inv[gs]["total_energy_MWh"]
326
+ else:
327
+ y_E_new[g] = 0.0
328
+ y_E[g] = y_E_0[g]
329
+
330
+ # Derive y_E_ret from constraint (13d)
331
+ y_E_ret = {}
332
+ for g in G_STOR:
333
+ if gamma_E[g] > 0:
334
+ y_E_ret[g] = y_E_new[g] - (y_E[g] - y_E_0[g]) / gamma_E[g]
335
+ else:
336
+ y_E_ret[g] = 0.0
337
+
338
+ # Transmission capacity variables
339
+ y_F_new = {}
340
+ y_F = {}
341
+ for l_idx in L:
342
+ ls = str(l_idx)
343
+ if ls in trans_inv:
344
+ y_F_new[l_idx] = trans_inv[ls]["new_MW"]
345
+ y_F[l_idx] = trans_inv[ls]["total_capacity_MW"]
346
+ else:
347
+ y_F_new[l_idx] = 0.0
348
+ y_F[l_idx] = trans_lines[l_idx]["existing_capacity_MW"]
349
+
350
+ # MILP investment variables, including transmission expansion, are integer
351
+ # counts of the increments declared above.
352
+ if sol.get("formulation", "MILP") == "MILP":
353
+ integer_values = [
354
+ (f"y_P_new[{g}]", y_P_new[g]) for g in G
355
+ ] + [
356
+ (f"y_P_ret[{g}]", y_P_ret[g]) for g in G
357
+ ] + [
358
+ (f"y_E_new[{g}]", y_E_new[g]) for g in G_STOR
359
+ ] + [
360
+ (f"y_F_new[{line}]", y_F_new[line]) for line in L
361
+ ]
362
+ for name, value in integer_values:
363
+ difference = abs(float(value) - round(float(value)))
364
+ if difference > 1e-4:
365
+ record_violation(
366
+ 50, float(value), float(round(float(value))), difference,
367
+ f"MILP investment variable {name}={value} is not integral",
368
+ )
369
+
370
+ # =========================================================================
371
+ # Check Investment Constraints (Constraints 1-12) -- unchanged from original
372
+ # =========================================================================
373
+
374
+ # Constraint 1 (12a)
375
+ for g in G:
376
+ lhs_val = gamma_P[g] * y_P_new[g]
377
+ rhs_val = y_P_max[g]
378
+ check_leq(1, lhs_val, rhs_val,
379
+ f"Gen {g} ({generators[g]['resource_type']}): "
380
+ f"gamma_P*y_P_new={lhs_val:.2f} exceeds max_cap={rhs_val:.2f}")
381
+
382
+ # Constraint 2 (12b)
383
+ for g in G:
384
+ lhs_val = gamma_P[g] * y_P_ret[g]
385
+ rhs_val = y_P_0[g]
386
+ check_leq(2, lhs_val, rhs_val,
387
+ f"Gen {g} ({generators[g]['resource_type']}): "
388
+ f"gamma_P*y_P_ret={lhs_val:.2f} exceeds existing_cap={rhs_val:.2f}")
389
+
390
+ # Constraint 3 (12c)
391
+ for g in G:
392
+ if g in G_NONRET:
393
+ lhs_val = y_P_ret[g]
394
+ rhs_val = 0.0
395
+ check_eq(3, lhs_val, rhs_val,
396
+ f"Gen {g} ({generators[g]['resource_type']}): "
397
+ f"non-retirable but y_P_ret={lhs_val:.6f}")
398
+
399
+ # Constraint 4 (12d)
400
+ for g in G:
401
+ lhs_val = y_P[g]
402
+ rhs_val = y_P_0[g] + gamma_P[g] * (y_P_new[g] - y_P_ret[g])
403
+ check_eq(4, lhs_val, rhs_val,
404
+ f"Gen {g} ({generators[g]['resource_type']}): "
405
+ f"y_P={lhs_val:.4f} != y_P_0+gamma_P*(new-ret)={rhs_val:.4f}")
406
+
407
+ # Constraint 5 (13a)
408
+ for g in G_STOR:
409
+ lhs_val = gamma_E[g] * y_E_new[g]
410
+ rhs_val = y_E_max[g]
411
+ check_leq(5, lhs_val, rhs_val,
412
+ f"Storage {g}: gamma_E*y_E_new={lhs_val:.2f} exceeds "
413
+ f"max_E_cap={rhs_val:.2f}")
414
+
415
+ # Constraint 6 (13b)
416
+ for g in G_STOR:
417
+ lhs_val = gamma_E[g] * y_E_ret[g]
418
+ rhs_val = y_E_0[g]
419
+ check_leq(6, lhs_val, rhs_val,
420
+ f"Storage {g}: gamma_E*y_E_ret={lhs_val:.2f} exceeds "
421
+ f"existing_E_cap={rhs_val:.2f}")
422
+
423
+ # Constraint 7 (13c)
424
+ for g in G_STOR:
425
+ if g in G_NONRET:
426
+ lhs_val = y_E_ret[g]
427
+ rhs_val = 0.0
428
+ check_eq(7, lhs_val, rhs_val,
429
+ f"Storage {g}: non-retirable but y_E_ret={lhs_val:.6f}")
430
+
431
+ # Constraint 8 (13d)
432
+ for g in G_STOR:
433
+ lhs_val = y_E[g]
434
+ rhs_val = y_E_0[g] + gamma_E[g] * (y_E_new[g] - y_E_ret[g])
435
+ check_eq(8, lhs_val, rhs_val,
436
+ f"Storage {g}: y_E={lhs_val:.4f} != "
437
+ f"y_E_0+gamma_E*(new-ret)={rhs_val:.4f}")
438
+
439
+ # Constraint 9 (13e)
440
+ for g in G_STOR:
441
+ lhs_val = rho_min_stor[g] * y_P[g]
442
+ rhs_val = y_E[g]
443
+ check_leq(9, lhs_val, rhs_val,
444
+ f"Storage {g}: rho_min*y_P={lhs_val:.2f} exceeds "
445
+ f"y_E={rhs_val:.2f}")
446
+
447
+ # Constraint 10 (13f)
448
+ for g in G_STOR:
449
+ lhs_val = rho_max_stor[g] * y_P[g]
450
+ rhs_val = y_E[g]
451
+ check_geq(10, lhs_val, rhs_val,
452
+ f"Storage {g}: rho_max*y_P={lhs_val:.2f} less than "
453
+ f"y_E={rhs_val:.2f}")
454
+
455
+ # Constraint 11 (14a)
456
+ for l_idx in L:
457
+ lhs_val = y_F_new[l_idx]
458
+ rhs_val = max(
459
+ 0.0,
460
+ trans_lines[l_idx]["max_capacity_MW"]
461
+ - trans_lines[l_idx]["existing_capacity_MW"],
462
+ )
463
+ check_leq(11, lhs_val, rhs_val,
464
+ f"Line {l_idx}: y_F_new={lhs_val:.2f} exceeds "
465
+ f"max_F_cap={rhs_val:.2f}")
466
+
467
+ # Constraint 12 (14b)
468
+ for l_idx in L:
469
+ lhs_val = y_F[l_idx]
470
+ rhs_val = trans_lines[l_idx]["existing_capacity_MW"] + y_F_new[l_idx]
471
+ check_eq(12, lhs_val, rhs_val,
472
+ f"Line {l_idx}: y_F={lhs_val:.4f} != "
473
+ f"y_F_0+y_F_new={rhs_val:.4f}")
474
+
475
+ # =========================================================================
476
+ # Constraints 13-48: skipped (operational variables not in solution).
477
+ # =========================================================================
478
+
479
+ # =========================================================================
480
+ # Constraint 49 (NEW): Objective-value envelope (Tier C anti-exploit)
481
+ #
482
+ # obj_lower = c^FIXED (Eq. 29, exact from investment variables)
483
+ # obj_upper = obj_lower + crude upper bounds on c^VAR, c^NSE, c^START,
484
+ # c^RPS, c^CO2 (loose but data-driven).
485
+ # =========================================================================
486
+ reported_obj = sol.get("objective_value")
487
+ try:
488
+ reported = float(reported_obj) if reported_obj is not None else None
489
+ except (TypeError, ValueError):
490
+ reported = None
491
+
492
+ if reported is not None:
493
+ # ------ Cost / parameter lookups (same conventions as gurobi_code.py) ------
494
+ def gp_val(g, key, default=0.0):
495
+ rtype = generators[g]["resource_type"]
496
+ return gen_params[rtype].get(key, default)
497
+
498
+ c_P_INV = {g: gp_val(g, "investment_cost_per_MW_yr") for g in G}
499
+ c_P_FOM = {g: gp_val(g, "fixed_OM_cost_per_MW_yr") for g in G}
500
+ c_VAR = {g: gp_val(g, "variable_cost_per_MWh") for g in G}
501
+ c_START = {g: gp_val(g, "start_up_cost", 0.0) for g in G_UC}
502
+ co2_rate = {g: gp_val(g, "CO2_emission_tons_per_MWh", 0.0) for g in G}
503
+
504
+ # Energy-side costs are explicit data, including released zeros.
505
+ if G_STOR and "battery" in gen_params:
506
+ c_E_INV_stor = {g: gen_params["battery"].get(
507
+ "energy_investment_cost_per_MWh_yr", 0.0) for g in G_STOR}
508
+ else:
509
+ c_E_INV_stor = {g: 0.0 for g in G_STOR}
510
+ c_E_FOM_stor = {
511
+ g: gen_params[generators[g]["resource_type"]].get(
512
+ "energy_fixed_OM_cost_per_MWh_yr", 0.0
513
+ )
514
+ for g in G_STOR
515
+ }
516
+ c_E_INV_hydro = {
517
+ g: gen_params[generators[g]["resource_type"]].get(
518
+ "energy_investment_cost_per_MWh_yr", 0.0
519
+ )
520
+ for g in G_HYDRO
521
+ }
522
+ c_E_FOM_hydro = {
523
+ g: gen_params[generators[g]["resource_type"]].get(
524
+ "energy_fixed_OM_cost_per_MWh_yr", 0.0
525
+ )
526
+ for g in G_HYDRO
527
+ }
528
+
529
+ # Transmission investment cost.
530
+ c_F_INV = {l_idx: trans_lines[l_idx].get("investment_cost_per_MW_yr", 0.0)
531
+ for l_idx in L}
532
+
533
+ # ------ Subperiod weights and total weighted hours / demand ------
534
+ params = inst.get("problem_parameters", {})
535
+ num_weeks = params.get("num_weeks", 0)
536
+ delta_w = params.get("hours_per_subperiod", 168)
537
+ total_hours = params.get("total_hours", num_weeks * delta_w)
538
+ subperiod_weights = inst.get("subperiod_weights", [1.0] * num_weeks)
539
+
540
+ # alpha_t = beta_w / delta_w; sum over t = sum_w beta_w
541
+ if delta_w > 0:
542
+ total_weighted_hours = float(sum(subperiod_weights))
543
+ else:
544
+ total_weighted_hours = float(total_hours)
545
+
546
+ # Total weighted demand = sum_{w,t in H_w, z} alpha_t * d_{z,t}
547
+ # alpha is constant beta_w/delta_w within each subperiod; we collapse by week.
548
+ demand = inst.get("demand", {})
549
+ total_weighted_demand = 0.0
550
+ if delta_w > 0:
551
+ for z_key, dem_list in demand.items():
552
+ # weight every hour by its subperiod's alpha
553
+ for w in range(num_weeks):
554
+ beta_w = subperiod_weights[w] if w < len(subperiod_weights) else 1.0
555
+ alpha = beta_w / delta_w
556
+ t0 = w * delta_w
557
+ t1 = min((w + 1) * delta_w, len(dem_list))
558
+ for t in range(t0, t1):
559
+ total_weighted_demand += alpha * float(dem_list[t])
560
+
561
+ # ------ obj_lower = c^FIXED (Eq. 29, exact) ------
562
+ c_fixed = 0.0
563
+ # Investment costs: sum_g c_P_INV * gamma_P * y_P_new = c_P_INV * new_MW
564
+ for g in G:
565
+ new_mw = gamma_P[g] * float(y_P_new[g])
566
+ c_fixed += float(c_P_INV[g]) * new_mw
567
+ # Storage energy investment: sum c_E_INV * gamma_E * y_E_new
568
+ for g in G_STOR:
569
+ c_fixed += float(c_E_INV_stor[g]) * gamma_E[g] * float(y_E_new[g])
570
+ c_fixed += float(c_E_FOM_stor[g]) * float(y_E[g])
571
+ for g in G_HYDRO:
572
+ duration = float(gen_params[generators[g]["resource_type"]]["duration_MWh_per_MW"])
573
+ c_fixed += float(c_E_INV_hydro[g]) * duration * float(y_P_new[g])
574
+ c_fixed += float(c_E_FOM_hydro[g]) * duration * float(y_P[g])
575
+ # Fixed O&M: sum_g c_P_FOM * y_P
576
+ for g in G:
577
+ c_fixed += float(c_P_FOM[g]) * float(y_P[g])
578
+ # Transmission investment
579
+ for l_idx in L:
580
+ c_fixed += float(c_F_INV[l_idx]) * float(y_F_new[l_idx])
581
+
582
+ obj_lower = c_fixed
583
+
584
+ # ------ obj_upper = c^FIXED + crude upper bound on operational costs ------
585
+ # Each generator can produce at most y_P[g] MWh per hour for all hours;
586
+ # similarly storage withdrawals are bounded by y_P[g].
587
+ c_var_max = 0.0
588
+ for g in G:
589
+ c_var_max += float(c_VAR[g]) * float(y_P[g]) * total_weighted_hours
590
+ for g in G_STOR:
591
+ c_var_max += float(c_VAR[g]) * float(y_P[g]) * total_weighted_hours
592
+
593
+ # NSE upper bound: every segment's max fraction of demand, at its cost
594
+ c_nse_max = 0.0
595
+ for seg in inst.get("consumer_segments", []):
596
+ seg_zone = seg.get("zone")
597
+ seg_cost = float(seg.get("cost_per_MWh", 0.0))
598
+ seg_frac = float(seg.get("max_nse_fraction", 0.0))
599
+ if seg_cost <= 0.0 or seg_frac <= 0.0:
600
+ continue
601
+ zone_key = str(seg_zone)
602
+ if zone_key not in demand:
603
+ continue
604
+ dem_list = demand[zone_key]
605
+ zone_weighted_demand = 0.0
606
+ if delta_w > 0:
607
+ for w in range(num_weeks):
608
+ beta_w = subperiod_weights[w] if w < len(subperiod_weights) else 1.0
609
+ alpha = beta_w / delta_w
610
+ t0 = w * delta_w
611
+ t1 = min((w + 1) * delta_w, len(dem_list))
612
+ for t in range(t0, t1):
613
+ zone_weighted_demand += alpha * float(dem_list[t])
614
+ c_nse_max += seg_cost * seg_frac * zone_weighted_demand
615
+
616
+ # START upper bound: each UC unit could start every hour
617
+ c_start_max = 0.0
618
+ for g in G_UC:
619
+ if gamma_P[g] <= 0:
620
+ continue
621
+ num_units_bound = float(y_P[g]) / gamma_P[g]
622
+ c_start_max += float(c_START.get(g, 0.0)) * num_units_bound * total_weighted_hours
623
+
624
+ # RPS / CO2 noncompliance penalties (loose upper bounds)
625
+ policy = inst.get("policy", {})
626
+ c_RPS = float(policy.get("RPS_noncompliance_cost_per_MWh", 0.0) or 0.0)
627
+ c_CO2 = float(policy.get("CO2_noncompliance_cost_per_ton", 0.0) or 0.0)
628
+ # RPS noncompliance bounded by total weighted demand (full RPS shortfall)
629
+ c_rps_max = c_RPS * total_weighted_demand
630
+ # CO2 noncompliance bounded by max possible emissions (all gens at full)
631
+ co2_max_emissions = 0.0
632
+ for g in G:
633
+ co2_max_emissions += float(co2_rate.get(g, 0.0)) * float(y_P[g]) * total_weighted_hours
634
+ for g in G_STOR:
635
+ co2_max_emissions += float(co2_rate.get(g, 0.0)) * float(y_P[g]) * total_weighted_hours
636
+ c_co2_max = c_CO2 * co2_max_emissions
637
+
638
+ obj_upper = c_fixed + c_var_max + c_nse_max + c_start_max + c_rps_max + c_co2_max
639
+
640
+ # Safety floor so even an all-zero investment doesn't make obj_upper
641
+ # too small to catch MAX_FLOAT; tied to total demand at $1/MWh.
642
+ obj_upper = max(obj_upper, 1.0 + total_weighted_demand)
643
+
644
+ # ------ Compare ------
645
+ tol_obj_lo = max(1e-3, 1e-3 * abs(obj_lower))
646
+ tol_obj_hi = max(1e-3, 1e-3 * abs(obj_upper))
647
+
648
+ # NaN / Inf are always rejected.
649
+ if math.isnan(reported) or math.isinf(reported):
650
+ record_violation(
651
+ 49, float("nan" if math.isnan(reported) else reported),
652
+ float(obj_upper),
653
+ float("inf"),
654
+ f"Constraint 49 (Objective consistency): reported objective_value="
655
+ f"{reported_obj!r} is not a finite number; "
656
+ f"expected value in [{obj_lower:.6g}, {obj_upper:.6g}]."
657
+ )
658
+ else:
659
+ shortfall = obj_lower - reported
660
+ overshoot = reported - obj_upper
661
+ if shortfall > tol_obj_lo:
662
+ record_violation(
663
+ 49, float(obj_lower), float(reported), float(shortfall),
664
+ f"Constraint 49 (Objective consistency): reported objective_value="
665
+ f"{reported:.6f} is below the lower bound obj_lower=c^FIXED="
666
+ f"{obj_lower:.6f}; shortfall={shortfall:.6g}, tol={tol_obj_lo:.6g}"
667
+ )
668
+ if overshoot > tol_obj_hi:
669
+ record_violation(
670
+ 49, float(reported), float(obj_upper), float(overshoot),
671
+ f"Constraint 49 (Objective consistency): reported objective_value="
672
+ f"{reported:.6f} exceeds worst-case upper bound obj_upper="
673
+ f"{obj_upper:.6f} (c^FIXED={c_fixed:.6f}, c^VAR_max={c_var_max:.6g}, "
674
+ f"c^NSE_max={c_nse_max:.6g}, c^START_max={c_start_max:.6g}, "
675
+ f"c^RPS_max={c_rps_max:.6g}, c^CO2_max={c_co2_max:.6g}); "
676
+ f"overshoot={overshoot:.6g}, tol={tol_obj_hi:.6g}"
677
+ )
678
+
679
+ # The envelope above remains a cheap early screen. For an otherwise valid
680
+ # plan, validate the complete hourly witness by direct substitution.
681
+ if not violated_constraints and reported is not None and math.isfinite(reported):
682
+ try:
683
+ if instance_path is None:
684
+ raise ValueError("instance_path is required for solverless validation")
685
+ expected, witness_errors, _ = validate_complete_witness(
686
+ instance_path, sol, Path(__file__).resolve().parent
687
+ )
688
+ links = {}
689
+ investments = sol.get("investments", {})
690
+ for generator in range(len(inst["generators"])):
691
+ entry = investments.get(str(generator), {})
692
+ links[f"y_P_new[{generator}]"] = float(entry.get("new_units", 0.0))
693
+ links[f"y_P_ret[{generator}]"] = abs(float(entry.get("retired_units", 0.0)))
694
+ if "total_capacity_MW" in entry:
695
+ links[f"y_P[{generator}]"] = float(entry["total_capacity_MW"])
696
+ storage = sol.get("storage_energy_investments", {})
697
+ for key, entry in storage.items():
698
+ generator = int(key)
699
+ links[f"y_E_new[{generator}]"] = float(entry.get("new_units", 0.0))
700
+ links[f"y_E[{generator}]"] = float(entry["total_energy_MWh"])
701
+ transmission = sol.get("transmission_investments", {})
702
+ for line in range(len(inst["transmission_lines"])):
703
+ entry = transmission.get(str(line), {})
704
+ links[f"y_F_new[{line}]"] = float(entry.get("new_MW", 0.0))
705
+ if "total_capacity_MW" in entry:
706
+ links[f"y_F[{line}]"] = float(entry["total_capacity_MW"])
707
+ witness_errors.extend(require_linked_variables(sol, links))
708
+ if witness_errors or expected is None:
709
+ raise ValueError("; ".join(witness_errors[:20]) or "missing witness objective")
710
+ except Exception as error:
711
+ record_violation(
712
+ 49,
713
+ 1.0,
714
+ 0.0,
715
+ 1.0,
716
+ "Constraint 49 (Objective consistency): trusted fixed-investment "
717
+ f"recourse failed: {type(error).__name__}: {str(error)[:300]}",
718
+ )
719
+ else:
720
+ difference = abs(reported - expected)
721
+ objective_tol = max(1e-3, 1e-4 * max(1.0, abs(expected)))
722
+ if difference > objective_tol:
723
+ record_violation(
724
+ 49,
725
+ reported,
726
+ expected,
727
+ difference,
728
+ "Constraint 49 (Objective consistency): reported "
729
+ f"objective_value={reported:.6f} does not equal trusted "
730
+ f"fixed-investment cost={expected:.6f} "
731
+ f"(difference={difference:.6g}, tol={objective_tol:.6g})",
732
+ )
733
+
734
+ # =========================================================================
735
+ # Build output (matches original feasibility_check.py shape)
736
+ # =========================================================================
737
+ sorted_violated = sorted(violated_constraints)
738
+ aggregated_violations = []
739
+ for c in sorted_violated:
740
+ msgs = violation_details[c]
741
+ if len(msgs) == 1:
742
+ aggregated_violations.append(msgs[0])
743
+ else:
744
+ aggregated_violations.append(
745
+ f"Constraint {c}: {len(msgs)} violations. "
746
+ f"Example: {msgs[0]}")
747
+
748
+ return {
749
+ "feasible": len(sorted_violated) == 0,
750
+ "violated_constraints": sorted_violated,
751
+ "violations": aggregated_violations,
752
+ "violation_magnitudes": violation_magnitudes
753
+ }
754
+
755
+
756
+ def main():
757
+ parser = argparse.ArgumentParser(
758
+ description="Feasibility checker for energy systems planning solutions")
759
+ parser.add_argument("--instance_path", type=str, required=True)
760
+ parser.add_argument("--solution_path", type=str, required=True)
761
+ parser.add_argument("--result_path", type=str, required=True)
762
+ args = parser.parse_args()
763
+
764
+ with open(args.instance_path) as f:
765
+ inst = json.load(f)
766
+ with open(args.solution_path) as f:
767
+ sol = json.load(f)
768
+ _frontieror_contract_result = _frontieror_validate_solution_contract(sol)
769
+ if _frontieror_contract_result is not None:
770
+ with open(args.result_path, "w") as _frontieror_result_handle:
771
+ json.dump(
772
+ _frontieror_contract_result,
773
+ _frontieror_result_handle,
774
+ indent=2,
775
+ )
776
+ return
777
+
778
+ result = check_feasibility(inst, sol, args.instance_path)
779
+
780
+ with open(args.result_path, "w") as f:
781
+ json.dump(result, f, indent=2)
782
+
783
+ if result["feasible"]:
784
+ print("Solution is FEASIBLE (investment constraints + exact recourse objective).")
785
+ else:
786
+ print(f"Solution is INFEASIBLE. Violated constraints: {result['violated_constraints']}")
787
+ for msg in result["violations"]:
788
+ print(f" - {msg}")
789
+
790
+
791
+ if __name__ == "__main__":
792
+ try:
793
+ main()
794
+ except Exception as _frontieror_unexpected_error:
795
+ if not _frontieror_write_unexpected_rejection(
796
+ _frontieror_unexpected_error
797
+ ):
798
+ raise
tasks/rahmaniani2022/gurobi_code.py ADDED
@@ -0,0 +1,991 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Monolithic energy systems planning MILP model from Jacobson et al. (2023),
3
+ "A computationally efficient Benders decomposition for energy systems planning
4
+ problems with detailed operations and time-coupling constraints."
5
+
6
+ Implements the full formulation (Appendix B) using Gurobi.
7
+ """
8
+
9
+ import argparse
10
+ import json
11
+ import time
12
+ import gurobipy as gp
13
+ from gurobipy import GRB
14
+ import os as _os, sys as _sys
15
+ # Walk up from this file's directory to find repo root (containing scripts/).
16
+ _GUROBI_CODE_START_TIME = time.time()
17
+ _repo = _os.path.dirname(_os.path.abspath(__file__))
18
+ while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')):
19
+ _repo = _os.path.dirname(_repo)
20
+ if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')):
21
+ _sys.path.insert(0, _repo)
22
+ try:
23
+ from scripts.utils.gurobi_log_helper import install_gurobi_logger
24
+ except ImportError:
25
+ def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable
26
+ pass
27
+
28
+
29
+ def load_instance(path):
30
+ with open(path) as f:
31
+ return json.load(f)
32
+
33
+
34
+ def build_model(inst, formulation="MILP", quiet=False):
35
+ """Build the monolithic Gurobi model from the instance data."""
36
+
37
+ m = gp.Model("energy_systems_planning")
38
+ m.setParam("Threads", 1)
39
+ if quiet:
40
+ m.setParam("OutputFlag", 0)
41
+
42
+ # =========================================================================
43
+ # Unpack instance data
44
+ # =========================================================================
45
+ params = inst["problem_parameters"]
46
+ policy = inst["policy"]
47
+ generators = inst["generators"]
48
+ gen_params = inst["generator_parameters"]
49
+ existing_cap = inst["existing_capacity"]
50
+ demand = inst["demand"]
51
+ consumer_segs = inst["consumer_segments"]
52
+ trans_lines = inst["transmission_lines"]
53
+ availability = inst["availability"]
54
+ hydro_inflow = inst["hydro_inflow"]
55
+ subperiod_weights = inst["subperiod_weights"]
56
+
57
+ num_zones = params["num_zones"]
58
+ num_weeks = params["num_weeks"]
59
+ delta_w = params["hours_per_subperiod"] # 168
60
+ total_hours = params["total_hours"]
61
+
62
+ # =========================================================================
63
+ # Build index sets
64
+ # =========================================================================
65
+ G = list(range(len(generators)))
66
+ G_UC = [g for g in G if generators[g]["is_UC"]]
67
+ G_nonUC = [g for g in G if not generators[g]["is_UC"]]
68
+ G_STOR = [g for g in G if generators[g]["is_storage"]]
69
+ G_HYDRO = [g for g in G if generators[g]["is_hydro"]]
70
+ G_RPS = [g for g in G if generators[g]["is_RPS_qualifying"]]
71
+ G_NONRET = [g for g in G if not generators[g]["can_retire"]]
72
+ G_NONRET_set = set(G_NONRET)
73
+ G_UC_set = set(G_UC)
74
+ G_STOR_set = set(G_STOR)
75
+ G_HYDRO_set = set(G_HYDRO)
76
+
77
+ # Resources that have min output but are NOT UC, storage, or hydro
78
+ G_minout = [g for g in G if not generators[g]["is_UC"]
79
+ and not generators[g]["is_storage"]
80
+ and not generators[g]["is_hydro"]]
81
+
82
+ Z = list(range(num_zones))
83
+ W = list(range(num_weeks))
84
+ L = list(range(len(trans_lines)))
85
+
86
+ # G_z: generators in zone z
87
+ G_z = {z: [] for z in Z}
88
+ for g in G:
89
+ G_z[generators[g]["zone"]].append(g)
90
+
91
+ G_z_STOR = {z: [g for g in G_z[z] if g in G_STOR_set] for z in Z}
92
+
93
+ # Lines into / out of zone z
94
+ I_z_in = {z: [] for z in Z}
95
+ I_z_out = {z: [] for z in Z}
96
+ for l_idx, line in enumerate(trans_lines):
97
+ I_z_out[line["from_zone"]].append(l_idx)
98
+ I_z_in[line["to_zone"]].append(l_idx)
99
+
100
+ # Subperiod structure: H_w, t_w_0 (first), t_w (last)
101
+ # Hours are 0-indexed internally
102
+ H_w = {}
103
+ t_w_0 = {}
104
+ t_w_last = {}
105
+ for w in W:
106
+ start = w * delta_w
107
+ end = (w + 1) * delta_w
108
+ H_w[w] = list(range(start, end))
109
+ t_w_0[w] = start
110
+ t_w_last[w] = end - 1
111
+
112
+ T = list(range(total_hours))
113
+
114
+ # Map each timestep to its subperiod
115
+ t_to_w = {}
116
+ for w in W:
117
+ for t in H_w[w]:
118
+ t_to_w[t] = w
119
+
120
+ # =========================================================================
121
+ # Parameters
122
+ # =========================================================================
123
+
124
+ release_convention = inst["released_investment_convention"]
125
+
126
+ # gamma_P: released investment increment. UC resources use their physical
127
+ # cluster size; non-UC resources use explicit 1-MW integer increments.
128
+ gamma_P = {}
129
+ for g in G:
130
+ if g in G_UC_set:
131
+ gamma_P[g] = generators[g]["capacity_size_MW"]
132
+ else:
133
+ gamma_P[g] = float(release_convention["non_uc_power_increment_MW"])
134
+
135
+ # gamma_E: energy capacity size for storage
136
+ gamma_E = {}
137
+ for g in G_STOR:
138
+ # Per math_model line 38: gamma_E_SIZE set to 1 for g not in G^UC
139
+ # Battery is non-UC, so gamma_E = 1.0
140
+ if g in G_UC_set:
141
+ gamma_E[g] = gen_params["battery"]["energy_capacity_size_MWh"]
142
+ else:
143
+ gamma_E[g] = float(
144
+ release_convention["non_uc_storage_energy_increment_MWh"]
145
+ )
146
+
147
+ # Existing capacities
148
+ y_P_0 = {}
149
+ for g in G:
150
+ y_P_0[g] = existing_cap.get(str(g), 0.0)
151
+
152
+ y_E_0 = {}
153
+ for g in G_STOR:
154
+ bp = gen_params["battery"]
155
+ # existing energy = (existing_MW / capacity_size_MW) * energy_capacity_size_MWh
156
+ if bp["capacity_size_MW"] > 0:
157
+ y_E_0[g] = (y_P_0[g] / bp["capacity_size_MW"]) * bp["energy_capacity_size_MWh"]
158
+ else:
159
+ y_E_0[g] = 0.0
160
+
161
+ # alpha_t = beta_w / delta_w
162
+ alpha = {}
163
+ for w in W:
164
+ a = subperiod_weights[w] / delta_w
165
+ for t in H_w[w]:
166
+ alpha[t] = a
167
+
168
+ # Generator type parameters
169
+ def gp_val(g, key, default=0.0):
170
+ rtype = generators[g]["resource_type"]
171
+ p = gen_params[rtype]
172
+ return p.get(key, default)
173
+
174
+ # Cost parameters
175
+ c_P_INV = {g: gp_val(g, "investment_cost_per_MW_yr") for g in G}
176
+ c_P_FOM = {g: gp_val(g, "fixed_OM_cost_per_MW_yr") for g in G}
177
+ c_VAR = {g: gp_val(g, "variable_cost_per_MWh") for g in G}
178
+ c_START = {g: gp_val(g, "start_up_cost") for g in G_UC}
179
+
180
+ c_E_INV_stor = {g: gen_params["battery"]["energy_investment_cost_per_MWh_yr"] for g in G_STOR}
181
+ c_E_FOM_stor = {
182
+ g: gen_params["battery"]["energy_fixed_OM_cost_per_MWh_yr"]
183
+ for g in G_STOR
184
+ }
185
+
186
+ # These released zero values are now explicit instance parameters.
187
+ c_E_INV_hydro = {
188
+ g: gen_params["hydro"]["energy_investment_cost_per_MWh_yr"]
189
+ for g in G_HYDRO
190
+ }
191
+ c_E_FOM_hydro = {
192
+ g: gen_params["hydro"]["energy_fixed_OM_cost_per_MWh_yr"]
193
+ for g in G_HYDRO
194
+ }
195
+
196
+ # Hydro duration rho_g
197
+ rho_hydro = {g: gen_params["hydro"]["duration_MWh_per_MW"] for g in G_HYDRO}
198
+
199
+ # Max capacities
200
+ y_P_max = {g: gp_val(g, "max_capacity_MW") for g in G}
201
+ y_E_max = {g: gen_params["battery"]["max_energy_capacity_MWh"] for g in G_STOR}
202
+
203
+ # Storage parameters
204
+ eta_charge = {g: gen_params["battery"]["charging_efficiency"] for g in G_STOR}
205
+ eta_discharge = {g: gen_params["battery"]["discharging_efficiency"] for g in G_STOR}
206
+ eta_self_discharge = {g: gen_params["battery"]["self_discharge_rate_pct"] for g in G_STOR}
207
+ rho_min_stor = {g: gen_params["battery"]["min_duration_MWh_per_MW"] for g in G_STOR}
208
+ rho_max_stor = {g: gen_params["battery"]["max_duration_MWh_per_MW"] for g in G_STOR}
209
+
210
+ # Operational parameters
211
+ min_output = {g: gp_val(g, "min_output_frac") for g in G}
212
+ ramp_up = {g: gp_val(g, "ramp_up_rate_pct_per_hr") for g in G}
213
+ ramp_down = {g: gp_val(g, "ramp_down_rate_pct_per_hr") for g in G}
214
+ min_up_time = {g: int(gp_val(g, "min_up_time_hr")) for g in G_UC}
215
+ min_down_time = {g: int(gp_val(g, "min_down_time_hr")) for g in G_UC}
216
+
217
+ # Availability
218
+ avail = {}
219
+ for g in G:
220
+ key = str(g)
221
+ if key in availability:
222
+ avail[g] = availability[key]
223
+ else:
224
+ avail[g] = [1.0] * total_hours
225
+
226
+ # Hydro inflow
227
+ h_inflow = {}
228
+ for g in G_HYDRO:
229
+ key = str(g)
230
+ if key in hydro_inflow:
231
+ h_inflow[g] = hydro_inflow[key]
232
+ else:
233
+ h_inflow[g] = [0.0] * total_hours
234
+
235
+ # Demand
236
+ d_zt = {}
237
+ for z in Z:
238
+ dem = demand[str(z)]
239
+ for t in T:
240
+ d_zt[z, t] = dem[t]
241
+
242
+ # Emissions
243
+ co2_rate = {g: gp_val(g, "CO2_emission_tons_per_MWh") for g in G}
244
+
245
+ # Policy
246
+ RPS_share = policy["RPS_share"]
247
+ CO2_cap_rate = policy["CO2_cap_tons_per_MWh"]
248
+ c_RPS = policy["RPS_noncompliance_cost_per_MWh"]
249
+ c_CO2 = policy["CO2_noncompliance_cost_per_ton"]
250
+
251
+ # NSE segments: list of (segment_id, zone, max_nse_fraction, cost_per_MWh)
252
+ # Build unique (s, z) pairs
253
+ nse_segments = []
254
+ for seg in consumer_segs:
255
+ nse_segments.append((seg["segment_id"], seg["zone"],
256
+ seg["max_nse_fraction"], seg["cost_per_MWh"]))
257
+
258
+ # Transmission
259
+ y_F_0 = {l: trans_lines[l]["existing_capacity_MW"] for l in L}
260
+ y_F_max = {l: trans_lines[l]["max_capacity_MW"] for l in L}
261
+ c_F_INV = {l: trans_lines[l]["investment_cost_per_MW_yr"] for l in L}
262
+
263
+ # Determine variable type for investment
264
+ is_milp = (formulation == "MILP")
265
+ inv_vtype = GRB.INTEGER if is_milp else GRB.CONTINUOUS
266
+
267
+ # =========================================================================
268
+ # DECISION VARIABLES
269
+ # =========================================================================
270
+ print("Creating variables...")
271
+
272
+ # --- Investment variables ---
273
+ y_P_new = m.addVars(G, vtype=inv_vtype, lb=0, name="y_P_new")
274
+ y_P_ret = m.addVars(G, vtype=inv_vtype, lb=0, name="y_P_ret")
275
+ y_P = m.addVars(G, vtype=GRB.CONTINUOUS, lb=0, name="y_P")
276
+
277
+ y_E_new = m.addVars(G_STOR, vtype=inv_vtype, lb=0, name="y_E_new")
278
+ y_E_ret = m.addVars(G_STOR, vtype=inv_vtype, lb=0, name="y_E_ret")
279
+ y_E = m.addVars(G_STOR, vtype=GRB.CONTINUOUS, lb=0, name="y_E")
280
+
281
+ # Transmission expansion follows the same integer-MW MILP convention.
282
+ y_F_new = m.addVars(L, vtype=inv_vtype, lb=0, name="y_F_new")
283
+ y_F = m.addVars(L, vtype=GRB.CONTINUOUS, lb=0, name="y_F")
284
+
285
+ # --- Operational variables ---
286
+ # x_inj[g,t]: generation injection
287
+ x_inj = m.addVars(G, T, vtype=GRB.CONTINUOUS, lb=0, name="x_inj")
288
+
289
+ # x_wdw[g,t]: storage withdrawal (charging)
290
+ x_wdw = m.addVars(G_STOR, T, vtype=GRB.CONTINUOUS, lb=0, name="x_wdw")
291
+
292
+ # x_nse[s_idx, t]: NSE for segment index s_idx
293
+ nse_indices = [(i, t) for i in range(len(nse_segments)) for t in T]
294
+ x_nse = m.addVars(nse_indices, vtype=GRB.CONTINUOUS, lb=0, name="x_nse")
295
+
296
+ # x_soc[g,t]: state of charge (storage)
297
+ x_soc = m.addVars(G_STOR, T, vtype=GRB.CONTINUOUS, lb=0, name="x_soc")
298
+
299
+ # x_lvl[g,t]: reservoir level (hydro)
300
+ x_lvl = m.addVars(G_HYDRO, T, vtype=GRB.CONTINUOUS, lb=0, name="x_lvl")
301
+
302
+ # x_spill[g,t]: hydro spillage
303
+ x_spill = m.addVars(G_HYDRO, T, vtype=GRB.CONTINUOUS, lb=0, name="x_spill")
304
+
305
+ # x_flow[l,t]: transmission flow (free variable)
306
+ x_flow = m.addVars(L, T, vtype=GRB.CONTINUOUS, lb=-GRB.INFINITY, name="x_flow")
307
+
308
+ # UC variables (always continuous/relaxed)
309
+ x_commit = m.addVars(G_UC, T, vtype=GRB.CONTINUOUS, lb=0, name="x_commit")
310
+ x_start = m.addVars(G_UC, T, vtype=GRB.CONTINUOUS, lb=0, name="x_start")
311
+ x_shut = m.addVars(G_UC, T, vtype=GRB.CONTINUOUS, lb=0, name="x_shut")
312
+
313
+ # Policy slack variables
314
+ x_RPS = m.addVars(W, vtype=GRB.CONTINUOUS, lb=0, name="x_RPS")
315
+ x_CO2 = m.addVars(W, vtype=GRB.CONTINUOUS, lb=0, name="x_CO2")
316
+
317
+ m.update()
318
+
319
+ # =========================================================================
320
+ # OBJECTIVE FUNCTION (Eq. 29-34)
321
+ # =========================================================================
322
+ print("Building objective...")
323
+
324
+ # c^FIXED (Eq. 29)
325
+ c_fixed = gp.LinExpr()
326
+
327
+ # Investment costs: sum_g c_P_INV * gamma_P * y_P_new
328
+ for g in G:
329
+ c_fixed += c_P_INV[g] * gamma_P[g] * y_P_new[g]
330
+
331
+ # Storage energy investment: sum_{g in STOR} c_E_INV * gamma_E * y_E_new
332
+ for g in G_STOR:
333
+ c_fixed += c_E_INV_stor[g] * gamma_E[g] * y_E_new[g]
334
+
335
+ # Hydro energy investment: sum_{g in HYDRO} c_E_INV_hydro * rho_g * y_P_new
336
+ for g in G_HYDRO:
337
+ c_fixed += c_E_INV_hydro[g] * rho_hydro[g] * y_P_new[g]
338
+
339
+ # FOM: sum_g c_P_FOM * y_P
340
+ for g in G:
341
+ c_fixed += c_P_FOM[g] * y_P[g]
342
+
343
+ # Storage energy FOM: sum_{g in STOR} c_E_FOM * y_E
344
+ for g in G_STOR:
345
+ c_fixed += c_E_FOM_stor[g] * y_E[g]
346
+
347
+ # Hydro energy FOM: sum_{g in HYDRO} c_E_FOM_hydro * rho_g * y_P
348
+ for g in G_HYDRO:
349
+ c_fixed += c_E_FOM_hydro[g] * rho_hydro[g] * y_P[g]
350
+
351
+ # Transmission investment: sum_l c_F_INV * y_F_new
352
+ for l in L:
353
+ c_fixed += c_F_INV[l] * y_F_new[l]
354
+
355
+ # c^VAR (Eq. 30)
356
+ c_var = gp.LinExpr()
357
+ for g in G:
358
+ if c_VAR[g] == 0.0:
359
+ continue
360
+ for t in T:
361
+ c_var += c_VAR[g] * alpha[t] * x_inj[g, t]
362
+ for g in G_STOR:
363
+ if c_VAR[g] == 0.0:
364
+ continue
365
+ for t in T:
366
+ c_var += c_VAR[g] * alpha[t] * x_wdw[g, t]
367
+
368
+ # c^NSE (Eq. 31)
369
+ c_nse = gp.LinExpr()
370
+ for i, (sid, z, frac, cost) in enumerate(nse_segments):
371
+ if cost == 0.0:
372
+ continue
373
+ for t in T:
374
+ c_nse += cost * alpha[t] * x_nse[i, t]
375
+
376
+ # c^START (Eq. 32)
377
+ c_start = gp.LinExpr()
378
+ for g in G_UC:
379
+ if c_START[g] == 0.0:
380
+ continue
381
+ for t in T:
382
+ c_start += c_START[g] * alpha[t] * x_start[g, t]
383
+
384
+ # c^RPS + c^CO2 (Eq. 33)
385
+ c_policy = gp.LinExpr()
386
+ for w in W:
387
+ c_policy += c_RPS * x_RPS[w]
388
+ c_policy += c_CO2 * x_CO2[w]
389
+
390
+ m.setObjective(c_fixed + c_var + c_nse + c_start + c_policy, GRB.MINIMIZE)
391
+
392
+ # =========================================================================
393
+ # CONSTRAINTS
394
+ # =========================================================================
395
+
396
+ # ---- B.1 Investment Constraints ----
397
+ print("Adding investment constraints...")
398
+
399
+ # (12a) gamma_P * y_P_new <= y_P_max
400
+ for g in G:
401
+ m.addConstr(gamma_P[g] * y_P_new[g] <= y_P_max[g], name=f"inv_cap_{g}")
402
+
403
+ # (12b) gamma_P * y_P_ret <= y_P_0
404
+ for g in G:
405
+ m.addConstr(gamma_P[g] * y_P_ret[g] <= y_P_0[g], name=f"ret_cap_{g}")
406
+
407
+ # (12c) y_P_ret = 0 for non-retirable
408
+ for g in G_NONRET:
409
+ m.addConstr(y_P_ret[g] == 0, name=f"noret_{g}")
410
+
411
+ # (12d) y_P = y_P_0 + gamma_P * (y_P_new - y_P_ret)
412
+ for g in G:
413
+ m.addConstr(y_P[g] == y_P_0[g] + gamma_P[g] * (y_P_new[g] - y_P_ret[g]),
414
+ name=f"cap_bal_{g}")
415
+
416
+ # (13a) gamma_E * y_E_new <= y_E_max
417
+ for g in G_STOR:
418
+ m.addConstr(gamma_E[g] * y_E_new[g] <= y_E_max[g], name=f"stor_inv_{g}")
419
+
420
+ # (13b) gamma_E * y_E_ret <= y_E_0
421
+ for g in G_STOR:
422
+ m.addConstr(gamma_E[g] * y_E_ret[g] <= y_E_0[g], name=f"stor_ret_{g}")
423
+
424
+ # (13c) y_E_ret = 0 for non-retirable storage
425
+ for g in G_STOR:
426
+ if g in G_NONRET_set:
427
+ m.addConstr(y_E_ret[g] == 0, name=f"stor_noret_{g}")
428
+
429
+ # (13d) y_E = y_E_0 + gamma_E * (y_E_new - y_E_ret)
430
+ for g in G_STOR:
431
+ m.addConstr(y_E[g] == y_E_0[g] + gamma_E[g] * (y_E_new[g] - y_E_ret[g]),
432
+ name=f"stor_bal_{g}")
433
+
434
+ # (13e) rho_min * y_P <= y_E
435
+ for g in G_STOR:
436
+ m.addConstr(rho_min_stor[g] * y_P[g] <= y_E[g], name=f"stor_minrho_{g}")
437
+
438
+ # (13f) rho_max * y_P >= y_E
439
+ for g in G_STOR:
440
+ m.addConstr(rho_max_stor[g] * y_P[g] >= y_E[g], name=f"stor_maxrho_{g}")
441
+
442
+ # (14a) max_capacity_MW is total capacity after expansion.
443
+ for l in L:
444
+ m.addConstr(
445
+ y_F_new[l] <= max(0.0, y_F_max[l] - y_F_0[l]),
446
+ name=f"trans_inv_{l}",
447
+ )
448
+
449
+ # (14b) y_F = y_F_0 + y_F_new
450
+ for l in L:
451
+ m.addConstr(y_F[l] == y_F_0[l] + y_F_new[l], name=f"trans_bal_{l}")
452
+
453
+ # ---- B.2 Operational Constraints ----
454
+ print("Adding operational constraints...")
455
+
456
+ # (15) Power balance: for each zone z, timestep t
457
+ for z in Z:
458
+ for t in T:
459
+ lhs = gp.LinExpr()
460
+ # + sum_{g in G_z} x_inj
461
+ for g in G_z[z]:
462
+ lhs += x_inj[g, t]
463
+ # - sum_{g in G_z^STOR} x_wdw
464
+ for g in G_z_STOR[z]:
465
+ lhs -= x_wdw[g, t]
466
+ # - sum_{l in I_z_out} x_flow + sum_{l in I_z_in} x_flow
467
+ for l in I_z_out[z]:
468
+ lhs -= x_flow[l, t]
469
+ for l in I_z_in[z]:
470
+ lhs += x_flow[l, t]
471
+ # + sum_s x_nse
472
+ for i, (sid, sz, frac, cost) in enumerate(nse_segments):
473
+ if sz == z:
474
+ lhs += x_nse[i, t]
475
+ m.addConstr(lhs == d_zt[z, t], name=f"pbal_{z}_{t}")
476
+
477
+ # (16a) x_inj <= sigma * y_P for non-UC
478
+ print(" Output limits...")
479
+ for g in G_nonUC:
480
+ for t in T:
481
+ m.addConstr(x_inj[g, t] <= avail[g][t] * y_P[g],
482
+ name=f"out_lim_{g}_{t}")
483
+
484
+ # (16b) x_wdw <= sigma * y_P for storage
485
+ for g in G_STOR:
486
+ for t in T:
487
+ m.addConstr(x_wdw[g, t] <= avail[g][t] * y_P[g],
488
+ name=f"wdw_lim_{g}_{t}")
489
+
490
+ # (16c) x_inj + x_wdw <= y_P for storage
491
+ for g in G_STOR:
492
+ for t in T:
493
+ m.addConstr(x_inj[g, t] + x_wdw[g, t] <= y_P[g],
494
+ name=f"stor_pw_{g}_{t}")
495
+
496
+ # (16d) x_soc <= y_E
497
+ for g in G_STOR:
498
+ for t in T:
499
+ m.addConstr(x_soc[g, t] <= y_E[g], name=f"soc_lim_{g}_{t}")
500
+
501
+ # (16e) x_lvl <= rho * y_P for hydro
502
+ for g in G_HYDRO:
503
+ for t in T:
504
+ m.addConstr(x_lvl[g, t] <= rho_hydro[g] * y_P[g],
505
+ name=f"lvl_lim_{g}_{t}")
506
+
507
+ # (16f) eta_charge * x_wdw <= y_E - x_soc
508
+ for g in G_STOR:
509
+ for t in T:
510
+ m.addConstr(eta_charge[g] * x_wdw[g, t] <= y_E[g] - x_soc[g, t],
511
+ name=f"chrg_room_{g}_{t}")
512
+
513
+ # (16g) x_inj / eta_discharge <= x_soc
514
+ for g in G_STOR:
515
+ for t in T:
516
+ m.addConstr(x_inj[g, t] <= eta_discharge[g] * x_soc[g, t],
517
+ name=f"dchrg_avail_{g}_{t}")
518
+
519
+ # (17a) x_inj >= theta * y_P for non-UC, non-storage, non-hydro
520
+ print(" Minimum output...")
521
+ for g in G_minout:
522
+ theta = min_output[g]
523
+ if theta > 0:
524
+ for t in T:
525
+ m.addConstr(x_inj[g, t] >= theta * y_P[g],
526
+ name=f"min_out_{g}_{t}")
527
+
528
+ # (17b) x_inj + x_spill >= theta * y_P for hydro
529
+ for g in G_HYDRO:
530
+ theta = min_output[g]
531
+ if theta > 0:
532
+ for t in T:
533
+ m.addConstr(x_inj[g, t] + x_spill[g, t] >= theta * y_P[g],
534
+ name=f"hydro_min_{g}_{t}")
535
+
536
+ # (18a, 18b) -y_F <= x_flow <= y_F
537
+ print(" Transmission limits...")
538
+ for l in L:
539
+ for t in T:
540
+ m.addConstr(x_flow[l, t] <= y_F[l], name=f"flow_ub_{l}_{t}")
541
+ m.addConstr(-x_flow[l, t] <= y_F[l], name=f"flow_lb_{l}_{t}")
542
+
543
+ # (19) x_nse <= nu_s * d_{z,t}
544
+ print(" NSE limits...")
545
+ for i, (sid, z, frac, cost) in enumerate(nse_segments):
546
+ for t in T:
547
+ m.addConstr(x_nse[i, t] <= frac * d_zt[z, t],
548
+ name=f"nse_lim_{i}_{t}")
549
+
550
+ # (20a, 20b) Storage dynamics
551
+ print(" Storage dynamics...")
552
+ for g in G_STOR:
553
+ ec = eta_charge[g]
554
+ ed = eta_discharge[g]
555
+ sd = eta_self_discharge[g]
556
+ for w in W:
557
+ hours = H_w[w]
558
+ first = hours[0]
559
+ last = hours[-1]
560
+
561
+ # (20b) Wrap-around: first timestep links to last
562
+ m.addConstr(
563
+ x_soc[g, first] - x_soc[g, last] ==
564
+ ec * x_wdw[g, first] - x_inj[g, first] / ed - sd * x_soc[g, last],
565
+ name=f"soc_wrap_{g}_{w}")
566
+
567
+ # (20a) Interior timesteps
568
+ for idx in range(1, len(hours)):
569
+ t = hours[idx]
570
+ t_prev = hours[idx - 1]
571
+ m.addConstr(
572
+ x_soc[g, t] - x_soc[g, t_prev] ==
573
+ ec * x_wdw[g, t] - x_inj[g, t] / ed - sd * x_soc[g, t_prev],
574
+ name=f"soc_dyn_{g}_{t}")
575
+
576
+ # (20c, 20d) Hydro dynamics
577
+ print(" Hydro dynamics...")
578
+ for g in G_HYDRO:
579
+ for w in W:
580
+ hours = H_w[w]
581
+ first = hours[0]
582
+ last = hours[-1]
583
+
584
+ # (20d) Wrap-around
585
+ m.addConstr(
586
+ x_lvl[g, first] - x_lvl[g, last] ==
587
+ h_inflow[g][first] * y_P[g] - x_inj[g, first] - x_spill[g, first],
588
+ name=f"hydro_wrap_{g}_{w}")
589
+
590
+ # (20c) Interior timesteps
591
+ for idx in range(1, len(hours)):
592
+ t = hours[idx]
593
+ t_prev = hours[idx - 1]
594
+ m.addConstr(
595
+ x_lvl[g, t] - x_lvl[g, t_prev] ==
596
+ h_inflow[g][t] * y_P[g] - x_inj[g, t] - x_spill[g, t],
597
+ name=f"hydro_dyn_{g}_{t}")
598
+
599
+ # (21a-21d) Non-UC ramping
600
+ print(" Non-UC ramping...")
601
+ for g in G_nonUC:
602
+ mu_up = ramp_up[g]
603
+ mu_dn = ramp_down[g]
604
+ if mu_up == 0 and mu_dn == 0:
605
+ continue
606
+ for w in W:
607
+ hours = H_w[w]
608
+ first = hours[0]
609
+ last = hours[-1]
610
+
611
+ # (21c) wrap: x_inj[first] - x_inj[last] <= mu_up * y_P
612
+ if mu_up > 0:
613
+ m.addConstr(x_inj[g, first] - x_inj[g, last] <= mu_up * y_P[g],
614
+ name=f"ramp_up_wrap_{g}_{w}")
615
+ # (21d) wrap: x_inj[last] - x_inj[first] <= mu_dn * y_P
616
+ if mu_dn > 0:
617
+ m.addConstr(x_inj[g, last] - x_inj[g, first] <= mu_dn * y_P[g],
618
+ name=f"ramp_dn_wrap_{g}_{w}")
619
+
620
+ # (21a, 21b) Interior
621
+ for idx in range(1, len(hours)):
622
+ t = hours[idx]
623
+ t_prev = hours[idx - 1]
624
+ if mu_up > 0:
625
+ m.addConstr(x_inj[g, t] - x_inj[g, t_prev] <= mu_up * y_P[g],
626
+ name=f"ramp_up_{g}_{t}")
627
+ if mu_dn > 0:
628
+ m.addConstr(x_inj[g, t_prev] - x_inj[g, t] <= mu_dn * y_P[g],
629
+ name=f"ramp_dn_{g}_{t}")
630
+
631
+ # (22a-22g) UC constraints
632
+ print(" UC constraints...")
633
+ for g in G_UC:
634
+ gp_size = gamma_P[g]
635
+ theta = min_output[g]
636
+ for t in T:
637
+ # (22a) gamma * commit <= y_P
638
+ m.addConstr(gp_size * x_commit[g, t] <= y_P[g],
639
+ name=f"uc_cap_{g}_{t}")
640
+ # (22b) gamma * start <= y_P
641
+ m.addConstr(gp_size * x_start[g, t] <= y_P[g],
642
+ name=f"uc_start_cap_{g}_{t}")
643
+ # (22c) gamma * shut <= y_P
644
+ m.addConstr(gp_size * x_shut[g, t] <= y_P[g],
645
+ name=f"uc_shut_cap_{g}_{t}")
646
+ # (22d) x_inj >= commit * theta * gamma
647
+ m.addConstr(x_inj[g, t] >= x_commit[g, t] * theta * gp_size,
648
+ name=f"uc_min_{g}_{t}")
649
+ # (22e) x_inj <= commit * sigma * gamma
650
+ m.addConstr(x_inj[g, t] <= x_commit[g, t] * avail[g][t] * gp_size,
651
+ name=f"uc_max_{g}_{t}")
652
+
653
+ # (22f, 22g) Commitment state transitions
654
+ for w in W:
655
+ hours = H_w[w]
656
+ first = hours[0]
657
+ last = hours[-1]
658
+
659
+ # (22g) Wrap-around
660
+ m.addConstr(
661
+ x_commit[g, first] - x_commit[g, last] ==
662
+ x_start[g, first] - x_shut[g, first],
663
+ name=f"uc_trans_wrap_{g}_{w}")
664
+
665
+ # (22f) Interior
666
+ for idx in range(1, len(hours)):
667
+ t = hours[idx]
668
+ t_prev = hours[idx - 1]
669
+ m.addConstr(
670
+ x_commit[g, t] - x_commit[g, t_prev] ==
671
+ x_start[g, t] - x_shut[g, t],
672
+ name=f"uc_trans_{g}_{t}")
673
+
674
+ # (23a-23d) UC ramping
675
+ print(" UC ramping...")
676
+ for g in G_UC:
677
+ gp_size = gamma_P[g]
678
+ theta = min_output[g]
679
+ mu_up = ramp_up[g]
680
+ mu_dn = ramp_down[g]
681
+
682
+ for w in W:
683
+ hours = H_w[w]
684
+ first = hours[0]
685
+ last = hours[-1]
686
+
687
+ # Helper for ramp coefficients
688
+ def start_coeff_up(t_idx):
689
+ sig = avail[g][t_idx]
690
+ return min(sig, max(theta, mu_up))
691
+
692
+ def start_coeff_dn(t_idx):
693
+ sig = avail[g][t_idx]
694
+ return min(sig, max(theta, mu_dn))
695
+
696
+ # (23c) Wrap-around up: x_inj[first] - x_inj[last] <= ...
697
+ m.addConstr(
698
+ x_inj[g, first] - x_inj[g, last] <=
699
+ gp_size * mu_up * (x_commit[g, first] - x_start[g, first])
700
+ + gp_size * start_coeff_up(first) * x_start[g, first]
701
+ - gp_size * theta * x_shut[g, first],
702
+ name=f"uc_ramp_up_wrap_{g}_{w}")
703
+
704
+ # (23d) Wrap-around down: x_inj[last] - x_inj[first] <= ...
705
+ m.addConstr(
706
+ x_inj[g, last] - x_inj[g, first] <=
707
+ gp_size * mu_dn * (x_commit[g, first] - x_start[g, first])
708
+ + gp_size * start_coeff_dn(first) * x_start[g, first]
709
+ - gp_size * theta * x_shut[g, first],
710
+ name=f"uc_ramp_dn_wrap_{g}_{w}")
711
+
712
+ # (23a, 23b) Interior
713
+ for idx in range(1, len(hours)):
714
+ t = hours[idx]
715
+ t_prev = hours[idx - 1]
716
+
717
+ # (23a) Up
718
+ m.addConstr(
719
+ x_inj[g, t] - x_inj[g, t_prev] <=
720
+ gp_size * mu_up * (x_commit[g, t] - x_start[g, t])
721
+ + gp_size * start_coeff_up(t) * x_start[g, t]
722
+ - gp_size * theta * x_shut[g, t],
723
+ name=f"uc_ramp_up_{g}_{t}")
724
+
725
+ # (23b) Down
726
+ m.addConstr(
727
+ x_inj[g, t_prev] - x_inj[g, t] <=
728
+ gp_size * mu_dn * (x_commit[g, t] - x_start[g, t])
729
+ + gp_size * start_coeff_dn(t) * x_start[g, t]
730
+ - gp_size * theta * x_shut[g, t],
731
+ name=f"uc_ramp_dn_{g}_{t}")
732
+
733
+ # (24a, 24b, 25) Minimum up/down time
734
+ print(" Min up/down time...")
735
+ for g in G_UC:
736
+ gp_size = gamma_P[g]
737
+ tau_up = min_up_time[g]
738
+ tau_dn = min_down_time[g]
739
+
740
+ for w in W:
741
+ hours = H_w[w]
742
+ n_hours = len(hours)
743
+
744
+ for local_idx in range(n_hours):
745
+ t = hours[local_idx]
746
+
747
+ # (24a) x_commit[g,t] >= sum_{k in Omega_up(t)} x_start[g,k]
748
+ if tau_up > 0:
749
+ lhs = gp.LinExpr()
750
+ for step in range(tau_up + 1): # 0..tau_up
751
+ # phi_{w,step}(t): step steps before t (circular)
752
+ k_local = (local_idx - step) % n_hours
753
+ k = hours[k_local]
754
+ lhs += x_start[g, k]
755
+ m.addConstr(x_commit[g, t] >= lhs,
756
+ name=f"min_up_{g}_{t}")
757
+
758
+ # (24b) x_commit[g,t] + sum_{k in Omega_dn(t)} x_shut[g,k] <= y_P / gamma
759
+ if tau_dn > 0:
760
+ lhs = x_commit[g, t]
761
+ for step in range(tau_dn + 1): # 0..tau_dn
762
+ k_local = (local_idx - step) % n_hours
763
+ k = hours[k_local]
764
+ lhs += x_shut[g, k]
765
+ m.addConstr(lhs <= y_P[g] / gp_size,
766
+ name=f"min_dn_{g}_{t}")
767
+
768
+ # ---- B.3 Policy Constraints ----
769
+ print("Adding policy constraints...")
770
+
771
+ # Compute total weighted demand
772
+ total_weighted_demand = sum(alpha[t] * d_zt[z, t] for z in Z for t in T)
773
+
774
+ # (26) RPS constraint
775
+ if RPS_share > 0 or c_RPS > 0:
776
+ rps_lhs = gp.LinExpr()
777
+ for w in W:
778
+ for t in H_w[w]:
779
+ for g in G_RPS:
780
+ rps_lhs += alpha[t] * x_inj[g, t]
781
+ rps_lhs += x_RPS[w]
782
+ m.addConstr(rps_lhs >= RPS_share * total_weighted_demand, name="rps")
783
+
784
+ # (27a, 28) CO2 cap
785
+ # overline{c}^{CO2} = CO2_cap_tons_per_MWh * total_weighted_demand
786
+ # But for CO2 scenario, eq 28 says cap = 0.05 * total_weighted_demand
787
+ # The instance provides CO2_cap_tons_per_MWh which encodes this.
788
+ co2_cap = CO2_cap_rate * total_weighted_demand
789
+
790
+ co2_lhs = gp.LinExpr()
791
+ for w in W:
792
+ for t in H_w[w]:
793
+ for g in G:
794
+ if co2_rate[g] != 0:
795
+ co2_lhs += alpha[t] * co2_rate[g] * x_inj[g, t]
796
+ for g in G_STOR:
797
+ if co2_rate[g] != 0:
798
+ co2_lhs += alpha[t] * co2_rate[g] * x_wdw[g, t]
799
+ co2_lhs -= x_CO2[w]
800
+ m.addConstr(co2_lhs <= co2_cap, name="co2_cap")
801
+
802
+ if not quiet:
803
+ print(f"Model has {m.NumVars} variables and {m.NumConstrs} constraints.")
804
+ return m, {
805
+ "generators": generators,
806
+ "y_P_new": y_P_new,
807
+ "y_P_ret": y_P_ret,
808
+ "y_P": y_P,
809
+ "y_E_new": y_E_new,
810
+ "y_E_ret": y_E_ret,
811
+ "y_E": y_E,
812
+ "y_F_new": y_F_new,
813
+ "y_F": y_F,
814
+ "G": G,
815
+ "G_STOR": G_STOR,
816
+ "G_HYDRO": G_HYDRO,
817
+ "L": L,
818
+ "gamma_P": gamma_P,
819
+ "gamma_E": gamma_E,
820
+ }
821
+
822
+
823
+ def solve_model(m, time_limit=None, formulation="MILP"):
824
+ """Configure solver parameters and solve."""
825
+
826
+ tol = 1e-3
827
+
828
+ # Barrier method with crossover off (for monolithic)
829
+ m.Params.Method = 2 # Barrier
830
+ m.Params.Crossover = 0 # Crossover off
831
+ m.Params.BarConvTol = tol
832
+ m.Params.OptimalityTol = tol
833
+ m.Params.FeasibilityTol = tol
834
+
835
+ if formulation == "MILP":
836
+ m.Params.MIPGap = 1e-4
837
+
838
+ if time_limit is not None:
839
+ m.Params.TimeLimit = time_limit
840
+ m.Params.MIPFocus = 1
841
+ m.Params.NoRelHeurTime = min(60.0, time_limit * 0.05)
842
+
843
+ print("Solving...")
844
+ start_time = time.time()
845
+ m.optimize()
846
+ elapsed = time.time() - start_time
847
+ print(f"Solve time: {elapsed:.2f} seconds")
848
+
849
+ return elapsed
850
+
851
+
852
+ def extract_solution(m, model_data):
853
+ """Extract solution values and build output dict."""
854
+
855
+ sol = {}
856
+
857
+ status = m.Status
858
+ sol["status"] = status
859
+ sol["status_name"] = {
860
+ 1: "LOADED", 2: "OPTIMAL", 3: "INFEASIBLE", 4: "INF_OR_UNBD",
861
+ 5: "UNBOUNDED", 6: "CUTOFF", 7: "ITERATION_LIMIT",
862
+ 8: "NODE_LIMIT", 9: "TIME_LIMIT", 10: "SOLUTION_LIMIT",
863
+ 11: "INTERRUPTED", 12: "NUMERIC", 13: "SUBOPTIMAL",
864
+ 14: "INPROGRESS", 15: "USER_OBJ_LIMIT", 16: "WORK_LIMIT",
865
+ 17: "MEM_LIMIT"
866
+ }.get(status, "UNKNOWN")
867
+
868
+ if status in (GRB.OPTIMAL, GRB.SUBOPTIMAL, GRB.TIME_LIMIT, GRB.SOLUTION_LIMIT,
869
+ GRB.ITERATION_LIMIT, GRB.NODE_LIMIT, GRB.INTERRUPTED):
870
+ try:
871
+ sol["objective_value"] = m.ObjVal
872
+ except Exception:
873
+ sol["objective_value"] = None
874
+ else:
875
+ sol["objective_value"] = None
876
+
877
+ if m.SolCount > 0:
878
+ try:
879
+ sol["objective_bound"] = m.ObjBound
880
+ except Exception:
881
+ sol["objective_bound"] = None
882
+
883
+ # Extract investment decisions
884
+ investments = {}
885
+ generators = model_data["generators"]
886
+ y_P_new = model_data["y_P_new"]
887
+ y_P_ret = model_data["y_P_ret"]
888
+ y_P = model_data["y_P"]
889
+ gamma_P = model_data["gamma_P"]
890
+
891
+ for g in model_data["G"]:
892
+ gen = generators[g]
893
+ pnew = y_P_new[g].X
894
+ pret = y_P_ret[g].X
895
+ pcap = y_P[g].X
896
+ if abs(pnew) > 1e-6 or abs(pret) > 1e-6:
897
+ investments[str(g)] = {
898
+ "resource_type": gen["resource_type"],
899
+ "zone": gen["zone"],
900
+ "new_units": pnew,
901
+ "new_MW": pnew * gamma_P[g],
902
+ "retired_units": pret,
903
+ "retired_MW": pret * gamma_P[g],
904
+ "total_capacity_MW": pcap
905
+ }
906
+
907
+ sol["investments"] = investments
908
+
909
+ # Storage energy investments
910
+ stor_investments = {}
911
+ y_E_new = model_data["y_E_new"]
912
+ y_E = model_data["y_E"]
913
+ gamma_E = model_data["gamma_E"]
914
+ for g in model_data["G_STOR"]:
915
+ enew = y_E_new[g].X
916
+ ecap = y_E[g].X
917
+ if abs(enew) > 1e-6:
918
+ stor_investments[str(g)] = {
919
+ "new_units": enew,
920
+ "new_MWh": enew * gamma_E[g],
921
+ "total_energy_MWh": ecap
922
+ }
923
+ sol["storage_energy_investments"] = stor_investments
924
+
925
+ # Transmission investments
926
+ trans_investments = {}
927
+ y_F_new = model_data["y_F_new"]
928
+ y_F = model_data["y_F"]
929
+ for l in model_data["L"]:
930
+ fnew = y_F_new[l].X
931
+ if abs(fnew) > 1e-6:
932
+ trans_investments[str(l)] = {
933
+ "new_MW": fnew,
934
+ "total_capacity_MW": y_F[l].X
935
+ }
936
+ sol["transmission_investments"] = trans_investments
937
+ else:
938
+ sol["investments"] = {}
939
+ sol["storage_energy_investments"] = {}
940
+ sol["transmission_investments"] = {}
941
+
942
+ return sol
943
+
944
+
945
+ def main():
946
+ parser = argparse.ArgumentParser(
947
+ description="Monolithic energy systems planning model (Jacobson et al. 2023)")
948
+ parser.add_argument("--instance_path", type=str, required=True,
949
+ help="Path to JSON instance file")
950
+ parser.add_argument("--solution_path", type=str, default="gurobi_solution_1.json",
951
+ help="Path for output solution JSON")
952
+ parser.add_argument("--time_limit", type=int, default=None,
953
+ help="Solver time limit in seconds")
954
+ parser.add_argument("--formulation", type=str, default="MILP",
955
+ choices=["LP", "MILP"],
956
+ help="Formulation type (LP or MILP)")
957
+ parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions")
958
+ args = parser.parse_args()
959
+ install_gurobi_logger(args.log_path)
960
+
961
+ print(f"Loading instance from {args.instance_path}")
962
+ inst = load_instance(args.instance_path)
963
+
964
+ formulation = args.formulation
965
+ # If instance specifies only one formulation type, use that
966
+ form_types = inst["problem_parameters"].get("formulation_types", ["LP", "MILP"])
967
+ if formulation not in form_types:
968
+ print(f"Warning: requested formulation {formulation} not in instance types {form_types}.")
969
+
970
+ print(f"Building {formulation} model...")
971
+ model, model_data = build_model(inst, formulation=formulation)
972
+
973
+ elapsed = solve_model(model, time_limit=args.time_limit, formulation=formulation)
974
+
975
+ solution = extract_solution(model, model_data)
976
+ solution["solve_time_seconds"] = elapsed
977
+ solution["formulation"] = formulation
978
+ solution["instance_path"] = args.instance_path
979
+
980
+ print(f"\nStatus: {solution['status_name']}")
981
+ if solution["objective_value"] is not None:
982
+ print(f"Objective value: {solution['objective_value']:.6f}")
983
+
984
+ with open(args.solution_path, "w") as f:
985
+ solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME
986
+ json.dump(solution, f, indent=2)
987
+ print(f"Solution written to {args.solution_path}")
988
+
989
+
990
+ if __name__ == "__main__":
991
+ main()
tasks/rahmaniani2022/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/rahmaniani2022/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/rahmaniani2022/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/rahmaniani2022/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/rahmaniani2022/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/rahmaniani2022/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/rahmaniani2022/gurobi_solution/large_solution_1.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c31331734d4c0dc15b9607b9f6f522cfdc88b6c05853bbd32318afadc7b947e9
3
+ size 580345
tasks/rahmaniani2022/gurobi_solution/large_solution_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6418ba94f6699fabc1595e06fc247148f86c7e2abf44aa32613b7230e2bbadb4
3
+ size 428584
tasks/rahmaniani2022/gurobi_solution/large_solution_3.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f37ee8b8b2b44a71825a75d538954e987d4b0ae8613f06b6c78d18263fb5657e
3
+ size 553489
tasks/rahmaniani2022/gurobi_solution/large_solution_4.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e2c133201a1901112c439b6c0aff21e7e8751d36b5dcf8a93d6e10f5d99b7c7
3
+ size 540634
tasks/rahmaniani2022/gurobi_solution/large_solution_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c1af973c722b25b6fb6ca79eb81a939533e80a5a04e28407e151aa6786bb6d7
3
+ size 509345
tasks/rahmaniani2022/gurobi_solution/tiny_solution.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:109626733b8280583dfe1d6f2f72db0dd7e850f754e92da47bb7d0a7067a8ed4
3
+ size 912573
tasks/rahmaniani2022/gurobi_solution_log/large_log_1.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3abc3a128b4da4b5f3687c2d1169ebd7013bdd6f6366421f1471c60e348377b1
3
+ size 2618
tasks/rahmaniani2022/gurobi_solution_log/large_log_2.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68a5613e8c0fff9218eadd6d14e1ef0970f1160e72eea7fb4bed4ea5c4587129
3
+ size 2242
tasks/rahmaniani2022/gurobi_solution_log/large_log_3.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3fc1f1d414a17bb0f0be7d20cd20b379f0998e77d009bb76559bf0373b99673c
3
+ size 57
tasks/rahmaniani2022/gurobi_solution_log/large_log_4.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb928790663fe1c0afb2c712ec2c1bcb4d2bd846cd4b0a1a8b21d27a891ae65e
3
+ size 114
tasks/rahmaniani2022/gurobi_solution_log/large_log_5.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3cb9fc0fa06ea45684e37cfdc9ea88fe30614b8710a1e101947c2a3a7f5f60fc
3
+ size 557
tasks/rahmaniani2022/gurobi_solution_log/tiny_log.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc9e38e530f553ff3ed86d26b1615c19db3ee3ed0af07a37c789ebbfdc0d5490
3
+ size 109
tasks/rahmaniani2022/instance/large_instance_1.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eadcf5c89bfcd588e1825a6027e7ce42effe2ff164771ed9a12e8d36dcf6d8f7
3
+ size 1953647
tasks/rahmaniani2022/instance/large_instance_2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bdeb36375a8968da973ea273fff77c65d0f54ec471392e628e64b942dc9c429c
3
+ size 1952683
tasks/rahmaniani2022/instance/large_instance_3.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:404f2d3c0bedf8761c024ef820118a3e4244f5da75832d5b7ca6620d9a15ef30
3
+ size 1947572
tasks/rahmaniani2022/instance/large_instance_4.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6887fe1608a652cdec62abd626e3dd9dee7cf820ccf42efa3292caf316747cce
3
+ size 1942600
tasks/rahmaniani2022/instance/large_instance_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f326d6f07923a2cd0d03c1f24ef34f860705d8d809a3bc5b7812d4bce30732f1
3
+ size 1942894