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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552 | class SankeyChart:
"""
Interactive Sankey diagram for energy system flow visualization.
Creates comprehensive energy flow diagrams showing the path from primary
energy sources through transformation and storage to final consumption
sectors. The chart includes automatic node positioning, loop detection,
and integrated summary pie charts.
The visualization groups energy carriers by type (Electricity, Methane, Heat,
Solids, Liquids, Uranium, Biogas, Hydrogen) and tracks flows through three
main stages: Primary (import/generation), Transformation & Storage, and
Secondary (final consumption by sector).
Attributes
----------
location
Geographic location being visualized.
year
Year of the energy data.
flows
Tracking all energy flows between nodes.
nodes
Node positions, colors, and labels.
has_loop
Flag indicating if transformation block contains loops.
primary
Primary energy data for pie chart.
fed
Final energy demand data for pie chart.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""
Initialize the SankeyChart with energy flow data.
Extracts location and year from the input data, sets up node
and flow tracking structures, and initializes the base chart configuration.
"""
df, cfg = args[0], args[1]
self._df = df
self.cfg = cfg
self.unit = cfg.unit or df.attrs["unit"]
self.metric_name = df.attrs["name"]
self.fig = go.Figure()
self.col_values = ""
self.location = self._df.index.unique(DM.LOCATION).item()
self.year = self._df.index.unique(DM.YEAR).item()
self._df = self._df.droplevel(DM.YEAR).droplevel(DM.LOCATION)
self._df.columns = ["value"]
self.flows = pd.DataFrame(
index=pd.MultiIndex.from_tuples([], names=["source", "target"]),
columns=["value", "color", "customdata"],
)
self.nodes = pd.DataFrame(
data=NODE_DATA,
columns=["name", "label", "color", "x", "y"],
).set_index("name")
# track if the Sankey has a loop in the transformation block
self.has_loop = False
# track pie chart data
self.primary = []
self.fed = []
def plot(self) -> None:
"""
Create the complete Sankey diagram with pie charts.
Orchestrates the full plotting process by connecting all energy carriers,
handling transformation flows and losses, positioning nodes, and creating
the final multi-panel visualization with integrated pie charts.
"""
# plotly draws traces connected first in the background. The connection
# order should correspond with the order of keys in GROUP_COLORS.
self.connect_electricity()
self.connect_methane()
self.connect_heat()
self.connect_solids()
self.connect_liquids()
self.connect_uranium()
self.connect_biogas()
self.connect_hydrogen()
self.forward_transformation()
self.connect_transformation_losses()
# reduce nodes data frame to prevent misalignment in sankey nodes
flows_used = self.flows.index.unique("source").union( # noqa: F841
self.flows.index.unique("target")
)
self.nodes = self.nodes.query("name in @flows_used")
self.nodes["id"] = [*range(len(self.nodes))]
if self.has_loop:
self.fix_node_y_positions()
self.fig = make_subplots(
rows=4,
cols=2,
specs=[
[{"type": "domain", "rowspan": 4}, {"type": "xy"}],
[None, {"type": "domain"}],
[None, {"type": "domain"}],
[None, {"type": "domain"}],
],
subplot_titles=("", "", "Primary Energy", "Final Energy Demand", ""),
column_widths=[0.85, 0.15],
horizontal_spacing=0.00,
vertical_spacing=0.1,
)
sankey = Sankey(
name="Energy Carrier",
arrangement="fixed" if self.has_loop else "snap",
valuesuffix=self.unit,
textfont_family="Montserrat, monospaced",
textfont_weight="bold",
node=dict(
line=dict(color="black", width=0.5),
label=self.nodes["label"],
color=self.nodes["color"],
line_width=1,
hovertemplate="%{label}<extra></extra>",
x=self.nodes["x"],
y=self.nodes["y"],
pad=10,
thickness=10,
),
link=dict(
source=self.flows.index.get_level_values("source").map(
self.nodes["id"]
),
target=self.flows.index.get_level_values("target").map(
self.nodes["id"]
),
value=self.flows["value"],
color=self.flows["color"],
customdata=self.flows["customdata"],
hovertemplate="%{customdata} <extra></extra>",
),
)
self.fig.add_trace(sankey, row=1, col=1)
self._add_pie_chart("PRIMARY", row=2, col=2)
self._add_pie_chart("FED", row=3, col=2)
self._set_legend()
self._set_base_layout()
self._set_title()
self.check_nodal_balance()
def connect_electricity(self) -> None:
"""
Connect electricity flows from generation through transformation to consumption.
Processes electricity sector including renewable generation (wind, solar, hydro),
imports, transformation through power plants and storage, bypasses, and final
consumption by sectors. Handles distribution losses and V2G harmonization.
"""
bus_carrier = ["AC", "low voltage"] # ignoring battery, home battery buses
name = "ELECTRICITY"
import_ = filter_by(
self._df,
bus_carrier=bus_carrier,
carrier=["Import Foreign", "Import Domestic"],
)
self._flow_import(import_, name)
generation = filter_by(
self._df, bus_carrier=bus_carrier, component=["Generator", "StorageUnit"]
)
wind = generation.filter(like="wind", axis=0)
self._flow_generation(wind, name, "WIND", COLOUR.blue_moonstone)
solar = generation.filter(like="solar", axis=0)
self._flow_generation(solar, name, "SOLAR", COLOUR.yellow_bright)
hydro = generation.filter(regex="ror|hydro", axis=0)
self._flow_generation(hydro, name, "HYDRO", COLOUR.blue_persian)
primary = pd.concat([import_, wind, solar, hydro])
self._flow_primary(primary, name)
regex = "Foreign|Domestic|hydro|decentral|rural|pipeline"
transformation = filter_by(
self._df,
bus_carrier=bus_carrier,
component=["Link", "Store", "StorageUnit"],
).pipe(drop_from_multtindex_by_regex, regex)
transformation_demand = self._flow_transformation_in(transformation, name)
transformation_supply = self._flow_transformation_out(transformation, name)
bypass = primary.sum() - transformation_demand.sum()
self._flow_bypass(bypass.item(), name)
secondary = transformation_supply.sum() + bypass
self._flow_secondary(secondary.item(), name)
final = filter_by(self._df, bus_carrier=bus_carrier).abs()
self._flow_sector(final, "industry", name, "INDUSTRY")
self._flow_sector(final, "Foreign|Domestic", name, "EXPORT", append_label=True)
self._flow_sector(final, "agriculture", name, "AGRICULTURE")
# include losses from decentral heat production technologies
self._flow_sector(final, "rural|decentral|'electricity'", name, "HH_SERVICES")
self._flow_sector(final, "BEV charger", name, "TRANSPORT")
distribution_losses = filter_by(
self._df,
carrier=[
"electricity distribution grid",
"Transmission Losses",
"gas pipeline",
"gas pipeline new",
"H2 pipeline",
"H2 pipeline (Kernnetz)",
"H2 pipeline retrofitted",
],
)
self._connect(
distribution_losses,
"ELECTRICITY_SECONDARY_OUT",
"DIST_LOSS",
color=COLOUR.grey_neutral,
)
self._check_remainder(bus_carrier)
def connect_hydrogen(self) -> None:
"""
Connect hydrogen flows from import/production to final consumption.
Processes hydrogen sector flows including imports, industrial production,
transformation through electrolysis and storage, and consumption by
industry, households, and transport sectors.
"""
bus_carrier = "H2"
name = "HYDROGEN"
color = self.nodes.loc[f"{name}_PRIMARY_IN", "color"]
import_ = filter_by(
self._df,
bus_carrier=bus_carrier,
carrier=[
"Import Foreign",
"Import Domestic",
"import H2",
],
)
h2_for_industry = filter_by(
self._df, bus_carrier=bus_carrier, carrier="H2 for industry"
)
if h2_for_industry.sum().item() > 0:
# industry produces hydrogen in 2020 in some regions.
# those amounts are assigned to import
import_ = pd.concat([import_, h2_for_industry])
self._df.drop(h2_for_industry.index, inplace=True)
self._flow_import(import_, name)
self._flow_primary(import_, name)
regex = "Foreign|Domestic|h2 for industry|decentral|rural"
transform = filter_by(
self._df, bus_carrier=bus_carrier, component=["Link", "Store"]
).pipe(drop_from_multtindex_by_regex, regex)
# storage = filter_by(self._df, bus_carrier=bus_carrier, component="Store")
transformation_demand = self._flow_transformation_in(transform, name)
transformation_supply = self._flow_transformation_out(transform, name)
bypass = import_.sum() - transformation_demand.sum()
self._flow_bypass(bypass.item(), name)
secondary = transformation_supply.sum() + bypass
self._flow_secondary(secondary.item(), name)
final = filter_by(self._df, bus_carrier=bus_carrier).abs()
self._flow_loop(transformation_supply, final, name, color)
self._flow_sector(final, "industry", name, "INDUSTRY")
self._flow_sector(final, "rural|decentral", name, "HH_SERVICES")
self._flow_sector(final, "transport", name, "TRANSPORT")
self._flow_sector(final, "Foreign|Domestic", name, "EXPORT", append_label=True)
self._check_remainder(bus_carrier)
def connect_methane(self) -> None:
"""
Connect methane/gas flows from import through transformation to consumption.
Processes natural gas and synthetic methane flows including pipeline and LNG
imports, transformation through power plants and industrial processes,
and consumption by sectors with loop detection for gas-to-gas processes.
"""
bus_carrier = "gas"
name = "METHANE"
color = self.nodes.loc[f"{name}_PRIMARY_IN", "color"]
import_ = filter_by(
self._df,
bus_carrier=bus_carrier,
carrier=[
"Import Foreign",
"Import Domestic",
"pipeline gas",
"lng gas",
"production gas",
"import gas",
],
)
self._flow_import(import_, name)
self._flow_primary(import_, name)
regex = "Foreign|Domestic|gas for industry|decentral|rural"
transform = filter_by(
self._df, bus_carrier=bus_carrier, component=["Link", "Store"]
).pipe(drop_from_multtindex_by_regex, regex)
transformation_demand = self._flow_transformation_in(transform, name)
transformation_supply = self._flow_transformation_out(transform, name)
bypass = import_.sum() - transformation_demand.sum()
self._flow_bypass(bypass.item(), name)
secondary = transformation_supply.sum() + bypass
self._flow_secondary(secondary.item(), name)
final = filter_by(self._df, bus_carrier=bus_carrier).abs()
self._flow_sector(final, "industry", name, "INDUSTRY")
self._flow_sector(final, "rural|decentral", name, "HH_SERVICES")
self._flow_sector(final, "Foreign|Domestic", name, "EXPORT", append_label=True)
self._flow_loop(transformation_supply, final, name, color)
self._check_remainder(bus_carrier)
def connect_biogas(self) -> None:
"""
Connect biogas flows from generation to transformation.
Processes biogas generation and direct forwarding to transformation
processes, typically for conversion to electricity or upgraded gas.
"""
bus_carrier = "biogas"
name = "BIOGAS"
color = self.nodes.loc[f"{name}_PRIMARY_IN", "color"]
generation = filter_by(
self._df,
bus_carrier=bus_carrier,
component="Generator",
)
label = name
self._flow_generation(generation, name, label, color)
self._flow_primary(generation, name)
processing = filter_by(self._df, bus_carrier=bus_carrier, component="Link")
self._connect(
processing,
f"{name}_PRIMARY_OUT",
"TRANS_IN",
)
self._check_remainder(bus_carrier)
def connect_solids(self) -> None:
"""
Connect solid fuel flows from import/generation to consumption.
Processes coal, lignite, biomass, waste, and HVC flows including imports,
domestic generation, transformation losses, and consumption by industry
and households. Handles waste-to-energy and resource loss tracking.
"""
bus_carrier = [
"coal",
"lignite",
"solid biomass",
"municipal solid waste",
"non-sequestered HVC",
]
name = "SOLIDS"
color = self._get_color(f"{name}_PRIMARY_IN")
import_ = filter_by(
self._df,
bus_carrier=bus_carrier,
carrier=[
"Import Foreign",
"Import Domestic",
"Global Import",
],
)
self._flow_import(import_, name)
generation = filter_by(
self._df, bus_carrier=bus_carrier, component=["Generator", "Store"]
)
self._flow_generation(generation, name, name, color)
# HVC to air is an unused resource. Some countries do not have
# techs that use waste e.g., waste CHPs
primary_losses = filter_by(
self._df, bus_carrier=bus_carrier, carrier="HVC to air"
)
self._connect(
primary_losses, "SOLIDS_PRIMARY_OUT", "UNUSED", color=COLOUR.grey_neutral
)
primary = pd.concat([import_, generation])
self._flow_primary(primary, name)
# waste to HVC is only used to track CO2 emissions
waste_to_hvc = filter_by(
self._df, carrier="municipal solid waste", component="Link"
)
assert waste_to_hvc.sum().abs().item() < 1e-6, waste_to_hvc
self._df.drop(waste_to_hvc.index, inplace=True)
transformation = filter_by(
self._df,
bus_carrier=bus_carrier,
component="Link",
).pipe(
drop_from_multtindex_by_regex,
"Foreign|Domestic|decentral|rural|for industry",
)
transformation_demand = self._flow_transformation_in(transformation, name)
transformation_supply = transformation[transformation.gt(0)].dropna()
assert transformation_supply.empty
bypass = (
primary.sum() - transformation_demand.sum() - primary_losses.abs().sum()
)
self._flow_bypass(bypass.item(), name)
secondary = transformation_supply.sum() + bypass
self._flow_secondary(secondary.item(), name)
final = filter_by(self._df, bus_carrier=bus_carrier).abs()
self._flow_sector(final, "industry", name, "INDUSTRY")
self._flow_sector(final, "Foreign|Domestic", name, "EXPORT", append_label=True)
self._flow_sector(final, "rural|decentral", name, "HH_SERVICES")
self._check_remainder(bus_carrier)
def connect_liquids(self) -> None:
"""
Connect liquid fuel flows from import through transformation to consumption.
Processes oil, methanol, NH3, and electrobiofuel flows including imports,
transformation through refining and synthesis, and consumption by transport,
industry, shipping, aviation, and agriculture sectors.
"""
name = "LIQUIDS"
bus_carrier = [
"oil",
"methanol",
"NH3",
"electrobiofuels",
]
# WARNING - /IdeaProjects/pypsa-at/evals/plots/sankey.py - Warning[Balearic Islands 2030]: ELECTRICITY_PRIMARY_OUT has a discrepancy of 12.64 TWh
# WARNING - /IdeaProjects/pypsa-at/evals/plots/sankey.py - Warning[Balearic Islands 2030]: ELECTRICITY_SECONDARY_IN has a discrepancy of -12.64 TWh
# WARNING - /IdeaProjects/pypsa-at/evals/plots/sankey.py - Warning[Balearic Islands 2030]: LIQUIDS_PRIMARY_OUT has a discrepancy of 55.85 TWh
# WARNING - /IdeaProjects/pypsa-at/evals/plots/sankey.py - Warning[Balearic Islands 2030]: LIQUIDS_SECONDARY_IN has a discrepancy of -55.85 TWh
# WARNING - /IdeaProjects/pypsa-at/evals/plots/sankey.py - Warning[Italy 2050]: LIQUIDS_PRIMARY_OUT has a discrepancy of 19.48 TWh
# WARNING - /IdeaProjects/pypsa-at/evals/plots/sankey.py - Warning[Italy 2050]: LIQUIDS_SECONDARY_IN has a discrepancy of -19.48 TWh
import_ = filter_by(
self._df,
bus_carrier=bus_carrier,
carrier=[
"Import Foreign",
"Import Domestic",
"Global Import",
"import NH3",
"import oil",
"import methanol",
],
)
self._flow_import(import_, name)
self._flow_primary(import_, name)
transformation = filter_by(
self._df,
bus_carrier=bus_carrier,
component="Link",
).pipe(
drop_from_multtindex_by_regex,
"decentral|rural|industry|shipping|agriculture|transport|aviation|refining",
)
transformation_demand = self._flow_transformation_in(transformation, name)
transformation_supply = self._flow_transformation_out(transformation, name)
bypass = import_.sum() - transformation_demand.sum()
self._flow_bypass(bypass.item(), name)
secondary = transformation_supply.sum() + bypass.sum()
self._flow_secondary(secondary.item(), name)
final = filter_by(self._df, bus_carrier=bus_carrier).abs()
self._flow_sector(final, "industry|NH3", name, "INDUSTRY")
self._flow_sector(final, "Foreign|Domestic", name, "EXPORT", append_label=True)
self._flow_sector(final, "rural|decentral", name, "HH_SERVICES")
self._flow_sector(final, "transport|shipping|aviation", name, "TRANSPORT")
self._flow_sector(final, "agriculture", name, "AGRICULTURE")
if self.location == "Europe":
# # assign EU Ammonia Loads to agriculture sector
# nh3_load = filter_by(
# self._df, bus_carrier="NH3", carrier="NH3", component="Load"
# )
# self._flow_sector(nh3_load, r"NH3", name, "AGRICULTURE")
# drop oil refining process
oil_refining = filter_by(
self._df, bus_carrier="oil", carrier="oil refining", component="Link"
)
self._df.drop(oil_refining.index, inplace=True)
stores = filter_by(self._df, bus_carrier=bus_carrier, component="Store")
assert stores.sum().abs().item() < 1e-6
self._df.drop(stores.index, inplace=True)
self._check_remainder(bus_carrier)
def connect_uranium(self) -> None:
"""
Connect uranium flows from import to nuclear transformation.
Processes uranium imports (treated as nuclear power plant demand)
and forwards to transformation block for electricity generation.
"""
bus_carrier = "uranium"
name = "URANIUM"
# Global Import is the regionalized carrier for Uranium EU imports
import_ = filter_by(self._df, bus_carrier=bus_carrier, carrier="Global Import")
self._flow_import(import_, name)
self._flow_primary(import_, name)
transformation = filter_by(
self._df,
bus_carrier=bus_carrier,
component="Link",
)
self._flow_transformation_in(transformation, name)
# # todo: connect Link nuclear uranium -35.201016 as transformation IN
# self._forward(
# "URANIUM_PRIMARY_OUT",
# "TRANS_IN",
# import_.sum().item(),
# )
# drop EU components
if self.location == "Europe":
to_drop = filter_by(
self._df, bus_carrier=bus_carrier, component=["Generator", "Store"]
)
self._df.drop(to_drop.index, inplace=True)
self._check_remainder(bus_carrier)
def connect_heat(self) -> None:
"""
Connect heat flows from ambient sources through systems to consumption.
Processes ambient heat, solar thermal, and heat pump flows including
central and decentral heating systems, storage, distribution losses,
and consumption by households, industry, and agriculture.
"""
name = "HEAT"
bus_carrier = [
"ambient heat",
"rural heat",
"urban central heat",
"urban decentral heat",
]
color = self._get_color(f"{name}_PRIMARY_IN")
generation = filter_by(
self._df, bus_carrier=bus_carrier, component=["Generator", "Link"]
).filter(regex="solar thermal|ambient heat", axis=0)
self._flow_generation(generation, name, name, color)
self._flow_primary(generation, name)
regex = "decentral|rural|industry|agriculture|DAC"
transformation = filter_by(
self._df,
bus_carrier=bus_carrier,
component="Link",
).pipe(drop_from_multtindex_by_regex, regex)
storage_demand = transformation[transformation.lt(0)].dropna().mul(-1)
central_heat = generation.filter(like=" central ", axis=0)
storage_supply = transformation[transformation.gt(0)].dropna()
transformation_supply = pd.concat([storage_supply, central_heat])
transformation_demand = pd.concat([storage_demand, central_heat])
# transformation_demand = self._flow_transformation_in(transformation, name)
# transformation_supply = self._flow_transformation_out(transformation, name)
self._connect(
transformation_demand,
f"{name}_PRIMARY_OUT",
"TRANS_IN",
)
bypass = generation.sum() - transformation_demand.sum()
self._flow_bypass(bypass.item(), name)
self._connect(
transformation_supply,
"TRANS_OUT",
f"{name}_SECONDARY_IN",
color=color,
)
# self._forward(f"{name}_BYPASS_OUT", f"{name}_SECONDARY_IN", bypass)
secondary = transformation_supply.sum() + bypass
self._flow_secondary(secondary.item(), name)
final = filter_by(self._df, bus_carrier=bus_carrier).abs()
self._flow_sector(final, "industry|DAC", name, "INDUSTRY")
self._flow_sector(final, "agriculture", name, "AGRICULTURE")
vents = final.filter(like="heat vent", axis=0)
self._connect(
vents,
f"{name}_SECONDARY_OUT",
"DIST_LOSS",
color=COLOUR.grey_neutral,
)
industry = final.filter(regex="industry|DAC", axis=0)
agriculture = final.filter(regex="agriculture", axis=0)
hh_services = secondary - industry.sum() - vents.sum() - agriculture.sum()
self._forward(f"{name}_SECONDARY_OUT", "HH_SERVICES", hh_services.item())
# if hh_services <= 0:
# # some amounts of gas/electricity/solid biomass for heat are for agriculture
# logger.warning(
# f"Negative remaining Heat Load detected in "
# f"{self.location} and year {self.year}:\n{hh_services}"
# )
# # assuming that electricity supplies these amounts to the largest load
# self._forward(f"{name}_SECONDARY_OUT", "HH_SERVICES", hh_services)
# decentral heat technologies connect to FED via their input
# bus_carrier because this form of energy is metered. central Load
# also needs to be dropped.
to_drop = filter_by(
self._df, bus_carrier=bus_carrier, component=["Link", "Load", "Generator"]
).filter(regex="decentral|rural|central", axis=0)
self._df.drop(to_drop.index, inplace=True)
remaining = filter_by(self._df, bus_carrier=bus_carrier)
assert remaining.empty, (
f"Missing amounts detected for location "
f"{self.location} and year {self.year}:\n{remaining}"
)
def forward_transformation(self) -> None:
"""
Connect transformation input to output flows.
Creates the central transformation flow that aggregates all inputs
to the transformation block and forwards them to outputs.
"""
transformation = self.flows.query("target == 'TRANS_IN'")
self._forward(
"TRANS_IN",
"TRANS_OUT",
transformation["value"].sum(),
)
def connect_transformation_losses(self) -> None:
"""
Connect transformation losses from output to loss sink.
Processes conversion losses from power plants, storage systems,
and other transformation technologies, grouping by carrier type
and connecting to the transformation loss node.
"""
bus_carrier = [
bc for bc in self._df.index.unique("bus_carrier") if bc.endswith("losses")
]
regex = "rural|decentral|gas for industry CC"
losses = filter_by(self._df, bus_carrier=bus_carrier).pipe(
drop_from_multtindex_by_regex, regex
)
# rename losses carrier to shorten the display table by summarizing to bus_carrier
to_bus_carrier = {
c: bc
for c, bc in zip(
losses.index.get_level_values("carrier"),
losses.index.get_level_values("bus_carrier").map(
lambda x: x.replace(" losses", "")
),
)
}
to_groups = {bus_carrier: k for k, v in GROUPS.items() for bus_carrier in v}
losses = (
losses.pipe(rename_aggregate, to_bus_carrier)
.pipe(rename_aggregate, to_groups)
.pipe(rename_aggregate, "losses", level="bus_carrier")
)
self._connect(
losses,
"TRANS_OUT",
"TRANS_LOSS",
color=COLOUR.grey_neutral,
)
def check_nodal_balance(self) -> None:
"""
Verify energy balance at primary, secondary, and transformation nodes.
Checks that inflows equal outflows for internal nodes and logs
warnings for any significant imbalances that exceed the cutoff threshold.
"""
checks = (
"PRIMARY",
"SECONDARY",
"TRANS_",
)
for node in self.nodes.index:
# skip left and right border nodes because they are never balanced
if not any([s in node for s in checks]):
continue
node_in = filter_by(self.flows, source=node)
node_out = filter_by(self.flows, target=node)
diff = node_in["value"].sum() - node_out["value"].sum()
if abs(diff) > 0.1: # self.cfg.cutoff
logger.warning(
f"Warning[{self.location} {self.year}]: {node} has a "
f"discrepancy of {diff:.2f} {self.unit}"
)
def fix_node_y_positions(self) -> None:
"""
Adjust vertical node positions when transformation loops are detected.
Recalculates node positions proportional to flow magnitudes to prevent
visual overlap when the transformation block contains loops. Maintains
proper spacing and ensures positions stay within plot bounds.
"""
# Calculate maximum flow for normalization
maximum = 0
for x, nodes in self.nodes.groupby("x"):
idx = nodes.index.tolist()
src_total = filter_by(self.flows, source=idx)["value"].sum()
dst_total = filter_by(self.flows, target=idx)["value"].sum()
maximum = max(maximum, src_total, dst_total)
# Add padding for visual spacing
maximum *= 1.05
for x, nodes in self.nodes.groupby("x"):
idx = nodes.index.tolist()
# Skip loss nodes - position them at bottom
loss_nodes = [i for i in idx if i in ("TRANS_LOSS", "DIST_LOSS", "UNUSED")]
if loss_nodes:
# for i, node in enumerate(loss_nodes):
# self.nodes.at[node, "y"] = 0.95 + (i * 0.02)
continue
# Get flow data for this column
src_flows = filter_by(self.flows, source=idx)
dst_flows = filter_by(self.flows, target=idx)
# Use the side with the larger total flow for positioning
if src_flows["value"].sum() >= dst_flows["value"].sum():
flows = src_flows.groupby("source")["value"].sum()
else:
flows = dst_flows.groupby("target")["value"].sum()
# Sort nodes by their original y position to maintain order
node_order = nodes.sort_values("y").index.tolist()
# Calculate cumulative positions
cumulative_pos = 0
spacing = 0.02 # Small gap between nodes
for node_name in node_order:
if node_name in flows.index:
node_size = flows[node_name] / maximum
else:
node_size = 0.01 # Minimum size for nodes with no flow
# Position node at current cumulative position
self.nodes.at[node_name, "y"] = cumulative_pos + (node_size / 2)
# Update cumulative position
cumulative_pos += node_size + spacing
# Normalize positions to ensure they stay within [0, 0.9] range
max_y = self.nodes.loc[node_order, "y"].max()
if max_y > 0.9:
scale_factor = 0.9 / max_y
for node_name in node_order:
self.nodes.at[node_name, "y"] *= scale_factor
def _connect(
self, df: pd.DataFrame, source: str, target: str, color: str | None = None
) -> None:
"""
Create a flow connection between two nodes.
Parameters
----------
df
Flow data to connect.
source
Source node identifier.
target
Target node identifier.
color
Color override for the flow.
Notes
-----
Aggregates the data values, creates hover information,
and removes processed data from the main dataset.
"""
value = df.abs().sum().item()
if value < self.cfg.cutoff:
self._df.drop(df.index, inplace=True, errors="ignore")
return
df = df.abs().sort_values(by="value", ascending=False)
longest_carrier = df.index.get_level_values("carrier").map(len).max() + 1
customdata = "<br>".join(
[
self._format_customdata_line(c, v, self.unit, longest_carrier)
for c, v in zip(df.index.get_level_values("carrier"), df["value"])
if prettify_number(v) != "0.0"
]
)
customdata += f"<br><b>{prettify_number(value)} {self.unit} in Total</b>"
# add a row with the link's value
color = color or self.nodes.loc[source, "color"] # allow explicit override
self.flows.loc[(source, target), self.flows.columns] = [
value,
color,
customdata,
]
self._df.drop(df.index, inplace=True, errors="ignore")
def _forward(
self, source: str, target: str, value: float, color: str | None = None
) -> None:
"""
Create a simple flow connection with a single value.
Parameters
----------
source
Source node identifier.
target
Target node identifier.
value
Flow value to connect.
color
Color override for the flow.
"""
if value < self.cfg.cutoff:
return
self.flows.loc[(source, target), self.flows.columns] = [
value,
color or self.nodes.loc[source, "color"],
f"{prettify_number(value)} {self._df.attrs['unit']}",
]
def _flow_loop(
self,
transformation_supply: pd.DataFrame,
final: pd.DataFrame,
name: str,
color: str,
) -> None:
"""
Handle loop flows in transformation systems.
Detects and creates loop flows when transformation output exceeds final consumption,
indicating internal recycling or feedback loops within the transformation block.
Adjusts existing flows to prevent double-counting.
Parameters
----------
transformation_supply
Transformation output flows.
final
Final consumption flows.
name
Energy carrier name for flow identification.
color
Color for the loop flow visualization.
"""
loop = (transformation_supply.sum() - final.sum()).item()
if has_loop := (loop > self.cfg.cutoff):
self.has_loop = has_loop
self._forward("TRANS_OUT", "TRANS_IN", loop, color=color)
# self._forward(f"{name}_SECONDARY_IN", f"{name}_PRIMARY_OUT", loop, color=color)
if (f"{name}_PRIMARY_OUT", "TRANS_IN") in self.flows.index:
self.flows.at[(f"{name}_PRIMARY_OUT", "TRANS_IN"), "value"] -= loop
if ("TRANS_OUT", f"{name}_SECONDARY_IN") in self.flows.index:
self.flows.at[("TRANS_OUT", f"{name}_SECONDARY_IN"), "value"] -= loop
def _flow_primary(self, df: pd.DataFrame, name: str) -> None:
"""
Create primary energy flow connections.
Establishes the flow from primary input to primary output nodes and
updates the primary input node label with the total flow value.
Parameters
----------
df
Primary energy flow data.
name
Energy carrier name for node identification.
"""
primary = df.sum().item()
self._forward(
f"{name}_PRIMARY_IN",
f"{name}_PRIMARY_OUT",
primary,
)
self.nodes.at[f"{name}_PRIMARY_IN", "label"] = (
f"{prettify_number(primary)} {self.unit}"
)
def _flow_import(self, df: pd.DataFrame, name: str) -> None:
"""
Create import flow connections to primary energy input.
Connects import flows to the primary energy input node and updates
the import node label with carrier-specific import amounts.
Parameters
----------
df
Import flow data.
name
Energy carrier name for target identification.
"""
target = f"{name}_PRIMARY_IN"
self._connect(
df,
"IMPORT",
target,
color=self._get_color(target),
)
value = df.abs().sum().item()
if value > 0.05:
self.nodes.at["IMPORT", "label"] += (
f"<br>{prettify_number(value)} {self.unit} {name.title()}"
)
def _flow_generation(
self, df: pd.DataFrame, name: str, label: str, color: str
) -> None:
"""
Create generation flow connections for renewable sources.
Connects generation sources (wind, solar, hydro, etc.) to the primary
energy input and tracks the data for pie chart visualization.
Parameters
----------
df
Generation flow data.
name
Energy carrier name for target identification.
label
Source label for the generation node.
color
Color for the flow visualization.
"""
self.primary.append(df)
self._connect(
df,
label,
f"{name}_PRIMARY_IN",
color=color,
)
def _flow_transformation_in(self, df: pd.DataFrame, name: str) -> pd.DataFrame:
"""
Process transformation input flows and connect to the transformation block.
Extracts negative flows (demand) from transformation data,
handles special cases like V2G harmonization for electricity,
and connects to the transformation input node.
Parameters
----------
df
Complete transformation flow data.
name
Energy carrier name for flow identification.
Returns
-------
:
Processed transformation demand flows.
"""
transformation_demand = df[df.lt(0)].dropna().mul(-1)
if name == "ELECTRICITY":
transformation_demand = self._harmonize_v2g(df, transformation_demand)
# separate storage
# stores = filter_by(transformation_demand, component="Store")
# charger = transformation_demand.filter(like="charger", axis=0)
# storage_demand = pd.concat([stores, charger])
self._connect(
transformation_demand,
f"{name}_PRIMARY_OUT",
"TRANS_IN",
)
return transformation_demand
def _flow_transformation_out(self, df: pd.DataFrame, name: str) -> pd.DataFrame:
"""
Process transformation output flows and connect from transformation block.
Extracts positive flows (supply) from transformation data
and connects them from the transformation output to secondary input.
Parameters
----------
df
Complete transformation flow data.
name
Energy carrier name for flow identification.
Returns
-------
:
Processed transformation supply flows.
"""
transformation_supply = df[df.gt(0)].dropna()
target = f"{name}_SECONDARY_IN"
self._connect(
transformation_supply,
"TRANS_OUT",
target,
self._get_color(target),
)
return transformation_supply
def _flow_bypass(self, value: float, name: str) -> None:
"""
Create bypass flows that skip transformation.
Establishes flow paths for energy that bypasses transformation,
going directly from primary to secondary through bypass nodes.
Updates bypass the input node label with the flow value.
Parameters
----------
value
Bypass flow amount.
name
Energy carrier name for node identification.
"""
self._forward(
f"{name}_PRIMARY_OUT",
f"{name}_BYPASS_IN",
value,
)
self._forward(
f"{name}_BYPASS_IN",
f"{name}_BYPASS_OUT",
value,
)
self._forward(
f"{name}_BYPASS_OUT",
f"{name}_SECONDARY_IN",
value,
)
self.nodes.at[f"{name}_BYPASS_IN", "label"] = (
f"{prettify_number(value)} {self.unit}"
)
def _flow_secondary(self, value: float, name: str) -> None:
"""
Create secondary energy flow connections.
Establishes the flow from secondary input to secondary output nodes
and updates the secondary input node label with the total flow value.
Parameters
----------
value
Secondary flow amount.
name
Energy carrier name for node identification.
"""
self._forward(
f"{name}_SECONDARY_IN",
f"{name}_SECONDARY_OUT",
value,
)
self.nodes.at[f"{name}_SECONDARY_IN", "label"] = (
f"{prettify_number(value)} {self.unit}"
)
def _flow_sector(
self,
df: pd.DataFrame,
regex: str,
name: str,
sector: str,
append_label: bool = False,
) -> None:
"""
Create sector consumption flow connections.
Filters flows by regex pattern, connects them to the specified sector,
and tracks data for the final energy demand pie chart. Optionally appends
flow information to sector node labels.
Parameters
----------
df
Complete flow data to filter.
regex
Regular expression pattern for filtering flows.
name
Energy carrier name for source identification.
sector
Target sector node identifier.
append_label
Whether to append flow info to sector label.
"""
demand = df.filter(regex=regex, axis=0)
self.fed.append(demand)
self._connect(
demand,
f"{name}_SECONDARY_OUT",
sector,
)
value = demand.sum().item()
if append_label and value > self.cfg.cutoff:
self.nodes.at["EXPORT", "label"] += (
f"<br>{name.title()} {prettify_number(value)} {self.unit}"
)
def _set_node_label(
self, idx: str, value: float, name: str = "", append: bool = False
) -> None:
"""
Set or append node label with flow value.
Updates node labels with formatted flow values and units.
Can either replace the existing label or append to it.
Parameters
----------
idx
Node identifier.
value
Flow value to display.
name
Optional name to include in the label.
append
Whether to append to the existing label or replace it.
"""
if idx not in self.nodes.index:
return
if append:
self.nodes.at[idx, "label"] += (
f"<br>{prettify_number(value)} {self.unit} {name}"
)
else:
self.nodes.at[idx, "label"] = f"{prettify_number(value)} {self.unit}"
def _set_base_layout(self) -> None:
"""
Configure the base layout properties for the figure.
Sets up subplot visibility, grid properties, background colors,
legend positioning, and embeds run metadata for export.
"""
self.fig.update_layout(
height=800,
showlegend=True,
legend=dict(
orientation="h",
yanchor="bottom",
y=-0.1,
xanchor="left",
x=0.0,
font=dict(size=14),
),
)
# hide scatter plot used to show the legend
self.fig.update_xaxes(visible=False, row=1, col=2)
self.fig.update_yaxes(visible=False, row=1, col=2)
# hide subplot backgrounds
self.fig.update_layout(
xaxis2=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis2=dict(showgrid=False, zeroline=False, showticklabels=False),
plot_bgcolor="rgba(0,0,0,0)", # applies to all xy subplots
)
# export the metadata directly in the Layout property for JSON
self.fig.update_layout(meta=[RUN_META_DATA])
def _set_title(self) -> None:
"""
Set the chart title using location and year information.
Formats and applies the title based on the configuration template
with appropriate font sizing.
"""
title = self.cfg.title.format(location=self.location, unit=self.year)
self.fig.update_layout(
title=dict(text=title, font_size=self.cfg.title_font_size)
)
def _set_legend(self) -> None:
"""
Add color-coded legend for energy carrier groups.
Creates legend entries for each energy carrier group using the
standardized color scheme and positions them horizontally.
"""
# add legend for sankey traces
for carrier_group in GROUPS:
self.fig.add_trace(
go.Scatter(
x=[None],
y=[None],
mode="markers",
marker=dict(size=10, color=COLOUR_SCHEME[carrier_group]),
name=carrier_group,
showlegend=True,
),
row=1,
col=2,
)
def _add_pie_chart(self, kind: str, row: int, col: int) -> None:
"""
Add a pie chart to the subplot layout.
Parameters
----------
kind
Chart type - 'PRIMARY' for primary energy or 'FED' for final energy demand.
row
Subplot row position.
col
Subplot column position.
Notes
-----
Creates proportional pie charts showing energy breakdown by carrier type
with matching colors and hover information.
"""
if kind == "PRIMARY":
df = pd.concat(self.primary)
domain_id = 1
elif kind == "FED":
df = pd.concat(self.fed)
domain_id = 2
else:
raise ValueError(f"Unknown kind: {kind}")
to_groups = {bus_carrier: k for k, v in GROUPS.items() for bus_carrier in v}
data = (
rename_aggregate(df, to_groups, level="bus_carrier")
.groupby("bus_carrier")
.sum()
.reset_index()
)
data = data[data["value"] >= self.cfg.cutoff]
pie = go.Pie(
values=data["value"],
labels=data["bus_carrier"],
customdata=[prettify_number(v) for v in data["value"]],
hovertemplate="%{label}<br>%{customdata} " + self.unit + "<extra></extra>",
marker=dict(colors=[COLOUR_SCHEME[x] for x in data["bus_carrier"]]),
showlegend=False,
hole=0.6,
texttemplate="%{percent:.1%}",
textposition="inside",
text=data["value"].map(prettify_number),
textinfo="percent+label+text",
)
self.fig.add_trace(pie, row=row, col=col)
# Add annotation in the donut hole
domain = self.fig.data[domain_id].domain
self.fig.add_annotation(
text=self.unit,
xref="paper",
yref="paper",
x=(domain.x[0] + domain.x[1]) / 2,
y=(domain.y[0] + domain.y[1]) / 2,
showarrow=False,
font=dict(size=12),
)
def _get_color(self, node_id: str) -> str:
"""
Get the color assigned to a specific node.
Parameters
----------
node_id
Node identifier to look up.
Returns
-------
:
Color value for the specified node.
"""
return self.nodes.at[node_id, "color"]
def _harmonize_v2g(
self, transformation: pd.DataFrame, transformation_demand: pd.DataFrame
) -> pd.DataFrame:
"""
Harmonize vehicle-to-grid flows with BEV charging demand.
Moves V2G and hides EV battery to connect electricity demand
for transport directly without storage. Increase BEV charger by
V2G supply. The BEV Charger will serve as the Transport sectoral
demand, effectively hiding the storage systems for EV.
Parameters
----------
transformation
Full transformation data.
transformation_demand
Transformation demand data.
Returns
-------
:
Modified transformation demand with V2G flows properly allocated.
Notes
-----
Adjusts BEV charger demand by V2G supply amounts and treats V2G as
storage demand to avoid double-counting in the transport sector.
"""
v2g_demand = transformation.query("carrier == 'V2G'").rename(
{"V2G": "V2G demand"}
)
# increase BEV charger withdrawal by V2G amounts and drop it from
# transformation demand since its transport load
bev = ("Link", "BEV charger", "low voltage")
transformation_demand.drop(bev, inplace=True, errors="ignore")
if not v2g_demand.empty:
self._df.loc[bev, "value"] -= v2g_demand["value"].item()
# add V2G as a transformation (storage) demand
transformation_demand = pd.concat([transformation_demand, v2g_demand])
return transformation_demand
def _check_remainder(self, bus_carrier: str | list[str]) -> None:
"""
Verify all flows for a bus carrier have been processed.
Parameters
----------
bus_carrier
Bus carrier name(s) to check for remaining unprocessed flows.
Raises
------
AssertionError
If any flows remain unprocessed for the specified bus carrier(s).
"""
remaining = filter_by(self._df, bus_carrier=bus_carrier)
assert remaining.empty, (
f"Missing amounts detected for location "
f"{self.location} and year {self.year}:\n{remaining}"
)
@staticmethod
def _format_customdata_line(
carrier: str, value: float, unit: str, target_length: int
) -> str:
"""
Format a single line of hover information for energy flows.
Parameters
----------
carrier
Energy carrier name.
value
Flow value.
unit
Unit string.
target_length
Target length for formatting alignment (currently unused).
Returns
-------
:
Formatted string for hover display.
"""
# padding = target_length - len(carrier)
# return carrier + " " * padding + f"{prettify_number(value)} {unit}"
return f"{prettify_number(value)} {unit} {carrier}"
|