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

data.datasets.gas_grid.remove_isolated_gas_buses()   A

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 10
rs 10
c 0
b 0
f 0
cc 1
nop 0
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.9",
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
    # Remove links disconnected of the rest of the grid
421
    # Remove manually for disconnected link EntsoG_Map__ST_195 and EntsoG_Map__ST_108
422
    gas_pipelines_list = gas_pipelines_list[
423
        gas_pipelines_list["node_id"] != "['SEQ_11790_p', 'Stor_EU_107']"
424
    ]
425
    gas_pipelines_list = gas_pipelines_list[
426
        ~gas_pipelines_list["id"].str.match("EntsoG_Map__ST_108")
427
    ]
428
429
    # Manually add pipeline to artificially connect isolated pipeline
430
    gas_pipelines_list.at["new_pipe", "param"] = gas_pipelines_list[
431
        gas_pipelines_list["id"] == "NO_PS_8_Seg_0_Seg_23"
432
    ]["param"].values[0]
433
    gas_pipelines_list.at[
434
        "new_pipe", "node_id"
435
    ] = "['SEQ_12442_p', 'LKD_N_200']"
436
    gas_pipelines_list.at["new_pipe", "lat"] = "[53.358536, 53.412719]"
437
    gas_pipelines_list.at["new_pipe", "long"] = "[7.041677, 7.093251]"
438
    gas_pipelines_list.at["new_pipe", "country_code"] = "['DE', 'DE']"
439
440
    gas_pipelines_list["link_id"] = range(
441
        new_id, new_id + len(gas_pipelines_list)
442
    )
443
    gas_pipelines_list["link_id"] = gas_pipelines_list["link_id"].astype(int)
444
445
    # Cut data to federal state if in testmode
446
    NUTS1 = []
447
    for index, row in gas_pipelines_list.iterrows():
448
        param = ast.literal_eval(row["param"])
449
        NUTS1.append(param["nuts_id_1"])
450
    gas_pipelines_list["NUTS1"] = NUTS1
451
452
    map_states = {
453
        "Baden-Württemberg": "DE1",
454
        "Nordrhein-Westfalen": "DEA",
455
        "Hessen": "DE7",
456
        "Brandenburg": "DE4",
457
        "Bremen": "DE5",
458
        "Rheinland-Pfalz": "DEB",
459
        "Sachsen-Anhalt": "DEE",
460
        "Schleswig-Holstein": "DEF",
461
        "Mecklenburg-Vorpommern": "DE8",
462
        "Thüringen": "DEG",
463
        "Niedersachsen": "DE9",
464
        "Sachsen": "DED",
465
        "Hamburg": "DE6",
466
        "Saarland": "DEC",
467
        "Berlin": "DE3",
468
        "Bayern": "DE2",
469
        "Everything": "Nan",
470
    }
471
    gas_pipelines_list["NUTS1_0"] = [x[0] for x in gas_pipelines_list["NUTS1"]]
472
    gas_pipelines_list["NUTS1_1"] = [x[1] for x in gas_pipelines_list["NUTS1"]]
473
474
    boundary = settings()["egon-data"]["--dataset-boundary"]
475
476
    if boundary != "Everything":
477
478
        gas_pipelines_list = gas_pipelines_list[
479
            gas_pipelines_list["NUTS1_0"].str.contains(map_states[boundary])
480
            | gas_pipelines_list["NUTS1_1"].str.contains(map_states[boundary])
481
        ]
482
483
    # Add missing columns
484
    gas_pipelines_list["scn_name"] = scn_name
485
    gas_pipelines_list["carrier"] = main_gas_carrier
486
    gas_pipelines_list["p_nom_extendable"] = False
487
488
    diameter = []
489
    geom = []
490
    topo = []
491
    length_km = []
492
493
    for index, row in gas_pipelines_list.iterrows():
494
495
        param = ast.literal_eval(row["param"])
496
        diameter.append(param["diameter_mm"])
