Passed
Pull Request — dev (#1006)
by
unknown
01:37
created

data.datasets.gas_grid.insert_gas_pipeline_list()   A

Complexity

Conditions 1

Size

Total Lines 45
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 45
rs 9.4
c 0
b 0
f 0
cc 1
nop 2
1
# -*- coding: utf-8 -*-
2
"""
3
The central module containing all code dealing with importing data from SciGRID_gas IGGIELGN data
4
"""
5
from pathlib import Path
6
from urllib.request import urlretrieve
7
from zipfile import ZipFile
8
import ast
9
import json
10
import os
11
12
from geoalchemy2.types import Geometry
13
from shapely import geometry
14
import geopandas
15
import numpy as np
16
import pandas as pd
17
18
from egon.data import config, db
19
from egon.data.config import settings
20
from egon.data.datasets import Dataset
21
from egon.data.datasets.electrical_neighbours import central_buses_egon100
22
from egon.data.datasets.etrago_helpers import copy_and_modify_buses
23
from egon.data.datasets.scenario_parameters import get_sector_parameters
24
25
26
class GasNodesandPipes(Dataset):
27
    def __init__(self, dependencies):
28
        super().__init__(
29
            name="GasNodesandPipes",
30
            version="0.0.7",
31
            dependencies=dependencies,
32
            tasks=(insert_gas_data, insert_gas_data_eGon100RE),
33
        )
34
35
36
def download_SciGRID_gas_data():
37
    """
38
    Download SciGRID_gas IGGIELGN data from Zenodo
39
40
    """
41
    path = Path(".") / "datasets" / "gas_data"
42
    os.makedirs(path, exist_ok=True)
43
44
    basename = "IGGIELGN"
45
    zip_file = Path(".") / "datasets" / "gas_data" / "IGGIELGN.zip"
46
    zenodo_zip_file_url = (
47
        "https://zenodo.org/record/4767098/files/" + basename + ".zip"
48
    )
49
    if not os.path.isfile(zip_file):
50
        urlretrieve(zenodo_zip_file_url, zip_file)
51
52
    components = [
53
        "Nodes",
54
        "PipeSegments",
55
        "Productions",
56
        "Storages",
57
        "LNGs",
58
    ]  #'Compressors'
59
    files = []
60
    for i in components:
61
        files.append("data/" + basename + "_" + i + ".csv")
62
63
    with ZipFile(zip_file, "r") as zipObj:
64
        listOfFileNames = zipObj.namelist()
65
        for fileName in listOfFileNames:
66
            if fileName in files:
67
                zipObj.extract(fileName, path)
68
69
70
def define_gas_nodes_list():
71
    """Define list of gas nodes from SciGRID_gas IGGIELGN data
72
73
    Returns
74
    -------
75
    gas_nodes_list : dataframe
76
        Dataframe containing the gas nodes (Europe)
77
78
    """
79
    # Select next id value
80
    new_id = db.next_etrago_id("bus")
81
82
    target_file = (
83
        Path(".") / "datasets" / "gas_data" / "data" / "IGGIELGN_Nodes.csv"
84
    )
85
86
    gas_nodes_list = pd.read_csv(
87
        target_file,
88
        delimiter=";",
89
        decimal=".",
90
        usecols=["lat", "long", "id", "country_code", "param"],
91
    )
92
93
    # Correct non valid neighbouring country nodes
94
    gas_nodes_list.loc[
95
        gas_nodes_list["id"] == "INET_N_1182", "country_code"
96
    ] = "AT"
97
    gas_nodes_list.loc[
98
        gas_nodes_list["id"] == "SEQ_10608_p", "country_code"
99
    ] = "NL"
100
101
    gas_nodes_list = gas_nodes_list.rename(columns={"lat": "y", "long": "x"})
102
103
    gas_nodes_list["bus_id"] = range(new_id, new_id + len(gas_nodes_list))
104
    gas_nodes_list = gas_nodes_list.set_index("id")
105
106
    return gas_nodes_list
107
108
109
def ch4_nodes_number_G(gas_nodes_list):
110
    """Insert list of CH4 nodes from SciGRID_gas IGGIELGN data
111
        Parameters
112
    ----------
113
    gas_nodes_list : dataframe
114
        Dataframe containing the gas nodes (Europe)
115
    Returns
116
    -------
117
        N_ch4_nodes_G : int
118
            Number of CH4 buses in Germany (independantly from the mode used)
119
    """
120
121
    ch4_nodes_list = gas_nodes_list[
122
        gas_nodes_list["country_code"].str.match("DE")
123
    ]
124
    N_ch4_nodes_G = len(ch4_nodes_list)
125
126
    return N_ch4_nodes_G
127
128
129
def insert_CH4_nodes_list(gas_nodes_list):
130
    """Insert list of CH4 nodes from SciGRID_gas IGGIELGN data
131
132
    Insert detailled description
133
134
    Parameters
135
    ----------
136
    gas_nodes_list : dataframe
137
        Dataframe containing the gas nodes (Europe)
138
139
    Returns
140
    -------
141
    None
142
143
    """
144
    # Connect to local database
145
    engine = db.engine()
146
147
    gas_nodes_list = gas_nodes_list[
148
        gas_nodes_list["country_code"].str.match("DE")
149
    ]  # To eventually replace with a test if the nodes are in the german boundaries.
150
151
    # Cut data to federal state if in testmode
152
    NUTS1 = []
153
    for index, row in gas_nodes_list.iterrows():
154
        param = ast.literal_eval(row["param"])
155
        NUTS1.append(param["nuts_id_1"])
156
    gas_nodes_list = gas_nodes_list.assign(NUTS1=NUTS1)
157
158
    boundary = settings()["egon-data"]["--dataset-boundary"]
159
    if boundary != "Everything":
160
        map_states = {
161
            "Baden-Württemberg": "DE1",
162
            "Nordrhein-Westfalen": "DEA",
163
            "Hessen": "DE7",
164
            "Brandenburg": "DE4",
165
            "Bremen": "DE5",
166
            "Rheinland-Pfalz": "DEB",
167
            "Sachsen-Anhalt": "DEE",
168
            "Schleswig-Holstein": "DEF",
169
            "Mecklenburg-Vorpommern": "DE8",
170
            "Thüringen": "DEG",
171
            "Niedersachsen": "DE9",
172
            "Sachsen": "DED",
173
            "Hamburg": "DE6",
174
            "Saarland": "DEC",
175
            "Berlin": "DE3",
176
            "Bayern": "DE2",
177
        }
178
179
        gas_nodes_list = gas_nodes_list[
180
            gas_nodes_list["NUTS1"].isin([map_states[boundary], np.nan])
181
        ]
182
183
        # A completer avec nodes related to pipelines which have an end in the selected area et evt deplacer ds define_gas_nodes_list
184
185
    # Add missing columns
186
    c = {"scn_name": "eGon2035", "carrier": "CH4"}
187
    gas_nodes_list = gas_nodes_list.assign(**c)
188
189
    gas_nodes_list = geopandas.GeoDataFrame(
190
        gas_nodes_list,
191
        geometry=geopandas.points_from_xy(
192
            gas_nodes_list["x"], gas_nodes_list["y"]
193
        ),
194
    )
195
    gas_nodes_list = gas_nodes_list.rename(
196
        columns={"geometry": "geom"}
197
    ).set_geometry("geom", crs=4326)
198
199
    gas_nodes_list = gas_nodes_list.reset_index(drop=True)
200
    gas_nodes_list = gas_nodes_list.drop(
201
        columns=["NUTS1", "param", "country_code"]
202
    )
203
204
    # Insert data to db
205
    db.execute_sql(
206
        f"""
207
    DELETE FROM grid.egon_etrago_bus WHERE "carrier" = 'CH4' AND
208
    scn_name = '{c['scn_name']}' AND country = 'DE';
209
    """
210
    )
211
212
    # Insert CH4 data to db
213
    print(gas_nodes_list)
214
    gas_nodes_list.to_postgis(
215
        "egon_etrago_bus",
216
        engine,
217
        schema="grid",
218
        index=False,
219
        if_exists="append",
220
        dtype={"geom": Geometry()},
221
    )
222
223
224
def insert_gas_buses_abroad(scn_name="eGon2035"):
225
    """Insert central CH4 buses in foreign countries for eGon2035
226
227
    Detailled description to be completed:
228
    Insert central gas buses in foreign countries to db, same buses
229
    than the foreign AC buses
230
231
    Parameters
232
    ----------
233
    scn_name : str
234
        Name of the scenario
235
236
    Returns
237
    -------
238
    gdf_abroad_buses : dataframe
239
        Dataframe containing the CH4 buses in the neighbouring countries
240
        and one in the center of Germany in test mode
241
    """
242
    # Select sources and targets from dataset configuration
243
    sources = config.datasets()["electrical_neighbours"]["sources"]
244
245
    main_gas_carrier = get_sector_parameters("gas", scenario=scn_name)[
246
        "main_gas_carrier"
247
    ]
248
249
    # Connect to local database
250
    engine = db.engine()
251
    db.execute_sql(
252
        f"""
253
    DELETE FROM grid.egon_etrago_bus WHERE "carrier" = '{main_gas_carrier}' AND
254
    scn_name = '{scn_name}' AND country != 'DE';
255
    """
256
    )
257
258
    # Select the foreign buses
259
    gdf_abroad_buses = central_buses_egon100(sources)
260
    gdf_abroad_buses = gdf_abroad_buses.drop_duplicates(subset=["country"])
261
262
    # Select next id value
263
    new_id = db.next_etrago_id("bus")
264
265
    gdf_abroad_buses = gdf_abroad_buses.drop(
266
        columns=[
267
            "v_nom",
268
            "v_mag_pu_set",
269
            "v_mag_pu_min",
270
            "v_mag_pu_max",
271
            "geom",
272
        ]
273
    )
274
    gdf_abroad_buses["scn_name"] = "eGon2035"
275
    gdf_abroad_buses["carrier"] = main_gas_carrier
276
    gdf_abroad_buses["bus_id"] = range(new_id, new_id + len(gdf_abroad_buses))
277
278
    # Add central bus in Russia
279
    gdf_abroad_buses = gdf_abroad_buses.append(
280
        {
281
            "scn_name": scn_name,
282
            "bus_id": (new_id + len(gdf_abroad_buses) + 1),
283
            "x": 41,
284
            "y": 55,
285
            "country": "RU",
286
            "carrier": main_gas_carrier,
287
        },
288
        ignore_index=True,
289
    )
290
    # if in test mode, add bus in center of Germany
291
    boundary = settings()["egon-data"]["--dataset-boundary"]
292
293
    if boundary != "Everything":
294
        gdf_abroad_buses = gdf_abroad_buses.append(
295
            {
296
                "scn_name": scn_name,
297
                "bus_id": (new_id + len(gdf_abroad_buses) + 1),
298
                "x": 10.4234469,
299
                "y": 51.0834196,
300
                "country": "DE",
301
                "carrier": main_gas_carrier,
302
            },
303
            ignore_index=True,
304
        )
305
306
    gdf_abroad_buses = geopandas.GeoDataFrame(
307
        gdf_abroad_buses,
308
        geometry=geopandas.points_from_xy(
309
            gdf_abroad_buses["x"], gdf_abroad_buses["y"]
310
        ),
311
    )
312
    gdf_abroad_buses = gdf_abroad_buses.rename(
313
        columns={"geometry": "geom"}
314
    ).set_geometry("geom", crs=4326)
315
316
    # Insert to db
317
    gdf_abroad_buses.to_postgis(
318
        "egon_etrago_bus",
319
        engine,
320
        schema="grid",
321
        index=False,
322
        if_exists="append",
323
        dtype={"geom": Geometry()},
324
    )
325
    return gdf_abroad_buses
326
327
328
def define_gas_pipeline_list(
329
    gas_nodes_list, abroad_gas_nodes_list, scn_name="eGon2035"
330
):
331
    """Define gas pipelines in Germany from SciGRID_gas IGGIELGN data
332
333
    Insert detailled description
334
335
    Parameters
336
    ----------
337
    gas_nodes_list : dataframe
338
        description missing
339
    abroad_gas_nodes_list: dataframe
340
        description missing
341
    scn_name : str
342
        Name of the scenario
343
344
    Returns
345
    -------
346
    gas_pipelines_list : pandas.DataFrame
347
        Dataframe containing the gas pipelines in Germany
348
349
    """
350
    abroad_gas_nodes_list = abroad_gas_nodes_list.set_index("country")
351
352
    main_gas_carrier = get_sector_parameters("gas", scenario=scn_name)[
353
        "main_gas_carrier"
354
    ]
355
356
    # Select next id value
357
    new_id = db.next_etrago_id("link")
358
359
    classifiaction_file = (
360
        Path(".")
361
        / "data_bundle_egon_data"
362
        / "pipeline_classification_gas"
363
        / "pipeline_classification.csv"
364
    )
365
366
    classification = pd.read_csv(
367
        classifiaction_file,
368
        delimiter=",",
369
        usecols=["classification", "max_transport_capacity_Gwh/d"],
370
    )
371
372
    target_file = (
373
        Path(".")
374
        / "datasets"
375
        / "gas_data"
376
        / "data"
377
        / "IGGIELGN_PipeSegments.csv"
378
    )
379
380
    gas_pipelines_list = pd.read_csv(
381
        target_file,
382
        delimiter=";",
383
        decimal=".",
384
        usecols=["id", "node_id", "lat", "long", "country_code", "param"],
385
    )
386
387
    # Select the links having at least one bus in Germany
388
    gas_pipelines_list = gas_pipelines_list[
389
        gas_pipelines_list["country_code"].str.contains("DE")
390
    ]
391
392
    # Remove links disconnected of the rest of the grid
393
    # Remove manually for disconnected link EntsoG_Map__ST_195
394
    gas_pipelines_list = gas_pipelines_list[
395
        ~gas_pipelines_list["id"].str.match("EntsoG_Map__ST_195")
396
    ]
397
398
    gas_pipelines_list["link_id"] = range(
399
        new_id, new_id + len(gas_pipelines_list)
400
    )
401
    gas_pipelines_list["link_id"] = gas_pipelines_list["link_id"].astype(int)
402
403
    # Cut data to federal state if in testmode
404
    NUTS1 = []
405
    for index, row in gas_pipelines_list.iterrows():
406
        param = ast.literal_eval(row["param"])
407
        NUTS1.append(param["nuts_id_1"])
408
    gas_pipelines_list["NUTS1"] = NUTS1
409
410
    map_states = {
411
        "Baden-Württemberg": "DE1",
412
        "Nordrhein-Westfalen": "DEA",
413
        "Hessen": "DE7",
414
        "Brandenburg": "DE4",
415
        "Bremen": "DE5",
416
        "Rheinland-Pfalz": "DEB",
417
        "Sachsen-Anhalt": "DEE",
418
        "Schleswig-Holstein": "DEF",
419
        "Mecklenburg-Vorpommern": "DE8",
420
        "Thüringen": "DEG",
421
        "Niedersachsen": "DE9",
422
        "Sachsen": "DED",
423
        "Hamburg": "DE6",
424
        "Saarland": "DEC",
425
        "Berlin": "DE3",
426
        "Bayern": "DE2",
427
        "Everything": "Nan",
428
    }
429
    gas_pipelines_list["NUTS1_0"] = [x[0] for x in gas_pipelines_list["NUTS1"]]
430
    gas_pipelines_list["NUTS1_1"] = [x[1] for x in gas_pipelines_list["NUTS1"]]
431
432
    boundary = settings()["egon-data"]["--dataset-boundary"]
433
434
    if boundary != "Everything":
435
436
        gas_pipelines_list = gas_pipelines_list[
437
            gas_pipelines_list["NUTS1_0"].str.contains(map_states[boundary])
438
            | gas_pipelines_list["NUTS1_1"].str.contains(map_states[boundary])
439
        ]
440
441
    # Add missing columns
442
    gas_pipelines_list["scn_name"] = scn_name
443
    gas_pipelines_list["carrier"] = main_gas_carrier
444
    gas_pipelines_list["p_nom_extendable"] = False
445
446
    diameter = []
447
    geom = []
448
    topo = []
449
    length_km = []
450
451
    for index, row in gas_pipelines_list.iterrows():
452
453
        param = ast.literal_eval(row["param"])
454
        diameter.append(param["diameter_mm"])
455
        length_km.append(param["length_km"])
456
457
        long_e = json.loads(row["long"])
458
        lat_e = json.loads(row["lat"])
459
        crd_e = list(zip(long_e, lat_e))
460
        topo.append(geometry.LineString(crd_e))
461
462
        long_path = param["path_long"]
463
        lat_path = param["path_lat"]
464
        crd = list(zip(long_path, lat_path))
465
        crd.insert(0, crd_e[0])
466
        crd.append(crd_e[1])
467
        lines = []
468
        for i in range(len(crd) - 1):
469
            lines.append(geometry.LineString([crd[i], crd[i + 1]]))
470
        geom.append(geometry.MultiLineString(lines))
471
472
    gas_pipelines_list["diameter"] = diameter
473
    gas_pipelines_list["geom"] = geom
474
    gas_pipelines_list["topo"] = topo
475
    gas_pipelines_list["length_km"] = length_km
476
    gas_pipelines_list = gas_pipelines_list.set_geometry("geom", crs=4326)
477
478
    country_0 = []
479
    country_1 = []
480
    for index, row in gas_pipelines_list.iterrows():
481
        c = ast.literal_eval(row["country_code"])
482
        country_0.append(c[0])
483
        country_1.append(c[1])
484
485
    gas_pipelines_list["country_0"] = country_0
486
    gas_pipelines_list["country_1"] = country_1
487
488
    # Correct non valid neighbouring country nodes
489
    gas_pipelines_list.loc[
490
        gas_pipelines_list["country_0"] == "XX", "country_0"
491
    ] = "NO"
492
    gas_pipelines_list.loc[
493
        gas_pipelines_list["country_1"] == "FI", "country_1"
494
    ] = "RU"
495
    gas_pipelines_list.loc[
496
        gas_pipelines_list["id"] == "ST_2612_Seg_0_Seg_0", "country_0"
497
    ] = "AT"  # bus "INET_N_1182" DE -> AT
498
    gas_pipelines_list.loc[
499
        gas_pipelines_list["id"] == "INET_PL_385_EE_3_Seg_0_Seg_1", "country_1"
500
    ] = "AT"  # "INET_N_1182" DE -> AT
501
    gas_pipelines_list.loc[
502
        gas_pipelines_list["id"] == "LKD_PS_0_Seg_0_Seg_3", "country_0"
503
    ] = "NL"  # bus "SEQ_10608_p" DE -> NL
504
505
    # Remove link test if length = 0
506
    gas_pipelines_list = gas_pipelines_list[
507
        gas_pipelines_list["length_km"] != 0
508
    ]
509
510
    # Adjust columns
511
    bus0 = []
512
    bus1 = []
513
    geom_adjusted = []
514
    topo_adjusted = []
515
    length_adjusted = []
516
    pipe_class = []
517
518
    for index, row in gas_pipelines_list.iterrows():
519
        buses = row["node_id"].strip("][").split(", ")
520
521
        if (
522
            (boundary != "Everything")
523
            & (row["NUTS1_0"] != map_states[boundary])
524
            & (row["country_0"] == "DE")
525
        ):
526
            bus0.append(abroad_gas_nodes_list.loc["DE", "bus_id"])
527
            bus1.append(gas_nodes_list.loc[buses[1][1:-1], "bus_id"])
528
            long_e = [
529
                abroad_gas_nodes_list.loc["DE", "x"],
530
                json.loads(row["long"])[1],
531
            ]
532
            lat_e = [
533
                abroad_gas_nodes_list.loc["DE", "y"],
534
                json.loads(row["lat"])[1],
535
            ]
536
            geom_pipe = geometry.MultiLineString(
537
                [geometry.LineString(list(zip(long_e, lat_e)))]
538
            )
539
            topo_adjusted.append(geometry.LineString(list(zip(long_e, lat_e))))
540
541
        elif row["country_0"] != "DE":
542
            country = str(row["country_0"])
543
            bus0.append(abroad_gas_nodes_list.loc[country, "bus_id"])
544
            bus1.append(gas_nodes_list.loc[buses[1][1:-1], "bus_id"])
545
            long_e = [
546
                abroad_gas_nodes_list.loc[country, "x"],
547
                json.loads(row["long"])[1],
548
            ]
549
            lat_e = [
550
                abroad_gas_nodes_list.loc[country, "y"],
551
                json.loads(row["lat"])[1],
552
            ]
553
            geom_pipe = geometry.MultiLineString(
554
                [geometry.LineString(list(zip(long_e, lat_e)))]
555
            )
556
            topo_adjusted.append(geometry.LineString(list(zip(long_e, lat_e))))
557
558
        elif (
559
            (boundary != "Everything")
560
            & (row["NUTS1_1"] != map_states[boundary])
561
            & (row["country_1"] == "DE")
562
        ):
563
            bus0.append(gas_nodes_list.loc[buses[0][1:-1], "bus_id"])
564
            bus1.append(abroad_gas_nodes_list.loc["DE", "bus_id"])
565
            long_e = [
566
                json.loads(row["long"])[0],
567
                abroad_gas_nodes_list.loc["DE", "x"],
568
            ]
569
            lat_e = [
570
                json.loads(row["lat"])[0],
571
                abroad_gas_nodes_list.loc["DE", "y"],
572
            ]
573
            geom_pipe = geometry.MultiLineString(
574
                [geometry.LineString(list(zip(long_e, lat_e)))]
575
            )
576
            topo_adjusted.append(geometry.LineString(list(zip(long_e, lat_e))))
577
578
        elif row["country_1"] != "DE":
579
            country = str(row["country_1"])
580
            bus0.append(gas_nodes_list.loc[buses[0][1:-1], "bus_id"])
581
            bus1.append(abroad_gas_nodes_list.loc[country, "bus_id"])
582
            long_e = [
583
                json.loads(row["long"])[0],
584
                abroad_gas_nodes_list.loc[country, "x"],
585
            ]
586
            lat_e = [
587
                json.loads(row["lat"])[0],
588
                abroad_gas_nodes_list.loc[country, "y"],
589
            ]
590
            geom_pipe = geometry.MultiLineString(
591
                [geometry.LineString(list(zip(long_e, lat_e)))]
592
            )
593
            topo_adjusted.append(geometry.LineString(list(zip(long_e, lat_e))))
594
595
        else:
596
            bus0.append(gas_nodes_list.loc[buses[0][1:-1], "bus_id"])
597
            bus1.append(gas_nodes_list.loc[buses[1][1:-1], "bus_id"])
598
            geom_pipe = row["geom"]
599
            topo_adjusted.append(row["topo"])
600
601
        geom_adjusted.append(geom_pipe)
602
        length_adjusted.append(geom_pipe.length)
603
604
        if row["diameter"] >= 1000:
605
            pipe_class = "A"
606
        elif 700 <= row["diameter"] <= 1000:
607
            pipe_class = "B"
608
        elif 500 <= row["diameter"] <= 700:
609
            pipe_class = "C"
610
        elif 350 <= row["diameter"] <= 500:
611
            pipe_class = "D"
612
        elif 200 <= row["diameter"] <= 350:
613
            pipe_class = "E"
614
        elif 100 <= row["diameter"] <= 200:
615
            pipe_class = "F"
616
        elif row["diameter"] <= 100:
617
            pipe_class = "G"
618
619
    gas_pipelines_list["bus0"] = bus0
620
    gas_pipelines_list["bus1"] = bus1
621
    gas_pipelines_list["geom"] = geom_adjusted
622
    gas_pipelines_list["topo"] = topo_adjusted
623
    gas_pipelines_list["length"] = length_adjusted
624
    gas_pipelines_list["pipe_class"] = pipe_class
625
626
    # Remove pipes having the same node for start and end
627
    gas_pipelines_list = gas_pipelines_list[
628
        gas_pipelines_list["bus0"] != gas_pipelines_list["bus1"]
629
    ]
630
631
    gas_pipelines_list = gas_pipelines_list.merge(
632
        classification,
633
        how="left",
634
        left_on="pipe_class",
635
        right_on="classification",
636
    )
637
    gas_pipelines_list["p_nom"] = gas_pipelines_list[
638
        "max_transport_capacity_Gwh/d"
639
    ] * (1000 / 24)
640
641
    # Remove useless columns
642
    gas_pipelines_list = gas_pipelines_list.drop(
643
        columns=[
644
            "id",
645
            "node_id",
646
            "param",
647
            "NUTS1",
648
            "NUTS1_0",
649
            "NUTS1_1",
650
            "country_code",
651
            "diameter",
652
            "pipe_class",
653
            "classification",
654
            "max_transport_capacity_Gwh/d",
655
            "lat",
656
            "long",
657
            "length_km",
658
        ]
659
    )
660
661
    return gas_pipelines_list
662
663
664
def insert_gas_pipeline_list(gas_pipelines_list, scn_name="eGon2035"):
665
    """Insert list of gas pipelines in the database
666
667
    Insert detailled description
668
669
    Parameters
670
    ----------
671
    gas_pipelines_list : pandas.DataFrame
672
        Dataframe containing the gas pipelines in Germany
673
    scn_name : str
674
        Name of the scenario
675
676
    """
677
    main_gas_carrier = get_sector_parameters("gas", scenario=scn_name)[
678
        "main_gas_carrier"
679
    ]
680
    engine = db.engine()
681
    gas_pipelines_list = gas_pipelines_list.drop(
682
        columns=[
683
            "country_0",
684
            "country_1",
685
        ]
686
    )
687
688
    # Clean db
689
    db.execute_sql(
690
        f"""DELETE FROM grid.egon_etrago_link
691
        WHERE "carrier" = '{main_gas_carrier}'
692
        AND scn_name = '{scn_name}';
693
        """
694
    )
695
696
    print(gas_pipelines_list)
697
    # Insert data to db
698
    gas_pipelines_list.to_postgis(
699
        "egon_etrago_gas_link",
700
        engine,
701
        schema="grid",
702
        index=False,
703
        if_exists="replace",
704
        dtype={"geom": Geometry(), "topo": Geometry()},
705
    )
706
707
    db.execute_sql(
708
        """
709
    select UpdateGeometrySRID('grid', 'egon_etrago_gas_link', 'topo', 4326) ;
710
711
    INSERT INTO grid.egon_etrago_link (scn_name,
712
                                              link_id, carrier,
713
                                              bus0, bus1,
714
                                              p_nom, p_nom_extendable, length,
715
                                              geom, topo)
716
    SELECT scn_name,
717
                link_id, carrier,
718
                bus0, bus1,
719
                p_nom, p_nom_extendable, length,
720
                geom, topo
721
722
    FROM grid.egon_etrago_gas_link;
723
724
    DROP TABLE grid.egon_etrago_gas_link;
725
        """
726
    )
727
728
729
def remove_isolated_gas_buses():
730
    """Delete gas buses which are not connected to the gas grid.
731
    Returns
732
    -------
733
    None.
734
    """
735
    targets = config.datasets()["gas_grid"]["targets"]
736
737
    db.execute_sql(
738
        f"""
739
        DELETE FROM {targets['buses']['schema']}.{targets['buses']['table']}
740
        WHERE "carrier" = 'CH4'
741
        AND scn_name = 'eGon2035'
742
        AND country = 'DE'
743
        AND "bus_id" NOT IN
744
            (SELECT bus0 FROM {targets['links']['schema']}.{targets['links']['table']}
745
            WHERE scn_name = 'eGon2035'
746
            AND carrier = 'CH4')
747
        AND "bus_id" NOT IN
748
            (SELECT bus1 FROM {targets['links']['schema']}.{targets['links']['table']}
749
            WHERE scn_name = 'eGon2035'
750
            AND carrier = 'CH4');
751
    """
752
    )
753
754
755
def insert_gas_data():
756
    """Overall function for importing gas data from SciGRID_gas
757
    Returns
758
    -------
759
    None.
760
    """
761
    download_SciGRID_gas_data()
762
763
    gas_nodes_list = define_gas_nodes_list()
764
765
    insert_CH4_nodes_list(gas_nodes_list)
766
    abroad_gas_nodes_list = insert_gas_buses_abroad()
767
768
    gas_pipeline_list = define_gas_pipeline_list(
769
        gas_nodes_list, abroad_gas_nodes_list
770
    )
771
    insert_gas_pipeline_list(gas_pipeline_list)
772
    remove_isolated_gas_buses()
773
774
775
def insert_gas_data_eGon100RE():
776
    """Overall function for importing gas data from SciGRID_gas
777
    Returns
778
    -------
779
    None.
780
    """
781
    # copy buses
782
    copy_and_modify_buses("eGon2035", "eGon100RE", {"carrier": ["CH4"]})
783
784
    # get CH4 pipelines and modify their nominal capacity with the
785
    # retrofitting factor
786
    gdf = db.select_geodataframe(
787
        f"""
788
        SELECT * FROM grid.egon_etrago_link
789
        WHERE carrier = 'CH4' AND scn_name = 'eGon2035' AND
790
        bus0 IN (
791
            SELECT bus_id FROM grid.egon_etrago_bus
792
            WHERE scn_name = 'eGon2035' AND country = 'DE'
793
        ) AND bus1 IN (
794
            SELECT bus_id FROM grid.egon_etrago_bus
795
            WHERE scn_name = 'eGon2035' AND country = 'DE'
796
        );
797
        """,
798
        epsg=4326,
799
        geom_col="topo",
800
    )
801
802
    # Update scenario specific information
803
    scn_name = "eGon100RE"
804
    gdf["scn_name"] = scn_name
805
    scn_params = get_sector_parameters("gas", scn_name)
806
807
    for param in ["capital_cost", "marginal_cost", "efficiency"]:
808
        try:
809
            gdf.loc[:, param] = scn_params[param]["CH4"]
810
        except KeyError:
811
            pass
812
813
    # remaining CH4 share is 1 - retroffited pipeline share
814
    gdf["p_nom"] *= (
815
        1 - scn_params["retrofitted_CH4pipeline-to-H2pipeline_share"]
816
    )
817
818
    # delete old entries
819
    db.execute_sql(
820
        f"""
821
        DELETE FROM grid.egon_etrago_link
822
        WHERE carrier = 'CH4' AND scn_name = '{scn_name}' AND
823
        bus0 NOT IN (
824
            SELECT bus_id FROM grid.egon_etrago_bus
825
            WHERE scn_name = '{scn_name}' AND country != 'DE'
826
        ) AND bus1 NOT IN (
827
            SELECT bus_id FROM grid.egon_etrago_bus
828
            WHERE scn_name = '{scn_name}' AND country != 'DE'
829
        );
830
        """
831
    )
832
833
    gdf.to_postgis(
834
        "egon_etrago_link",
835
        schema="grid",
836
        if_exists="append",
837
        con=db.engine(),
838
        index=False,
839
        dtype={"geom": Geometry(), "topo": Geometry()},
840
    )
841