Passed
Push — dev ( 854d9c...2ebbae )
by Stephan
01:34 queued 11s
created

re_potential_areas   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 124
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 73
dl 0
loc 124
rs 10
c 0
b 0
f 0
wmc 7
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
    dataset = egon.data.config.settings()['egon-data']['--dataset-boundary']
46
    url_section = (
47
        'url'
48
        if dataset == 'Everything'
49
        else 'url_testmode'
50
        if dataset == 'Schleswig-Holstein'
51
        else raise ValueError(f"'{dataset}' is not a valid dataset boundary.")
52
    )
53
54
    url_target_file_map = zip(
55
        pa_config['original_data']['source'][url_section],
56
        [os.path.join(os.path.dirname(__file__), file)
57
         for file in pa_config['original_data']['target'][
58
             'path_table_map'].keys()]
59
    )
60
61
    for url, file in url_target_file_map:
62
        if not os.path.isfile(file):
63
            urlretrieve(url, file)
64
65
66
def create_tables():
67
    """Create tables for RE potential areas"""
68
69
    data_config = egon.data.config.datasets()
70
71
    schema = data_config['re_potential_areas']['original_data'][
72
        'target'].get('schema', 'supply')
73
74
    db.execute_sql(f'CREATE SCHEMA IF NOT EXISTS {schema};')
75
    engine = db.engine()
76
77
    # drop tables
78
    EgonRePotentialAreaPvAgriculture.__table__.drop(engine, checkfirst=True)
79
    EgonRePotentialAreaPvRoadRailway.__table__.drop(engine, checkfirst=True)
80
    EgonRePotentialAreaWind.__table__.drop(engine, checkfirst=True)
81
82
    # create tables
83
    EgonRePotentialAreaPvAgriculture.__table__.create(bind=engine,
84
                                                      checkfirst=True)
85
    EgonRePotentialAreaPvRoadRailway.__table__.create(bind=engine,
86
                                                      checkfirst=True)
87
    EgonRePotentialAreaWind.__table__.create(bind=engine,
88
                                             checkfirst=True)
89
90
91
def insert_data():
92
    """Insert data into DB"""
93
94
    data_config = egon.data.config.datasets()
95
    pa_config = data_config['re_potential_areas']
96
97
    file_table_map = {
98
        os.path.join(os.path.dirname(__file__), file): table
99
        for file, table in pa_config['original_data']['target'][
100
            'path_table_map'].items()
101
    }
102
103
    engine_local_db = db.engine()
104
105
    for file, table in file_table_map.items():
106
        data = gpd.read_file(file).to_crs("EPSG:3035")
107
        data.rename(columns={'geometry': 'geom'}, inplace=True)
108
        data.set_geometry('geom', inplace=True)
109
110
        schema = pa_config['original_data']['target'].get('schema', 'supply')
111
112
        # create database table from geopandas dataframe
113
        data.to_postgis(
114
            table,
115
            engine_local_db,
116
            schema=schema,
117
            index=False,
118
            if_exists="append",
119
            dtype={"geom": Geometry()},
120
        )
121