497
        length_km.append(param["length_km"])
498
499
        long_e = json.loads(row["long"])
500
        lat_e = json.loads(row["lat"])
501
        crd_e = list(zip(long_e, lat_e))
502
        topo.append(geometry.LineString(crd_e))
503
504
        long_path = param["path_long"]
505
        lat_path = param["path_lat"]
506
        crd = list(zip(long_path, lat_path))
507
        crd.insert(0, crd_e[0])
508
        crd.append(crd_e[1])
509
        lines = []
510
        for i in range(len(crd) - 1):
511
            lines.append(geometry.LineString([crd[i], crd[i + 1]]))
512
        geom.append(geometry.MultiLineString(lines))
513
514
    gas_pipelines_list["diameter"] = diameter
515
    gas_pipelines_list["geom"] = geom
516
    gas_pipelines_list["topo"] = topo
517
    gas_pipelines_list["length_km"] = length_km
518
    gas_pipelines_list = gas_pipelines_list.set_geometry("geom", crs=4326)
519
520
    country_0 = []
521
    country_1 = []
522
    for index, row in gas_pipelines_list.iterrows():
523
        c = ast.literal_eval(row["country_code"])
524
        country_0.append(c[0])
525
        country_1.append(c[1])
526
527
    gas_pipelines_list["country_0"] = country_0
528
    gas_pipelines_list["country_1"] = country_1
529
530
    # Correct non valid neighbouring country nodes
531
    gas_pipelines_list.loc[
532
        gas_pipelines_list["country_0"] == "XX", "country_0"
533
    ] = "NO"
534
    gas_pipelines_list.loc[
535
        gas_pipelines_list["country_1"] == "FI", "country_1"
536
    ] = "RU"
537
    gas_pipelines_list.loc[
538
        gas_pipelines_list["id"] == "ST_2612_Seg_0_Seg_0", "country_0"
539
    ] = "AT"  # bus "INET_N_1182" DE -> AT
540
    gas_pipelines_list.loc[
541
        gas_pipelines_list["id"] == "INET_PL_385_EE_3_Seg_0_Seg_1", "country_1"
542
    ] = "AT"  # "INET_N_1182" DE -> AT
543
    gas_pipelines_list.loc[
544
        gas_pipelines_list["id"] == "LKD_PS_0_Seg_0_Seg_3", "country_0"
545
    ] = "NL"  # bus "SEQ_10608_p" DE -> NL
546
547
    # Remove uncorrect pipelines
548
    gas_pipelines_list = gas_pipelines_list[
549
        (gas_pipelines_list["id"] != "PLNG_2637_Seg_0_Seg_0_Seg_0")
550
        & (gas_pipelines_list["id"] != "NSG_6650_Seg_2_Seg_0")
551
        & (gas_pipelines_list["id"] != "NSG_6734_Seg_2_Seg_0")
552
    ]
553
554
    # Remove link test if length = 0
555
    gas_pipelines_list = gas_pipelines_list[
556
        gas_pipelines_list["length_km"] != 0
557
    ]
558
559
    # Adjust columns
560
    bus0 = []
561
    bus1 = []
562
    geom_adjusted = []
563
    topo_adjusted = []
564
    length_adjusted = []
565
    pipe_class = []
566
567
    for index, row in gas_pipelines_list.iterrows():
568
        buses = row["node_id"].strip("][").split(", ")
569
570
        if (
571
            (boundary != "Everything")
572
            & (row["NUTS1_0"] != map_states[boundary])
573
            & (row["country_0"] == "DE")
574
        ):
575
            bus0.append(abroad_gas_nodes_list.loc["DE", "bus_id"])
576
            bus1.append(gas_nodes_list.loc[buses[1][1:-1], "bus_id"])
577
            long_e = [
578
                abroad_gas_nodes_list.loc["DE", "x"],
579
                json.loads(row["long"])[1],
580
            ]
