Passed
Push — dev ( 2ebbae...7e4575 )
by Stephan
01:43
created

re_potential_areas.insert_data()   A

Complexity

Conditions 2

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 20
nop 0
dl 0
loc 29
rs 9.4
c 0
b 0
f 0
1
"""The central module containing all code dealing with importing data on
2
potential areas for wind onshore and ground-mounted PV.
3
"""
4
5
import os
6
from urllib.request import urlretrieve
7
import geopandas as gpd
8
from sqlalchemy.ext.declarative import declarative_base
9
from sqlalchemy import Column, Integer
10
from geoalchemy2 import Geometry
11
12
import egon.data.config
13
from egon.data import db
14
15
Base = declarative_base()
16
17
18
class EgonRePotentialAreaPvAgriculture(Base):
19
    __tablename__ = 'egon_re_potential_area_pv_agriculture'
20
    __table_args__ = {'schema': 'supply'}
21
    id = Column(Integer, primary_key=True)
22
    geom = Column(Geometry('MULTIPOLYGON', 3035))
23
24
25
class EgonRePotentialAreaPvRoadRailway(Base):
26
    __tablename__ = 'egon_re_potential_area_pv_road_railway'
27
    __table_args__ = {'schema': 'supply'}
28
    id = Column(Integer, primary_key=True)
29
    geom = Column(Geometry('MULTIPOLYGON', 3035))
30
31
32
class EgonRePotentialAreaWind(Base):
33
    __tablename__ = 'egon_re_potential_area_wind'
34
    __table_args__ = {'schema': 'supply'}
35
    id = Column(Integer, primary_key=True)
36
    geom = Column(Geometry('MULTIPOLYGON', 3035))
37
38
39
def download_datasets():
40
    """Download geopackages from Zenodo."""
41
42
    data_config = egon.data.config.datasets()
43
    pa_config = data_config['re_potential_areas']
44
45
    def ve(s):
46
        raise (ValueError(s))
47
48
    dataset = egon.data.config.settings()['egon-data']['--dataset-boundary']
49
    url_section = (
50
        'url'
51
        if dataset == 'Everything'
52
        else 'url_testmode'
53
        if dataset == 'Schleswig-Holstein'
54
        else ve(f"'{dataset}' is not a valid dataset boundary.")
55
    )
56
57
    url_target_file_map = zip(
58
        pa_config['original_data']['source'][url_section],
59
        [os.path.join(os.path.dirname(__file__), file)
60
         for file in pa_config['original_data']['target'][
61
             'path_table_map'].keys()]
62
    )
63
64
    for url, file in url_target_file_map:
65
        if not os.path.isfile(file):
66
            urlretrieve(url, file)
67
68
69
def create_tables():
70
    """Create tables for RE potential areas"""
71
72
    data_config = egon.data.config.datasets()
73
74
    schema = data_config['re_potential_areas']['original_data'][
75
        'target'].get('schema', 'supply')
76
77
    db.execute_sql(f'CREATE SCHEMA IF NOT EXISTS {schema};')
78
    engine = db.engine()
79
80
    # drop tables
81
    EgonRePotentialAreaPvAgriculture.__table__.drop(engine, checkfirst=True)
82
    EgonRePotentialAreaPvRoadRailway.__table__.drop(engine, checkfirst=True)
83
    EgonRePotentialAreaWind.__table__.drop(engine, checkfirst=True)
84
85
    # create tables
86
    EgonRePotentialAreaPvAgriculture.__table__.create(bind=engine,
87
                                                      checkfirst=True)
88
    EgonRePotentialAreaPvRoadRailway.__table__.create(bind=engine,
89
                                                      checkfirst=True)
90
    EgonRePotentialAreaWind.__table__.create(bind=engine,
91
                                             checkfirst=True)
92
93
94
def insert_data():
95
    """Insert data into DB"""
96
97
    data_config = egon.data.config.datasets()
98
    pa_config = data_config['re_potential_areas']
99
100
    file_table_map = {
101
        os.path.join(os.path.dirname(__file__), file): table
102
        for file, table in pa_config['original_data']['target'][
103
            'path_table_map'].items()
104
    }
105
106
    engine_local_db = db.engine()
107
108
    for file, table in file_table_map.items():
109
        data = gpd.read_file(file).to_crs("EPSG:3035")
110
        data.rename(columns={'geometry': 'geom'}, inplace=True)
111
        data.set_geometry('geom', inplace=True)
112
113
        schema = pa_config['original_data']['target'].get('schema', 'supply')
114
115
        # create database table from geopandas dataframe
116
        data.to_postgis(
117
            table,
118
            engine_local_db,
119
            schema=schema,
120
            index=False,
121
            if_exists="append",
122
            dtype={"geom": Geometry()},
123
        )
124