Passed
Pull Request — dev (#934)
by
unknown
01:39
created

data.datasets.electricity_demand_timeseries.mapping   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 1
eloc 20
dl 0
loc 31
rs 10
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A map_all_used_buildings() 0 10 1
1
from sqlalchemy import Column, Integer, String
2
from sqlalchemy.ext.declarative import declarative_base
3
from sqlalchemy.types import Boolean
4
5
from egon.data import db
6
7
Base = declarative_base()
8
9
10
class EgonMapZensusMvgdBuildings(Base):
11
    __tablename__ = "egon_map_zensus_mvgd_buildings"
12
    __table_args__ = {"schema": "boundaries"}
13
14
    building_id = Column(Integer, primary_key=True)
15
    sector = Column(String, primary_key=True)
16
    zensus_population_id = Column(Integer, index=True)
17
    bus_id = Column(Integer, index=True)
18
    osm = Column(Boolean, index=True)
19
20
21
def map_all_used_buildings():
22
    """This function maps all used buildings from OSM and synthetic ones."""
23
24
    EgonMapZensusMvgdBuildings.__table__.drop(
25
        bind=db.engine(), checkfirst=True
26
    )
27
    EgonMapZensusMvgdBuildings.__table__.create(bind=db.engine())
28
29
    db.execute_sql(
30
        sql_string=f"""
31
        INSERT INTO {EgonMapZensusMvgdBuildings.__table_args__["schema"]}.
32
        {EgonMapZensusMvgdBuildings.__tablename__}
33
            SELECT
34
                bld.id as building_id,
35
                peak.sector,
36
                zensus.id as zensus_population_id,
37
                mvgd.bus_id::integer
38
            FROM (
39
                SELECT "id"::integer, geom_point
40
                FROM openstreetmap.osm_buildings_synthetic
41
                UNION
42
                SELECT "id"::integer, geom_point
43
                FROM openstreetmap.osm_buildings_filtered
44
            ) AS bld,
45
                demand.egon_building_electricity_peak_loads AS peak,
46
                society.destatis_zensus_population_per_ha
47
                AS zensus,
48
                boundaries.egon_map_zensus_grid_districts AS mvgd
49
            WHERE bld.id = peak.building_id
50
                AND peak.scenario = 'eGon2035'
51
                AND ST_Within(bld.geom_point, zensus.geom)
52
                AND mvgd.zensus_population_id = zensus.id;
53
54
            UPDATE boundaries.egon_map_zensus_mvgd_buildings
55
            SET     "osm" = TRUE;
56
57
            UPDATE boundaries.egon_map_zensus_mvgd_buildings as bld
58
            SET     "osm" = FALSE
59
            FROM (
60
                SELECT "id"::integer
61
                FROM openstreetmap.osm_buildings_synthetic
62
                ) as synth
63
            WHERE bld.building_id = synth.id;
64
        """
65
    )
66