581
            lat_e = [
582
                abroad_gas_nodes_list.loc["DE", "y"],
583
                json.loads(row["lat"])[1],
584
            ]
585
            geom_pipe = geometry.MultiLineString(
586
                [geometry.LineString(list(zip(long_e, lat_e)))]
587
            )
588
            topo_adjusted.append(geometry.LineString(list(zip(long_e, lat_e))))
589
590
        elif row["country_0"] != "DE":
591
            country = str(row["country_0"])
592
            bus0.append(abroad_gas_nodes_list.loc[country, "bus_id"])
593
            bus1.append(gas_nodes_list.loc[buses[1][1:-1], "bus_id"])
594
            long_e = [
595
                abroad_gas_nodes_list.loc[country, "x"],
596
                json.loads(row["long"])[1],
597
            ]
598
            lat_e = [
599
                abroad_gas_nodes_list.loc[country, "y"],
600
                json.loads(row["lat"])[1],
601
            ]
602
            geom_pipe = geometry.MultiLineString(
603
                [geometry.LineString(list(zip(long_e, lat_e)))]
604
            )
605
            topo_adjusted.append(geometry.LineString(list(zip(long_e, lat_e))))
606
607
        elif (
608
            (boundary != "Everything")
609
            & (row["NUTS1_1"] != map_states[boundary])
610
            & (row["country_1"] == "DE")
611
        ):
612
            bus0.append(gas_nodes_list.loc[buses[0][1:-1], "bus_id"])
613
            bus1.append(abroad_gas_nodes_list.loc["DE", "bus_id"])
614
            long_e = [
615
                json.loads(row["long"])[0],
616
                abroad_gas_nodes_list.loc["DE", "x"],
617
            ]
618
            lat_e = [
619
                json.loads(row["lat"])[0],
620
                abroad_gas_nodes_list.loc["DE", "y"],
621
            ]
622
            geom_pipe = geometry.MultiLineString(
623
                [geometry.LineString(list(zip(long_e, lat_e)))]
624
            )
625
            topo_adjusted.append(geometry.LineString(list(zip(long_e, lat_e))))
626
627
        elif row["country_1"] != "DE":
628
            country = str(row["country_1"])
629
            bus0.append(gas_nodes_list.loc[buses[0][1:-1], "bus_id"])
630
            bus1.append(abroad_gas_nodes_list.loc[country, "bus_id"])
631
            long_e = [
632
                json.loads(row["long"])[0],
633
                abroad_gas_nodes_list.loc[country, "x"],
634
            ]
635
            lat_e = [
636
                json.loads(row["lat"])[0],
637
                abroad_gas_nodes_list.loc[country, "y"],
638
            ]
639
            geom_pipe = geometry.MultiLineString(
640
                [geometry.LineString(list(zip(long_e, lat_e)))]
641
            )
642
            topo_adjusted.append(geometry.LineString(list(zip(long_e, lat_e))))
643
644
        else:
645
            bus0.append(gas_nodes_list.loc[buses[0][1:-1], "bus_id"])
646
            bus1.append(gas_nodes_list.loc[buses[1][1:-1], "bus_id"])
647
            geom_pipe = row["geom"]
648
            topo_adjusted.append(row["topo"])
649
650
        geom_adjusted.append(geom_pipe)
651
        length_adjusted.append(geom_pipe.length)
652
653
        if row["diameter"] >= 1000:
654
            pipe_class = "A"
655
        elif 700 <= row["diameter"] <= 1000:
656
            pipe_class = "B"
657
        elif 500 <= row["diameter"] <= 700:
658
            pipe_class = "C"
659
        elif 350 <= row["diameter"] <= 500:
660
            pipe_class = "D"
661
        elif 200 <= row["diameter"] <= 350:
662
            pipe_class = "E"
663
        elif 100 <= row["diameter"] <= 200:
664
            pipe_class = "F"
665
        elif row["diameter"] <= 100:
666
            pipe_class = "G"
