-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstep3.py
More file actions
1645 lines (1401 loc) · 50 KB
/
Copy pathstep3.py
File metadata and controls
1645 lines (1401 loc) · 50 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import pandas as pd
import pyomo.environ as pyo
from helpers import (
solve_pyomo_model,
build_generator_fleet,
build_wind_availability,
build_demand_data,
)
from plots_step3 import plot_base_vs_stressed_nodal_prices
def build_step3_inputs(data_folder, hour):
"""
Build generator, demand, bus, and line data for one selected hour.
Parameters
----------
data_folder : str
Path to the input data folder.
hour : int
Selected hour for the market-clearing problem.
Returns
-------
generators : pandas.DataFrame
Generator data with hourly available capacity ``p_max``.
demands : pandas.DataFrame
Demand data for the selected hour.
buses : pandas.DataFrame
Bus table.
lines : pandas.DataFrame
Line table with susceptance and line limits.
info : dict
Summary information for the selected hour.
"""
generators = build_generator_fleet(data_folder).copy()
wind_availability = build_wind_availability(data_folder).copy()
demands = build_demand_data(data_folder, hour=hour).copy()
# Read and clean transmission line data.
lines = pd.read_csv(f"{data_folder}/rts24_lines.csv").rename(
columns={
"From": "from_node",
"To": "to_node",
"Reactance_pu": "x",
"Capacity_MVA": "f_max",
}
)
lines["line_id"] = [f"L{i + 1}" for i in range(len(lines))]
lines[["from_node", "to_node"]] = lines[["from_node", "to_node"]].astype(int)
lines[["x", "f_max"]] = lines[["x", "f_max"]].astype(float)
lines["b"] = 1.0 / lines["x"]
# Build the full bus list from generators, demand, and lines.
bus_ids = sorted(
set(generators["node"])
.union(set(demands["node"]))
.union(set(lines["from_node"]))
.union(set(lines["to_node"]))
)
buses = pd.DataFrame({"node": bus_ids})
# Start from nominal generator capacity.
generators["p_max"] = generators["p_nom"].astype(float)
# Adjust wind capacity using the selected-hour wind capacity factors.
wind_cf_hour = (
wind_availability.loc[wind_availability["hour"] == hour]
.set_index("gen_id")["cf"]
)
is_wind = generators["type"].astype(str).str.lower() == "wind"
generators.loc[is_wind, "p_max"] = (
generators.loc[is_wind, "gen_id"].map(wind_cf_hour).fillna(0.0)
* generators.loc[is_wind, "p_nom"]
)
info = {
"hour": hour,
"system_demand": demands["q_max"].sum(),
"number_of_buses": len(buses),
"number_of_lines": len(lines),
"average_wind_cf": float(wind_cf_hour.mean()) if not wind_cf_hour.empty else 0.0,
}
return generators, demands, buses, lines, info
def apply_line_changes(lines, line_changes):
"""
Apply line-capacity changes to a line table.
Parameters
----------
lines : pandas.DataFrame
Original line table.
line_changes : dict or None
Mapping ``line_id -> value``.
If ``value <= 1.0``, it is interpreted as a multiplicative factor.
If ``value > 1.0``, it is interpreted as a new absolute capacity.
Returns
-------
lines_mod : pandas.DataFrame
Modified line table.
"""
lines_mod = lines.copy()
if line_changes:
for line_id, value in line_changes.items():
mask = lines_mod["line_id"] == line_id
if value <= 1.0:
lines_mod.loc[mask, "f_max"] = lines_mod.loc[mask, "f_max"] * value
else:
lines_mod.loc[mask, "f_max"] = float(value)
return lines_mod
def extract_model_stats(model, solve_time):
"""
Extract model statistics for reporting.
Parameters
----------
model : pyomo.environ.ConcreteModel
Solved Pyomo model.
solve_time : float
Computational time in seconds.
Returns
-------
stats : dict
Dictionary with number of variables, number of constraints, and solve time.
"""
return {
"n_variables": sum(
1 for _ in model.component_data_objects(pyo.Var, active=True)
),
"n_constraints": sum(
1 for _ in model.component_data_objects(pyo.Constraint, active=True)
),
"solve_time": solve_time,
}
# ============================================================
# NODAL MODEL
# ============================================================
def build_step3_nodal_model(generators, demands, buses, lines):
"""
Build the nodal welfare-maximizing market model with DC power flow.
Parameters
----------
generators : pandas.DataFrame
Generator input data.
demands : pandas.DataFrame
Demand input data.
buses : pandas.DataFrame
Bus table.
lines : pandas.DataFrame
Line table.
Returns
-------
model : pyomo.environ.ConcreteModel
Nodal optimization model.
"""
model = pyo.ConcreteModel()
generators = generators.copy()
demands = demands.copy()
buses = buses.copy()
lines = lines.copy()
generators["gen_id"] = generators["gen_id"].astype(str)
demands["load_id"] = demands["load_id"].astype(str)
lines["line_id"] = lines["line_id"].astype(str)
model.G = pyo.Set(initialize=generators["gen_id"].tolist())
model.D = pyo.Set(initialize=demands["load_id"].tolist())
model.N = pyo.Set(initialize=buses["node"].tolist())
model.L = pyo.Set(initialize=lines["line_id"].tolist())
# Generator, demand, and line parameters.
model.Pmax = pyo.Param(
model.G, initialize=generators.set_index("gen_id")["p_max"].to_dict()
)
model.MCost = pyo.Param(
model.G, initialize=generators.set_index("gen_id")["mcost"].to_dict()
)
model.GenNode = pyo.Param(
model.G, initialize=generators.set_index("gen_id")["node"].to_dict()
)
model.Qmax = pyo.Param(
model.D, initialize=demands.set_index("load_id")["q_max"].to_dict()
)
model.BidPrice = pyo.Param(
model.D, initialize=demands.set_index("load_id")["bid_price"].to_dict()
)
model.LoadNode = pyo.Param(
model.D, initialize=demands.set_index("load_id")["node"].to_dict()
)
model.LineFrom = pyo.Param(
model.L, initialize=lines.set_index("line_id")["from_node"].to_dict()
)
model.LineTo = pyo.Param(
model.L, initialize=lines.set_index("line_id")["to_node"].to_dict()
)
model.LineB = pyo.Param(
model.L, initialize=lines.set_index("line_id")["b"].to_dict()
)
model.LineFmax = pyo.Param(
model.L, initialize=lines.set_index("line_id")["f_max"].to_dict()
)
# Decision variables.
model.p = pyo.Var(model.G, domain=pyo.NonNegativeReals)
model.q = pyo.Var(model.D, domain=pyo.NonNegativeReals)
model.theta = pyo.Var(model.N, domain=pyo.Reals)
model.f = pyo.Var(model.L, domain=pyo.Reals)
# Maximize welfare.
model.Objective = pyo.Objective(
expr=sum(model.BidPrice[d] * model.q[d] for d in model.D)
- sum(model.MCost[g] * model.p[g] for g in model.G),
sense=pyo.maximize,
)
model.GeneratorCapacity = pyo.Constraint(
model.G, rule=lambda m, g: m.p[g] <= m.Pmax[g]
)
model.DemandLimit = pyo.Constraint(
model.D, rule=lambda m, d: m.q[d] <= m.Qmax[d]
)
# DC line flow equations and line limits.
def line_flow_rule(m, l):
return m.f[l] == m.LineB[l] * (
m.theta[m.LineFrom[l]] - m.theta[m.LineTo[l]]
)
model.LineFlow = pyo.Constraint(model.L, rule=line_flow_rule)
model.LineUpper = pyo.Constraint(
model.L, rule=lambda m, l: m.f[l] <= m.LineFmax[l]
)
model.LineLower = pyo.Constraint(
model.L, rule=lambda m, l: m.f[l] >= -m.LineFmax[l]
)
# Nodal balance at every bus.
def nodal_balance_rule(m, n):
generation = sum(m.p[g] for g in m.G if m.GenNode[g] == n)
demand = sum(m.q[d] for d in m.D if m.LoadNode[d] == n)
inflow = sum(m.f[l] for l in m.L if m.LineTo[l] == n)
outflow = sum(m.f[l] for l in m.L if m.LineFrom[l] == n)
return generation + inflow == demand + outflow
model.NodalBalance = pyo.Constraint(model.N, rule=nodal_balance_rule)
# Fix one reference angle.
slack_bus = int(buses["node"].min())
model.ReferenceAngle = pyo.Constraint(expr=model.theta[slack_bus] == 0.0)
model.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
return model
def solve_step3_nodal(generators, demands, buses, lines, solver_name):
"""
Solve the nodal Step 3 model.
Parameters
----------
generators : pandas.DataFrame
Generator input data.
demands : pandas.DataFrame
Demand input data.
buses : pandas.DataFrame
Bus table.
lines : pandas.DataFrame
Line table.
solver_name : str
Solver name.
Returns
-------
model : pyomo.environ.ConcreteModel
Solved nodal model.
solve_time : float
Computational time in seconds.
"""
model = build_step3_nodal_model(generators, demands, buses, lines)
start_time = time.perf_counter()
solve_pyomo_model(model, solver_name=solver_name)
solve_time = time.perf_counter() - start_time
return model, solve_time
def extract_nodal_results(model, generators, demands, buses, lines, solve_time):
"""
Extract detailed nodal results and summary metrics.
Parameters
----------
model : pyomo.environ.ConcreteModel
Solved nodal model.
generators : pandas.DataFrame
Generator input data.
demands : pandas.DataFrame
Demand input data.
buses : pandas.DataFrame
Bus table.
lines : pandas.DataFrame
Line table.
solve_time : float
Computational time in seconds.
Returns
-------
results : dict
Detailed nodal result tables and summary metrics.
"""
generation = generators.copy()
generation["gen_id"] = generation["gen_id"].astype(str)
generation["dispatch"] = generation["gen_id"].map(lambda g: pyo.value(model.p[g]))
generation["unused_capacity"] = generation["p_max"] - generation["dispatch"]
demand = demands.copy()
demand["load_id"] = demand["load_id"].astype(str)
demand["served_demand"] = demand["load_id"].map(lambda d: pyo.value(model.q[d]))
demand["curtailed_demand"] = demand["q_max"] - demand["served_demand"]
buses_out = buses.copy()
buses_out["theta"] = buses_out["node"].map(lambda n: pyo.value(model.theta[n]))
buses_out["nodal_price"] = buses_out["node"].map(
lambda n: -model.dual.get(model.NodalBalance[n], 0.0)
)
nodal_demand = (
demand.groupby("node", as_index=False)[
["q_max", "served_demand", "curtailed_demand"]
]
.sum()
.rename(columns={"q_max": "demand"})
)
buses_out = buses_out.merge(nodal_demand, on="node", how="left").fillna(
{"demand": 0.0, "served_demand": 0.0, "curtailed_demand": 0.0}
)
price_by_node = buses_out.set_index("node")["nodal_price"].to_dict()
lines_out = lines.copy()
lines_out["line_id"] = lines_out["line_id"].astype(str)
lines_out["flow"] = lines_out["line_id"].map(lambda l: pyo.value(model.f[l]))
lines_out["loading_abs"] = lines_out["flow"].abs()
lines_out["loading_pct"] = 100 * lines_out["loading_abs"] / lines_out["f_max"]
lines_out["is_congested"] = (
lines_out["loading_abs"] >= (lines_out["f_max"] - 1e-6)
)
# Add price-based economic quantities.
generation["nodal_price"] = generation["node"].map(price_by_node)
generation["revenue"] = generation["dispatch"] * generation["nodal_price"]
generation["variable_cost"] = generation["dispatch"] * generation["mcost"]
generation["profit"] = generation["revenue"] - generation["variable_cost"]
demand["nodal_price"] = demand["node"].map(price_by_node)
demand["utility"] = demand["served_demand"] * (
demand["bid_price"] - demand["nodal_price"]
)
stats = extract_model_stats(model, solve_time)
return {
"generation": generation,
"demand": demand,
"buses": buses_out,
"lines": lines_out,
"summary": {
"total_generation": generation["dispatch"].sum(),
"total_demand": demand["q_max"].sum(),
"total_served_demand": demand["served_demand"].sum(),
"total_curtailed_demand": demand["curtailed_demand"].sum(),
"total_welfare": pyo.value(model.Objective),
"min_nodal_price": buses_out["nodal_price"].min(),
"max_nodal_price": buses_out["nodal_price"].max(),
"number_of_congested_lines": int(lines_out["is_congested"].sum()),
"total_generator_profit": generation["profit"].sum(),
"total_demand_utility": demand["utility"].sum(),
"n_variables": stats["n_variables"],
"n_constraints": stats["n_constraints"],
"solve_time": stats["solve_time"],
},
}
# ============================================================
# ZONAL MODEL
# ============================================================
def build_zone_mapping():
"""
Build the three-zone partition used for the zonal approximation.
Returns
-------
zone_map : dict
Mapping from node number to zone label.
"""
zone_map = {}
for node in [16, 17, 18, 19, 20, 21, 22, 23]:
zone_map[node] = "Z1"
for node in [1, 3, 4, 14, 15, 24]:
zone_map[node] = "Z2"
for node in [2, 5, 6, 7, 8, 9, 10, 11, 12, 13]:
zone_map[node] = "Z3"
return zone_map
def build_interzonal_atc(lines, zone_map):
"""
Build interzonal ATC values from the underlying network.
Parameters
----------
lines : pandas.DataFrame
Line table.
zone_map : dict
Mapping from node to zone.
Returns
-------
atc : pandas.DataFrame
Interzonal ATC table.
"""
atc_rows = []
for _, row in lines.iterrows():
zone_from = zone_map[row["from_node"]]
zone_to = zone_map[row["to_node"]]
if zone_from != zone_to:
z1, z2 = sorted([zone_from, zone_to])
atc_rows.append(
{
"zone_from": z1,
"zone_to": z2,
"f_max": row["f_max"],
}
)
atc = (
pd.DataFrame(atc_rows)
.groupby(["zone_from", "zone_to"], as_index=False)["f_max"]
.sum()
)
atc["link_id"] = [f"{row.zone_from}_{row.zone_to}" for row in atc.itertuples()]
return atc
def build_step3_zonal_model(generators, demands, zone_map, atc):
"""
Build the zonal welfare-maximizing market model with ATC constraints.
Parameters
----------
generators : pandas.DataFrame
Generator input data.
demands : pandas.DataFrame
Demand input data.
zone_map : dict
Mapping from node to zone.
atc : pandas.DataFrame
Interzonal ATC table.
Returns
-------
model : pyomo.environ.ConcreteModel
Zonal optimization model.
"""
model = pyo.ConcreteModel()
generators = generators.copy()
demands = demands.copy()
atc = atc.copy()
generators["gen_id"] = generators["gen_id"].astype(str)
generators["zone"] = generators["node"].map(zone_map)
demands["load_id"] = demands["load_id"].astype(str)
demands["zone"] = demands["node"].map(zone_map)
atc["link_id"] = atc["link_id"].astype(str)
zones = sorted(set(zone_map.values()))
model.G = pyo.Set(initialize=generators["gen_id"].tolist())
model.D = pyo.Set(initialize=demands["load_id"].tolist())
model.Z = pyo.Set(initialize=zones)
model.K = pyo.Set(initialize=atc["link_id"].tolist())
model.Pmax = pyo.Param(
model.G, initialize=generators.set_index("gen_id")["p_max"].to_dict()
)
model.MCost = pyo.Param(
model.G, initialize=generators.set_index("gen_id")["mcost"].to_dict()
)
model.GenZone = pyo.Param(
model.G,
initialize=generators.set_index("gen_id")["zone"].to_dict(),
within=pyo.Any,
)
model.Qmax = pyo.Param(
model.D, initialize=demands.set_index("load_id")["q_max"].to_dict()
)
model.BidPrice = pyo.Param(
model.D, initialize=demands.set_index("load_id")["bid_price"].to_dict()
)
model.LoadZone = pyo.Param(
model.D,
initialize=demands.set_index("load_id")["zone"].to_dict(),
within=pyo.Any,
)
model.LinkFrom = pyo.Param(
model.K,
initialize=atc.set_index("link_id")["zone_from"].to_dict(),
within=pyo.Any,
)
model.LinkTo = pyo.Param(
model.K,
initialize=atc.set_index("link_id")["zone_to"].to_dict(),
within=pyo.Any,
)
model.LinkFmax = pyo.Param(
model.K, initialize=atc.set_index("link_id")["f_max"].to_dict()
)
model.p = pyo.Var(model.G, domain=pyo.NonNegativeReals)
model.q = pyo.Var(model.D, domain=pyo.NonNegativeReals)
model.f = pyo.Var(model.K, domain=pyo.Reals)
model.Objective = pyo.Objective(
expr=sum(model.BidPrice[d] * model.q[d] for d in model.D)
- sum(model.MCost[g] * model.p[g] for g in model.G),
sense=pyo.maximize,
)
model.GeneratorCapacity = pyo.Constraint(
model.G, rule=lambda m, g: m.p[g] <= m.Pmax[g]
)
model.DemandLimit = pyo.Constraint(
model.D, rule=lambda m, d: m.q[d] <= m.Qmax[d]
)
model.LinkUpper = pyo.Constraint(
model.K, rule=lambda m, k: m.f[k] <= m.LinkFmax[k]
)
model.LinkLower = pyo.Constraint(
model.K, rule=lambda m, k: m.f[k] >= -m.LinkFmax[k]
)
# Zonal balance.
def zonal_balance_rule(m, z):
generation = sum(m.p[g] for g in m.G if m.GenZone[g] == z)
demand = sum(m.q[d] for d in m.D if m.LoadZone[d] == z)
inflow = sum(m.f[k] for k in m.K if m.LinkTo[k] == z)
outflow = sum(m.f[k] for k in m.K if m.LinkFrom[k] == z)
return generation + inflow == demand + outflow
model.ZonalBalance = pyo.Constraint(model.Z, rule=zonal_balance_rule)
model.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
return model
def solve_step3_zonal(generators, demands, zone_map, atc, solver_name):
"""
Solve the zonal Step 3 model.
Parameters
----------
generators : pandas.DataFrame
Generator input data.
demands : pandas.DataFrame
Demand input data.
zone_map : dict
Mapping from node to zone.
atc : pandas.DataFrame
Interzonal ATC table.
solver_name : str
Solver name.
Returns
-------
model : pyomo.environ.ConcreteModel
Solved zonal model.
solve_time : float
Computational time in seconds.
"""
model = build_step3_zonal_model(generators, demands, zone_map, atc)
start_time = time.perf_counter()
solve_pyomo_model(model, solver_name=solver_name)
solve_time = time.perf_counter() - start_time
return model, solve_time
def extract_zonal_results(model, generators, demands, zone_map, atc, solve_time):
"""
Extract detailed zonal results and summary metrics.
Parameters
----------
model : pyomo.environ.ConcreteModel
Solved zonal model.
generators : pandas.DataFrame
Generator input data.
demands : pandas.DataFrame
Demand input data.
zone_map : dict
Mapping from node to zone.
atc : pandas.DataFrame
Interzonal ATC table.
solve_time : float
Computational time in seconds.
Returns
-------
results : dict
Detailed zonal result tables and summary metrics.
"""
generators = generators.copy()
demands = demands.copy()
atc = atc.copy()
generators["gen_id"] = generators["gen_id"].astype(str)
generators["zone"] = generators["node"].map(zone_map)
demands["load_id"] = demands["load_id"].astype(str)
demands["zone"] = demands["node"].map(zone_map)
atc["link_id"] = atc["link_id"].astype(str)
generation = generators.copy()
generation["dispatch"] = generation["gen_id"].map(lambda g: pyo.value(model.p[g]))
generation["unused_capacity"] = generation["p_max"] - generation["dispatch"]
demand = demands.copy()
demand["served_demand"] = demand["load_id"].map(lambda d: pyo.value(model.q[d]))
demand["curtailed_demand"] = demand["q_max"] - demand["served_demand"]
zones = sorted(set(zone_map.values()))
zones_out = pd.DataFrame({"zone": zones})
zones_out["zonal_price"] = zones_out["zone"].map(
lambda z: -model.dual.get(model.ZonalBalance[z], 0.0)
)
zones_out = zones_out.merge(
demand.groupby("zone", as_index=False)["q_max"]
.sum()
.rename(columns={"q_max": "demand"}),
on="zone",
how="left",
)
zones_out = zones_out.merge(
demand.groupby("zone", as_index=False)["served_demand"]
.sum()
.rename(columns={"served_demand": "total_served_demand"}),
on="zone",
how="left",
)
zones_out[["demand", "total_served_demand"]] = zones_out[
["demand", "total_served_demand"]
].fillna(0.0)
generation_by_zone = generation.groupby("zone", as_index=False)["dispatch"].sum()
zones_out = zones_out.merge(
generation_by_zone.rename(columns={"dispatch": "total_generation"}),
on="zone",
how="left",
)
zones_out["total_generation"] = zones_out["total_generation"].fillna(0.0)
zones_out["net_export"] = (
zones_out["total_generation"] - zones_out["total_served_demand"]
)
zonal_price_map = zones_out.set_index("zone")["zonal_price"].to_dict()
generation["zonal_price"] = generation["zone"].map(zonal_price_map)
generation["revenue"] = generation["dispatch"] * generation["zonal_price"]
generation["variable_cost"] = generation["dispatch"] * generation["mcost"]
generation["profit"] = generation["revenue"] - generation["variable_cost"]
demand["zonal_price"] = demand["zone"].map(zonal_price_map)
demand["utility"] = demand["served_demand"] * (
demand["bid_price"] - demand["zonal_price"]
)
links_out = atc.copy()
links_out["flow"] = links_out["link_id"].map(lambda k: pyo.value(model.f[k]))
links_out["loading_abs"] = links_out["flow"].abs()
links_out["loading_pct"] = 100 * links_out["loading_abs"] / links_out["f_max"]
links_out["is_congested"] = (
links_out["loading_abs"] >= (links_out["f_max"] - 1e-6)
)
stats = extract_model_stats(model, solve_time)
return {
"generation": generation,
"demand": demand,
"zones": zones_out,
"links": links_out,
"summary": {
"total_generation": generation["dispatch"].sum(),
"total_demand": demand["q_max"].sum(),
"total_served_demand": demand["served_demand"].sum(),
"total_curtailed_demand": demand["curtailed_demand"].sum(),
"total_welfare": pyo.value(model.Objective),
"min_zonal_price": zones_out["zonal_price"].min(),
"max_zonal_price": zones_out["zonal_price"].max(),
"number_of_congested_links": int(links_out["is_congested"].sum()),
"total_generator_profit": generation["profit"].sum(),
"total_demand_utility": demand["utility"].sum(),
"n_variables": stats["n_variables"],
"n_constraints": stats["n_constraints"],
"solve_time": stats["solve_time"],
},
}
# ============================================================
# RUNNERS
# ============================================================
def run_nodal_case(data_folder, hour, solver_name, line_changes):
"""
Run one nodal case.
Parameters
----------
data_folder : str
Path to the input data.
hour : int
Selected hour.
solver_name : str
Solver name.
line_changes : dict or None
Line-capacity changes.
Returns
-------
results : dict
Nodal results.
info : dict
Input summary information.
generators : pandas.DataFrame
Generator table used.
demands : pandas.DataFrame
Demand table used.
buses : pandas.DataFrame
Bus table used.
lines : pandas.DataFrame
Line table used.
"""
generators, demands, buses, lines, info = build_step3_inputs(data_folder, hour)
lines = apply_line_changes(lines, line_changes)
model, solve_time = solve_step3_nodal(
generators,
demands,
buses,
lines,
solver_name,
)
results = extract_nodal_results(
model,
generators,
demands,
buses,
lines,
solve_time,
)
return results, info, generators, demands, buses, lines
def run_sensitivity_analysis(data_folder, hour, line_changes_by_case, solver_name):
"""
Run nodal sensitivity cases with user-defined line-capacity changes.
Parameters
----------
data_folder : str
Path to the input data.
hour : int
Selected hour.
line_changes_by_case : dict
Mapping from case name to line-capacity changes.
solver_name : str
Solver name.
Returns
-------
summary_df : pandas.DataFrame
Summary table across nodal sensitivity cases.
case_results : dict
Detailed nodal results by case.
"""
rows = []
case_results = {}
for case_name, line_changes in line_changes_by_case.items():
results, _, _, _, _, lines_used = run_nodal_case(
data_folder,
hour,
solver_name,
line_changes,
)
changed_lines = lines_used.loc[
lines_used["line_id"].isin(line_changes.keys()),
["line_id", "f_max"],
]
changed_lines_desc = (
", ".join(f"{row.line_id}={row.f_max:.1f}" for row in changed_lines.itertuples())
if not changed_lines.empty
else "none"
)
rows.append(
{
"case": case_name,
"changed_lines": changed_lines_desc,
"total_welfare": results["summary"]["total_welfare"],
"min_nodal_price": results["summary"]["min_nodal_price"],
"max_nodal_price": results["summary"]["max_nodal_price"],
"price_spread": results["summary"]["max_nodal_price"]
- results["summary"]["min_nodal_price"],
"number_of_congested_lines": results["summary"]["number_of_congested_lines"],
"n_variables": results["summary"]["n_variables"],
"n_constraints": results["summary"]["n_constraints"],
"solve_time": results["summary"]["solve_time"],
}
)
case_results[case_name] = results
return pd.DataFrame(rows), case_results
def run_zonal_case(
data_folder,
hour,
solver_name,
zone_map,
line_changes,
atc_factor,
atc_changes,
):
"""
Run one zonal case.
Parameters
----------
data_folder : str
Path to the input data.
hour : int
Selected hour.
solver_name : str
Solver name.
zone_map : dict or None
Mapping from node to zone.
line_changes : dict or None
Line-capacity changes applied before building ATCs.
atc_factor : float
Uniform factor applied to all ATCs.
atc_changes : dict or None
Link-specific ATC scaling factors.
Returns
-------
results : dict
Zonal results.
info : dict
Input summary information.
generators : pandas.DataFrame
Generator table used.
demands : pandas.DataFrame
Demand table used.
zone_map : dict
Zone mapping used.
lines : pandas.DataFrame
Line table used.
atc : pandas.DataFrame
Interzonal ATC table used.
"""
generators, demands, _, lines, info = build_step3_inputs(data_folder, hour)
lines = apply_line_changes(lines, line_changes)
zone_map = build_zone_mapping() if zone_map is None else zone_map
atc = build_interzonal_atc(lines, zone_map).copy()
atc["f_max"] = atc["f_max"] * atc_factor
if atc_changes:
for link_id, factor in atc_changes.items():
mask = atc["link_id"] == link_id
atc.loc[mask, "f_max"] = atc.loc[mask, "f_max"] * factor
model, solve_time = solve_step3_zonal(
generators,
demands,
zone_map,
atc,
solver_name,
)
results = extract_zonal_results(
model,
generators,
demands,
zone_map,
atc,
solve_time,
)
return results, info, generators, demands, zone_map, lines, atc
def run_zonal_atc_sensitivity(
data_folder,
hour,
zone_map,
line_changes,
atc_factors,
target_link_id,
solver_name,
):
"""
Run zonal sensitivity by scaling all ATCs or one selected ATC link.
Parameters
----------
data_folder : str
Path to the input data.
hour : int
Selected hour.
zone_map : dict or None
Mapping from node to zone.
line_changes : dict or None
Line-capacity changes applied before building ATCs.
atc_factors : list[float]
List of ATC scaling factors.
target_link_id : str or None
One selected link to scale. If ``None``, all ATCs are scaled.
solver_name : str
Solver name.
Returns
-------
summary_df : pandas.DataFrame
Summary table across zonal sensitivity cases.
case_results : dict
Detailed zonal results by factor.
zone_map : dict
Zone mapping used.
"""
rows = []
case_results = {}
for factor in atc_factors:
atc_changes = {target_link_id: factor} if target_link_id is not None else None
atc_factor = 1.0 if target_link_id is not None else factor
results, _, _, _, zone_map_used, _, _ = run_zonal_case(
data_folder,
hour,
solver_name,
zone_map,
line_changes,
atc_factor,
atc_changes,
)
zones = results["zones"].copy()
zonal_price_spread = zones["zonal_price"].max() - zones["zonal_price"].min()