-
Notifications
You must be signed in to change notification settings - Fork 4
/
eGon2035.py
executable file
·1588 lines (1357 loc) · 47.1 KB
/
eGon2035.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
"""Central module containing code dealing with gas neighbours for eGon2035
"""
from pathlib import Path
from urllib.request import urlretrieve
import ast
import zipfile
from shapely.geometry import LineString, MultiLineString
import geopandas as gpd
import pandas as pd
import pypsa
from egon.data import config, db
from egon.data.datasets.electrical_neighbours import (
get_foreign_bus_id,
get_map_buses,
)
from egon.data.datasets.gas_neighbours.gas_abroad import (
insert_gas_grid_capacities,
)
from egon.data.datasets.scenario_parameters import get_sector_parameters
countries = [
"AT",
"BE",
"CH",
"CZ",
"DK",
"FR",
"GB",
"LU",
"NL",
"NO",
"PL",
"RU",
"SE",
"UK",
]
def get_foreign_gas_bus_id(carrier="CH4"):
"""Calculate the etrago bus id based on the geometry
Map node_ids from TYNDP and etragos bus_id
Parameters
----------
carrier : str
Name of the carrier
Returns
-------
pandas.Series
List of mapped node_ids from TYNDP and etragos bus_id
"""
sources = config.datasets()["gas_neighbours"]["sources"]
scn_name = "eGon2035"
bus_id = db.select_geodataframe(
f"""
SELECT bus_id, ST_Buffer(geom, 1) as geom, country
FROM grid.egon_etrago_bus
WHERE scn_name = '{scn_name}'
AND carrier = '{carrier}'
AND country != 'DE'
""",
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 read_LNG_capacities():
"""Read LNG import capacities from Scigrid gas data
Returns
-------
IGGIELGN_LNGs: pandas.Series
LNG terminal capacities per foreign country node (in GWh/d)
"""
lng_file = "datasets/gas_data/data/IGGIELGN_LNGs.csv"
IGGIELGN_LNGs = gpd.read_file(lng_file)
map_countries_scigrid = {
"BE": "BE00",
"EE": "EE00",
"EL": "GR00",
"ES": "ES00",
"FI": "FI00",
"FR": "FR00",
"GB": "UK00",
"IT": "ITCN",
"LT": "LT00",
"LV": "LV00",
"MT": "MT00",
"NL": "NL00",
"PL": "PL00",
"PT": "PT00",
"SE": "SE01",
}
conversion_factor = 437.5 # MCM/day to MWh/h
c2 = 24 / 1000 # MWh/h to GWh/d
p_nom = []
for index, row in IGGIELGN_LNGs.iterrows():
param = ast.literal_eval(row["param"])
p_nom.append(
param["max_cap_store2pipe_M_m3_per_d"] * conversion_factor * c2
)
IGGIELGN_LNGs["LNG max_cap_store2pipe_M_m3_per_d (in GWh/d)"] = p_nom
IGGIELGN_LNGs.drop(
[
"uncertainty",
"method",
"param",
"comment",
"tags",
"source_id",
"lat",
"long",
"geometry",
"id",
"name",
"node_id",
],
axis=1,
inplace=True,
)
IGGIELGN_LNGs["Country"] = IGGIELGN_LNGs["country_code"].map(
map_countries_scigrid
)
IGGIELGN_LNGs = (
IGGIELGN_LNGs.groupby(["Country"])[
"LNG max_cap_store2pipe_M_m3_per_d (in GWh/d)"
]
.sum()
.sort_index()
)
return IGGIELGN_LNGs
def calc_capacities():
"""Calculates gas production capacities of neighbouring countries
For each neigbouring country, this function calculates the gas
generation capacity in 2035 using the function
:py:func:`calc_capacity_per_year` for 2030 and 2040 and
interpolates the results. These capacities include LNG import, as
well as conventional and biogas production.
Two conventional gas generators are added for Norway and Russia
interpolating the supply potential values from the TYNPD 2020
for 2030 and 2040.
Returns
-------
grouped_capacities: pandas.DataFrame
Gas production capacities per foreign node
"""
sources = config.datasets()["gas_neighbours"]["sources"]
# insert installed capacities
file = zipfile.ZipFile(f"tyndp/{sources['tyndp_capacities']}")
df0 = pd.read_excel(
file.open("TYNDP-2020-Scenario-Datafile.xlsx").read(),
sheet_name="Gas Data",
)
df = (
df0.query(
'Scenario == "Distributed Energy" &'
' (Case == "Peak" | Case == "Average") &'
# Case: 2 Week/Average/DF/Peak
' Category == "Production"'
)
.drop(
columns=[
"Generator_ID",
"Climate Year",
"Simulation_ID",
"Node 1",
"Path",
"Direct/Indirect",
"Sector",
"Note",
"Category",
"Scenario",
]
)
.set_index("Node/Line")
.sort_index()
)
lng = read_LNG_capacities()
df_2030 = calc_capacity_per_year(df, lng, 2030)
df_2040 = calc_capacity_per_year(df, lng, 2040)
# Conversion GWh/d to MWh/h
conversion_factor = 1000 / 24
df_2035 = pd.concat([df_2040, df_2030], axis=1)
df_2035 = df_2035.drop(
columns=[
"Value_conv_2040",
"Value_conv_2030",
"Value_bio_2040",
"Value_bio_2030",
]
)
df_2035["cap_2035"] = (df_2035["CH4_2030"] + df_2035["CH4_2040"]) / 2
df_2035["e_nom_max"] = (
((df_2035["e_nom_max_2030"] + df_2035["e_nom_max_2040"]) / 2)
* conversion_factor
* 8760
)
df_2035["share_LNG_2035"] = (
df_2035["share_LNG_2030"] + df_2035["share_LNG_2040"]
) / 2
df_2035["share_conv_pipe_2035"] = (
df_2035["share_conv_pipe_2030"] + df_2035["share_conv_pipe_2040"]
) / 2
df_2035["share_bio_2035"] = (
df_2035["share_bio_2030"] + df_2035["share_bio_2040"]
) / 2
grouped_capacities = df_2035.drop(
columns=[
"share_LNG_2030",
"share_LNG_2040",
"share_conv_pipe_2030",
"share_conv_pipe_2040",
"share_bio_2030",
"share_bio_2040",
"CH4_2040",
"CH4_2030",
"e_nom_max_2030",
"e_nom_max_2040",
]
).reset_index()
grouped_capacities["cap_2035"] = (
grouped_capacities["cap_2035"] * conversion_factor
)
# Add generators in Norway and Russia
df_conv = (
df0.query('Case == "Min" & Category == "Supply Potential"')
.drop(
columns=[
"Generator_ID",
"Climate Year",
"Simulation_ID",
"Node 1",
"Path",
"Direct/Indirect",
"Sector",
"Note",
"Category",
"Scenario",
"Parameter",
"Case",
]
)
.set_index("Node/Line")
.sort_index()
)
df_conv_2030 = df_conv[df_conv["Year"] == 2030].rename(
columns={"Value": "Value_2030"}
)
df_conv_2040 = df_conv[df_conv["Year"] == 2040].rename(
columns={"Value": "Value_2040"}
)
df_conv_2035 = pd.concat([df_conv_2040, df_conv_2030], axis=1)
df_conv_2035["cap_2035"] = (
(df_conv_2035["Value_2030"] + df_conv_2035["Value_2040"]) / 2
) * conversion_factor
df_conv_2035["e_nom_max"] = df_conv_2035["cap_2035"] * 8760
df_conv_2035["share_LNG_2035"] = 0
df_conv_2035["share_conv_pipe_2035"] = 1
df_conv_2035["share_bio_2035"] = 0
df_conv_2035 = df_conv_2035.drop(
columns=[
"Year",
"Value_2030",
"Value_2040",
]
).reset_index()
df_conv_2035 = df_conv_2035.rename(columns={"Node/Line": "index"})
grouped_capacities = grouped_capacities.append(df_conv_2035)
# choose capacities for considered countries
grouped_capacities = grouped_capacities[
grouped_capacities["index"].str[:2].isin(countries)
]
return grouped_capacities
def calc_capacity_per_year(df, lng, year):
"""Calculates gas production capacities for a specified year
For a specified year and for the foreign country nodes this function
calculates the gas production capacities, considering the gas
(conventional and bio) production capacities from TYNDP data and the
LNG import capacities from Scigrid gas data.
The columns of the returned dataframe are the following:
* Value_bio_year: biogas production capacity (in GWh/d)
* Value_conv_year: conventional gas production capacity including
LNG imports (in GWh/d)
* CH4_year: total gas production capacity (in GWh/d). This value
is calculated using the peak production value from the TYNDP.
* e_nom_max_year: total gas production capacity representative
for the whole year (in GWh/d). This value is calculated using
the average production value from the TYNDP and will then be
used to limit the energy that can be generated in one year.
* share_LNG_year: share of LGN import capacity in the total gas
production capacity
* share_conv_pipe_year: share of conventional gas extraction
capacity in the total gas production capacity
* share_bio_year: share of biogas production capacity in the
total gas production capacity
Parameters
----------
df : pandas.DataFrame
Gas (conventional and bio) production capacities from TYNDP (in GWh/d)
lng : pandas.Series
LNG terminal capacities per foreign country node (in GWh/d)
year : int
Year to calculate gas production capacities for
Returns
-------
df_year : pandas.DataFrame
Gas production capacities (in GWh/d) per foreign country node
"""
df_conv_peak = (
df[
(df["Parameter"] == "Conventional")
& (df["Year"] == year)
& (df["Case"] == "Peak")
]
.rename(columns={"Value": f"Value_conv_{year}_peak"})
.drop(columns=["Parameter", "Year", "Case"])
)
df_conv_average = (
df[
(df["Parameter"] == "Conventional")
& (df["Year"] == year)
& (df["Case"] == "Average")
]
.rename(columns={"Value": f"Value_conv_{year}_average"})
.drop(columns=["Parameter", "Year", "Case"])
)
df_bioch4 = (
df[
(df["Parameter"] == "Biomethane")
& (df["Year"] == year)
& (df["Case"] == "Peak")
# Peak and Average have the same values for biogas
# production in 2030 and 2040
]
.rename(columns={"Value": f"Value_bio_{year}"})
.drop(columns=["Parameter", "Year", "Case"])
)
# Some values are duplicated (DE00 in 2030)
df_conv_peak = df_conv_peak[~df_conv_peak.index.duplicated(keep="first")]
df_conv_average = df_conv_average[
~df_conv_average.index.duplicated(keep="first")
]
df_year = pd.concat(
[df_conv_peak, df_conv_average, df_bioch4, lng], axis=1
).fillna(0)
df_year = df_year[
~(
(df_year[f"Value_conv_{year}_peak"] == 0)
& (df_year[f"Value_bio_{year}"] == 0)
& (df_year["LNG max_cap_store2pipe_M_m3_per_d (in GWh/d)"] == 0)
)
]
df_year[f"Value_conv_{year}"] = (
df_year[f"Value_conv_{year}_peak"]
+ df_year["LNG max_cap_store2pipe_M_m3_per_d (in GWh/d)"]
)
df_year[f"CH4_{year}"] = (
df_year[f"Value_conv_{year}"] + df_year[f"Value_bio_{year}"]
)
df_year[f"e_nom_max_{year}"] = (
df_year[f"Value_conv_{year}_average"]
+ df_year[f"Value_bio_{year}"]
+ df_year["LNG max_cap_store2pipe_M_m3_per_d (in GWh/d)"]
)
df_year[f"share_LNG_{year}"] = (
df_year["LNG max_cap_store2pipe_M_m3_per_d (in GWh/d)"]
/ df_year[f"e_nom_max_{year}"]
)
df_year[f"share_conv_pipe_{year}"] = (
df_year[f"Value_conv_{year}_average"] / df_year[f"e_nom_max_{year}"]
)
df_year[f"share_bio_{year}"] = (
df_year[f"Value_bio_{year}"] / df_year[f"e_nom_max_{year}"]
)
df_year = df_year.drop(
columns=[
"LNG max_cap_store2pipe_M_m3_per_d (in GWh/d)",
f"Value_conv_{year}_average",
f"Value_conv_{year}_peak",
]
)
return df_year
def insert_generators(gen):
"""Insert gas generators for foreign countries into the database
Insert gas generators for foreign countries into the database.
The marginal cost of the methane is calculated as the sum of the
imported LNG cost, the conventional natural gas cost and the
biomethane cost, weighted by their share in the total import/
production capacity.
LNG gas is considered to be 30% more expensive than the natural gas
transported by pipelines (source: iwd, 2022).
Parameters
----------
gen : pandas.DataFrame
Gas production capacities per foreign node and energy carrier
Returns
-------
None
"""
sources = config.datasets()["gas_neighbours"]["sources"]
targets = config.datasets()["gas_neighbours"]["targets"]
map_buses = get_map_buses()
scn_params = get_sector_parameters("gas", "eGon2035")
# Delete existing data
db.execute_sql(
f"""
DELETE FROM
{targets['generators']['schema']}.{targets['generators']['table']}
WHERE bus IN (
SELECT bus_id FROM
{sources['buses']['schema']}.{sources['buses']['table']}
WHERE country != 'DE'
AND scn_name = 'eGon2035')
AND scn_name = 'eGon2035'
AND carrier = 'CH4';
"""
)
# Set bus_id
gen.loc[gen[gen["index"].isin(map_buses.keys())].index, "index"] = gen.loc[
gen[gen["index"].isin(map_buses.keys())].index, "index"
].map(map_buses)
gen.loc[:, "bus"] = (
get_foreign_gas_bus_id().loc[gen.loc[:, "index"]].values
)
# Add missing columns
c = {"scn_name": "eGon2035", "carrier": "CH4"}
gen = gen.assign(**c)
new_id = db.next_etrago_id("generator")
gen["generator_id"] = range(new_id, new_id + len(gen))
gen["p_nom"] = gen["cap_2035"]
gen["marginal_cost"] = (
gen["share_LNG_2035"] * scn_params["marginal_cost"]["CH4"] * 1.3
+ gen["share_conv_pipe_2035"] * scn_params["marginal_cost"]["CH4"]
+ gen["share_bio_2035"] * scn_params["marginal_cost"]["biogas"]
)
# Remove useless columns
gen = gen.drop(
columns=[
"index",
"share_LNG_2035",
"share_conv_pipe_2035",
"share_bio_2035",
"cap_2035",
]
)
# Insert data to db
gen.to_sql(
targets["generators"]["table"],
db.engine(),
schema=targets["generators"]["schema"],
index=False,
if_exists="append",
)
def calc_global_ch4_demand(Norway_global_demand_1y):
"""Calculates global CH4 demands abroad for eGon2035 scenario
The data comes from TYNDP 2020 according to NEP 2021 from the
scenario 'Distributed Energy'; linear interpolates between 2030
and 2040.
Returns
-------
pandas.DataFrame
Global (yearly) CH4 final demand per foreign node
"""
sources = config.datasets()["gas_neighbours"]["sources"]
file = zipfile.ZipFile(f"tyndp/{sources['tyndp_capacities']}")
df = pd.read_excel(
file.open("TYNDP-2020-Scenario-Datafile.xlsx").read(),
sheet_name="Gas Data",
)
df = (
df.query(
'Scenario == "Distributed Energy" & '
'Case == "Average" &'
'Category == "Demand"'
)
.drop(
columns=[
"Generator_ID",
"Climate Year",
"Simulation_ID",
"Node 1",
"Path",
"Direct/Indirect",
"Sector",
"Note",
"Category",
"Case",
"Scenario",
]
)
.set_index("Node/Line")
)
df_2030 = (
df[(df["Parameter"] == "Final demand") & (df["Year"] == 2030)]
.rename(columns={"Value": "Value_2030"})
.drop(columns=["Parameter", "Year"])
)
df_2040 = (
df[(df["Parameter"] == "Final demand") & (df["Year"] == 2040)]
.rename(columns={"Value": "Value_2040"})
.drop(columns=["Parameter", "Year"])
)
# Conversion GWh/d to MWh/y
conversion_factor = 1000 * 365
df_2035 = pd.concat([df_2040, df_2030], axis=1)
df_2035["GlobD_2035"] = (
(df_2035["Value_2030"] + df_2035["Value_2040"]) / 2
) * conversion_factor
df_2035.loc["NOS0"] = [
0,
0,
Norway_global_demand_1y,
] # Manually add Norway demand
grouped_demands = df_2035.drop(
columns=["Value_2030", "Value_2040"]
).reset_index()
# choose demands for considered countries
return grouped_demands[
grouped_demands["Node/Line"].str[:2].isin(countries)
]
def import_ch4_demandTS():
"""Calculate global CH4 demand in Norway and CH4 demand profile
Import from the PyPSA-eur-sec run the time series of residential
rural heat per neighbor country. This time series is used to
calculate:
* the global (yearly) heat demand of Norway
(that will be supplied by CH4)
* the normalized CH4 hourly resolved demand profile
Returns
-------
Norway_global_demand: Float
Yearly heat demand of Norway in MWh
neighbor_loads_t: pandas.DataFrame
Normalized CH4 hourly resolved demand profiles per neighbor country
"""
cwd = Path(".")
target_file = (
cwd
/ "data_bundle_egon_data"
/ "pypsa_eur_sec"
/ "2022-07-26-egondata-integration"
/ "postnetworks"
/ "elec_s_37_lv2.0__Co2L0-1H-T-H-B-I-dist1_2050.nc"
)
network = pypsa.Network(str(target_file))
# Set country tag for all buses
network.buses.country = network.buses.index.str[:2]
neighbors = network.buses[network.buses.country != "DE"]
neighbors = neighbors[
(neighbors["country"].isin(countries))
& (neighbors["carrier"] == "residential rural heat")
].drop_duplicates(subset="country")
neighbor_loads = network.loads[network.loads.bus.isin(neighbors.index)]
neighbor_loads_t_index = neighbor_loads.index[
neighbor_loads.index.isin(network.loads_t.p_set.columns)
]
neighbor_loads_t = network.loads_t["p_set"][neighbor_loads_t_index]
Norway_global_demand = neighbor_loads_t[
"NO3 0 residential rural heat"
].sum()
for i in neighbor_loads_t.columns:
neighbor_loads_t[i] = neighbor_loads_t[i] / neighbor_loads_t[i].sum()
return Norway_global_demand, neighbor_loads_t
def insert_ch4_demand(global_demand, normalized_ch4_demandTS):
"""Insert CH4 demands abroad into the database for eGon2035
Parameters
----------
global_demand : pandas.DataFrame
Global CH4 demand per foreign node in 1 year
gas_demandTS : pandas.DataFrame
Normalized time series of the demand per foreign country
Returns
-------
None
"""
sources = config.datasets()["gas_neighbours"]["sources"]
targets = config.datasets()["gas_neighbours"]["targets"]
map_buses = get_map_buses()
scn_name = "eGon2035"
carrier = "CH4"
# Delete existing data
db.execute_sql(
f"""
DELETE FROM
{
targets['load_time series']['schema']
}.{
targets['load_time series']['table']
}
WHERE "load_id" IN (
SELECT load_id FROM
{targets['loads']['schema']}.{targets['loads']['table']}
WHERE bus IN (
SELECT bus_id FROM
{sources['buses']['schema']}.{sources['buses']['table']}
WHERE country != 'DE'
AND scn_name = '{scn_name}')
AND scn_name = '{scn_name}'
AND carrier = '{carrier}'
);
"""
)
db.execute_sql(
f"""
DELETE FROM
{targets['loads']['schema']}.{targets['loads']['table']}
WHERE bus IN (
SELECT bus_id FROM
{sources['buses']['schema']}.{sources['buses']['table']}
WHERE country != 'DE'
AND scn_name = '{scn_name}')
AND scn_name = '{scn_name}'
AND carrier = '{carrier}'
"""
)
# Set bus_id
global_demand.loc[
global_demand[global_demand["Node/Line"].isin(map_buses.keys())].index,
"Node/Line",
] = global_demand.loc[
global_demand[global_demand["Node/Line"].isin(map_buses.keys())].index,
"Node/Line",
].map(
map_buses
)
global_demand.loc[:, "bus"] = (
get_foreign_gas_bus_id().loc[global_demand.loc[:, "Node/Line"]].values
)
# Add missing columns
c = {"scn_name": scn_name, "carrier": carrier}
global_demand = global_demand.assign(**c)
new_id = db.next_etrago_id("load")
global_demand["load_id"] = range(new_id, new_id + len(global_demand))
ch4_demand_TS = global_demand.copy()
# Remove useless columns
global_demand = global_demand.drop(columns=["Node/Line", "GlobD_2035"])
# Insert data to db
global_demand.to_sql(
targets["loads"]["table"],
db.engine(),
schema=targets["loads"]["schema"],
index=False,
if_exists="append",
)
# Insert time series
ch4_demand_TS["Node/Line"] = ch4_demand_TS["Node/Line"].replace(
["UK00"], "GB"
)
p_set = []
for index, row in ch4_demand_TS.iterrows():
normalized_TS_df = normalized_ch4_demandTS.loc[
:,
normalized_ch4_demandTS.columns.str.contains(row["Node/Line"][:2]),
]
p_set.append(
(
normalized_TS_df[normalized_TS_df.columns[0]]
* row["GlobD_2035"]
).tolist()
)
ch4_demand_TS["p_set"] = p_set
ch4_demand_TS["temp_id"] = 1
ch4_demand_TS = ch4_demand_TS.drop(
columns=["Node/Line", "GlobD_2035", "bus", "carrier"]
)
# Insert data to DB
ch4_demand_TS.to_sql(
targets["load_time series"]["table"],
db.engine(),
schema=targets["load_time series"]["schema"],
index=False,
if_exists="append",
)
def calc_ch4_storage_capacities():
"""Calculate CH4 storage capacities for neighboring countries
Returns
-------
ch4_storage_capacities: pandas.DataFrame
Methane gas storage capacities per country in MWh
"""
target_file = (
Path(".") / "datasets" / "gas_data" / "data" / "IGGIELGN_Storages.csv"
)
ch4_storage_capacities = pd.read_csv(
target_file,
delimiter=";",
decimal=".",
usecols=["country_code", "param"],
)
ch4_storage_capacities = ch4_storage_capacities[
ch4_storage_capacities["country_code"].isin(countries)
]
map_countries_scigrid = {
"AT": "AT00",
"BE": "BE00",
"CZ": "CZ00",
"DK": "DKE1",
"EE": "EE00",
"EL": "GR00",
"ES": "ES00",
"FI": "FI00",
"FR": "FR00",
"GB": "UK00",
"IT": "ITCN",
"LT": "LT00",
"LV": "LV00",
"MT": "MT00",
"NL": "NL00",
"PL": "PL00",
"PT": "PT00",
"SE": "SE01",
}
# Define new columns
max_workingGas_M_m3 = []
end_year = []
for index, row in ch4_storage_capacities.iterrows():
param = ast.literal_eval(row["param"])
end_year.append(param["end_year"])
max_workingGas_M_m3.append(param["max_workingGas_M_m3"])
end_year = [float("inf") if x is None else x for x in end_year]
ch4_storage_capacities = ch4_storage_capacities.assign(end_year=end_year)
ch4_storage_capacities = ch4_storage_capacities[
ch4_storage_capacities["end_year"] >= 2035
]
# Calculate e_nom
conv_factor = (
10830 # M_m3 to MWh - gross calorific value = 39 MJ/m3 (eurogas.org)
)
ch4_storage_capacities["e_nom"] = [
conv_factor * i for i in max_workingGas_M_m3
]
ch4_storage_capacities.drop(
["param", "end_year"],
axis=1,
inplace=True,
)
ch4_storage_capacities["Country"] = ch4_storage_capacities[
"country_code"
].map(map_countries_scigrid)
ch4_storage_capacities = ch4_storage_capacities.groupby(
["country_code"]
).agg(
{
"e_nom": "sum",
"Country": "first",
},
)
ch4_storage_capacities = ch4_storage_capacities.drop(["RU"])
ch4_storage_capacities.loc[:, "bus"] = (
get_foreign_gas_bus_id()
.loc[ch4_storage_capacities.loc[:, "Country"]]
.values
)
return ch4_storage_capacities
def insert_storage(ch4_storage_capacities):
"""Insert CH4 storage capacities into the database for eGon2035
Parameters
----------
ch4_storage_capacities : pandas.DataFrame
Methane gas storage capacities per country in MWh
Returns
-------
None
"""
sources = config.datasets()["gas_neighbours"]["sources"]
targets = config.datasets()["gas_neighbours"]["targets"]
# Clean table
db.execute_sql(
f"""
DELETE FROM {targets['stores']['schema']}.{targets['stores']['table']}
WHERE "carrier" = 'CH4'
AND scn_name = 'eGon2035'
AND bus IN (
SELECT bus_id
FROM {sources['buses']['schema']}.{sources['buses']['table']}
WHERE scn_name = 'eGon2035'
AND country != 'DE'
);
"""
)
# Add missing columns
c = {"scn_name": "eGon2035", "carrier": "CH4"}
ch4_storage_capacities = ch4_storage_capacities.assign(**c)
new_id = db.next_etrago_id("store")
ch4_storage_capacities["store_id"] = range(
new_id, new_id + len(ch4_storage_capacities)
)
ch4_storage_capacities.drop(
["Country"],
axis=1,
inplace=True,
)
ch4_storage_capacities = ch4_storage_capacities.reset_index(drop=True)
# Insert data to db
ch4_storage_capacities.to_sql(
targets["stores"]["table"],
db.engine(),
schema=targets["stores"]["schema"],
index=False,
if_exists="append",
)
def calc_global_power_to_h2_demand():
"""Calculate H2 demand abroad for eGon2035 scenario
Calculates global power demand abroad linked to H2 production.
The data comes from TYNDP 2020 according to NEP 2021 from the
scenario 'Distributed Energy'; linear interpolate between 2030
and 2040.
Returns
-------
global_power_to_h2_demand : pandas.DataFrame
Global hourly power-to-h2 demand per foreign node
"""
sources = config.datasets()["gas_neighbours"]["sources"]
file = zipfile.ZipFile(f"tyndp/{sources['tyndp_capacities']}")
df = pd.read_excel(
file.open("TYNDP-2020-Scenario-Datafile.xlsx").read(),
sheet_name="Gas Data",
)
df = (
df.query(
'Scenario == "Distributed Energy" & '
'Case == "Average" &'
'Parameter == "P2H2"'
)
.drop(
columns=[
"Generator_ID",
"Climate Year",
"Simulation_ID",
"Node 1",
"Path",
"Direct/Indirect",
"Sector",
"Note",
"Category",
"Case",
"Scenario",
"Parameter",
]
)
.set_index("Node/Line")
)
df_2030 = (
df[df["Year"] == 2030]
.rename(columns={"Value": "Value_2030"})