667
668
    gas_pipelines_list["bus0"] = bus0
669
    gas_pipelines_list["bus1"] = bus1
670
    gas_pipelines_list["geom"] = geom_adjusted
671
    gas_pipelines_list["topo"] = topo_adjusted
672
    gas_pipelines_list["length"] = length_adjusted
673
    gas_pipelines_list["pipe_class"] = pipe_class
674
675
    # Remove pipes having the same node for start and end
676
    gas_pipelines_list = gas_pipelines_list[
677
        gas_pipelines_list["bus0"] != gas_pipelines_list["bus1"]
678
    ]
679
680
    gas_pipelines_list = gas_pipelines_list.merge(
681
        classification,
682
        how="left",
683
        left_on="pipe_class",
684
        right_on="classification",
685
    )
686
    gas_pipelines_list["p_nom"] = gas_pipelines_list[
687
        "max_transport_capacity_Gwh/d"
688
    ] * (1000 / 24)
689
690
    # Remove useless columns
691
    gas_pipelines_list = gas_pipelines_list.drop(
692
        columns=[
693
            "id",
694
            "node_id",
695
            "param",
696
            "NUTS1",
697
            "NUTS1_0",
698
            "NUTS1_1",
699
            "country_code",
700
            "diameter",
701
            "pipe_class",
702
            "classification",
703
            "max_transport_capacity_Gwh/d",
704
            "lat",
705
            "long",
706
            "length_km",
707
        ]
708
    )
709
710
    return gas_pipelines_list
711
712
713
def insert_gas_pipeline_list(gas_pipelines_list, scn_name="eGon2035"):
714
    """Insert list of gas pipelines in the database
715
716
    Insert detailled description
717
718
    Parameters
719
    ----------
720
    gas_pipelines_list : pandas.DataFrame
721
        Dataframe containing the gas pipelines in Germany
722
    scn_name : str
723
        Name of the scenario
724
725
    """
726
    main_gas_carrier = get_sector_parameters("gas", scenario=scn_name)[
727
        "main_gas_carrier"
728
    ]
729
    engine = db.engine()
730
    gas_pipelines_list = gas_pipelines_list.drop(
731
        columns=[
732
            "country_0",
733
            "country_1",
734
        ]
735
    )
736
737
    # Clean db
738
    db.execute_sql(
739
        f"""DELETE FROM grid.egon_etrago_link
740
        WHERE "carrier" = '{main_gas_carrier}'
741
        AND scn_name = '{scn_name}';
742
        """
743
    )
744
745
    print(gas_pipelines_list)
746
    # Insert data to db
747
    gas_pipelines_list.to_postgis(
748
        "egon_etrago_gas_link",
749
        engine,
750
        schema="grid",
751
        index=False,
752
        if_exists="replace",
753
        dtype={"geom": Geometry(), "topo": Geometry()},
754
    )
755
756
    db.execute_sql(
757
        """
758
    select UpdateGeometrySRID('grid', 'egon_etrago_gas_link', 'topo', 4326) ;
759
760
    INSERT INTO grid.egon_etrago_link (scn_name,
761
                                              link_id, carrier,
762
                                              bus0, bus1,
763
                                              p_nom, p_nom_extendable, length,
764
                                              geom, topo)
765
    SELECT scn_name,
766
                link_id, carrier,
767
                bus0, bus1,
768
                p_nom, p_nom_extendable, length,
769
                geom, topo
770
771
    FROM grid.egon_etrago_gas_link;
772
773
    DROP TABLE grid.egon_etrago_gas_link;
774
        """
775
    )
776
777
778
def remove_isolated_gas_buses():
779
    """Delete gas buses which are not connected to the gas grid.
780
    Returns
781
    -------
782
    None.
783
    """
784
    targets = config.datasets()["gas_grid"]["targets"]
