Passed
Pull Request — dev (#1020)
by
unknown
02:51 queued 01:17
created

data.datasets.loadarea.loadareas_add_demand()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
"""
2
OSM landuse extraction and load areas creation.
3
4
**Landuse**
5
6
* Landuse data is extracted from OpenStreetMap: residential, retail,
7
  industrial, Agricultural
8
* Data is cut with German borders (VG 250), data outside is dropped
9
* Invalid geometries are fixed
10
* Results are stored in table `openstreetmap.osm_landuse`
11
12
**Load Areas**
13
14
TBD
15
"""
16
17
import os
18
19
from airflow.operators.postgres_operator import PostgresOperator
20
from geoalchemy2.types import Geometry
21
from sqlalchemy import Column, Float, Integer, String
22
from sqlalchemy.dialects.postgresql import HSTORE
23
from sqlalchemy.ext.declarative import declarative_base
24
import importlib_resources as resources
25
26
from egon.data import db
27
from egon.data.datasets import Dataset
28
import egon.data.config
29
30
# will be later imported from another file ###
31
Base = declarative_base()
32
33
34
class OsmPolygonUrban(Base):
35
    __tablename__ = "osm_landuse"
36
    __table_args__ = {"schema": "openstreetmap"}
37
    id = Column(Integer, primary_key=True)
38
    osm_id = Column(Integer)
39
    name = Column(String)
40
    sector = Column(Integer)
41
    sector_name = Column(String(20))
42
    area_ha = Column(Float)
43
    tags = Column(HSTORE)
44
    vg250 = Column(String(10))
45
    geom = Column(Geometry("MultiPolygon", 3035))
46
47
48
class OsmLanduse(Dataset):
49
    def __init__(self, dependencies):
50
        super().__init__(
51
            name="OsmLanduse",
52
            version="0.0.0",
53
            dependencies=dependencies,
54
            tasks=(
55
                create_landuse_table,
56
                PostgresOperator(
57
                    task_id="osm_landuse_extraction",
58
                    sql=resources.read_text(
59
                        __name__, "osm_landuse_extraction.sql"
60
                    ),
61
                    postgres_conn_id="egon_data",
62
                    autocommit=True,
63
                ),
64
            ),
65
        )
66
67
68
class LoadArea(Dataset):
69
    def __init__(self, dependencies):
70
        super().__init__(
71
            name="LoadArea",
72
            version="0.0.1",
73
            dependencies=dependencies,
74
            tasks=(
75
                osm_landuse_melt,
76
                census_cells_melt,
77
                osm_landuse_census_cells_melt,
78
                loadareas_create,
79
                loadareas_add_demand,
80
                drop_temp_tables,
81
            ),
82
        )
83
84
85
def create_landuse_table():
86
    """Create tables for landuse data
87
    Returns
88
    -------
89
    None.
90
    """
91
    cfg = egon.data.config.datasets()["landuse"]["target"]
92
93
    # Create schema if not exists
94
    db.execute_sql(f"""CREATE SCHEMA IF NOT EXISTS {cfg['schema']};""")
95
96
    # Drop tables
97
    db.execute_sql(
98
        f"""DROP TABLE IF EXISTS
99
            {cfg['schema']}.{cfg['table']} CASCADE;"""
100
    )
101
102
    engine = db.engine()
103
    OsmPolygonUrban.__table__.create(bind=engine, checkfirst=True)
104
105
106
def execute_sql_script(script):
107
    """Execute SQL script
108
109
    Parameters
110
    ----------
111
    script : str
112
        Filename of script
113
    """
114
    db.execute_sql_script(os.path.join(os.path.dirname(__file__), script))
115
116
117
def osm_landuse_melt():
118
    """Melt all OSM landuse areas by: buffer, union, unbuffer"""
119
    print("Melting OSM landuse areas from openstreetmap.osm_landuse...")
120
    execute_sql_script("osm_landuse_melt.sql")
121
122
123
def census_cells_melt():
124
    """Melt all census cells: buffer, union, unbuffer"""
125
    print(
126
        "Melting census cells from "
127
        "society.destatis_zensus_population_per_ha_inside_germany..."
128
    )
129
    execute_sql_script("census_cells_melt.sql")
130
131
132
def osm_landuse_census_cells_melt():
133
    """Melt OSM landuse areas and census cells"""
134
    print(
135
        "Melting OSM landuse areas from openstreetmap.osm_landuse_melted and "
136
        "census cells from "
137
        "society.egon_destatis_zensus_cells_melted_cluster..."
138
    )
139
    execute_sql_script("osm_landuse_census_cells_melt.sql")
140
141
142
def loadareas_create():
143
    """Create load areas from merged OSM landuse and census cells:
144
145
    * Cut Loadarea with MV Griddistrict
146
    * Identify and exclude Loadarea smaller than 100m².
147
    * Generate Centre of Loadareas with Centroid and PointOnSurface.
148
    * Calculate population from Census 2011.
149
    * Cut all 4 OSM sectors with MV Griddistricts.
150
    * Calculate statistics like NUTS and AGS code.
151
    * Check for Loadareas without AGS code.
152
    """
153
    print("Create initial load areas and add some sector stats...")
154
    execute_sql_script("loadareas_create.sql")
155
156
157
def loadareas_add_demand():
158
    """Adds consumption and peak load per sector to load areas"""
159
    print("Add consumption and peak loads to load areas...")
160
    execute_sql_script("loadareas_add_demand.sql")
161
162
163
def drop_temp_tables():
164
    print("Dropping temp tables, views and sequences...")
165
    execute_sql_script("drop_temp_tables.sql")
166