Passed
Pull Request — dev (#1068)
by
unknown
01:29
created

data.datasets.gas_grid.insert_gas_data_eGon100RE()   A

Complexity

Conditions 3

Size

Total Lines 65
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 65
rs 9.28
c 0
b 0
f 0
cc 3
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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