785
786
    db.execute_sql(
787
        f"""
788
        DELETE FROM {targets['buses']['schema']}.{targets['buses']['table']}
789
        WHERE "carrier" = 'CH4'
790
        AND scn_name = 'eGon2035'
791
        AND country = 'DE'
792
        AND "bus_id" NOT IN
793
            (SELECT bus0 FROM {targets['links']['schema']}.{targets['links']['table']}
794
            WHERE scn_name = 'eGon2035'
795
            AND carrier = 'CH4')
796
        AND "bus_id" NOT IN
797
            (SELECT bus1 FROM {targets['links']['schema']}.{targets['links']['table']}
798
            WHERE scn_name = 'eGon2035'
799
            AND carrier = 'CH4');
800
    """
801
    )
802
803
804
def insert_gas_data():
805
    """Overall function for importing gas data from SciGRID_gas
806
    Returns
807
    -------
808
    None.
809
    """
810
    download_SciGRID_gas_data()
811
812
    gas_nodes_list = define_gas_nodes_list()
813
814
    insert_CH4_nodes_list(gas_nodes_list)
815
    abroad_gas_nodes_list = insert_gas_buses_abroad()
816
817
    gas_pipeline_list = define_gas_pipeline_list(
818
        gas_nodes_list, abroad_gas_nodes_list
819
    )
820
    insert_gas_pipeline_list(gas_pipeline_list)
821
    remove_isolated_gas_buses()
822
823
824
def insert_gas_data_eGon100RE():
825
    """Overall function for importing gas data from SciGRID_gas
826
    Returns
827
    -------
828
    None.
829
    """
830
    # copy buses
831
    copy_and_modify_buses("eGon2035", "eGon100RE", {"carrier": ["CH4"]})
832
833
    # get CH4 pipelines and modify their nominal capacity with the
834
    # retrofitting factor
835
    gdf = db.select_geodataframe(
836
        f"""
837
        SELECT * FROM grid.egon_etrago_link
838
        WHERE carrier = 'CH4' AND scn_name = 'eGon2035' AND
839
        bus0 IN (
840
            SELECT bus_id FROM grid.egon_etrago_bus
841
            WHERE scn_name = 'eGon2035' AND country = 'DE'
842
        ) AND bus1 IN (
843
            SELECT bus_id FROM grid.egon_etrago_bus
844
            WHERE scn_name = 'eGon2035' AND country = 'DE'
845
        );
846
        """,
847
        epsg=4326,
848
        geom_col="topo",
849
    )
850
851
    # Update scenario specific information
852
    scn_name = "eGon100RE"
853
    gdf["scn_name"] = scn_name
854
    scn_params = get_sector_parameters("gas", scn_name)
855
856
    for param in ["capital_cost", "marginal_cost", "efficiency"]:
857
        try:
858
            gdf.loc[:, param] = scn_params[param]["CH4"]
859
        except KeyError:
860
            pass
861
862
    # remaining CH4 share is 1 - retroffited pipeline share
863
    gdf["p_nom"] *= (
864
        1 - scn_params["retrofitted_CH4pipeline-to-H2pipeline_share"]
865
    )
866
867
    # delete old entries
868
    db.execute_sql(
869
        f"""
870
        DELETE FROM grid.egon_etrago_link
871
        WHERE carrier = 'CH4' AND scn_name = '{scn_name}' AND
872
        bus0 NOT IN (
873
            SELECT bus_id FROM grid.egon_etrago_bus
874
            WHERE scn_name = '{scn_name}' AND country != 'DE'
875
        ) AND bus1 NOT IN (
876
            SELECT bus_id FROM grid.egon_etrago_bus
877
            WHERE scn_name = '{scn_name}' AND country != 'DE'
878
        );
879
        """
880
    )
881
882
    gdf.to_postgis(
883
        "egon_etrago_link",
884
        schema="grid",
885
        if_exists="append",
886
        con=db.engine(),
887
        index=False,
888
        dtype={"geom": Geometry(), "topo": Geometry()},
889
    )
890