Passed
Pull Request — dev (#917)
by
unknown
01:36
created

data.datasets.gas_neighbours.gas_abroad   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 182
Duplicated Lines 30.77 %

Importance

Changes 0
Metric Value
wmc 7
eloc 56
dl 56
loc 182
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A get_foreign_gas_bus_id() 56 56 3
A insert_gas_grid_capacities() 0 107 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
"""Module containing functions to insert gas abroad
2
3
In this module, functions useful to insert the gas components (H2 and
4
CH4) abroad for eGon2035 and eGon100RE are defined.
5
6
"""
7
8
import zipfile
9
10
from geoalchemy2.types import Geometry
11
import geopandas as gpd
12
import pandas as pd
13
14
from egon.data import config, db
15
16
17 View Code Duplication
def get_foreign_gas_bus_id(carrier="CH4", scn_name="eGon2035"):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
18
    """Calculate the etrago bus id based on the geometry
19
20
    Mapp node_ids from TYNDP and etragos bus_id
21
22
    Parameters
23
    ----------
24
    carrier : str
25
        Name of the carrier
26
    scn_name : str
27
        Name of the scenario
28
29
    Returns
30
    -------
31
    pandas.Series
32
        List of mapped node_ids from TYNDP and etragos bus_id
33
34
    """
35
    sources = config.datasets()["gas_neighbours"]["sources"]
36
37
    bus_id = db.select_geodataframe(
38
        f"""
39
        SELECT bus_id, ST_Buffer(geom, 1) as geom, country
40
        FROM grid.egon_etrago_bus
41
        WHERE scn_name = '{scn_name}'
42
        AND carrier = '{carrier}'
43
        AND country != 'DE'
44
        """,
45
        epsg=3035,
46
    )
47
48
    if scn_name is "eGon2035":
49
        # insert installed capacities
50
        file = zipfile.ZipFile(f"tyndp/{sources['tyndp_capacities']}")
51
52
        # Select buses in neighbouring countries as geodataframe
53
        buses = pd.read_excel(
54
            file.open("TYNDP-2020-Scenario-Datafile.xlsx").read(),
55
            sheet_name="Nodes - Dict",
56
        ).query("longitude==longitude")
57
        buses = gpd.GeoDataFrame(
58
            buses,
59
            crs=4326,
60
            geometry=gpd.points_from_xy(buses.longitude, buses.latitude),
61
        ).to_crs(3035)
62
63
        buses["bus_id"] = 0
64
65
        # Select bus_id from etrago with shortest distance to TYNDP node
66
        for i, row in buses.iterrows():
67
            distance = bus_id.set_index("bus_id").geom.distance(row.geometry)
68
            buses.loc[i, "bus_id"] = distance[
69
                distance == distance.min()
70
            ].index.values[0]
71
72
        return buses.set_index("node_id").bus_id
73
74
75
def insert_gas_grid_capacities(Neighbouring_pipe_capacities_list, scn_name):
76
    """Insert crossbordering gas pipelines in the database
77
78
    This function insert a list of crossbordering gas pipelines after
79
    cleaning the database.
80
    For eGon2035, all the CH4 crossbordering pipelines are inserted
81
    there (no H2 grid in this scenario).
82
    For eGon100RE, only the the crossbordering pipelines with Germany
83
    are inserted there (the other ones are inerted in PypsaEurSec),
84
    but in this scenario there are H2 and CH4 pipelines.
85
86
    Parameters
87
    ----------
88
    Neighbouring_pipe_capacities_list : pandas.DataFrame
89
        List of the crossbordering gas pipelines
90
    scn_name : str
91
        Name of the scenario
92
93
    Returns
94
    -------
95
    None
96
97
    """
98
    sources = config.datasets()["gas_neighbours"]["sources"]
99
    targets = config.datasets()["gas_neighbours"]["targets"]
100
101
    # Delete existing data
102
    if scn_name == "eGon2035":
103
        carrier_link = "CH4"
104
        carrier_bus = "CH4"
105
106
        db.execute_sql(
107
            f"""
108
            DELETE FROM 
109
            {sources['links']['schema']}.{sources['links']['table']}
110
            WHERE "bus0" IN (
111
                SELECT bus_id FROM 
112
                {sources['buses']['schema']}.{sources['buses']['table']}
113
                    WHERE country != 'DE'
114
                    AND carrier = '{carrier_bus}'
115
                    AND scn_name = '{scn_name}')
116
            OR "bus1" IN (
117
                SELECT bus_id FROM 
118
                {sources['buses']['schema']}.{sources['buses']['table']}
119
                    WHERE country != 'DE'
120
                    AND carrier = '{carrier_bus}' 
121
                    AND scn_name = '{scn_name}')
122
            AND scn_name = '{scn_name}'
123
            AND carrier = '{carrier_link}'            
124
            ;
125
            """
126
        )
127
128
    carriers = {
129
        "CH4": {"bus_inDE": "CH4", "bus_abroad": "CH4"},
130
        "H2_retrofit": {"bus_inDE": "H2_grid", "bus_abroad": "H2"},
131
    }
132
133
    if scn_name == "eGon100RE":
134
        for c in carriers:
135
            db.execute_sql(
136
                f"""
137
                DELETE FROM
138
                {sources['links']['schema']}.{sources['links']['table']}
139
                WHERE ("bus0" IN (
140
                        SELECT bus_id FROM 
141
                        {sources['buses']['schema']}.{sources['buses']['table']}
142
                        WHERE country != 'DE'
143
                        AND carrier = '{carriers[c]["bus_abroad"]}'
144
                        AND scn_name = '{scn_name}')
145
                    AND "bus1" IN (SELECT bus_id FROM 
146
                        {sources['buses']['schema']}.{sources['buses']['table']}
147
                        WHERE country = 'DE'
148
                        AND carrier = '{carriers[c]["bus_inDE"]}' 
149
                        AND scn_name = '{scn_name}'))
150
                OR ("bus0" IN (
151
                        SELECT bus_id FROM 
152
                        {sources['buses']['schema']}.{sources['buses']['table']}
153
                        WHERE country = 'DE'
154
                        AND carrier = '{carriers[c]["bus_inDE"]}'
155
                        AND scn_name = '{scn_name}')
156
                AND "bus1" IN (
157
                        SELECT bus_id FROM 
158
                        {sources['buses']['schema']}.{sources['buses']['table']}
159
                        WHERE country != 'DE'
160
                        AND carrier = '{carriers[c]["bus_abroad"]}' 
161
                        AND scn_name = '{scn_name}'))
162
                AND scn_name = '{scn_name}'
163
                AND carrier = '{c.index}'            
164
                ;
165
                """
166
            )
167
168
    # Insert data to db
169
    Neighbouring_pipe_capacities_list.set_geometry(
170
        "geom", crs=4326
171
    ).to_postgis(
172
        "egon_etrago_gas_link",
173
        db.engine(),
174
        schema="grid",
175
        index=False,
176
        if_exists="replace",
177
        dtype={"geom": Geometry(), "topo": Geometry()},
178
    )
179
180
    db.execute_sql(
181
        f"""
182
    select UpdateGeometrySRID('grid', 'egon_etrago_gas_link', 'topo', 4326) ;
183
184
    INSERT INTO {targets['links']['schema']}.{targets['links']['table']} (
185
        scn_name, link_id, carrier,
186
        bus0, bus1, p_nom, length, geom, topo)
187
    
188
    SELECT scn_name, link_id, carrier, bus0, bus1, p_nom, length, geom, topo
189
190
    FROM grid.egon_etrago_gas_link;
191
192
    DROP TABLE grid.egon_etrago_gas_link;
193
        """
194
    )
195