forked from openego/eGon-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
electrical_neighbours.py
1913 lines (1635 loc) · 56.3 KB
/
electrical_neighbours.py
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
"""The central module containing all code dealing with electrical neighbours
"""
import zipfile
import entsoe
import requests
import logging
import geopandas as gpd
import pandas as pd
from shapely.geometry import LineString
from sqlalchemy.orm import sessionmaker
import egon.data.datasets.etrago_setup as etrago
import egon.data.datasets.scenario_parameters.parameters as scenario_parameters
from egon.data import config, db
from egon.data.datasets import Dataset
from egon.data.datasets.fix_ehv_subnetworks import select_bus_id
from egon.data.datasets.fill_etrago_gen import add_marginal_costs
from egon.data.datasets.scenario_parameters import get_sector_parameters
from os import path
def get_cross_border_buses(scenario, sources):
"""Returns buses from osmTGmod which are outside of Germany.
Parameters
----------
sources : dict
List of sources
Returns
-------
geopandas.GeoDataFrame
Electricity buses outside of Germany
"""
return db.select_geodataframe(
f"""
SELECT *
FROM {sources['electricity_buses']['schema']}.
{sources['electricity_buses']['table']}
WHERE
NOT ST_INTERSECTS (
geom,
(SELECT ST_Transform(ST_Buffer(geometry, 5), 4326) FROM
{sources['german_borders']['schema']}.
{sources['german_borders']['table']}))
AND (bus_id IN (
SELECT bus0 FROM
{sources['lines']['schema']}.{sources['lines']['table']})
OR bus_id IN (
SELECT bus1 FROM
{sources['lines']['schema']}.{sources['lines']['table']}))
AND scn_name = '{scenario}';
""",
epsg=4326,
)
def get_cross_border_lines(scenario, sources):
"""Returns lines from osmTGmod which end or start outside of Germany.
Parameters
----------
sources : dict
List of sources
Returns
-------
geopandas.GeoDataFrame
AC-lines outside of Germany
"""
return db.select_geodataframe(
f"""
SELECT *
FROM {sources['lines']['schema']}.{sources['lines']['table']} a
WHERE
ST_INTERSECTS (
a.topo,
(SELECT ST_Transform(ST_boundary(geometry), 4326)
FROM {sources['german_borders']['schema']}.
{sources['german_borders']['table']}))
AND scn_name = '{scenario}';
""",
epsg=4326,
)
def central_buses_egon100(sources):
"""Returns buses in the middle of foreign countries based on eGon100RE
Parameters
----------
sources : dict
List of sources
Returns
-------
pandas.DataFrame
Buses in the center of foreign countries
"""
return db.select_dataframe(
f"""
SELECT *
FROM {sources['electricity_buses']['schema']}.
{sources['electricity_buses']['table']}
WHERE country != 'DE'
AND scn_name = 'eGon100RE'
AND bus_id NOT IN (
SELECT bus_i
FROM {sources['osmtgmod_bus']['schema']}.
{sources['osmtgmod_bus']['table']})
AND carrier = 'AC'
"""
)
def buses(scenario, sources, targets):
"""Insert central buses in foreign countries per scenario
Parameters
----------
sources : dict
List of dataset sources
targets : dict
List of dataset targets
Returns
-------
central_buses : geoapndas.GeoDataFrame
Buses in the center of foreign countries
"""
sql_delete = f"""
DELETE FROM {sources['electricity_buses']['schema']}.
{sources['electricity_buses']['table']}
WHERE country != 'DE' AND scn_name = '{scenario}'
AND carrier = 'AC'
AND bus_id NOT IN (
SELECT bus_i
FROM {sources['osmtgmod_bus']['schema']}.
{sources['osmtgmod_bus']['table']})
"""
# Drop only buses with v_nom != 380 for eGon100RE
# to keep buses from pypsa-eur-sec
if scenario == "eGon100RE":
sql_delete += "AND v_nom < 380"
# Delete existing buses
db.execute_sql(sql_delete)
central_buses = central_buses_egon100(sources)
next_bus_id = db.next_etrago_id("bus") + 1
# if in test mode, add bus in center of Germany
if config.settings()["egon-data"]["--dataset-boundary"] != "Everything":
central_buses = pd.concat(
[
central_buses,
pd.DataFrame(
index=[central_buses.index.max() + 1],
data={
"scn_name": scenario,
"bus_id": next_bus_id,
"x": 10.4234469,
"y": 51.0834196,
"country": "DE",
"carrier": "AC",
"v_nom": 380.0,
},
),
],
ignore_index=True,
)
next_bus_id += 1
# Add buses for other voltage levels
foreign_buses = get_cross_border_buses(scenario, sources)
if config.settings()["egon-data"]["--dataset-boundary"] == "Everything":
foreign_buses = foreign_buses[foreign_buses.country != "DE"]
vnom_per_country = foreign_buses.groupby("country").v_nom.unique().copy()
for cntr in vnom_per_country.index:
print(cntr)
if 110.0 in vnom_per_country[cntr]:
central_buses = pd.concat(
[
central_buses,
pd.DataFrame(
index=[central_buses.index.max() + 1],
data={
"scn_name": scenario,
"bus_id": next_bus_id,
"x": central_buses[
central_buses.country == cntr
].x.unique()[0],
"y": central_buses[
central_buses.country == cntr
].y.unique()[0],
"country": cntr,
"carrier": "AC",
"v_nom": 110.0,
},
),
],
ignore_index=True,
)
next_bus_id += 1
if 220.0 in vnom_per_country[cntr]:
central_buses = pd.concat(
[
central_buses,
pd.DataFrame(
index=[central_buses.index.max() + 1],
data={
"scn_name": scenario,
"bus_id": next_bus_id,
"x": central_buses[
central_buses.country == cntr
].x.unique()[0],
"y": central_buses[
central_buses.country == cntr
].y.unique()[0],
"country": cntr,
"carrier": "AC",
"v_nom": 220.0,
},
),
],
ignore_index=True,
)
next_bus_id += 1
# Add geometry column
central_buses = gpd.GeoDataFrame(
central_buses,
geometry=gpd.points_from_xy(central_buses.x, central_buses.y),
crs="EPSG:4326",
)
central_buses["geom"] = central_buses.geometry.copy()
central_buses = central_buses.set_geometry("geom").drop(
"geometry", axis="columns"
)
central_buses.scn_name = scenario
# Insert all central buses for eGon2035
if scenario in ["eGon2035", "status2019"]:
central_buses.to_postgis(
targets["buses"]["table"],
schema=targets["buses"]["schema"],
if_exists="append",
con=db.engine(),
index=False,
)
# Insert only buses for eGon100RE that are not coming from pypsa-eur-sec
# (buses with another voltage_level or inside Germany in test mode)
else:
central_buses[
(central_buses.v_nom != 380) | (central_buses.country == "DE")
].to_postgis(
targets["buses"]["table"],
schema=targets["buses"]["schema"],
if_exists="append",
con=db.engine(),
index=False,
)
return central_buses
def cross_border_lines(scenario, sources, targets, central_buses):
"""Adds lines which connect border-crossing lines from osmtgmod
to the central buses in the corresponding neigbouring country
Parameters
----------
sources : dict
List of dataset sources
targets : dict
List of dataset targets
central_buses : geopandas.GeoDataFrame
Buses in the center of foreign countries
Returns
-------
new_lines : geopandas.GeoDataFrame
Lines that connect cross-border lines to central bus per country
"""
# Delete existing data
db.execute_sql(
f"""
DELETE FROM {targets['lines']['schema']}.
{targets['lines']['table']}
WHERE scn_name = '{scenario}'
AND line_id NOT IN (
SELECT branch_id
FROM {sources['osmtgmod_branch']['schema']}.
{sources['osmtgmod_branch']['table']}
WHERE result_id = 1 and (link_type = 'line' or
link_type = 'cable'))
AND bus0 IN (
SELECT bus_i
FROM {sources['osmtgmod_bus']['schema']}.
{sources['osmtgmod_bus']['table']})
AND bus1 NOT IN (
SELECT bus_i
FROM {sources['osmtgmod_bus']['schema']}.
{sources['osmtgmod_bus']['table']})
"""
)
# Calculate cross-border busses and lines from osmtgmod
foreign_buses = get_cross_border_buses(scenario, sources)
if config.settings()["egon-data"]["--dataset-boundary"] == "Everything":
foreign_buses = foreign_buses[foreign_buses.country != "DE"]
lines = get_cross_border_lines(scenario, sources)
# Select bus outside of Germany from border-crossing lines
lines.loc[
lines[lines.bus0.isin(foreign_buses.bus_id)].index, "foreign_bus"
] = lines.loc[lines[lines.bus0.isin(foreign_buses.bus_id)].index, "bus0"]
lines.loc[
lines[lines.bus1.isin(foreign_buses.bus_id)].index, "foreign_bus"
] = lines.loc[lines[lines.bus1.isin(foreign_buses.bus_id)].index, "bus1"]
# Drop lines with start and endpoint in Germany
lines = lines[lines.foreign_bus.notnull()]
lines.loc[:, "foreign_bus"] = lines.loc[:, "foreign_bus"].astype(int)
# Copy all parameters from border-crossing lines
new_lines = lines.copy().set_crs(4326)
# Set bus0 as foreign_bus from osmtgmod
new_lines.bus0 = new_lines.foreign_bus.copy()
new_lines.bus0 = new_lines.bus0.astype(int)
# Add country tag and set index
new_lines["country"] = (
foreign_buses.set_index("bus_id")
.loc[lines.foreign_bus, "country"]
.values
)
if config.settings()["egon-data"]["--dataset-boundary"] == "Everything":
new_lines = new_lines[~new_lines.country.isnull()]
new_lines.line_id = range(
db.next_etrago_id("line"), db.next_etrago_id("line") + len(new_lines)
)
# Set bus in center of foreogn countries as bus1
for i, row in new_lines.iterrows():
print(row)
new_lines.loc[i, "bus1"] = central_buses.bus_id[
(central_buses.country == row.country)
& (central_buses.v_nom == row.v_nom)
].values[0]
# Create geometry for new lines
new_lines["geom_bus0"] = (
foreign_buses.set_index("bus_id").geom[new_lines.bus0].values
)
new_lines["geom_bus1"] = (
central_buses.set_index("bus_id").geom[new_lines.bus1].values
)
new_lines["topo"] = new_lines.apply(
lambda x: LineString([x["geom_bus0"], x["geom_bus1"]]), axis=1
)
# Set topo as geometry column
new_lines = new_lines.set_geometry("topo").set_crs(4326)
# Calcultae length of lines based on topology
old_length = new_lines["length"].copy()
new_lines["length"] = new_lines.to_crs(3035).length / 1000
# Set electrical parameters based on lines from osmtgmod
for parameter in ["x", "r"]:
new_lines[parameter] = (
new_lines[parameter] / old_length * new_lines["length"]
)
for parameter in ["b", "g"]:
new_lines[parameter] = (
new_lines[parameter] * old_length / new_lines["length"]
)
# Drop intermediate columns
new_lines.drop(
["foreign_bus", "country", "geom_bus0", "geom_bus1", "geom"],
axis="columns",
inplace=True,
)
new_lines = new_lines[new_lines.bus0 != new_lines.bus1]
# Set scn_name
# Insert lines to the database
new_lines.to_postgis(
targets["lines"]["table"],
schema=targets["lines"]["schema"],
if_exists="append",
con=db.engine(),
index=False,
)
return new_lines
def choose_transformer(s_nom):
"""Select transformer and parameters from existing data in the grid model
It is assumed that transformers in the foreign countries are not limiting
the electricity flow, so the capacitiy s_nom is set to the minimum sum
of attached AC-lines.
The electrical parameters are set according to already inserted
transformers in the grid model for Germany.
Parameters
----------
s_nom : float
Minimal sum of nominal power of lines at one side
Returns
-------
int
Selected transformer nominal power
float
Selected transformer nominal impedance
"""
if s_nom <= 600:
return 600, 0.0002
elif (s_nom > 600) & (s_nom <= 1200):
return 1200, 0.0001
elif (s_nom > 1200) & (s_nom <= 1600):
return 1600, 0.000075
elif (s_nom > 1600) & (s_nom <= 2100):
return 2100, 0.00006667
elif (s_nom > 2100) & (s_nom <= 2600):
return 2600, 0.0000461538
elif (s_nom > 2600) & (s_nom <= 4800):
return 4800, 0.000025
elif (s_nom > 4800) & (s_nom <= 6000):
return 6000, 0.0000225
elif (s_nom > 6000) & (s_nom <= 7200):
return 7200, 0.0000194444
elif (s_nom > 7200) & (s_nom <= 8000):
return 8000, 0.000016875
elif (s_nom > 8000) & (s_nom <= 9000):
return 9000, 0.000015
elif (s_nom > 9000) & (s_nom <= 13000):
return 13000, 0.0000103846
elif (s_nom > 13000) & (s_nom <= 20000):
return 20000, 0.00000675
elif (s_nom > 20000) & (s_nom <= 33000):
return 33000, 0.00000409091
def central_transformer(scenario, sources, targets, central_buses, new_lines):
"""Connect central foreign buses with different voltage levels
Parameters
----------
sources : dict
List of dataset sources
targets : dict
List of dataset targets
central_buses : geopandas.GeoDataFrame
Buses in the center of foreign countries
new_lines : geopandas.GeoDataFrame
Lines that connect cross-border lines to central bus per country
Returns
-------
None.
"""
# Delete existing transformers in foreign countries
db.execute_sql(
f"""
DELETE FROM {targets['transformers']['schema']}.
{targets['transformers']['table']}
WHERE scn_name = '{scenario}'
AND trafo_id NOT IN (
SELECT branch_id
FROM {sources['osmtgmod_branch']['schema']}.
{sources['osmtgmod_branch']['table']}
WHERE result_id = 1 and link_type = 'transformer')
"""
)
# Initalize the dataframe for transformers
trafo = gpd.GeoDataFrame(
columns=["trafo_id", "bus0", "bus1", "s_nom"], dtype=int
)
trafo_id = db.next_etrago_id("transformer")
# Add one transformer per central foreign bus with v_nom != 380
for i, row in central_buses[central_buses.v_nom != 380].iterrows():
s_nom_0 = new_lines[new_lines.bus0 == row.bus_id].s_nom.sum()
s_nom_1 = new_lines[new_lines.bus1 == row.bus_id].s_nom.sum()
if s_nom_0 == 0.0:
s_nom = s_nom_1
elif s_nom_1 == 0.0:
s_nom = s_nom_0
else:
s_nom = min([s_nom_0, s_nom_1])
s_nom, x = choose_transformer(s_nom)
trafo = pd.concat(
[
trafo,
pd.DataFrame(
index=[trafo.index.max() + 1],
data={
"trafo_id": trafo_id,
"bus0": row.bus_id,
"bus1": central_buses[
(central_buses.v_nom == 380)
& (central_buses.country == row.country)
].bus_id.values[0],
"s_nom": s_nom,
"x": x,
},
),
],
ignore_index=True,
)
trafo_id += 1
# Set data type
trafo = trafo.astype({"trafo_id": "int", "bus0": "int", "bus1": "int"})
trafo["scn_name"] = scenario
# Insert transformers to the database
trafo.to_sql(
targets["transformers"]["table"],
schema=targets["transformers"]["schema"],
if_exists="append",
con=db.engine(),
index=False,
)
def foreign_dc_lines(scenario, sources, targets, central_buses):
"""Insert DC lines to foreign countries manually
Parameters
----------
sources : dict
List of dataset sources
targets : dict
List of dataset targets
central_buses : geopandas.GeoDataFrame
Buses in the center of foreign countries
Returns
-------
None.
"""
# Delete existing dc lines to foreign countries
db.execute_sql(
f"""
DELETE FROM {targets['links']['schema']}.
{targets['links']['table']}
WHERE scn_name = '{scenario}'
AND carrier = 'DC'
AND bus0 IN (
SELECT bus_id
FROM {sources['electricity_buses']['schema']}.
{sources['electricity_buses']['table']}
WHERE scn_name = '{scenario}'
AND carrier = 'AC'
AND country = 'DE')
AND bus1 IN (
SELECT bus_id
FROM {sources['electricity_buses']['schema']}.
{sources['electricity_buses']['table']}
WHERE scn_name = '{scenario}'
AND carrier = 'AC'
AND country != 'DE')
"""
)
capital_cost = get_sector_parameters("electricity", "eGon2035")[
"capital_cost"
]
# Add DC line from Lübeck to Sweden
converter_luebeck = select_bus_id(
10.802358024202768,
53.897547401787,
380,
scenario,
"AC",
find_closest=True,
)
foreign_links = pd.DataFrame(
index=[0],
data={
"link_id": db.next_etrago_id("link"),
"bus0": converter_luebeck,
"bus1": central_buses[
(central_buses.country == "SE") & (central_buses.v_nom == 380)
]
.squeeze()
.bus_id,
"p_nom": 600,
"length": 262,
},
)
# When not in test-mode, add DC line from Bentwisch to Denmark
if config.settings()["egon-data"]["--dataset-boundary"] == "Everything":
converter_bentwisch = select_bus_id(
12.213671694775988,
54.09974494662279,
380,
scenario,
"AC",
find_closest=True,
)
foreign_links = pd.concat(
[
foreign_links,
pd.DataFrame(
index=[1],
data={
"link_id": db.next_etrago_id("link") + 1,
"bus0": converter_bentwisch,
"bus1": central_buses[
(central_buses.country == "DK")
& (central_buses.v_nom == 380)
& (central_buses.x > 10)
]
.squeeze()
.bus_id,
"p_nom": 600,
"length": 170,
},
),
]
)
# Set parameters for all DC lines
foreign_links["capital_cost"] = (
capital_cost["dc_cable"] * foreign_links.length
+ 2 * capital_cost["dc_inverter"]
)
foreign_links["p_min_pu"] = -1
foreign_links["p_nom_extendable"] = True
foreign_links["p_nom_min"] = foreign_links["p_nom"]
foreign_links["scn_name"] = scenario
foreign_links["carrier"] = "DC"
foreign_links["efficiency"] = 1
# Add topology
foreign_links = etrago.link_geom_from_buses(foreign_links, scenario)
# Insert DC lines to the database
foreign_links.to_postgis(
targets["links"]["table"],
schema=targets["links"]["schema"],
if_exists="append",
con=db.engine(),
index=False,
)
def grid():
"""Insert electrical grid compoenents for neighbouring countries
Returns
-------
None.
"""
# Select sources and targets from dataset configuration
sources = config.datasets()["electrical_neighbours"]["sources"]
targets = config.datasets()["electrical_neighbours"]["targets"]
for scenario in config.settings()["egon-data"]["--scenarios"]:
central_buses = buses(scenario, sources, targets)
foreign_lines = cross_border_lines(
scenario, sources, targets, central_buses
)
central_transformer(
scenario, sources, targets, central_buses, foreign_lines
)
foreign_dc_lines(scenario, sources, targets, central_buses)
def map_carriers_tyndp():
"""Map carriers from TYNDP-data to carriers used in eGon
Returns
-------
dict
Carrier from TYNDP and eGon
"""
return {
"Battery": "battery",
"DSR": "demand_side_response",
"Gas CCGT new": "gas",
"Gas CCGT old 2": "gas",
"Gas CCGT present 1": "gas",
"Gas CCGT present 2": "gas",
"Gas conventional old 1": "gas",
"Gas conventional old 2": "gas",
"Gas OCGT new": "gas",
"Gas OCGT old": "gas",
"Gas CCGT old 1": "gas",
"Gas CCGT old 2 Bio": "biogas",
"Gas conventional old 2 Bio": "biogas",
"Hard coal new": "coal",
"Hard coal old 1": "coal",
"Hard coal old 2": "coal",
"Hard coal old 2 Bio": "coal",
"Heavy oil old 1": "oil",
"Heavy oil old 1 Bio": "oil",
"Heavy oil old 2": "oil",
"Light oil": "oil",
"Lignite new": "lignite",
"Lignite old 1": "lignite",
"Lignite old 2": "lignite",
"Lignite old 1 Bio": "lignite",
"Lignite old 2 Bio": "lignite",
"Nuclear": "nuclear",
"Offshore Wind": "wind_offshore",
"Onshore Wind": "wind_onshore",
"Other non-RES": "others",
"Other RES": "others",
"P2G": "power_to_gas",
"PS Closed": "pumped_hydro",
"PS Open": "reservoir",
"Reservoir": "reservoir",
"Run-of-River": "run_of_river",
"Solar PV": "solar",
"Solar Thermal": "others",
"Waste": "Other RES",
}
def get_foreign_bus_id(scenario):
"""Calculte the etrago bus id from Nodes of TYNDP based on the geometry
Returns
-------
pandas.Series
List of mapped node_ids from TYNDP and etragos bus_id
"""
sources = config.datasets()["electrical_neighbours"]["sources"]
bus_id = db.select_geodataframe(
f"""SELECT bus_id, ST_Buffer(geom, 1) as geom, country
FROM grid.egon_etrago_bus
WHERE scn_name = '{scenario}'
AND carrier = 'AC'
AND v_nom = 380.
AND country != 'DE'
AND bus_id NOT IN (
SELECT bus_i
FROM osmtgmod_results.bus_data)
""",
epsg=3035,
)
# insert installed capacities
file = zipfile.ZipFile(f"tyndp/{sources['tyndp_capacities']}")
# Select buses in neighbouring countries as geodataframe
buses = pd.read_excel(
file.open("TYNDP-2020-Scenario-Datafile.xlsx").read(),
sheet_name="Nodes - Dict",
).query("longitude==longitude")
buses = gpd.GeoDataFrame(
buses,
crs=4326,
geometry=gpd.points_from_xy(buses.longitude, buses.latitude),
).to_crs(3035)
buses["bus_id"] = 0
# Select bus_id from etrago with shortest distance to TYNDP node
for i, row in buses.iterrows():
distance = bus_id.set_index("bus_id").geom.distance(row.geometry)
buses.loc[i, "bus_id"] = distance[
distance == distance.min()
].index.values[0]
return buses.set_index("node_id").bus_id
def calc_capacities():
"""Calculates installed capacities from TYNDP data
Returns
-------
pandas.DataFrame
Installed capacities per foreign node and energy carrier
"""
sources = config.datasets()["electrical_neighbours"]["sources"]
countries = [
"AT",
"BE",
"CH",
"CZ",
"DK",
"FR",
"NL",
"NO",
"SE",
"PL",
"UK",
]
# insert installed capacities
file = zipfile.ZipFile(f"tyndp/{sources['tyndp_capacities']}")
df = pd.read_excel(
file.open("TYNDP-2020-Scenario-Datafile.xlsx").read(),
sheet_name="Capacity",
)
# differneces between different climate years are very small (<1MW)
# choose 1984 because it is the mean value
df_2030 = (
df.rename({"Climate Year": "Climate_Year"}, axis="columns")
.query(
'Scenario == "Distributed Energy" & Year == 2030 & '
"Climate_Year == 1984"
)
.set_index(["Node/Line", "Generator_ID"])
)
df_2040 = (
df.rename({"Climate Year": "Climate_Year"}, axis="columns")
.query(
'Scenario == "Distributed Energy" & Year == 2040 & '
"Climate_Year == 1984"
)
.set_index(["Node/Line", "Generator_ID"])
)
# interpolate linear between 2030 and 2040 for 2035 accordning to
# scenario report of TSO's and the approval by BNetzA
df_2035 = pd.DataFrame(index=df_2030.index)
df_2035["cap_2030"] = df_2030.Value
df_2035["cap_2040"] = df_2040.Value
df_2035.fillna(0.0, inplace=True)
df_2035["cap_2035"] = (
df_2035["cap_2030"] + (df_2035["cap_2040"] - df_2035["cap_2030"]) / 2
)
df_2035 = df_2035.reset_index()
df_2035["carrier"] = df_2035.Generator_ID.map(map_carriers_tyndp())
# group capacities by new carriers
grouped_capacities = (
df_2035.groupby(["carrier", "Node/Line"]).cap_2035.sum().reset_index()
)
# choose capacities for considered countries
return grouped_capacities[
grouped_capacities["Node/Line"].str[:2].isin(countries)
]
def insert_generators(capacities):
"""Insert generators for foreign countries based on TYNDP-data
Parameters
----------
capacities : pandas.DataFrame
Installed capacities per foreign node and energy carrier
Returns
-------
None.
"""
targets = config.datasets()["electrical_neighbours"]["targets"]
map_buses = get_map_buses()
# Delete existing data
db.execute_sql(
f"""
DELETE FROM
{targets['generators']['schema']}.{targets['generators']['table']}
WHERE bus IN (
SELECT bus_id FROM
{targets['buses']['schema']}.{targets['buses']['table']}
WHERE country != 'DE'
AND scn_name = 'eGon2035')
AND scn_name = 'eGon2035'
AND carrier != 'CH4'
"""
)
db.execute_sql(
f"""
DELETE FROM
{targets['generators_timeseries']['schema']}.
{targets['generators_timeseries']['table']}
WHERE generator_id NOT IN (
SELECT generator_id FROM
{targets['generators']['schema']}.{targets['generators']['table']}
)
AND scn_name = 'eGon2035'
"""
)
# Select generators from TYNDP capacities
gen = capacities[
capacities.carrier.isin(
[
"others",
"wind_offshore",
"wind_onshore",
"solar",
"reservoir",
"run_of_river",
"lignite",
"coal",
"oil",
"nuclear",
]
)
]
# Set bus_id
gen.loc[
gen[gen["Node/Line"].isin(map_buses.keys())].index, "Node/Line"
] = gen.loc[
gen[gen["Node/Line"].isin(map_buses.keys())].index, "Node/Line"
].map(
map_buses
)
gen.loc[:, "bus"] = (
get_foreign_bus_id(scenario="eGon2035")
.loc[gen.loc[:, "Node/Line"]]
.values
)
# Add scenario column
gen["scenario"] = "eGon2035"
# Add marginal costs
gen = add_marginal_costs(gen)
# insert generators data
session = sessionmaker(bind=db.engine())()
for i, row in gen.iterrows():
entry = etrago.EgonPfHvGenerator(
scn_name=row.scenario,
generator_id=int(db.next_etrago_id("generator")),
bus=row.bus,
carrier=row.carrier,
p_nom=row.cap_2035,
marginal_cost=row.marginal_cost,
)
session.add(entry)
session.commit()
# assign generators time-series data
renew_carriers_2035 = ["wind_onshore", "wind_offshore", "solar"]
sql = f"""SELECT * FROM
{targets['generators_timeseries']['schema']}.
{targets['generators_timeseries']['table']}
WHERE scn_name = 'eGon100RE'
"""
series_egon100 = pd.read_sql_query(sql, db.engine())
sql = f""" SELECT * FROM
{targets['generators']['schema']}.{targets['generators']['table']}
WHERE bus IN (
SELECT bus_id FROM
{targets['buses']['schema']}.{targets['buses']['table']}
WHERE country != 'DE'
AND scn_name = 'eGon2035')
AND scn_name = 'eGon2035'
"""
gen_2035 = pd.read_sql_query(sql, db.engine())
gen_2035 = gen_2035[gen_2035.carrier.isin(renew_carriers_2035)]