| Total Complexity | 119 | 
| Total Lines | 2748 | 
| Duplicated Lines | 1.16 % | 
| Changes | 0 | ||
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:
Complex classes like data.datasets.power_plants.pv_rooftop_buildings often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | """  | 
            ||
| 2 | Distribute MaStR PV rooftop capacities to OSM and synthetic buildings. Generate new  | 
            ||
| 3 | PV rooftop generators for scenarios eGon2035 and eGon100RE.  | 
            ||
| 4 | Data cleaning: Drop duplicates and entries with missing critical data. Determine most  | 
            ||
| 5 | plausible capacity from multiple values given in MaStR data. Drop generators which don't  | 
            ||
| 6 | have any plausible capacity data (23.5MW > P > 0.1). Randomly and weighted add a  | 
            ||
| 7 | start-up date if it is missing. Extract zip and municipality from 'Standort' given in  | 
            ||
| 8 | MaStR data. Geocode unique zip and municipality combinations with Nominatim (1sec  | 
            ||
| 9 | delay). Drop generators for which geocoding failed or which are located outside the  | 
            ||
| 10 | municipalities of Germany. Add some visual sanity checks for cleaned data.  | 
            ||
| 11 | Allocation of MaStR data: Allocate each generator to an existing building from OSM.  | 
            ||
| 12 | Determine the quantile each generator and building is in depending on the capacity of  | 
            ||
| 13 | the generator and the area of the polygon of the building. Randomly distribute  | 
            ||
| 14 | generators within each municipality preferably within the same building area quantile as  | 
            ||
| 15 | the generators are capacity wise. If not enough buildings exists within a municipality  | 
            ||
| 16 | and quantile additional buildings from other quantiles are chosen randomly.  | 
            ||
| 17 | Desegregation of pv rooftop scenarios: The scenario data per federal state is linear  | 
            ||
| 18 | distributed to the mv grid districts according to the pv rooftop potential per mv grid  | 
            ||
| 19 | district. The rooftop potential is estimated from the building area given from the OSM  | 
            ||
| 20 | buildings. Grid districts, which are located in several federal states, are allocated PV  | 
            ||
| 21 | capacity according to their respective roof potential in the individual federal states.  | 
            ||
| 22 | The desegregation of PV plants within a grid districts respects existing plants from  | 
            ||
| 23 | MaStR, which did not reach their end of life. New PV plants are randomly and weighted  | 
            ||
| 24 | generated using a breakdown of MaStR data as generator basis. Plant metadata (e.g. plant  | 
            ||
| 25 | orientation) is also added random and weighted from MaStR data as basis.  | 
            ||
| 26 | """  | 
            ||
| 27 | from __future__ import annotations  | 
            ||
| 28 | |||
| 29 | from collections import Counter  | 
            ||
| 30 | from functools import wraps  | 
            ||
| 31 | from pathlib import Path  | 
            ||
| 32 | from time import perf_counter  | 
            ||
| 33 | from typing import Any  | 
            ||
| 34 | |||
| 35 | from geoalchemy2 import Geometry  | 
            ||
| 36 | from geopy.extra.rate_limiter import RateLimiter  | 
            ||
| 37 | from geopy.geocoders import Nominatim  | 
            ||
| 38 | from loguru import logger  | 
            ||
| 39 | from numpy.random import RandomState, default_rng  | 
            ||
| 40 | from pyproj.crs.crs import CRS  | 
            ||
| 41 | from sqlalchemy import BigInteger, Column, Float, Integer, String  | 
            ||
| 42 | from sqlalchemy.dialects.postgresql import HSTORE  | 
            ||
| 43 | from sqlalchemy.ext.declarative import declarative_base  | 
            ||
| 44 | import geopandas as gpd  | 
            ||
| 45 | import numpy as np  | 
            ||
| 46 | import pandas as pd  | 
            ||
| 47 | |||
| 48 | from egon.data import config, db  | 
            ||
| 49 | from egon.data.datasets.electricity_demand_timeseries.hh_buildings import (  | 
            ||
| 50 | OsmBuildingsSynthetic,  | 
            ||
| 51 | )  | 
            ||
| 52 | from egon.data.datasets.scenario_capacities import EgonScenarioCapacities  | 
            ||
| 53 | from egon.data.datasets.zensus_vg250 import Vg250Gem  | 
            ||
| 54 | |||
| 55 | engine = db.engine()  | 
            ||
| 56 | Base = declarative_base()  | 
            ||
| 57 | SEED = int(config.settings()["egon-data"]["--random-seed"])  | 
            ||
| 58 | |||
| 59 | # TODO: move to yml  | 
            ||
| 60 | # mastr data  | 
            ||
| 61 | MASTR_RELEVANT_COLS = [  | 
            ||
| 62 | "EinheitMastrNummer",  | 
            ||
| 63 | "Bruttoleistung",  | 
            ||
| 64 | "StatisikFlag",  | 
            ||
| 65 | "Bruttoleistung_extended",  | 
            ||
| 66 | "Nettonennleistung",  | 
            ||
| 67 | "InstallierteLeistung",  | 
            ||
| 68 | "zugeordneteWirkleistungWechselrichter",  | 
            ||
| 69 | "EinheitBetriebsstatus",  | 
            ||
| 70 | "Standort",  | 
            ||
| 71 | "Bundesland",  | 
            ||
| 72 | "Land",  | 
            ||
| 73 | "Landkreis",  | 
            ||
| 74 | "Gemeinde",  | 
            ||
| 75 | "Postleitzahl",  | 
            ||
| 76 | "Ort",  | 
            ||
| 77 | "GeplantesInbetriebnahmedatum",  | 
            ||
| 78 | "Inbetriebnahmedatum",  | 
            ||
| 79 | "GemeinsamerWechselrichterMitSpeicher",  | 
            ||
| 80 | "Lage",  | 
            ||
| 81 | "Leistungsbegrenzung",  | 
            ||
| 82 | "EinheitlicheAusrichtungUndNeigungswinkel",  | 
            ||
| 83 | "Hauptausrichtung",  | 
            ||
| 84 | "HauptausrichtungNeigungswinkel",  | 
            ||
| 85 | "Nebenausrichtung",  | 
            ||
| 86 | ]  | 
            ||
| 87 | |||
| 88 | MASTR_DTYPES = { | 
            ||
| 89 | "EinheitMastrNummer": str,  | 
            ||
| 90 | "Bruttoleistung": float,  | 
            ||
| 91 | "StatisikFlag": str,  | 
            ||
| 92 | "Bruttoleistung_extended": float,  | 
            ||
| 93 | "Nettonennleistung": float,  | 
            ||
| 94 | "InstallierteLeistung": float,  | 
            ||
| 95 | "zugeordneteWirkleistungWechselrichter": float,  | 
            ||
| 96 | "EinheitBetriebsstatus": str,  | 
            ||
| 97 | "Standort": str,  | 
            ||
| 98 | "Bundesland": str,  | 
            ||
| 99 | "Land": str,  | 
            ||
| 100 | "Landkreis": str,  | 
            ||
| 101 | "Gemeinde": str,  | 
            ||
| 102 | # "Postleitzahl": int, # fails because of nan values  | 
            ||
| 103 | "Ort": str,  | 
            ||
| 104 | "GemeinsamerWechselrichterMitSpeicher": str,  | 
            ||
| 105 | "Lage": str,  | 
            ||
| 106 | "Leistungsbegrenzung": str,  | 
            ||
| 107 | # this will parse nan values as false wich is not always correct  | 
            ||
| 108 | # "EinheitlicheAusrichtungUndNeigungswinkel": bool,  | 
            ||
| 109 | "Hauptausrichtung": str,  | 
            ||
| 110 | "HauptausrichtungNeigungswinkel": str,  | 
            ||
| 111 | "Nebenausrichtung": str,  | 
            ||
| 112 | "NebenausrichtungNeigungswinkel": str,  | 
            ||
| 113 | }  | 
            ||
| 114 | |||
| 115 | MASTR_PARSE_DATES = [  | 
            ||
| 116 | "GeplantesInbetriebnahmedatum",  | 
            ||
| 117 | "Inbetriebnahmedatum",  | 
            ||
| 118 | ]  | 
            ||
| 119 | |||
| 120 | MASTR_INDEX_COL = "EinheitMastrNummer"  | 
            ||
| 121 | |||
| 122 | EPSG = 4326  | 
            ||
| 123 | SRID = 3035  | 
            ||
| 124 | |||
| 125 | # data cleaning  | 
            ||
| 126 | MAX_REALISTIC_PV_CAP = 23500  | 
            ||
| 127 | MIN_REALISTIC_PV_CAP = 0.1  | 
            ||
| 128 | ROUNDING = 1  | 
            ||
| 129 | |||
| 130 | # geopy  | 
            ||
| 131 | MIN_DELAY_SECONDS = 1  | 
            ||
| 132 | USER_AGENT = "rli_kh_geocoder"  | 
            ||
| 133 | |||
| 134 | # show additional logging information  | 
            ||
| 135 | VERBOSE = False  | 
            ||
| 136 | |||
| 137 | EXPORT_DIR = Path(__name__).resolve().parent / "data"  | 
            ||
| 138 | EXPORT_FILE = "mastr_geocoded.gpkg"  | 
            ||
| 139 | EXPORT_PATH = EXPORT_DIR / EXPORT_FILE  | 
            ||
| 140 | DRIVER = "GPKG"  | 
            ||
| 141 | |||
| 142 | # Number of quantiles  | 
            ||
| 143 | Q = 5  | 
            ||
| 144 | |||
| 145 | # Scenario Data  | 
            ||
| 146 | CARRIER = "solar_rooftop"  | 
            ||
| 147 | SCENARIOS = ["eGon2035", "eGon100RE"]  | 
            ||
| 148 | SCENARIO_TIMESTAMP = { | 
            ||
| 149 |     "eGon2035": pd.Timestamp("2035-01-01", tz="UTC"), | 
            ||
| 150 |     "eGon100RE": pd.Timestamp("2050-01-01", tz="UTC"), | 
            ||
| 151 | }  | 
            ||
| 152 | PV_ROOFTOP_LIFETIME = pd.Timedelta(20 * 365, unit="D")  | 
            ||
| 153 | |||
| 154 | # Example Modul Trina Vertex S TSM-400DE09M.08 400 Wp  | 
            ||
| 155 | # https://www.photovoltaik4all.de/media/pdf/92/64/68/Trina_Datasheet_VertexS_DE09-08_2021_A.pdf  | 
            ||
| 156 | MODUL_CAP = 0.4 # kWp  | 
            ||
| 157 | MODUL_SIZE = 1.096 * 1.754 # m²  | 
            ||
| 158 | PV_CAP_PER_SQ_M = MODUL_CAP / MODUL_SIZE  | 
            ||
| 159 | |||
| 160 | # Estimation of usable roof area  | 
            ||
| 161 | # Factor for the conversion of building area to roof area  | 
            ||
| 162 | # estimation mean roof pitch: 35°  | 
            ||
| 163 | # estimation usable roof share: 80%  | 
            ||
| 164 | # estimation that only the south side of the building is used for pv  | 
            ||
| 165 | # see https://mediatum.ub.tum.de/doc/%20969497/969497.pdf  | 
            ||
| 166 | # AREA_FACTOR = 1.221  | 
            ||
| 167 | # USABLE_ROOF_SHARE = 0.8  | 
            ||
| 168 | # SOUTH_SHARE = 0.5  | 
            ||
| 169 | # ROOF_FACTOR = AREA_FACTOR * USABLE_ROOF_SHARE * SOUTH_SHARE  | 
            ||
| 170 | ROOF_FACTOR = 0.5  | 
            ||
| 171 | |||
| 172 | CAP_RANGES = [  | 
            ||
| 173 | (0, 30),  | 
            ||
| 174 | (30, 100),  | 
            ||
| 175 |     (100, float("inf")), | 
            ||
| 176 | ]  | 
            ||
| 177 | |||
| 178 | MIN_BUILDING_SIZE = 10.0  | 
            ||
| 179 | UPPER_QUNATILE = 0.95  | 
            ||
| 180 | LOWER_QUANTILE = 0.05  | 
            ||
| 181 | |||
| 182 | COLS_TO_RENAME = { | 
            ||
| 183 | "EinheitlicheAusrichtungUndNeigungswinkel": (  | 
            ||
| 184 | "einheitliche_ausrichtung_und_neigungswinkel"  | 
            ||
| 185 | ),  | 
            ||
| 186 | "Hauptausrichtung": "hauptausrichtung",  | 
            ||
| 187 | "HauptausrichtungNeigungswinkel": "hauptausrichtung_neigungswinkel",  | 
            ||
| 188 | }  | 
            ||
| 189 | |||
| 190 | COLS_TO_EXPORT = [  | 
            ||
| 191 | "scenario",  | 
            ||
| 192 | "bus_id",  | 
            ||
| 193 | "building_id",  | 
            ||
| 194 | "gens_id",  | 
            ||
| 195 | "capacity",  | 
            ||
| 196 | "einheitliche_ausrichtung_und_neigungswinkel",  | 
            ||
| 197 | "hauptausrichtung",  | 
            ||
| 198 | "hauptausrichtung_neigungswinkel",  | 
            ||
| 199 | "voltage_level",  | 
            ||
| 200 | "weather_cell_id",  | 
            ||
| 201 | ]  | 
            ||
| 202 | |||
| 203 | # TODO  | 
            ||
| 204 | INCLUDE_SYNTHETIC_BUILDINGS = True  | 
            ||
| 205 | ONLY_BUILDINGS_WITH_DEMAND = True  | 
            ||
| 206 | TEST_RUN = False  | 
            ||
| 207 | |||
| 208 | |||
| 209 | def timer_func(func):  | 
            ||
| 210 | @wraps(func)  | 
            ||
| 211 | def timeit_wrapper(*args, **kwargs):  | 
            ||
| 212 | start_time = perf_counter()  | 
            ||
| 213 | result = func(*args, **kwargs)  | 
            ||
| 214 | end_time = perf_counter()  | 
            ||
| 215 | total_time = end_time - start_time  | 
            ||
| 216 | logger.debug(  | 
            ||
| 217 |             f"Function {func.__name__} took {total_time:.4f} seconds." | 
            ||
| 218 | )  | 
            ||
| 219 | return result  | 
            ||
| 220 | |||
| 221 | return timeit_wrapper  | 
            ||
| 222 | |||
| 223 | |||
| 224 | @timer_func  | 
            ||
| 225 | def mastr_data(  | 
            ||
| 226 | index_col: str | int | list[str] | list[int],  | 
            ||
| 227 | usecols: list[str],  | 
            ||
| 228 | dtype: dict[str, Any] | None,  | 
            ||
| 229 | parse_dates: list[str] | None,  | 
            ||
| 230 | ) -> pd.DataFrame:  | 
            ||
| 231 | """  | 
            ||
| 232 | Read MaStR data from csv.  | 
            ||
| 233 | |||
| 234 | Parameters  | 
            ||
| 235 | -----------  | 
            ||
| 236 | index_col : str, int or list of str or int  | 
            ||
| 237 | Column(s) to use as the row labels of the DataFrame.  | 
            ||
| 238 | usecols : list of str  | 
            ||
| 239 | Return a subset of the columns.  | 
            ||
| 240 | dtype : dict of column (str) -> type (any), optional  | 
            ||
| 241 | Data type for data or columns.  | 
            ||
| 242 | parse_dates : list of names (str), optional  | 
            ||
| 243 | Try to parse given columns to datetime.  | 
            ||
| 244 | Returns  | 
            ||
| 245 | -------  | 
            ||
| 246 | pandas.DataFrame  | 
            ||
| 247 | DataFrame containing MaStR data.  | 
            ||
| 248 | """  | 
            ||
| 249 | mastr_path = Path(  | 
            ||
| 250 | config.datasets()["power_plants"]["sources"]["mastr_pv"]  | 
            ||
| 251 | ).resolve()  | 
            ||
| 252 | |||
| 253 | mastr_df = pd.read_csv(  | 
            ||
| 254 | mastr_path,  | 
            ||
| 255 | index_col=index_col,  | 
            ||
| 256 | usecols=usecols,  | 
            ||
| 257 | dtype=dtype,  | 
            ||
| 258 | parse_dates=parse_dates,  | 
            ||
| 259 | )  | 
            ||
| 260 | |||
| 261 | mastr_df = mastr_df.loc[  | 
            ||
| 262 | (mastr_df.StatisikFlag == "B")  | 
            ||
| 263 | & (mastr_df.EinheitBetriebsstatus == "InBetrieb")  | 
            ||
| 264 | & (mastr_df.Land == "Deutschland")  | 
            ||
| 265 | & (mastr_df.Lage == "BaulicheAnlagen")  | 
            ||
| 266 | ]  | 
            ||
| 267 | |||
| 268 | if (  | 
            ||
| 269 | config.settings()["egon-data"]["--dataset-boundary"]  | 
            ||
| 270 | == "Schleswig-Holstein"  | 
            ||
| 271 | ):  | 
            ||
| 272 | init_len = len(mastr_df)  | 
            ||
| 273 | |||
| 274 | mastr_df = mastr_df.loc[mastr_df.Bundesland == "SchleswigHolstein"]  | 
            ||
| 275 | |||
| 276 | logger.info(  | 
            ||
| 277 | f"Using only MaStR data within Schleswig-Holstein. "  | 
            ||
| 278 |             f"{init_len - len(mastr_df)} of {init_len} generators are dropped." | 
            ||
| 279 | )  | 
            ||
| 280 | |||
| 281 |     logger.debug("MaStR data loaded.") | 
            ||
| 282 | |||
| 283 | return mastr_df  | 
            ||
| 284 | |||
| 285 | |||
| 286 | @timer_func  | 
            ||
| 287 | def clean_mastr_data(  | 
            ||
| 288 | mastr_df: pd.DataFrame,  | 
            ||
| 289 | max_realistic_pv_cap: int | float,  | 
            ||
| 290 | min_realistic_pv_cap: int | float,  | 
            ||
| 291 | rounding: int,  | 
            ||
| 292 | seed: int,  | 
            ||
| 293 | ) -> pd.DataFrame:  | 
            ||
| 294 | """  | 
            ||
| 295 | Clean the MaStR data from implausible data.  | 
            ||
| 296 | |||
| 297 | * Drop MaStR ID duplicates.  | 
            ||
| 298 | * Drop generators with implausible capacities.  | 
            ||
| 299 | * Drop generators without any kind of start-up date.  | 
            ||
| 300 | * Clean up Standort column and capacity.  | 
            ||
| 301 | |||
| 302 | Parameters  | 
            ||
| 303 | -----------  | 
            ||
| 304 | mastr_df : pandas.DataFrame  | 
            ||
| 305 | DataFrame containing MaStR data.  | 
            ||
| 306 | max_realistic_pv_cap : int or float  | 
            ||
| 307 | Maximum capacity, which is considered to be realistic.  | 
            ||
| 308 | min_realistic_pv_cap : int or float  | 
            ||
| 309 | Minimum capacity, which is considered to be realistic.  | 
            ||
| 310 | rounding : int  | 
            ||
| 311 | Rounding to use when cleaning up capacity. E.g. when  | 
            ||
| 312 | rounding is 1 a capacity of 9.93 will be rounded to 9.9.  | 
            ||
| 313 | seed : int  | 
            ||
| 314 | Seed to use for random operations with NumPy and pandas.  | 
            ||
| 315 | Returns  | 
            ||
| 316 | -------  | 
            ||
| 317 | pandas.DataFrame  | 
            ||
| 318 | DataFrame containing cleaned MaStR data.  | 
            ||
| 319 | """  | 
            ||
| 320 | init_len = len(mastr_df)  | 
            ||
| 321 | |||
| 322 | # drop duplicates  | 
            ||
| 323 | mastr_df = mastr_df.loc[~mastr_df.index.duplicated()]  | 
            ||
| 324 | |||
| 325 | # drop invalid entries in standort  | 
            ||
| 326 | index_to_drop = mastr_df.loc[  | 
            ||
| 327 | (mastr_df.Standort.isna()) | (mastr_df.Standort.isnull())  | 
            ||
| 328 | ].index  | 
            ||
| 329 | |||
| 330 | mastr_df = mastr_df.loc[~mastr_df.index.isin(index_to_drop)]  | 
            ||
| 331 | |||
| 332 | df = mastr_df[  | 
            ||
| 333 | [  | 
            ||
| 334 | "Bruttoleistung",  | 
            ||
| 335 | "Bruttoleistung_extended",  | 
            ||
| 336 | "Nettonennleistung",  | 
            ||
| 337 | "zugeordneteWirkleistungWechselrichter",  | 
            ||
| 338 | "InstallierteLeistung",  | 
            ||
| 339 | ]  | 
            ||
| 340 | ].round(rounding)  | 
            ||
| 341 | |||
| 342 | # use only the smallest capacity rating if multiple are given  | 
            ||
| 343 | mastr_df = mastr_df.assign(  | 
            ||
| 344 | capacity=[  | 
            ||
| 345 | most_plausible(p_tub, min_realistic_pv_cap)  | 
            ||
| 346 | for p_tub in df.itertuples(index=False)  | 
            ||
| 347 | ]  | 
            ||
| 348 | )  | 
            ||
| 349 | |||
| 350 | # drop generators without any capacity info  | 
            ||
| 351 | # and capacity of zero  | 
            ||
| 352 | # and if the capacity is > 23.5 MW, because  | 
            ||
| 353 | # Germanies largest rooftop PV is 23 MW  | 
            ||
| 354 | # https://www.iwr.de/news/groesste-pv-dachanlage-europas-wird-in-sachsen-anhalt-gebaut-news37379  | 
            ||
| 355 | mastr_df = mastr_df.loc[  | 
            ||
| 356 | (~mastr_df.capacity.isna())  | 
            ||
| 357 | & (mastr_df.capacity <= max_realistic_pv_cap)  | 
            ||
| 358 | & (mastr_df.capacity > min_realistic_pv_cap)  | 
            ||
| 359 | ]  | 
            ||
| 360 | |||
| 361 | # get zip and municipality  | 
            ||
| 362 | mastr_df[["zip_and_municipality", "drop_this"]] = pd.DataFrame(  | 
            ||
| 363 | mastr_df.Standort.astype(str)  | 
            ||
| 364 | .apply(  | 
            ||
| 365 | zip_and_municipality_from_standort,  | 
            ||
| 366 | args=(VERBOSE,),  | 
            ||
| 367 | )  | 
            ||
| 368 | .tolist(),  | 
            ||
| 369 | index=mastr_df.index,  | 
            ||
| 370 | )  | 
            ||
| 371 | |||
| 372 | # drop invalid entries  | 
            ||
| 373 | mastr_df = mastr_df.loc[mastr_df.drop_this].drop(columns="drop_this")  | 
            ||
| 374 | |||
| 375 | # add ", Deutschland" just in case  | 
            ||
| 376 | mastr_df = mastr_df.assign(  | 
            ||
| 377 | zip_and_municipality=(mastr_df.zip_and_municipality + ", Deutschland")  | 
            ||
| 378 | )  | 
            ||
| 379 | |||
| 380 | # get consistent start-up date  | 
            ||
| 381 | mastr_df = mastr_df.assign(  | 
            ||
| 382 | start_up_date=mastr_df.Inbetriebnahmedatum,  | 
            ||
| 383 | )  | 
            ||
| 384 | |||
| 385 | mastr_df.loc[mastr_df.start_up_date.isna()] = mastr_df.loc[  | 
            ||
| 386 | mastr_df.start_up_date.isna()  | 
            ||
| 387 | ].assign(  | 
            ||
| 388 | start_up_date=mastr_df.GeplantesInbetriebnahmedatum.loc[  | 
            ||
| 389 | mastr_df.start_up_date.isna()  | 
            ||
| 390 | ]  | 
            ||
| 391 | )  | 
            ||
| 392 | |||
| 393 | # randomly and weighted fill missing start-up dates  | 
            ||
| 394 | pool = mastr_df.loc[  | 
            ||
| 395 | ~mastr_df.start_up_date.isna()  | 
            ||
| 396 | ].start_up_date.to_numpy()  | 
            ||
| 397 | |||
| 398 | size = len(mastr_df) - len(pool)  | 
            ||
| 399 | |||
| 400 | if size > 0:  | 
            ||
| 401 | np.random.seed(seed)  | 
            ||
| 402 | |||
| 403 | choice = np.random.choice(  | 
            ||
| 404 | pool,  | 
            ||
| 405 | size=size,  | 
            ||
| 406 | replace=False,  | 
            ||
| 407 | )  | 
            ||
| 408 | |||
| 409 | mastr_df.loc[mastr_df.start_up_date.isna()] = mastr_df.loc[  | 
            ||
| 410 | mastr_df.start_up_date.isna()  | 
            ||
| 411 | ].assign(start_up_date=choice)  | 
            ||
| 412 | |||
| 413 | logger.info(  | 
            ||
| 414 |             f"Randomly and weigthed added start-up date to {size} generators." | 
            ||
| 415 | )  | 
            ||
| 416 | |||
| 417 | mastr_df = mastr_df.assign(  | 
            ||
| 418 | start_up_date=pd.to_datetime(mastr_df.start_up_date, utc=True)  | 
            ||
| 419 | )  | 
            ||
| 420 | |||
| 421 | end_len = len(mastr_df)  | 
            ||
| 422 | logger.debug(  | 
            ||
| 423 |         f"Dropped {init_len - end_len} " | 
            ||
| 424 |         f"({((init_len - end_len) / init_len) * 100:g}%)" | 
            ||
| 425 |         f" of {init_len} rows from MaStR DataFrame." | 
            ||
| 426 | )  | 
            ||
| 427 | |||
| 428 | return mastr_df  | 
            ||
| 429 | |||
| 430 | |||
| 431 | def zip_and_municipality_from_standort(  | 
            ||
| 432 | standort: str,  | 
            ||
| 433 | verbose: bool = False,  | 
            ||
| 434 | ) -> tuple[str, bool]:  | 
            ||
| 435 | """  | 
            ||
| 436 | Get zip code and municipality from Standort string split into a list.  | 
            ||
| 437 | Parameters  | 
            ||
| 438 | -----------  | 
            ||
| 439 | standort : str  | 
            ||
| 440 | Standort as given from MaStR data.  | 
            ||
| 441 | verbose : bool  | 
            ||
| 442 | Logs additional info if True.  | 
            ||
| 443 | Returns  | 
            ||
| 444 | -------  | 
            ||
| 445 | str  | 
            ||
| 446 | Standort with only the zip code and municipality  | 
            ||
| 447 | as well a ', Germany' added.  | 
            ||
| 448 | """  | 
            ||
| 449 | if verbose:  | 
            ||
| 450 |         logger.debug(f"Uncleaned String: {standort}") | 
            ||
| 451 | |||
| 452 | standort_list = standort.split()  | 
            ||
| 453 | |||
| 454 | found = False  | 
            ||
| 455 | count = 0  | 
            ||
| 456 | |||
| 457 | for count, elem in enumerate(standort_list):  | 
            ||
| 458 | if len(elem) != 5:  | 
            ||
| 459 | continue  | 
            ||
| 460 | if not elem.isnumeric():  | 
            ||
| 461 | continue  | 
            ||
| 462 | |||
| 463 | found = True  | 
            ||
| 464 | |||
| 465 | break  | 
            ||
| 466 | |||
| 467 | if found:  | 
            ||
| 468 | cleaned_str = " ".join(standort_list[count:])  | 
            ||
| 469 | |||
| 470 | if verbose:  | 
            ||
| 471 |             logger.debug(f"Cleaned String:   {cleaned_str}") | 
            ||
| 472 | |||
| 473 | return cleaned_str, found  | 
            ||
| 474 | |||
| 475 | logger.warning(  | 
            ||
| 476 | "Couldn't identify zip code. This entry will be dropped."  | 
            ||
| 477 |         f" Original standort: {standort}." | 
            ||
| 478 | )  | 
            ||
| 479 | |||
| 480 | return standort, found  | 
            ||
| 481 | |||
| 482 | |||
| 483 | def most_plausible(  | 
            ||
| 484 | p_tub: tuple,  | 
            ||
| 485 | min_realistic_pv_cap: int | float,  | 
            ||
| 486 | ) -> float:  | 
            ||
| 487 | """  | 
            ||
| 488 | Try to determine the most plausible capacity.  | 
            ||
| 489 | Try to determine the most plausible capacity from a given  | 
            ||
| 490 | generator from MaStR data.  | 
            ||
| 491 | Parameters  | 
            ||
| 492 | -----------  | 
            ||
| 493 | p_tub : tuple  | 
            ||
| 494 | Tuple containing the different capacities given in  | 
            ||
| 495 | the MaStR data.  | 
            ||
| 496 | min_realistic_pv_cap : int or float  | 
            ||
| 497 | Minimum capacity, which is considered to be realistic.  | 
            ||
| 498 | Returns  | 
            ||
| 499 | -------  | 
            ||
| 500 | float  | 
            ||
| 501 | Capacity of the generator estimated as the most realistic.  | 
            ||
| 502 | """  | 
            ||
| 503 | count = Counter(p_tub).most_common(3)  | 
            ||
| 504 | |||
| 505 | if len(count) == 1:  | 
            ||
| 506 | return count[0][0]  | 
            ||
| 507 | |||
| 508 | val1 = count[0][0]  | 
            ||
| 509 | val2 = count[1][0]  | 
            ||
| 510 | |||
| 511 | if len(count) == 2:  | 
            ||
| 512 | min_val = min(val1, val2)  | 
            ||
| 513 | max_val = max(val1, val2)  | 
            ||
| 514 | else:  | 
            ||
| 515 | val3 = count[2][0]  | 
            ||
| 516 | |||
| 517 | min_val = min(val1, val2, val3)  | 
            ||
| 518 | max_val = max(val1, val2, val3)  | 
            ||
| 519 | |||
| 520 | if min_val < min_realistic_pv_cap:  | 
            ||
| 521 | return max_val  | 
            ||
| 522 | |||
| 523 | return min_val  | 
            ||
| 524 | |||
| 525 | |||
| 526 | def geocoder(  | 
            ||
| 527 | user_agent: str,  | 
            ||
| 528 | min_delay_seconds: int,  | 
            ||
| 529 | ) -> RateLimiter:  | 
            ||
| 530 | """  | 
            ||
| 531 | Setup Nominatim geocoding class.  | 
            ||
| 532 | Parameters  | 
            ||
| 533 | -----------  | 
            ||
| 534 | user_agent : str  | 
            ||
| 535 | The app name.  | 
            ||
| 536 | min_delay_seconds : int  | 
            ||
| 537 | Delay in seconds to use between requests to Nominatim.  | 
            ||
| 538 | A minimum of 1 is advised.  | 
            ||
| 539 | Returns  | 
            ||
| 540 | -------  | 
            ||
| 541 | geopy.extra.rate_limiter.RateLimiter  | 
            ||
| 542 | Nominatim RateLimiter geocoding class to use for geocoding.  | 
            ||
| 543 | """  | 
            ||
| 544 | locator = Nominatim(user_agent=user_agent)  | 
            ||
| 545 | return RateLimiter(  | 
            ||
| 546 | locator.geocode,  | 
            ||
| 547 | min_delay_seconds=min_delay_seconds,  | 
            ||
| 548 | )  | 
            ||
| 549 | |||
| 550 | |||
| 551 | def geocoding_data(  | 
            ||
| 552 | clean_mastr_df: pd.DataFrame,  | 
            ||
| 553 | ) -> pd.DataFrame:  | 
            ||
| 554 | """  | 
            ||
| 555 | Setup DataFrame to geocode.  | 
            ||
| 556 | Parameters  | 
            ||
| 557 | -----------  | 
            ||
| 558 | clean_mastr_df : pandas.DataFrame  | 
            ||
| 559 | DataFrame containing cleaned MaStR data.  | 
            ||
| 560 | Returns  | 
            ||
| 561 | -------  | 
            ||
| 562 | pandas.DataFrame  | 
            ||
| 563 | DataFrame containing all unique combinations of  | 
            ||
| 564 | zip codes with municipalities for geocoding.  | 
            ||
| 565 | """  | 
            ||
| 566 | return pd.DataFrame(  | 
            ||
| 567 | data=clean_mastr_df.zip_and_municipality.unique(),  | 
            ||
| 568 | columns=["zip_and_municipality"],  | 
            ||
| 569 | )  | 
            ||
| 570 | |||
| 571 | |||
| 572 | @timer_func  | 
            ||
| 573 | def geocode_data(  | 
            ||
| 574 | geocoding_df: pd.DataFrame,  | 
            ||
| 575 | ratelimiter: RateLimiter,  | 
            ||
| 576 | epsg: int,  | 
            ||
| 577 | ) -> gpd.GeoDataFrame:  | 
            ||
| 578 | """  | 
            ||
| 579 | Geocode zip code and municipality.  | 
            ||
| 580 | Extract latitude, longitude and altitude.  | 
            ||
| 581 | Transfrom latitude and longitude to shapely  | 
            ||
| 582 | Point and return a geopandas GeoDataFrame.  | 
            ||
| 583 | Parameters  | 
            ||
| 584 | -----------  | 
            ||
| 585 | geocoding_df : pandas.DataFrame  | 
            ||
| 586 | DataFrame containing all unique combinations of  | 
            ||
| 587 | zip codes with municipalities for geocoding.  | 
            ||
| 588 | ratelimiter : geopy.extra.rate_limiter.RateLimiter  | 
            ||
| 589 | Nominatim RateLimiter geocoding class to use for geocoding.  | 
            ||
| 590 | epsg : int  | 
            ||
| 591 | EPSG ID to use as CRS.  | 
            ||
| 592 | Returns  | 
            ||
| 593 | -------  | 
            ||
| 594 | geopandas.GeoDataFrame  | 
            ||
| 595 | GeoDataFrame containing all unique combinations of  | 
            ||
| 596 | zip codes with municipalities with matching geolocation.  | 
            ||
| 597 | """  | 
            ||
| 598 |     logger.info(f"Geocoding {len(geocoding_df)} locations.") | 
            ||
| 599 | |||
| 600 | geocode_df = geocoding_df.assign(  | 
            ||
| 601 | location=geocoding_df.zip_and_municipality.apply(ratelimiter)  | 
            ||
| 602 | )  | 
            ||
| 603 | |||
| 604 | geocode_df = geocode_df.assign(  | 
            ||
| 605 | point=geocode_df.location.apply(  | 
            ||
| 606 | lambda loc: tuple(loc.point) if loc else None  | 
            ||
| 607 | )  | 
            ||
| 608 | )  | 
            ||
| 609 | |||
| 610 | geocode_df[["latitude", "longitude", "altitude"]] = pd.DataFrame(  | 
            ||
| 611 | geocode_df.point.tolist(), index=geocode_df.index  | 
            ||
| 612 | )  | 
            ||
| 613 | |||
| 614 | return gpd.GeoDataFrame(  | 
            ||
| 615 | geocode_df,  | 
            ||
| 616 | geometry=gpd.points_from_xy(geocode_df.longitude, geocode_df.latitude),  | 
            ||
| 617 |         crs=f"EPSG:{epsg}", | 
            ||
| 618 | )  | 
            ||
| 619 | |||
| 620 | |||
| 621 | def merge_geocode_with_mastr(  | 
            ||
| 622 | clean_mastr_df: pd.DataFrame, geocode_gdf: gpd.GeoDataFrame  | 
            ||
| 623 | ) -> gpd.GeoDataFrame:  | 
            ||
| 624 | """  | 
            ||
| 625 | Merge geometry to original mastr data.  | 
            ||
| 626 | Parameters  | 
            ||
| 627 | -----------  | 
            ||
| 628 | clean_mastr_df : pandas.DataFrame  | 
            ||
| 629 | DataFrame containing cleaned MaStR data.  | 
            ||
| 630 | geocode_gdf : geopandas.GeoDataFrame  | 
            ||
| 631 | GeoDataFrame containing all unique combinations of  | 
            ||
| 632 | zip codes with municipalities with matching geolocation.  | 
            ||
| 633 | Returns  | 
            ||
| 634 | -------  | 
            ||
| 635 | gepandas.GeoDataFrame  | 
            ||
| 636 | GeoDataFrame containing cleaned MaStR data with  | 
            ||
| 637 | matching geolocation from geocoding.  | 
            ||
| 638 | """  | 
            ||
| 639 | return gpd.GeoDataFrame(  | 
            ||
| 640 | clean_mastr_df.merge(  | 
            ||
| 641 | geocode_gdf[["zip_and_municipality", "geometry"]],  | 
            ||
| 642 | how="left",  | 
            ||
| 643 | left_on="zip_and_municipality",  | 
            ||
| 644 | right_on="zip_and_municipality",  | 
            ||
| 645 | ),  | 
            ||
| 646 | crs=geocode_gdf.crs,  | 
            ||
| 647 | ).set_index(clean_mastr_df.index)  | 
            ||
| 648 | |||
| 649 | |||
| 650 | def drop_invalid_entries_from_gdf(  | 
            ||
| 651 | gdf: gpd.GeoDataFrame,  | 
            ||
| 652 | ) -> gpd.GeoDataFrame:  | 
            ||
| 653 | """  | 
            ||
| 654 | Drop invalid entries from geopandas GeoDataFrame.  | 
            ||
| 655 | TODO: how to omit the logging from geos here???  | 
            ||
| 656 | Parameters  | 
            ||
| 657 | -----------  | 
            ||
| 658 | gdf : geopandas.GeoDataFrame  | 
            ||
| 659 | GeoDataFrame to be checked for validity.  | 
            ||
| 660 | Returns  | 
            ||
| 661 | -------  | 
            ||
| 662 | gepandas.GeoDataFrame  | 
            ||
| 663 | GeoDataFrame with rows with invalid geometries  | 
            ||
| 664 | dropped.  | 
            ||
| 665 | """  | 
            ||
| 666 | valid_gdf = gdf.loc[gdf.is_valid]  | 
            ||
| 667 | |||
| 668 | logger.debug(  | 
            ||
| 669 |         f"{len(gdf) - len(valid_gdf)} " | 
            ||
| 670 |         f"({(len(gdf) - len(valid_gdf)) / len(gdf) * 100:g}%) " | 
            ||
| 671 |         f"of {len(gdf)} values were invalid and are dropped." | 
            ||
| 672 | )  | 
            ||
| 673 | |||
| 674 | return valid_gdf  | 
            ||
| 675 | |||
| 676 | |||
| 677 | @timer_func  | 
            ||
| 678 | def municipality_data() -> gpd.GeoDataFrame:  | 
            ||
| 679 | """  | 
            ||
| 680 | Get municipality data from eGo^n Database.  | 
            ||
| 681 | Returns  | 
            ||
| 682 | -------  | 
            ||
| 683 | gepandas.GeoDataFrame  | 
            ||
| 684 | GeoDataFrame with municipality data.  | 
            ||
| 685 | """  | 
            ||
| 686 | with db.session_scope() as session:  | 
            ||
| 687 |         query = session.query(Vg250Gem.ags, Vg250Gem.geometry.label("geom")) | 
            ||
| 688 | |||
| 689 | return gpd.read_postgis(  | 
            ||
| 690 | query.statement, query.session.bind, index_col="ags"  | 
            ||
| 691 | )  | 
            ||
| 692 | |||
| 693 | |||
| 694 | @timer_func  | 
            ||
| 695 | def add_ags_to_gens(  | 
            ||
| 696 | valid_mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 697 | municipalities_gdf: gpd.GeoDataFrame,  | 
            ||
| 698 | ) -> gpd.GeoDataFrame:  | 
            ||
| 699 | """  | 
            ||
| 700 | Add information about AGS ID to generators.  | 
            ||
| 701 | Parameters  | 
            ||
| 702 | -----------  | 
            ||
| 703 | valid_mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 704 | GeoDataFrame with valid and cleaned MaStR data.  | 
            ||
| 705 | municipalities_gdf : geopandas.GeoDataFrame  | 
            ||
| 706 | GeoDataFrame with municipality data.  | 
            ||
| 707 | Returns  | 
            ||
| 708 | -------  | 
            ||
| 709 | gepandas.GeoDataFrame  | 
            ||
| 710 | GeoDataFrame with valid and cleaned MaStR data  | 
            ||
| 711 | with AGS ID added.  | 
            ||
| 712 | """  | 
            ||
| 713 | return valid_mastr_gdf.sjoin(  | 
            ||
| 714 | municipalities_gdf,  | 
            ||
| 715 | how="left",  | 
            ||
| 716 | predicate="intersects",  | 
            ||
| 717 |     ).rename(columns={"index_right": "ags"}) | 
            ||
| 718 | |||
| 719 | |||
| 720 | def drop_gens_outside_muns(  | 
            ||
| 721 | valid_mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 722 | ) -> gpd.GeoDataFrame:  | 
            ||
| 723 | """  | 
            ||
| 724 | Drop all generators outside of municipalities.  | 
            ||
| 725 | Parameters  | 
            ||
| 726 | -----------  | 
            ||
| 727 | valid_mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 728 | GeoDataFrame with valid and cleaned MaStR data.  | 
            ||
| 729 | Returns  | 
            ||
| 730 | -------  | 
            ||
| 731 | gepandas.GeoDataFrame  | 
            ||
| 732 | GeoDataFrame with valid and cleaned MaStR data  | 
            ||
| 733 | with generatos without an AGS ID dropped.  | 
            ||
| 734 | """  | 
            ||
| 735 | gdf = valid_mastr_gdf.loc[~valid_mastr_gdf.ags.isna()]  | 
            ||
| 736 | |||
| 737 | logger.debug(  | 
            ||
| 738 |         f"{len(valid_mastr_gdf) - len(gdf)} " | 
            ||
| 739 |         f"({(len(valid_mastr_gdf) - len(gdf)) / len(valid_mastr_gdf) * 100:g}%) " | 
            ||
| 740 |         f"of {len(valid_mastr_gdf)} values are outside of the municipalities" | 
            ||
| 741 | " and are therefore dropped."  | 
            ||
| 742 | )  | 
            ||
| 743 | |||
| 744 | return gdf  | 
            ||
| 745 | |||
| 746 | |||
| 747 | class EgonMastrPvRoofGeocoded(Base):  | 
            ||
| 748 | __tablename__ = "egon_mastr_pv_roof_geocoded"  | 
            ||
| 749 |     __table_args__ = {"schema": "supply"} | 
            ||
| 750 | |||
| 751 | zip_and_municipality = Column(String, primary_key=True, index=True)  | 
            ||
| 752 | location = Column(String)  | 
            ||
| 753 | point = Column(String)  | 
            ||
| 754 | latitude = Column(Float)  | 
            ||
| 755 | longitude = Column(Float)  | 
            ||
| 756 | altitude = Column(Float)  | 
            ||
| 757 | geometry = Column(Geometry(srid=EPSG))  | 
            ||
| 758 | |||
| 759 | |||
| 760 | def create_geocoded_table(geocode_gdf):  | 
            ||
| 761 | """  | 
            ||
| 762 | Create geocoded table mastr pv rooftop  | 
            ||
| 763 | Parameters  | 
            ||
| 764 | -----------  | 
            ||
| 765 | geocode_gdf : geopandas.GeoDataFrame  | 
            ||
| 766 | GeoDataFrame containing geocoding information on pv rooftop locations.  | 
            ||
| 767 | """  | 
            ||
| 768 | EgonMastrPvRoofGeocoded.__table__.drop(bind=engine, checkfirst=True)  | 
            ||
| 769 | EgonMastrPvRoofGeocoded.__table__.create(bind=engine, checkfirst=True)  | 
            ||
| 770 | |||
| 771 | geocode_gdf.to_postgis(  | 
            ||
| 772 | name=EgonMastrPvRoofGeocoded.__table__.name,  | 
            ||
| 773 | schema=EgonMastrPvRoofGeocoded.__table__.schema,  | 
            ||
| 774 | con=db.engine(),  | 
            ||
| 775 | if_exists="append",  | 
            ||
| 776 | index=False,  | 
            ||
| 777 |         # dtype={} | 
            ||
| 778 | )  | 
            ||
| 779 | |||
| 780 | |||
| 781 | def geocoded_data_from_db(  | 
            ||
| 782 | epsg: str | int,  | 
            ||
| 783 | ) -> gpd.GeoDataFrame:  | 
            ||
| 784 | """  | 
            ||
| 785 | Read OSM buildings data from eGo^n Database.  | 
            ||
| 786 | Parameters  | 
            ||
| 787 | -----------  | 
            ||
| 788 | to_crs : pyproj.crs.crs.CRS  | 
            ||
| 789 | CRS to transform geometries to.  | 
            ||
| 790 | Returns  | 
            ||
| 791 | -------  | 
            ||
| 792 | geopandas.GeoDataFrame  | 
            ||
| 793 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 794 | """  | 
            ||
| 795 | with db.session_scope() as session:  | 
            ||
| 796 | query = session.query(  | 
            ||
| 797 | EgonMastrPvRoofGeocoded.zip_and_municipality,  | 
            ||
| 798 | EgonMastrPvRoofGeocoded.geometry,  | 
            ||
| 799 | )  | 
            ||
| 800 | |||
| 801 | return gpd.read_postgis(  | 
            ||
| 802 | query.statement, query.session.bind, geom_col="geometry"  | 
            ||
| 803 |     ).to_crs(f"EPSG:{epsg}") | 
            ||
| 804 | |||
| 805 | |||
| 806 | def load_mastr_data():  | 
            ||
| 807 | """Read PV rooftop data from MaStR CSV  | 
            ||
| 808 | Note: the source will be replaced as soon as the MaStR data is available  | 
            ||
| 809 | in DB.  | 
            ||
| 810 | Returns  | 
            ||
| 811 | -------  | 
            ||
| 812 | geopandas.GeoDataFrame  | 
            ||
| 813 | GeoDataFrame containing MaStR data with geocoded locations.  | 
            ||
| 814 | """  | 
            ||
| 815 | mastr_df = mastr_data(  | 
            ||
| 816 | MASTR_INDEX_COL,  | 
            ||
| 817 | MASTR_RELEVANT_COLS,  | 
            ||
| 818 | MASTR_DTYPES,  | 
            ||
| 819 | MASTR_PARSE_DATES,  | 
            ||
| 820 | )  | 
            ||
| 821 | |||
| 822 | clean_mastr_df = clean_mastr_data(  | 
            ||
| 823 | mastr_df,  | 
            ||
| 824 | max_realistic_pv_cap=MAX_REALISTIC_PV_CAP,  | 
            ||
| 825 | min_realistic_pv_cap=MIN_REALISTIC_PV_CAP,  | 
            ||
| 826 | seed=SEED,  | 
            ||
| 827 | rounding=ROUNDING,  | 
            ||
| 828 | )  | 
            ||
| 829 | |||
| 830 | geocode_gdf = geocoded_data_from_db(EPSG)  | 
            ||
| 831 | |||
| 832 | mastr_gdf = merge_geocode_with_mastr(clean_mastr_df, geocode_gdf)  | 
            ||
| 833 | |||
| 834 | valid_mastr_gdf = drop_invalid_entries_from_gdf(mastr_gdf)  | 
            ||
| 835 | |||
| 836 | municipalities_gdf = municipality_data()  | 
            ||
| 837 | |||
| 838 | valid_mastr_gdf = add_ags_to_gens(valid_mastr_gdf, municipalities_gdf)  | 
            ||
| 839 | |||
| 840 | return drop_gens_outside_muns(valid_mastr_gdf)  | 
            ||
| 841 | |||
| 842 | |||
| 843 | class OsmBuildingsFiltered(Base):  | 
            ||
| 844 | __tablename__ = "osm_buildings_filtered"  | 
            ||
| 845 |     __table_args__ = {"schema": "openstreetmap"} | 
            ||
| 846 | |||
| 847 | osm_id = Column(BigInteger)  | 
            ||
| 848 | amenity = Column(String)  | 
            ||
| 849 | building = Column(String)  | 
            ||
| 850 | name = Column(String)  | 
            ||
| 851 | geom = Column(Geometry(srid=SRID), index=True)  | 
            ||
| 852 | area = Column(Float)  | 
            ||
| 853 | geom_point = Column(Geometry(srid=SRID), index=True)  | 
            ||
| 854 | tags = Column(HSTORE)  | 
            ||
| 855 | id = Column(BigInteger, primary_key=True, index=True)  | 
            ||
| 856 | |||
| 857 | |||
| 858 | @timer_func  | 
            ||
| 859 | def osm_buildings(  | 
            ||
| 860 | to_crs: CRS,  | 
            ||
| 861 | ) -> gpd.GeoDataFrame:  | 
            ||
| 862 | """  | 
            ||
| 863 | Read OSM buildings data from eGo^n Database.  | 
            ||
| 864 | Parameters  | 
            ||
| 865 | -----------  | 
            ||
| 866 | to_crs : pyproj.crs.crs.CRS  | 
            ||
| 867 | CRS to transform geometries to.  | 
            ||
| 868 | Returns  | 
            ||
| 869 | -------  | 
            ||
| 870 | geopandas.GeoDataFrame  | 
            ||
| 871 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 872 | """  | 
            ||
| 873 | with db.session_scope() as session:  | 
            ||
| 874 | query = session.query(  | 
            ||
| 875 | OsmBuildingsFiltered.id,  | 
            ||
| 876 | OsmBuildingsFiltered.area,  | 
            ||
| 877 |             OsmBuildingsFiltered.geom_point.label("geom"), | 
            ||
| 878 | )  | 
            ||
| 879 | |||
| 880 | return gpd.read_postgis(  | 
            ||
| 881 | query.statement, query.session.bind, index_col="id"  | 
            ||
| 882 | ).to_crs(to_crs)  | 
            ||
| 883 | |||
| 884 | |||
| 885 | @timer_func  | 
            ||
| 886 | def synthetic_buildings(  | 
            ||
| 887 | to_crs: CRS,  | 
            ||
| 888 | ) -> gpd.GeoDataFrame:  | 
            ||
| 889 | """  | 
            ||
| 890 | Read synthetic buildings data from eGo^n Database.  | 
            ||
| 891 | Parameters  | 
            ||
| 892 | -----------  | 
            ||
| 893 | to_crs : pyproj.crs.crs.CRS  | 
            ||
| 894 | CRS to transform geometries to.  | 
            ||
| 895 | Returns  | 
            ||
| 896 | -------  | 
            ||
| 897 | geopandas.GeoDataFrame  | 
            ||
| 898 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 899 | """  | 
            ||
| 900 | with db.session_scope() as session:  | 
            ||
| 901 | query = session.query(  | 
            ||
| 902 | OsmBuildingsSynthetic.id,  | 
            ||
| 903 | OsmBuildingsSynthetic.area,  | 
            ||
| 904 |             OsmBuildingsSynthetic.geom_point.label("geom"), | 
            ||
| 905 | )  | 
            ||
| 906 | |||
| 907 | return gpd.read_postgis(  | 
            ||
| 908 | query.statement, query.session.bind, index_col="id"  | 
            ||
| 909 | ).to_crs(to_crs)  | 
            ||
| 910 | |||
| 911 | |||
| 912 | @timer_func  | 
            ||
| 913 | def add_ags_to_buildings(  | 
            ||
| 914 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 915 | municipalities_gdf: gpd.GeoDataFrame,  | 
            ||
| 916 | ) -> gpd.GeoDataFrame:  | 
            ||
| 917 | """  | 
            ||
| 918 | Add information about AGS ID to buildings.  | 
            ||
| 919 | Parameters  | 
            ||
| 920 | -----------  | 
            ||
| 921 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 922 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 923 | municipalities_gdf : geopandas.GeoDataFrame  | 
            ||
| 924 | GeoDataFrame with municipality data.  | 
            ||
| 925 | Returns  | 
            ||
| 926 | -------  | 
            ||
| 927 | gepandas.GeoDataFrame  | 
            ||
| 928 | GeoDataFrame containing OSM buildings data  | 
            ||
| 929 | with AGS ID added.  | 
            ||
| 930 | """  | 
            ||
| 931 | return buildings_gdf.sjoin(  | 
            ||
| 932 | municipalities_gdf,  | 
            ||
| 933 | how="left",  | 
            ||
| 934 | predicate="intersects",  | 
            ||
| 935 |     ).rename(columns={"index_right": "ags"}) | 
            ||
| 936 | |||
| 937 | |||
| 938 | def drop_buildings_outside_muns(  | 
            ||
| 939 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 940 | ) -> gpd.GeoDataFrame:  | 
            ||
| 941 | """  | 
            ||
| 942 | Drop all buildings outside of municipalities.  | 
            ||
| 943 | Parameters  | 
            ||
| 944 | -----------  | 
            ||
| 945 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 946 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 947 | Returns  | 
            ||
| 948 | -------  | 
            ||
| 949 | gepandas.GeoDataFrame  | 
            ||
| 950 | GeoDataFrame containing OSM buildings data  | 
            ||
| 951 | with buildings without an AGS ID dropped.  | 
            ||
| 952 | """  | 
            ||
| 953 | gdf = buildings_gdf.loc[~buildings_gdf.ags.isna()]  | 
            ||
| 954 | |||
| 955 | logger.debug(  | 
            ||
| 956 |         f"{len(buildings_gdf) - len(gdf)} " | 
            ||
| 957 |         f"({(len(buildings_gdf) - len(gdf)) / len(buildings_gdf) * 100:g}%) " | 
            ||
| 958 |         f"of {len(buildings_gdf)} values are outside of the municipalities " | 
            ||
| 959 | "and are therefore dropped."  | 
            ||
| 960 | )  | 
            ||
| 961 | |||
| 962 | return gdf  | 
            ||
| 963 | |||
| 964 | |||
| 965 | def egon_building_peak_loads():  | 
            ||
| 966 | sql = """  | 
            ||
| 967 | SELECT building_id  | 
            ||
| 968 | FROM demand.egon_building_electricity_peak_loads  | 
            ||
| 969 | WHERE scenario = 'eGon2035'  | 
            ||
| 970 | """  | 
            ||
| 971 | |||
| 972 | return (  | 
            ||
| 973 | db.select_dataframe(sql).building_id.astype(int).sort_values().unique()  | 
            ||
| 974 | )  | 
            ||
| 975 | |||
| 976 | |||
| 977 | @timer_func  | 
            ||
| 978 | def load_building_data():  | 
            ||
| 979 | """  | 
            ||
| 980 | Read buildings from DB  | 
            ||
| 981 | Tables:  | 
            ||
| 982 | |||
| 983 | * `openstreetmap.osm_buildings_filtered` (from OSM)  | 
            ||
| 984 | * `openstreetmap.osm_buildings_synthetic` (synthetic, created by us)  | 
            ||
| 985 | |||
| 986 | Use column `id` for both as it is unique hence you concat both datasets. If  | 
            ||
| 987 | INCLUDE_SYNTHETIC_BUILDINGS is False synthetic buildings will not be loaded.  | 
            ||
| 988 | |||
| 989 | Returns  | 
            ||
| 990 | -------  | 
            ||
| 991 | gepandas.GeoDataFrame  | 
            ||
| 992 | GeoDataFrame containing OSM buildings data with buildings without an AGS ID  | 
            ||
| 993 | dropped.  | 
            ||
| 994 | """  | 
            ||
| 995 | |||
| 996 | municipalities_gdf = municipality_data()  | 
            ||
| 997 | |||
| 998 | osm_buildings_gdf = osm_buildings(municipalities_gdf.crs)  | 
            ||
| 999 | |||
| 1000 | if INCLUDE_SYNTHETIC_BUILDINGS:  | 
            ||
| 1001 | synthetic_buildings_gdf = synthetic_buildings(municipalities_gdf.crs)  | 
            ||
| 1002 | |||
| 1003 | buildings_gdf = gpd.GeoDataFrame(  | 
            ||
| 1004 | pd.concat(  | 
            ||
| 1005 | [  | 
            ||
| 1006 | osm_buildings_gdf,  | 
            ||
| 1007 | synthetic_buildings_gdf,  | 
            ||
| 1008 | ]  | 
            ||
| 1009 | ),  | 
            ||
| 1010 | geometry="geom",  | 
            ||
| 1011 | crs=osm_buildings_gdf.crs,  | 
            ||
| 1012 |         ).rename(columns={"area": "building_area"}) | 
            ||
| 1013 | |||
| 1014 | buildings_gdf.index = buildings_gdf.index.astype(int)  | 
            ||
| 1015 | |||
| 1016 | else:  | 
            ||
| 1017 | buildings_gdf = osm_buildings_gdf.rename(  | 
            ||
| 1018 |             columns={"area": "building_area"} | 
            ||
| 1019 | )  | 
            ||
| 1020 | |||
| 1021 | if ONLY_BUILDINGS_WITH_DEMAND:  | 
            ||
| 1022 | building_ids = egon_building_peak_loads()  | 
            ||
| 1023 | |||
| 1024 | init_len = len(building_ids)  | 
            ||
| 1025 | |||
| 1026 | building_ids = np.intersect1d(  | 
            ||
| 1027 | list(map(int, building_ids)),  | 
            ||
| 1028 | list(map(int, buildings_gdf.index.to_numpy())),  | 
            ||
| 1029 | )  | 
            ||
| 1030 | |||
| 1031 | end_len = len(building_ids)  | 
            ||
| 1032 | |||
| 1033 | logger.debug(  | 
            ||
| 1034 |             f"{end_len/init_len * 100: g} % ({end_len} / {init_len}) of buildings have " | 
            ||
| 1035 | f"peak load."  | 
            ||
| 1036 | )  | 
            ||
| 1037 | |||
| 1038 | buildings_gdf = buildings_gdf.loc[building_ids]  | 
            ||
| 1039 | |||
| 1040 | buildings_ags_gdf = add_ags_to_buildings(buildings_gdf, municipalities_gdf)  | 
            ||
| 1041 | |||
| 1042 | buildings_ags_gdf = drop_buildings_outside_muns(buildings_ags_gdf)  | 
            ||
| 1043 | |||
| 1044 | grid_districts_gdf = grid_districts(EPSG)  | 
            ||
| 1045 | |||
| 1046 | federal_state_gdf = federal_state_data(grid_districts_gdf.crs)  | 
            ||
| 1047 | |||
| 1048 | grid_federal_state_gdf = overlay_grid_districts_with_counties(  | 
            ||
| 1049 | grid_districts_gdf,  | 
            ||
| 1050 | federal_state_gdf,  | 
            ||
| 1051 | )  | 
            ||
| 1052 | |||
| 1053 | buildings_overlay_gdf = add_overlay_id_to_buildings(  | 
            ||
| 1054 | buildings_ags_gdf,  | 
            ||
| 1055 | grid_federal_state_gdf,  | 
            ||
| 1056 | )  | 
            ||
| 1057 | |||
| 1058 |     logger.debug("Loaded buildings.") | 
            ||
| 1059 | |||
| 1060 | buildings_overlay_gdf = drop_buildings_outside_grids(buildings_overlay_gdf)  | 
            ||
| 1061 | |||
| 1062 | # overwrite bus_id with data from new table  | 
            ||
| 1063 | sql = "SELECT building_id, bus_id FROM boundaries.egon_map_zensus_mvgd_buildings"  | 
            ||
| 1064 | map_building_bus_df = db.select_dataframe(sql)  | 
            ||
| 1065 | |||
| 1066 | building_ids = np.intersect1d(  | 
            ||
| 1067 | list(map(int, map_building_bus_df.building_id.unique())),  | 
            ||
| 1068 | list(map(int, buildings_overlay_gdf.index.to_numpy())),  | 
            ||
| 1069 | )  | 
            ||
| 1070 | |||
| 1071 | buildings_within_gdf = buildings_overlay_gdf.loc[building_ids]  | 
            ||
| 1072 | |||
| 1073 | gdf = (  | 
            ||
| 1074 | buildings_within_gdf.reset_index()  | 
            ||
| 1075 | .drop(columns=["bus_id"])  | 
            ||
| 1076 | .merge(  | 
            ||
| 1077 | how="left",  | 
            ||
| 1078 | right=map_building_bus_df,  | 
            ||
| 1079 | left_on="id",  | 
            ||
| 1080 | right_on="building_id",  | 
            ||
| 1081 | )  | 
            ||
| 1082 | .drop(columns=["building_id"])  | 
            ||
| 1083 |         .set_index("id") | 
            ||
| 1084 | .sort_index()  | 
            ||
| 1085 | )  | 
            ||
| 1086 | |||
| 1087 | return gdf[~gdf.index.duplicated(keep="first")]  | 
            ||
| 1088 | |||
| 1089 | |||
| 1090 | @timer_func  | 
            ||
| 1091 | def sort_and_qcut_df(  | 
            ||
| 1092 | df: pd.DataFrame | gpd.GeoDataFrame,  | 
            ||
| 1093 | col: str,  | 
            ||
| 1094 | q: int,  | 
            ||
| 1095 | ) -> pd.DataFrame | gpd.GeoDataFrame:  | 
            ||
| 1096 | """  | 
            ||
| 1097 | Determine the quantile of a given attribute in a (Geo)DataFrame.  | 
            ||
| 1098 | Sort the (Geo)DataFrame in ascending order for the given attribute.  | 
            ||
| 1099 | Parameters  | 
            ||
| 1100 | -----------  | 
            ||
| 1101 | df : pandas.DataFrame or geopandas.GeoDataFrame  | 
            ||
| 1102 | (Geo)DataFrame to sort and qcut.  | 
            ||
| 1103 | col : str  | 
            ||
| 1104 | Name of the attribute to sort and qcut the (Geo)DataFrame on.  | 
            ||
| 1105 | q : int  | 
            ||
| 1106 | Number of quantiles.  | 
            ||
| 1107 | Returns  | 
            ||
| 1108 | -------  | 
            ||
| 1109 | pandas.DataFrame or gepandas.GeoDataFrame  | 
            ||
| 1110 | Sorted and qcut (Geo)DataFrame.  | 
            ||
| 1111 | """  | 
            ||
| 1112 | df = df.sort_values(col, ascending=True)  | 
            ||
| 1113 | |||
| 1114 | return df.assign(  | 
            ||
| 1115 | quant=pd.qcut(  | 
            ||
| 1116 | df[col],  | 
            ||
| 1117 | q=q,  | 
            ||
| 1118 | labels=range(q),  | 
            ||
| 1119 | )  | 
            ||
| 1120 | )  | 
            ||
| 1121 | |||
| 1122 | |||
| 1123 | @timer_func  | 
            ||
| 1124 | def allocate_pv(  | 
            ||
| 1125 | q_mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1126 | q_buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 1127 | seed: int,  | 
            ||
| 1128 | ) -> tuple[gpd.GeoDataFrame, gpd.GeoDataFrame]:  | 
            ||
| 1129 | """  | 
            ||
| 1130 | Allocate the MaStR pv generators to the OSM buildings.  | 
            ||
| 1131 | This will determine a building for each pv generator if there are more  | 
            ||
| 1132 | buildings than generators within a given AGS. Primarily generators are  | 
            ||
| 1133 | distributed with the same qunatile as the buildings. Multiple assignment  | 
            ||
| 1134 | is excluded.  | 
            ||
| 1135 | Parameters  | 
            ||
| 1136 | -----------  | 
            ||
| 1137 | q_mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1138 | GeoDataFrame containing geocoded and qcut MaStR data.  | 
            ||
| 1139 | q_buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 1140 | GeoDataFrame containing qcut OSM buildings data.  | 
            ||
| 1141 | seed : int  | 
            ||
| 1142 | Seed to use for random operations with NumPy and pandas.  | 
            ||
| 1143 | Returns  | 
            ||
| 1144 | -------  | 
            ||
| 1145 | tuple with two geopandas.GeoDataFrame s  | 
            ||
| 1146 | GeoDataFrame containing MaStR data allocated to building IDs.  | 
            ||
| 1147 | GeoDataFrame containing building data allocated to MaStR IDs.  | 
            ||
| 1148 | """  | 
            ||
| 1149 | rng = default_rng(seed=seed)  | 
            ||
| 1150 | |||
| 1151 | q_buildings_gdf = q_buildings_gdf.assign(gens_id=np.nan)  | 
            ||
| 1152 | q_mastr_gdf = q_mastr_gdf.assign(building_id=np.nan)  | 
            ||
| 1153 | |||
| 1154 | ags_list = q_buildings_gdf.ags.unique()  | 
            ||
| 1155 | |||
| 1156 | if TEST_RUN:  | 
            ||
| 1157 | ags_list = ags_list[:250]  | 
            ||
| 1158 | |||
| 1159 | num_ags = len(ags_list)  | 
            ||
| 1160 | |||
| 1161 | t0 = perf_counter()  | 
            ||
| 1162 | |||
| 1163 | for count, ags in enumerate(ags_list):  | 
            ||
| 1164 | |||
| 1165 | buildings = q_buildings_gdf.loc[  | 
            ||
| 1166 | (q_buildings_gdf.ags == ags) & (q_buildings_gdf.gens_id.isna())  | 
            ||
| 1167 | ]  | 
            ||
| 1168 | gens = q_mastr_gdf.loc[  | 
            ||
| 1169 | (q_mastr_gdf.ags == ags) & (q_mastr_gdf.building_id.isna())  | 
            ||
| 1170 | ]  | 
            ||
| 1171 | |||
| 1172 | len_build = len(buildings)  | 
            ||
| 1173 | len_gens = len(gens)  | 
            ||
| 1174 | |||
| 1175 | if len_build < len_gens:  | 
            ||
| 1176 | gens = gens.sample(len_build, random_state=RandomState(seed=seed))  | 
            ||
| 1177 | logger.error(  | 
            ||
| 1178 |                 f"There are {len_gens} generators and only {len_build}" | 
            ||
| 1179 |                 f" buildings in AGS {ags}. {len_gens - len(gens)} " | 
            ||
| 1180 | "generators were truncated to match the amount of buildings."  | 
            ||
| 1181 | )  | 
            ||
| 1182 | |||
| 1183 | assert len_build == len(gens)  | 
            ||
| 1184 | |||
| 1185 | for quant in gens.quant.unique():  | 
            ||
| 1186 | q_buildings = buildings.loc[  | 
            ||
| 1187 | (buildings.quant == quant) & (buildings.gens_id.isna())  | 
            ||
| 1188 | ]  | 
            ||
| 1189 | q_gens = gens.loc[gens.quant == quant]  | 
            ||
| 1190 | |||
| 1191 | len_build = len(q_buildings)  | 
            ||
| 1192 | len_gens = len(q_gens)  | 
            ||
| 1193 | |||
| 1194 | if len_build < len_gens:  | 
            ||
| 1195 | delta = len_gens - len_build  | 
            ||
| 1196 | |||
| 1197 | logger.warning(  | 
            ||
| 1198 |                     f"There are {len_gens} generators and only {len_build} " | 
            ||
| 1199 |                     f"buildings in AGS {ags} and quantile {quant}. {delta} " | 
            ||
| 1200 |                     f"buildings from AGS {ags} will be added randomly." | 
            ||
| 1201 | )  | 
            ||
| 1202 | |||
| 1203 | add_buildings = pd.Index(  | 
            ||
| 1204 | rng.choice(  | 
            ||
| 1205 | buildings.loc[  | 
            ||
| 1206 | (buildings.quant != quant)  | 
            ||
| 1207 | & (buildings.gens_id.isna())  | 
            ||
| 1208 | ].index,  | 
            ||
| 1209 | size=delta,  | 
            ||
| 1210 | replace=False,  | 
            ||
| 1211 | )  | 
            ||
| 1212 | )  | 
            ||
| 1213 | |||
| 1214 | q_buildings = buildings.loc[  | 
            ||
| 1215 | q_buildings.index.append(add_buildings)  | 
            ||
| 1216 | ]  | 
            ||
| 1217 | |||
| 1218 | assert len(q_buildings) == len_gens  | 
            ||
| 1219 | |||
| 1220 | chosen_buildings = pd.Index(  | 
            ||
| 1221 | rng.choice(  | 
            ||
| 1222 | q_buildings.index,  | 
            ||
| 1223 | size=len_gens,  | 
            ||
| 1224 | replace=False,  | 
            ||
| 1225 | )  | 
            ||
| 1226 | )  | 
            ||
| 1227 | |||
| 1228 | q_mastr_gdf.loc[q_gens.index, "building_id"] = chosen_buildings  | 
            ||
| 1229 | q_buildings_gdf.loc[chosen_buildings, "gens_id"] = q_gens.index  | 
            ||
| 1230 | |||
| 1231 | if count % 100 == 0:  | 
            ||
| 1232 | logger.debug(  | 
            ||
| 1233 |                 f"Allocation of {count / num_ags * 100:g} % of AGS done. It took " | 
            ||
| 1234 |                 f"{perf_counter() - t0:g} seconds." | 
            ||
| 1235 | )  | 
            ||
| 1236 | |||
| 1237 | t0 = perf_counter()  | 
            ||
| 1238 | |||
| 1239 | assigned_buildings = q_buildings_gdf.loc[~q_buildings_gdf.gens_id.isna()]  | 
            ||
| 1240 | |||
| 1241 | q_mastr_gdf.loc[  | 
            ||
| 1242 | assigned_buildings.gens_id, "building_id"  | 
            ||
| 1243 | ] = assigned_buildings.index  | 
            ||
| 1244 | |||
| 1245 |     logger.debug("Allocated status quo generators to buildings.") | 
            ||
| 1246 | |||
| 1247 | return frame_to_numeric(q_mastr_gdf), frame_to_numeric(q_buildings_gdf)  | 
            ||
| 1248 | |||
| 1249 | |||
| 1250 | def frame_to_numeric(  | 
            ||
| 1251 | df: pd.DataFrame | gpd.GeoDataFrame,  | 
            ||
| 1252 | ) -> pd.DataFrame | gpd.GeoDataFrame:  | 
            ||
| 1253 | """  | 
            ||
| 1254 | Try to convert all columns of a DataFrame to numeric ignoring errors.  | 
            ||
| 1255 | Parameters  | 
            ||
| 1256 | ----------  | 
            ||
| 1257 | df : pandas.DataFrame or geopandas.GeoDataFrame  | 
            ||
| 1258 | Returns  | 
            ||
| 1259 | -------  | 
            ||
| 1260 | pandas.DataFrame or geopandas.GeoDataFrame  | 
            ||
| 1261 | """  | 
            ||
| 1262 | if str(df.index.dtype) == "object":  | 
            ||
| 1263 | df.index = pd.to_numeric(df.index, errors="ignore")  | 
            ||
| 1264 | |||
| 1265 | for col in df.columns:  | 
            ||
| 1266 | if str(df[col].dtype) == "object":  | 
            ||
| 1267 | df[col] = pd.to_numeric(df[col], errors="ignore")  | 
            ||
| 1268 | |||
| 1269 | return df  | 
            ||
| 1270 | |||
| 1271 | |||
| 1272 | def validate_output(  | 
            ||
| 1273 | desagg_mastr_gdf: pd.DataFrame | gpd.GeoDataFrame,  | 
            ||
| 1274 | desagg_buildings_gdf: pd.DataFrame | gpd.GeoDataFrame,  | 
            ||
| 1275 | ) -> None:  | 
            ||
| 1276 | """  | 
            ||
| 1277 | Validate output.  | 
            ||
| 1278 | |||
| 1279 | * Validate that there are exactly as many buildings with a pv system as there are  | 
            ||
| 1280 | pv systems with a building  | 
            ||
| 1281 | * Validate that the building IDs with a pv system are the same building IDs as  | 
            ||
| 1282 | assigned to the pv systems  | 
            ||
| 1283 | * Validate that the pv system IDs with a building are the same pv system IDs as  | 
            ||
| 1284 | assigned to the buildings  | 
            ||
| 1285 | |||
| 1286 | Parameters  | 
            ||
| 1287 | -----------  | 
            ||
| 1288 | desagg_mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1289 | GeoDataFrame containing MaStR data allocated to building IDs.  | 
            ||
| 1290 | desagg_buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 1291 | GeoDataFrame containing building data allocated to MaStR IDs.  | 
            ||
| 1292 | """  | 
            ||
| 1293 | assert len(  | 
            ||
| 1294 | desagg_mastr_gdf.loc[~desagg_mastr_gdf.building_id.isna()]  | 
            ||
| 1295 | ) == len(desagg_buildings_gdf.loc[~desagg_buildings_gdf.gens_id.isna()])  | 
            ||
| 1296 | assert (  | 
            ||
| 1297 | np.sort(  | 
            ||
| 1298 | desagg_mastr_gdf.loc[  | 
            ||
| 1299 | ~desagg_mastr_gdf.building_id.isna()  | 
            ||
| 1300 | ].building_id.unique()  | 
            ||
| 1301 | )  | 
            ||
| 1302 | == np.sort(  | 
            ||
| 1303 | desagg_buildings_gdf.loc[  | 
            ||
| 1304 | ~desagg_buildings_gdf.gens_id.isna()  | 
            ||
| 1305 | ].index.unique()  | 
            ||
| 1306 | )  | 
            ||
| 1307 | ).all()  | 
            ||
| 1308 | assert (  | 
            ||
| 1309 | np.sort(  | 
            ||
| 1310 | desagg_mastr_gdf.loc[  | 
            ||
| 1311 | ~desagg_mastr_gdf.building_id.isna()  | 
            ||
| 1312 | ].index.unique()  | 
            ||
| 1313 | )  | 
            ||
| 1314 | == np.sort(  | 
            ||
| 1315 | desagg_buildings_gdf.loc[  | 
            ||
| 1316 | ~desagg_buildings_gdf.gens_id.isna()  | 
            ||
| 1317 | ].gens_id.unique()  | 
            ||
| 1318 | )  | 
            ||
| 1319 | ).all()  | 
            ||
| 1320 | |||
| 1321 |     logger.debug("Validated output.") | 
            ||
| 1322 | |||
| 1323 | |||
| 1324 | def drop_unallocated_gens(  | 
            ||
| 1325 | gdf: gpd.GeoDataFrame,  | 
            ||
| 1326 | ) -> gpd.GeoDataFrame:  | 
            ||
| 1327 | """  | 
            ||
| 1328 | Drop generators which did not get allocated.  | 
            ||
| 1329 | |||
| 1330 | Parameters  | 
            ||
| 1331 | -----------  | 
            ||
| 1332 | gdf : geopandas.GeoDataFrame  | 
            ||
| 1333 | GeoDataFrame containing MaStR data allocated to building IDs.  | 
            ||
| 1334 | Returns  | 
            ||
| 1335 | -------  | 
            ||
| 1336 | geopandas.GeoDataFrame  | 
            ||
| 1337 | GeoDataFrame containing MaStR data with generators dropped which did not get  | 
            ||
| 1338 | allocated.  | 
            ||
| 1339 | """  | 
            ||
| 1340 | init_len = len(gdf)  | 
            ||
| 1341 | gdf = gdf.loc[~gdf.building_id.isna()]  | 
            ||
| 1342 | end_len = len(gdf)  | 
            ||
| 1343 | |||
| 1344 | logger.debug(  | 
            ||
| 1345 |         f"Dropped {init_len - end_len} " | 
            ||
| 1346 |         f"({((init_len - end_len) / init_len) * 100:g}%)" | 
            ||
| 1347 |         f" of {init_len} unallocated rows from MaStR DataFrame." | 
            ||
| 1348 | )  | 
            ||
| 1349 | |||
| 1350 | return gdf  | 
            ||
| 1351 | |||
| 1352 | |||
| 1353 | @timer_func  | 
            ||
| 1354 | def allocate_to_buildings(  | 
            ||
| 1355 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1356 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 1357 | ) -> tuple[gpd.GeoDataFrame, gpd.GeoDataFrame]:  | 
            ||
| 1358 | """  | 
            ||
| 1359 | Allocate status quo pv rooftop generators to buildings.  | 
            ||
| 1360 | Parameters  | 
            ||
| 1361 | -----------  | 
            ||
| 1362 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1363 | GeoDataFrame containing MaStR data with geocoded locations.  | 
            ||
| 1364 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 1365 | GeoDataFrame containing OSM buildings data with buildings without an AGS ID  | 
            ||
| 1366 | dropped.  | 
            ||
| 1367 | Returns  | 
            ||
| 1368 | -------  | 
            ||
| 1369 | tuple with two geopandas.GeoDataFrame s  | 
            ||
| 1370 | GeoDataFrame containing MaStR data allocated to building IDs.  | 
            ||
| 1371 | GeoDataFrame containing building data allocated to MaStR IDs.  | 
            ||
| 1372 | """  | 
            ||
| 1373 |     logger.debug("Starting allocation of status quo.") | 
            ||
| 1374 | |||
| 1375 | q_mastr_gdf = sort_and_qcut_df(mastr_gdf, col="capacity", q=Q)  | 
            ||
| 1376 | q_buildings_gdf = sort_and_qcut_df(buildings_gdf, col="building_area", q=Q)  | 
            ||
| 1377 | |||
| 1378 | desagg_mastr_gdf, desagg_buildings_gdf = allocate_pv(  | 
            ||
| 1379 | q_mastr_gdf, q_buildings_gdf, SEED  | 
            ||
| 1380 | )  | 
            ||
| 1381 | |||
| 1382 | validate_output(desagg_mastr_gdf, desagg_buildings_gdf)  | 
            ||
| 1383 | |||
| 1384 | return drop_unallocated_gens(desagg_mastr_gdf), desagg_buildings_gdf  | 
            ||
| 1385 | |||
| 1386 | |||
| 1387 | @timer_func  | 
            ||
| 1388 | def grid_districts(  | 
            ||
| 1389 | epsg: int,  | 
            ||
| 1390 | ) -> gpd.GeoDataFrame:  | 
            ||
| 1391 | """  | 
            ||
| 1392 | Load mv grid district geo data from eGo^n Database as  | 
            ||
| 1393 | geopandas.GeoDataFrame.  | 
            ||
| 1394 | Parameters  | 
            ||
| 1395 | -----------  | 
            ||
| 1396 | epsg : int  | 
            ||
| 1397 | EPSG ID to use as CRS.  | 
            ||
| 1398 | Returns  | 
            ||
| 1399 | -------  | 
            ||
| 1400 | geopandas.GeoDataFrame  | 
            ||
| 1401 | GeoDataFrame containing mv grid district ID and geo shapes data.  | 
            ||
| 1402 | """  | 
            ||
| 1403 | gdf = db.select_geodataframe(  | 
            ||
| 1404 | """  | 
            ||
| 1405 | SELECT bus_id, geom  | 
            ||
| 1406 | FROM grid.egon_mv_grid_district  | 
            ||
| 1407 | ORDER BY bus_id  | 
            ||
| 1408 | """,  | 
            ||
| 1409 | index_col="bus_id",  | 
            ||
| 1410 | geom_col="geom",  | 
            ||
| 1411 | epsg=epsg,  | 
            ||
| 1412 | )  | 
            ||
| 1413 | |||
| 1414 | gdf.index = gdf.index.astype(int)  | 
            ||
| 1415 | |||
| 1416 |     logger.debug("Grid districts loaded.") | 
            ||
| 1417 | |||
| 1418 | return gdf  | 
            ||
| 1419 | |||
| 1420 | |||
| 1421 | def scenario_data(  | 
            ||
| 1422 | carrier: str = "solar_rooftop",  | 
            ||
| 1423 | scenario: str = "eGon2035",  | 
            ||
| 1424 | ) -> pd.DataFrame:  | 
            ||
| 1425 | """  | 
            ||
| 1426 | Get scenario capacity data from eGo^n Database.  | 
            ||
| 1427 | Parameters  | 
            ||
| 1428 | -----------  | 
            ||
| 1429 | carrier : str  | 
            ||
| 1430 | Carrier type to filter table by.  | 
            ||
| 1431 | scenario : str  | 
            ||
| 1432 | Scenario to filter table by.  | 
            ||
| 1433 | Returns  | 
            ||
| 1434 | -------  | 
            ||
| 1435 | geopandas.GeoDataFrame  | 
            ||
| 1436 | GeoDataFrame with scenario capacity data in GW.  | 
            ||
| 1437 | """  | 
            ||
| 1438 | with db.session_scope() as session:  | 
            ||
| 1439 | query = session.query(EgonScenarioCapacities).filter(  | 
            ||
| 1440 | EgonScenarioCapacities.carrier == carrier,  | 
            ||
| 1441 | EgonScenarioCapacities.scenario_name == scenario,  | 
            ||
| 1442 | )  | 
            ||
| 1443 | |||
| 1444 | df = pd.read_sql(  | 
            ||
| 1445 | query.statement, query.session.bind, index_col="index"  | 
            ||
| 1446 | ).sort_index()  | 
            ||
| 1447 | |||
| 1448 |     logger.debug("Scenario capacity data loaded.") | 
            ||
| 1449 | |||
| 1450 | return df  | 
            ||
| 1451 | |||
| 1452 | |||
| 1453 | View Code Duplication | class Vg250Lan(Base):  | 
            |
| 
                                                                                                    
                        
                         | 
                |||
| 1454 | __tablename__ = "vg250_lan"  | 
            ||
| 1455 |     __table_args__ = {"schema": "boundaries"} | 
            ||
| 1456 | |||
| 1457 | id = Column(BigInteger, primary_key=True, index=True)  | 
            ||
| 1458 | ade = Column(BigInteger)  | 
            ||
| 1459 | gf = Column(BigInteger)  | 
            ||
| 1460 | bsg = Column(BigInteger)  | 
            ||
| 1461 | ars = Column(String)  | 
            ||
| 1462 | ags = Column(String)  | 
            ||
| 1463 | sdv_ars = Column(String)  | 
            ||
| 1464 | gen = Column(String)  | 
            ||
| 1465 | bez = Column(String)  | 
            ||
| 1466 | ibz = Column(BigInteger)  | 
            ||
| 1467 | bem = Column(String)  | 
            ||
| 1468 | nbd = Column(String)  | 
            ||
| 1469 | sn_l = Column(String)  | 
            ||
| 1470 | sn_r = Column(String)  | 
            ||
| 1471 | sn_k = Column(String)  | 
            ||
| 1472 | sn_v1 = Column(String)  | 
            ||
| 1473 | sn_v2 = Column(String)  | 
            ||
| 1474 | sn_g = Column(String)  | 
            ||
| 1475 | fk_s3 = Column(String)  | 
            ||
| 1476 | nuts = Column(String)  | 
            ||
| 1477 | ars_0 = Column(String)  | 
            ||
| 1478 | ags_0 = Column(String)  | 
            ||
| 1479 | wsk = Column(String)  | 
            ||
| 1480 | debkg_id = Column(String)  | 
            ||
| 1481 | rs = Column(String)  | 
            ||
| 1482 | sdv_rs = Column(String)  | 
            ||
| 1483 | rs_0 = Column(String)  | 
            ||
| 1484 | geometry = Column(Geometry(srid=EPSG), index=True)  | 
            ||
| 1485 | |||
| 1486 | |||
| 1487 | def federal_state_data(to_crs: CRS) -> gpd.GeoDataFrame:  | 
            ||
| 1488 | """  | 
            ||
| 1489 | Get feder state data from eGo^n Database.  | 
            ||
| 1490 | Parameters  | 
            ||
| 1491 | -----------  | 
            ||
| 1492 | to_crs : pyproj.crs.crs.CRS  | 
            ||
| 1493 | CRS to transform geometries to.  | 
            ||
| 1494 | Returns  | 
            ||
| 1495 | -------  | 
            ||
| 1496 | geopandas.GeoDataFrame  | 
            ||
| 1497 | GeoDataFrame with federal state data.  | 
            ||
| 1498 | """  | 
            ||
| 1499 | with db.session_scope() as session:  | 
            ||
| 1500 | query = session.query(  | 
            ||
| 1501 |             Vg250Lan.id, Vg250Lan.nuts, Vg250Lan.geometry.label("geom") | 
            ||
| 1502 | )  | 
            ||
| 1503 | |||
| 1504 | gdf = gpd.read_postgis(  | 
            ||
| 1505 | query.statement, session.connection(), index_col="id"  | 
            ||
| 1506 | ).to_crs(to_crs)  | 
            ||
| 1507 | |||
| 1508 |     logger.debug("Federal State data loaded.") | 
            ||
| 1509 | |||
| 1510 | return gdf  | 
            ||
| 1511 | |||
| 1512 | |||
| 1513 | @timer_func  | 
            ||
| 1514 | def overlay_grid_districts_with_counties(  | 
            ||
| 1515 | mv_grid_district_gdf: gpd.GeoDataFrame,  | 
            ||
| 1516 | federal_state_gdf: gpd.GeoDataFrame,  | 
            ||
| 1517 | ) -> gpd.GeoDataFrame:  | 
            ||
| 1518 | """  | 
            ||
| 1519 | Calculate the intersections of mv grid districts and counties.  | 
            ||
| 1520 | Parameters  | 
            ||
| 1521 | -----------  | 
            ||
| 1522 | mv_grid_district_gdf : gpd.GeoDataFrame  | 
            ||
| 1523 | GeoDataFrame containing mv grid district ID and geo shapes data.  | 
            ||
| 1524 | federal_state_gdf : gpd.GeoDataFrame  | 
            ||
| 1525 | GeoDataFrame with federal state data.  | 
            ||
| 1526 | Returns  | 
            ||
| 1527 | -------  | 
            ||
| 1528 | geopandas.GeoDataFrame  | 
            ||
| 1529 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 1530 | """  | 
            ||
| 1531 | logger.debug(  | 
            ||
| 1532 | "Calculating intersection overlay between mv grid districts and "  | 
            ||
| 1533 | "counties. This may take a while..."  | 
            ||
| 1534 | )  | 
            ||
| 1535 | |||
| 1536 | gdf = gpd.overlay(  | 
            ||
| 1537 | federal_state_gdf.to_crs(mv_grid_district_gdf.crs),  | 
            ||
| 1538 | mv_grid_district_gdf.reset_index(),  | 
            ||
| 1539 | how="intersection",  | 
            ||
| 1540 | keep_geom_type=True,  | 
            ||
| 1541 | )  | 
            ||
| 1542 | |||
| 1543 |     logger.debug("Done!") | 
            ||
| 1544 | |||
| 1545 | return gdf  | 
            ||
| 1546 | |||
| 1547 | |||
| 1548 | @timer_func  | 
            ||
| 1549 | def add_overlay_id_to_buildings(  | 
            ||
| 1550 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 1551 | grid_federal_state_gdf: gpd.GeoDataFrame,  | 
            ||
| 1552 | ) -> gpd.GeoDataFrame:  | 
            ||
| 1553 | """  | 
            ||
| 1554 | Add information about overlay ID to buildings.  | 
            ||
| 1555 | Parameters  | 
            ||
| 1556 | -----------  | 
            ||
| 1557 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 1558 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 1559 | grid_federal_state_gdf : geopandas.GeoDataFrame  | 
            ||
| 1560 | GeoDataFrame with intersection shapes between counties and grid districts.  | 
            ||
| 1561 | Returns  | 
            ||
| 1562 | -------  | 
            ||
| 1563 | geopandas.GeoDataFrame  | 
            ||
| 1564 | GeoDataFrame containing OSM buildings data with overlay ID added.  | 
            ||
| 1565 | """  | 
            ||
| 1566 | gdf = (  | 
            ||
| 1567 | buildings_gdf.to_crs(grid_federal_state_gdf.crs)  | 
            ||
| 1568 | .sjoin(  | 
            ||
| 1569 | grid_federal_state_gdf,  | 
            ||
| 1570 | how="left",  | 
            ||
| 1571 | predicate="intersects",  | 
            ||
| 1572 | )  | 
            ||
| 1573 |         .rename(columns={"index_right": "overlay_id"}) | 
            ||
| 1574 | )  | 
            ||
| 1575 | |||
| 1576 |     logger.debug("Added overlay ID to OSM buildings.") | 
            ||
| 1577 | |||
| 1578 | return gdf  | 
            ||
| 1579 | |||
| 1580 | |||
| 1581 | def drop_buildings_outside_grids(  | 
            ||
| 1582 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 1583 | ) -> gpd.GeoDataFrame:  | 
            ||
| 1584 | """  | 
            ||
| 1585 | Drop all buildings outside of grid areas.  | 
            ||
| 1586 | Parameters  | 
            ||
| 1587 | -----------  | 
            ||
| 1588 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 1589 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 1590 | Returns  | 
            ||
| 1591 | -------  | 
            ||
| 1592 | gepandas.GeoDataFrame  | 
            ||
| 1593 | GeoDataFrame containing OSM buildings data  | 
            ||
| 1594 | with buildings without an bus ID dropped.  | 
            ||
| 1595 | """  | 
            ||
| 1596 | gdf = buildings_gdf.loc[~buildings_gdf.bus_id.isna()]  | 
            ||
| 1597 | |||
| 1598 | logger.debug(  | 
            ||
| 1599 |         f"{len(buildings_gdf) - len(gdf)} " | 
            ||
| 1600 |         f"({(len(buildings_gdf) - len(gdf)) / len(buildings_gdf) * 100:g}%) " | 
            ||
| 1601 |         f"of {len(buildings_gdf)} values are outside of the grid areas " | 
            ||
| 1602 | "and are therefore dropped."  | 
            ||
| 1603 | )  | 
            ||
| 1604 | |||
| 1605 | return gdf  | 
            ||
| 1606 | |||
| 1607 | |||
| 1608 | def cap_per_bus_id(  | 
            ||
| 1609 | scenario: str,  | 
            ||
| 1610 | ) -> pd.DataFrame:  | 
            ||
| 1611 | """  | 
            ||
| 1612 | Get table with total pv rooftop capacity per grid district.  | 
            ||
| 1613 | |||
| 1614 | Parameters  | 
            ||
| 1615 | -----------  | 
            ||
| 1616 | scenario : str  | 
            ||
| 1617 | Scenario name.  | 
            ||
| 1618 | Returns  | 
            ||
| 1619 | -------  | 
            ||
| 1620 | pandas.DataFrame  | 
            ||
| 1621 | DataFrame with total rooftop capacity per mv grid.  | 
            ||
| 1622 | """  | 
            ||
| 1623 | targets = config.datasets()["solar_rooftop"]["targets"]  | 
            ||
| 1624 | |||
| 1625 | sql = f"""  | 
            ||
| 1626 | SELECT bus as bus_id, p_nom as capacity  | 
            ||
| 1627 |     FROM {targets['generators']['schema']}.{targets['generators']['table']} | 
            ||
| 1628 | WHERE carrier = 'solar_rooftop'  | 
            ||
| 1629 |     AND scn_name = '{scenario}' | 
            ||
| 1630 | """  | 
            ||
| 1631 | |||
| 1632 | return db.select_dataframe(sql, index_col="bus_id")  | 
            ||
| 1633 | |||
| 1634 | # overlay_gdf = overlay_gdf.assign(capacity=np.nan)  | 
            ||
| 1635 | #  | 
            ||
| 1636 | # for cap, nuts in scenario_df[["capacity", "nuts"]].itertuples(index=False):  | 
            ||
| 1637 | # nuts_gdf = overlay_gdf.loc[overlay_gdf.nuts == nuts]  | 
            ||
| 1638 | #  | 
            ||
| 1639 | # capacity = nuts_gdf.building_area.multiply(  | 
            ||
| 1640 | # cap / nuts_gdf.building_area.sum()  | 
            ||
| 1641 | # )  | 
            ||
| 1642 | #  | 
            ||
| 1643 | # overlay_gdf.loc[nuts_gdf.index] = overlay_gdf.loc[  | 
            ||
| 1644 | # nuts_gdf.index  | 
            ||
| 1645 | # ].assign(capacity=capacity.multiply(conversion).to_numpy())  | 
            ||
| 1646 | #  | 
            ||
| 1647 |     # return overlay_gdf[["bus_id", "capacity"]].groupby("bus_id").sum() | 
            ||
| 1648 | |||
| 1649 | |||
| 1650 | def determine_end_of_life_gens(  | 
            ||
| 1651 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1652 | scenario_timestamp: pd.Timestamp,  | 
            ||
| 1653 | pv_rooftop_lifetime: pd.Timedelta,  | 
            ||
| 1654 | ) -> gpd.GeoDataFrame:  | 
            ||
| 1655 | """  | 
            ||
| 1656 | Determine if an old PV system has reached its end of life.  | 
            ||
| 1657 | Parameters  | 
            ||
| 1658 | -----------  | 
            ||
| 1659 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1660 | GeoDataFrame containing geocoded MaStR data.  | 
            ||
| 1661 | scenario_timestamp : pandas.Timestamp  | 
            ||
| 1662 | Timestamp at which the scenario takes place.  | 
            ||
| 1663 | pv_rooftop_lifetime : pandas.Timedelta  | 
            ||
| 1664 | Average expected lifetime of PV rooftop systems.  | 
            ||
| 1665 | Returns  | 
            ||
| 1666 | -------  | 
            ||
| 1667 | geopandas.GeoDataFrame  | 
            ||
| 1668 | GeoDataFrame containing geocoded MaStR data and info if the system  | 
            ||
| 1669 | has reached its end of life.  | 
            ||
| 1670 | """  | 
            ||
| 1671 | before = mastr_gdf.capacity.sum()  | 
            ||
| 1672 | |||
| 1673 | mastr_gdf = mastr_gdf.assign(  | 
            ||
| 1674 | age=scenario_timestamp - mastr_gdf.start_up_date  | 
            ||
| 1675 | )  | 
            ||
| 1676 | |||
| 1677 | mastr_gdf = mastr_gdf.assign(  | 
            ||
| 1678 | end_of_life=pv_rooftop_lifetime < mastr_gdf.age  | 
            ||
| 1679 | )  | 
            ||
| 1680 | |||
| 1681 | after = mastr_gdf.loc[~mastr_gdf.end_of_life].capacity.sum()  | 
            ||
| 1682 | |||
| 1683 | logger.debug(  | 
            ||
| 1684 | "Determined if pv rooftop systems reached their end of life.\nTotal capacity: "  | 
            ||
| 1685 |         f"{before}\nActive capacity: {after}" | 
            ||
| 1686 | )  | 
            ||
| 1687 | |||
| 1688 | return mastr_gdf  | 
            ||
| 1689 | |||
| 1690 | |||
| 1691 | def calculate_max_pv_cap_per_building(  | 
            ||
| 1692 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 1693 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1694 | pv_cap_per_sq_m: float | int,  | 
            ||
| 1695 | roof_factor: float | int,  | 
            ||
| 1696 | ) -> gpd.GeoDataFrame:  | 
            ||
| 1697 | """  | 
            ||
| 1698 | Calculate the estimated maximum possible PV capacity per building.  | 
            ||
| 1699 | Parameters  | 
            ||
| 1700 | -----------  | 
            ||
| 1701 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 1702 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 1703 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1704 | GeoDataFrame containing geocoded MaStR data.  | 
            ||
| 1705 | pv_cap_per_sq_m : float, int  | 
            ||
| 1706 | Average expected, installable PV capacity per square meter.  | 
            ||
| 1707 | roof_factor : float, int  | 
            ||
| 1708 | Average for PV usable roof area share.  | 
            ||
| 1709 | Returns  | 
            ||
| 1710 | -------  | 
            ||
| 1711 | geopandas.GeoDataFrame  | 
            ||
| 1712 | GeoDataFrame containing OSM buildings data with estimated maximum PV  | 
            ||
| 1713 | capacity.  | 
            ||
| 1714 | """  | 
            ||
| 1715 | gdf = (  | 
            ||
| 1716 | buildings_gdf.reset_index()  | 
            ||
| 1717 |         .rename(columns={"index": "id"}) | 
            ||
| 1718 | .merge(  | 
            ||
| 1719 | mastr_gdf[  | 
            ||
| 1720 | [  | 
            ||
| 1721 | "capacity",  | 
            ||
| 1722 | "end_of_life",  | 
            ||
| 1723 | "building_id",  | 
            ||
| 1724 | "EinheitlicheAusrichtungUndNeigungswinkel",  | 
            ||
| 1725 | "Hauptausrichtung",  | 
            ||
| 1726 | "HauptausrichtungNeigungswinkel",  | 
            ||
| 1727 | ]  | 
            ||
| 1728 | ],  | 
            ||
| 1729 | how="left",  | 
            ||
| 1730 | left_on="id",  | 
            ||
| 1731 | right_on="building_id",  | 
            ||
| 1732 | )  | 
            ||
| 1733 |         .set_index("id") | 
            ||
| 1734 | .drop(columns="building_id")  | 
            ||
| 1735 | )  | 
            ||
| 1736 | |||
| 1737 | return gdf.assign(  | 
            ||
| 1738 | max_cap=gdf.building_area.multiply(roof_factor * pv_cap_per_sq_m),  | 
            ||
| 1739 | end_of_life=gdf.end_of_life.fillna(True).astype(bool),  | 
            ||
| 1740 | bus_id=gdf.bus_id.astype(int),  | 
            ||
| 1741 | )  | 
            ||
| 1742 | |||
| 1743 | |||
| 1744 | def calculate_building_load_factor(  | 
            ||
| 1745 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1746 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 1747 | rounding: int = 4,  | 
            ||
| 1748 | ) -> gpd.GeoDataFrame:  | 
            ||
| 1749 | """  | 
            ||
| 1750 | Calculate the roof load factor from existing PV systems.  | 
            ||
| 1751 | Parameters  | 
            ||
| 1752 | -----------  | 
            ||
| 1753 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1754 | GeoDataFrame containing geocoded MaStR data.  | 
            ||
| 1755 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 1756 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 1757 | rounding : int  | 
            ||
| 1758 | Rounding to use for load factor.  | 
            ||
| 1759 | Returns  | 
            ||
| 1760 | -------  | 
            ||
| 1761 | geopandas.GeoDataFrame  | 
            ||
| 1762 | GeoDataFrame containing geocoded MaStR data with calculated load factor.  | 
            ||
| 1763 | """  | 
            ||
| 1764 | gdf = mastr_gdf.merge(  | 
            ||
| 1765 | buildings_gdf[["max_cap", "building_area"]]  | 
            ||
| 1766 | .loc[~buildings_gdf["max_cap"].isna()]  | 
            ||
| 1767 | .reset_index(),  | 
            ||
| 1768 | how="left",  | 
            ||
| 1769 | left_on="building_id",  | 
            ||
| 1770 | right_on="id",  | 
            ||
| 1771 |     ).set_index("id") | 
            ||
| 1772 | |||
| 1773 | return gdf.assign(load_factor=(gdf.capacity / gdf.max_cap).round(rounding))  | 
            ||
| 1774 | |||
| 1775 | |||
| 1776 | def get_probability_for_property(  | 
            ||
| 1777 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1778 | cap_range: tuple[int | float, int | float],  | 
            ||
| 1779 | prop: str,  | 
            ||
| 1780 | ) -> tuple[np.array, np.array]:  | 
            ||
| 1781 | """  | 
            ||
| 1782 | Calculate the probability of the different options of a property of the  | 
            ||
| 1783 | existing PV plants.  | 
            ||
| 1784 | Parameters  | 
            ||
| 1785 | -----------  | 
            ||
| 1786 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1787 | GeoDataFrame containing geocoded MaStR data.  | 
            ||
| 1788 | cap_range : tuple(int, int)  | 
            ||
| 1789 | Capacity range of PV plants to look at.  | 
            ||
| 1790 | prop : str  | 
            ||
| 1791 | Property to calculate probabilities for. String needs to be in columns  | 
            ||
| 1792 | of mastr_gdf.  | 
            ||
| 1793 | Returns  | 
            ||
| 1794 | -------  | 
            ||
| 1795 | tuple  | 
            ||
| 1796 | numpy.array  | 
            ||
| 1797 | Unique values of property.  | 
            ||
| 1798 | numpy.array  | 
            ||
| 1799 | Probabilties per unique value.  | 
            ||
| 1800 | """  | 
            ||
| 1801 | cap_range_gdf = mastr_gdf.loc[  | 
            ||
| 1802 | (mastr_gdf.capacity > cap_range[0])  | 
            ||
| 1803 | & (mastr_gdf.capacity <= cap_range[1])  | 
            ||
| 1804 | ]  | 
            ||
| 1805 | |||
| 1806 | if prop == "load_factor":  | 
            ||
| 1807 | cap_range_gdf = cap_range_gdf.loc[cap_range_gdf[prop] <= 1]  | 
            ||
| 1808 | |||
| 1809 | count = Counter(  | 
            ||
| 1810 | cap_range_gdf[prop].loc[  | 
            ||
| 1811 | ~cap_range_gdf[prop].isna()  | 
            ||
| 1812 | & ~cap_range_gdf[prop].isnull()  | 
            ||
| 1813 | & ~(cap_range_gdf[prop] == "None")  | 
            ||
| 1814 | ]  | 
            ||
| 1815 | )  | 
            ||
| 1816 | |||
| 1817 | values = np.array(list(count.keys()))  | 
            ||
| 1818 | probabilities = np.fromiter(count.values(), dtype=float)  | 
            ||
| 1819 | probabilities = probabilities / np.sum(probabilities)  | 
            ||
| 1820 | |||
| 1821 | return values, probabilities  | 
            ||
| 1822 | |||
| 1823 | |||
| 1824 | @timer_func  | 
            ||
| 1825 | def probabilities(  | 
            ||
| 1826 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1827 | cap_ranges: list[tuple[int | float, int | float]] | None = None,  | 
            ||
| 1828 | properties: list[str] | None = None,  | 
            ||
| 1829 | ) -> dict:  | 
            ||
| 1830 | """  | 
            ||
| 1831 | Calculate the probability of the different options of properties of the  | 
            ||
| 1832 | existing PV plants.  | 
            ||
| 1833 | Parameters  | 
            ||
| 1834 | -----------  | 
            ||
| 1835 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1836 | GeoDataFrame containing geocoded MaStR data.  | 
            ||
| 1837 | cap_ranges : list(tuple(int, int))  | 
            ||
| 1838 | List of capacity ranges to distinguish between. The first tuple should  | 
            ||
| 1839 | start with a zero and the last one should end with infinite.  | 
            ||
| 1840 | properties : list(str)  | 
            ||
| 1841 | List of properties to calculate probabilities for. Strings needs to be  | 
            ||
| 1842 | in columns of mastr_gdf.  | 
            ||
| 1843 | Returns  | 
            ||
| 1844 | -------  | 
            ||
| 1845 | dict  | 
            ||
| 1846 | Dictionary with values and probabilities per capacity range.  | 
            ||
| 1847 | """  | 
            ||
| 1848 | if cap_ranges is None:  | 
            ||
| 1849 | cap_ranges = [  | 
            ||
| 1850 | (0, 30),  | 
            ||
| 1851 | (30, 100),  | 
            ||
| 1852 |             (100, float("inf")), | 
            ||
| 1853 | ]  | 
            ||
| 1854 | if properties is None:  | 
            ||
| 1855 | properties = [  | 
            ||
| 1856 | "EinheitlicheAusrichtungUndNeigungswinkel",  | 
            ||
| 1857 | "Hauptausrichtung",  | 
            ||
| 1858 | "HauptausrichtungNeigungswinkel",  | 
            ||
| 1859 | "load_factor",  | 
            ||
| 1860 | ]  | 
            ||
| 1861 | |||
| 1862 |     prob_dict = {} | 
            ||
| 1863 | |||
| 1864 | for cap_range in cap_ranges:  | 
            ||
| 1865 |         prob_dict[cap_range] = { | 
            ||
| 1866 |             "values": {}, | 
            ||
| 1867 |             "probabilities": {}, | 
            ||
| 1868 | }  | 
            ||
| 1869 | |||
| 1870 | for prop in properties:  | 
            ||
| 1871 | v, p = get_probability_for_property(  | 
            ||
| 1872 | mastr_gdf,  | 
            ||
| 1873 | cap_range,  | 
            ||
| 1874 | prop,  | 
            ||
| 1875 | )  | 
            ||
| 1876 | |||
| 1877 | prob_dict[cap_range]["values"][prop] = v  | 
            ||
| 1878 | prob_dict[cap_range]["probabilities"][prop] = p  | 
            ||
| 1879 | |||
| 1880 | return prob_dict  | 
            ||
| 1881 | |||
| 1882 | |||
| 1883 | def cap_share_per_cap_range(  | 
            ||
| 1884 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1885 | cap_ranges: list[tuple[int | float, int | float]] | None = None,  | 
            ||
| 1886 | ) -> dict[tuple[int | float, int | float], float]:  | 
            ||
| 1887 | """  | 
            ||
| 1888 | Calculate the share of PV capacity from the total PV capacity within  | 
            ||
| 1889 | capacity ranges.  | 
            ||
| 1890 | Parameters  | 
            ||
| 1891 | -----------  | 
            ||
| 1892 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1893 | GeoDataFrame containing geocoded MaStR data.  | 
            ||
| 1894 | cap_ranges : list(tuple(int, int))  | 
            ||
| 1895 | List of capacity ranges to distinguish between. The first tuple should  | 
            ||
| 1896 | start with a zero and the last one should end with infinite.  | 
            ||
| 1897 | Returns  | 
            ||
| 1898 | -------  | 
            ||
| 1899 | dict  | 
            ||
| 1900 | Dictionary with share of PV capacity from the total PV capacity within  | 
            ||
| 1901 | capacity ranges.  | 
            ||
| 1902 | """  | 
            ||
| 1903 | if cap_ranges is None:  | 
            ||
| 1904 | cap_ranges = [  | 
            ||
| 1905 | (0, 30),  | 
            ||
| 1906 | (30, 100),  | 
            ||
| 1907 |             (100, float("inf")), | 
            ||
| 1908 | ]  | 
            ||
| 1909 | |||
| 1910 |     cap_share_dict = {} | 
            ||
| 1911 | |||
| 1912 | total_cap = mastr_gdf.capacity.sum()  | 
            ||
| 1913 | |||
| 1914 | for cap_range in cap_ranges:  | 
            ||
| 1915 | cap_share = (  | 
            ||
| 1916 | mastr_gdf.loc[  | 
            ||
| 1917 | (mastr_gdf.capacity > cap_range[0])  | 
            ||
| 1918 | & (mastr_gdf.capacity <= cap_range[1])  | 
            ||
| 1919 | ].capacity.sum()  | 
            ||
| 1920 | / total_cap  | 
            ||
| 1921 | )  | 
            ||
| 1922 | |||
| 1923 | cap_share_dict[cap_range] = cap_share  | 
            ||
| 1924 | |||
| 1925 | return cap_share_dict  | 
            ||
| 1926 | |||
| 1927 | |||
| 1928 | def mean_load_factor_per_cap_range(  | 
            ||
| 1929 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1930 | cap_ranges: list[tuple[int | float, int | float]] | None = None,  | 
            ||
| 1931 | ) -> dict[tuple[int | float, int | float], float]:  | 
            ||
| 1932 | """  | 
            ||
| 1933 | Calculate the mean roof load factor per capacity range from existing PV  | 
            ||
| 1934 | plants.  | 
            ||
| 1935 | Parameters  | 
            ||
| 1936 | -----------  | 
            ||
| 1937 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1938 | GeoDataFrame containing geocoded MaStR data.  | 
            ||
| 1939 | cap_ranges : list(tuple(int, int))  | 
            ||
| 1940 | List of capacity ranges to distinguish between. The first tuple should  | 
            ||
| 1941 | start with a zero and the last one should end with infinite.  | 
            ||
| 1942 | Returns  | 
            ||
| 1943 | -------  | 
            ||
| 1944 | dict  | 
            ||
| 1945 | Dictionary with mean roof load factor per capacity range.  | 
            ||
| 1946 | """  | 
            ||
| 1947 | if cap_ranges is None:  | 
            ||
| 1948 | cap_ranges = [  | 
            ||
| 1949 | (0, 30),  | 
            ||
| 1950 | (30, 100),  | 
            ||
| 1951 |             (100, float("inf")), | 
            ||
| 1952 | ]  | 
            ||
| 1953 | |||
| 1954 |     load_factor_dict = {} | 
            ||
| 1955 | |||
| 1956 | for cap_range in cap_ranges:  | 
            ||
| 1957 | load_factor = mastr_gdf.loc[  | 
            ||
| 1958 | (mastr_gdf.load_factor <= 1)  | 
            ||
| 1959 | & (mastr_gdf.capacity > cap_range[0])  | 
            ||
| 1960 | & (mastr_gdf.capacity <= cap_range[1])  | 
            ||
| 1961 | ].load_factor.mean()  | 
            ||
| 1962 | |||
| 1963 | load_factor_dict[cap_range] = load_factor  | 
            ||
| 1964 | |||
| 1965 | return load_factor_dict  | 
            ||
| 1966 | |||
| 1967 | |||
| 1968 | def building_area_range_per_cap_range(  | 
            ||
| 1969 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 1970 | cap_ranges: list[tuple[int | float, int | float]] | None = None,  | 
            ||
| 1971 | min_building_size: int | float = 10.0,  | 
            ||
| 1972 | upper_quantile: float = 0.95,  | 
            ||
| 1973 | lower_quantile: float = 0.05,  | 
            ||
| 1974 | ) -> dict[tuple[int | float, int | float], tuple[int | float, int | float]]:  | 
            ||
| 1975 | """  | 
            ||
| 1976 | Estimate normal building area range per capacity range.  | 
            ||
| 1977 | Calculate the mean roof load factor per capacity range from existing PV  | 
            ||
| 1978 | plants.  | 
            ||
| 1979 | Parameters  | 
            ||
| 1980 | -----------  | 
            ||
| 1981 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 1982 | GeoDataFrame containing geocoded MaStR data.  | 
            ||
| 1983 | cap_ranges : list(tuple(int, int))  | 
            ||
| 1984 | List of capacity ranges to distinguish between. The first tuple should  | 
            ||
| 1985 | start with a zero and the last one should end with infinite.  | 
            ||
| 1986 | min_building_size : int, float  | 
            ||
| 1987 | Minimal building size to consider for PV plants.  | 
            ||
| 1988 | upper_quantile : float  | 
            ||
| 1989 | Upper quantile to estimate maximum building size per capacity range.  | 
            ||
| 1990 | lower_quantile : float  | 
            ||
| 1991 | Lower quantile to estimate minimum building size per capacity range.  | 
            ||
| 1992 | Returns  | 
            ||
| 1993 | -------  | 
            ||
| 1994 | dict  | 
            ||
| 1995 | Dictionary with estimated normal building area range per capacity  | 
            ||
| 1996 | range.  | 
            ||
| 1997 | """  | 
            ||
| 1998 | if cap_ranges is None:  | 
            ||
| 1999 | cap_ranges = [  | 
            ||
| 2000 | (0, 30),  | 
            ||
| 2001 | (30, 100),  | 
            ||
| 2002 |             (100, float("inf")), | 
            ||
| 2003 | ]  | 
            ||
| 2004 | |||
| 2005 |     building_area_range_dict = {} | 
            ||
| 2006 | |||
| 2007 | n_ranges = len(cap_ranges)  | 
            ||
| 2008 | |||
| 2009 | for count, cap_range in enumerate(cap_ranges):  | 
            ||
| 2010 | cap_range_gdf = mastr_gdf.loc[  | 
            ||
| 2011 | (mastr_gdf.capacity > cap_range[0])  | 
            ||
| 2012 | & (mastr_gdf.capacity <= cap_range[1])  | 
            ||
| 2013 | ]  | 
            ||
| 2014 | |||
| 2015 | if count == 0:  | 
            ||
| 2016 | building_area_range_dict[cap_range] = (  | 
            ||
| 2017 | min_building_size,  | 
            ||
| 2018 | cap_range_gdf.building_area.quantile(upper_quantile),  | 
            ||
| 2019 | )  | 
            ||
| 2020 | elif count == n_ranges - 1:  | 
            ||
| 2021 | building_area_range_dict[cap_range] = (  | 
            ||
| 2022 | cap_range_gdf.building_area.quantile(lower_quantile),  | 
            ||
| 2023 |                 float("inf"), | 
            ||
| 2024 | )  | 
            ||
| 2025 | else:  | 
            ||
| 2026 | building_area_range_dict[cap_range] = (  | 
            ||
| 2027 | cap_range_gdf.building_area.quantile(lower_quantile),  | 
            ||
| 2028 | cap_range_gdf.building_area.quantile(upper_quantile),  | 
            ||
| 2029 | )  | 
            ||
| 2030 | |||
| 2031 | values = list(building_area_range_dict.values())  | 
            ||
| 2032 | |||
| 2033 |     building_area_range_normed_dict = {} | 
            ||
| 2034 | |||
| 2035 | for count, (cap_range, (min_area, max_area)) in enumerate(  | 
            ||
| 2036 | building_area_range_dict.items()  | 
            ||
| 2037 | ):  | 
            ||
| 2038 | if count == 0:  | 
            ||
| 2039 | building_area_range_normed_dict[cap_range] = (  | 
            ||
| 2040 | min_area,  | 
            ||
| 2041 | np.mean((values[count + 1][0], max_area)),  | 
            ||
| 2042 | )  | 
            ||
| 2043 | elif count == n_ranges - 1:  | 
            ||
| 2044 | building_area_range_normed_dict[cap_range] = (  | 
            ||
| 2045 | np.mean((values[count - 1][1], min_area)),  | 
            ||
| 2046 | max_area,  | 
            ||
| 2047 | )  | 
            ||
| 2048 | else:  | 
            ||
| 2049 | building_area_range_normed_dict[cap_range] = (  | 
            ||
| 2050 | np.mean((values[count - 1][1], min_area)),  | 
            ||
| 2051 | np.mean((values[count + 1][0], max_area)),  | 
            ||
| 2052 | )  | 
            ||
| 2053 | |||
| 2054 | return building_area_range_normed_dict  | 
            ||
| 2055 | |||
| 2056 | |||
| 2057 | @timer_func  | 
            ||
| 2058 | def desaggregate_pv_in_mv_grid(  | 
            ||
| 2059 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 2060 | pv_cap: float | int,  | 
            ||
| 2061 | **kwargs,  | 
            ||
| 2062 | ) -> gpd.GeoDataFrame:  | 
            ||
| 2063 | """  | 
            ||
| 2064 | Desaggregate PV capacity on buildings within a given grid district.  | 
            ||
| 2065 | Parameters  | 
            ||
| 2066 | -----------  | 
            ||
| 2067 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 2068 | GeoDataFrame containing buildings within the grid district.  | 
            ||
| 2069 | pv_cap : float, int  | 
            ||
| 2070 | PV capacity to desaggregate.  | 
            ||
| 2071 | Other Parameters  | 
            ||
| 2072 | -----------  | 
            ||
| 2073 | prob_dict : dict  | 
            ||
| 2074 | Dictionary with values and probabilities per capacity range.  | 
            ||
| 2075 | cap_share_dict : dict  | 
            ||
| 2076 | Dictionary with share of PV capacity from the total PV capacity within  | 
            ||
| 2077 | capacity ranges.  | 
            ||
| 2078 | building_area_range_dict : dict  | 
            ||
| 2079 | Dictionary with estimated normal building area range per capacity  | 
            ||
| 2080 | range.  | 
            ||
| 2081 | load_factor_dict : dict  | 
            ||
| 2082 | Dictionary with mean roof load factor per capacity range.  | 
            ||
| 2083 | seed : int  | 
            ||
| 2084 | Seed to use for random operations with NumPy and pandas.  | 
            ||
| 2085 | pv_cap_per_sq_m : float, int  | 
            ||
| 2086 | Average expected, installable PV capacity per square meter.  | 
            ||
| 2087 | Returns  | 
            ||
| 2088 | -------  | 
            ||
| 2089 | geopandas.GeoDataFrame  | 
            ||
| 2090 | GeoDataFrame containing OSM building data with desaggregated PV  | 
            ||
| 2091 | plants.  | 
            ||
| 2092 | """  | 
            ||
| 2093 | bus_id = int(buildings_gdf.bus_id.iat[0])  | 
            ||
| 2094 | |||
| 2095 | rng = default_rng(seed=kwargs["seed"])  | 
            ||
| 2096 | random_state = RandomState(seed=kwargs["seed"])  | 
            ||
| 2097 | |||
| 2098 | results_df = pd.DataFrame(columns=buildings_gdf.columns)  | 
            ||
| 2099 | |||
| 2100 | for cap_range, share in kwargs["cap_share_dict"].items():  | 
            ||
| 2101 | pv_cap_range = pv_cap * share  | 
            ||
| 2102 | |||
| 2103 | b_area_min, b_area_max = kwargs["building_area_range_dict"][cap_range]  | 
            ||
| 2104 | |||
| 2105 | cap_range_buildings_gdf = buildings_gdf.loc[  | 
            ||
| 2106 | ~buildings_gdf.index.isin(results_df.index)  | 
            ||
| 2107 | & (buildings_gdf.building_area > b_area_min)  | 
            ||
| 2108 | & (buildings_gdf.building_area <= b_area_max)  | 
            ||
| 2109 | ]  | 
            ||
| 2110 | |||
| 2111 | mean_load_factor = kwargs["load_factor_dict"][cap_range]  | 
            ||
| 2112 | cap_range_buildings_gdf = cap_range_buildings_gdf.assign(  | 
            ||
| 2113 | mean_cap=cap_range_buildings_gdf.max_cap * mean_load_factor,  | 
            ||
| 2114 | load_factor=np.nan,  | 
            ||
| 2115 | capacity=np.nan,  | 
            ||
| 2116 | )  | 
            ||
| 2117 | |||
| 2118 | total_mean_cap = cap_range_buildings_gdf.mean_cap.sum()  | 
            ||
| 2119 | |||
| 2120 | if total_mean_cap == 0:  | 
            ||
| 2121 | logger.warning(  | 
            ||
| 2122 |                 f"There are no matching roof for capacity range {cap_range} " | 
            ||
| 2123 |                 f"kW in grid {bus_id}. Using all buildings as fallback." | 
            ||
| 2124 | )  | 
            ||
| 2125 | |||
| 2126 | cap_range_buildings_gdf = buildings_gdf.loc[  | 
            ||
| 2127 | ~buildings_gdf.index.isin(results_df.index)  | 
            ||
| 2128 | ]  | 
            ||
| 2129 | |||
| 2130 | if len(cap_range_buildings_gdf) == 0:  | 
            ||
| 2131 | logger.warning(  | 
            ||
| 2132 | "There are no roofes available for capacity range "  | 
            ||
| 2133 |                     f"{cap_range} kW in grid {bus_id}. Allowing dual use." | 
            ||
| 2134 | )  | 
            ||
| 2135 | cap_range_buildings_gdf = buildings_gdf.copy()  | 
            ||
| 2136 | |||
| 2137 | cap_range_buildings_gdf = cap_range_buildings_gdf.assign(  | 
            ||
| 2138 | mean_cap=cap_range_buildings_gdf.max_cap * mean_load_factor,  | 
            ||
| 2139 | load_factor=np.nan,  | 
            ||
| 2140 | capacity=np.nan,  | 
            ||
| 2141 | )  | 
            ||
| 2142 | |||
| 2143 | total_mean_cap = cap_range_buildings_gdf.mean_cap.sum()  | 
            ||
| 2144 | |||
| 2145 | elif total_mean_cap < pv_cap_range:  | 
            ||
| 2146 | logger.warning(  | 
            ||
| 2147 |                 f"Average roof utilization of the roof area in grid {bus_id} " | 
            ||
| 2148 |                 f"and capacity range {cap_range} kW is not sufficient. The " | 
            ||
| 2149 | "roof utilization will be above average."  | 
            ||
| 2150 | )  | 
            ||
| 2151 | |||
| 2152 | frac = max(  | 
            ||
| 2153 | pv_cap_range / total_mean_cap,  | 
            ||
| 2154 | 1 / len(cap_range_buildings_gdf),  | 
            ||
| 2155 | )  | 
            ||
| 2156 | |||
| 2157 | samples_gdf = cap_range_buildings_gdf.sample(  | 
            ||
| 2158 | frac=min(1, frac),  | 
            ||
| 2159 | random_state=random_state,  | 
            ||
| 2160 | )  | 
            ||
| 2161 | |||
| 2162 | cap_range_dict = kwargs["prob_dict"][cap_range]  | 
            ||
| 2163 | |||
| 2164 | values_dict = cap_range_dict["values"]  | 
            ||
| 2165 | p_dict = cap_range_dict["probabilities"]  | 
            ||
| 2166 | |||
| 2167 | load_factors = rng.choice(  | 
            ||
| 2168 | a=values_dict["load_factor"],  | 
            ||
| 2169 | size=len(samples_gdf),  | 
            ||
| 2170 | p=p_dict["load_factor"],  | 
            ||
| 2171 | )  | 
            ||
| 2172 | |||
| 2173 | samples_gdf = samples_gdf.assign(  | 
            ||
| 2174 | load_factor=load_factors,  | 
            ||
| 2175 | capacity=(  | 
            ||
| 2176 | samples_gdf.building_area  | 
            ||
| 2177 | * load_factors  | 
            ||
| 2178 | * kwargs["pv_cap_per_sq_m"]  | 
            ||
| 2179 | ).clip(lower=0.4),  | 
            ||
| 2180 | )  | 
            ||
| 2181 | |||
| 2182 | missing_factor = pv_cap_range / samples_gdf.capacity.sum()  | 
            ||
| 2183 | |||
| 2184 | samples_gdf = samples_gdf.assign(  | 
            ||
| 2185 | capacity=(samples_gdf.capacity * missing_factor),  | 
            ||
| 2186 | load_factor=(samples_gdf.load_factor * missing_factor),  | 
            ||
| 2187 | )  | 
            ||
| 2188 | |||
| 2189 | assert np.isclose(  | 
            ||
| 2190 | samples_gdf.capacity.sum(),  | 
            ||
| 2191 | pv_cap_range,  | 
            ||
| 2192 | rtol=1e-03,  | 
            ||
| 2193 |         ), f"{samples_gdf.capacity.sum()} != {pv_cap_range}" | 
            ||
| 2194 | |||
| 2195 | results_df = pd.concat(  | 
            ||
| 2196 | [  | 
            ||
| 2197 | results_df,  | 
            ||
| 2198 | samples_gdf,  | 
            ||
| 2199 | ],  | 
            ||
| 2200 | )  | 
            ||
| 2201 | |||
| 2202 | total_missing_factor = pv_cap / results_df.capacity.sum()  | 
            ||
| 2203 | |||
| 2204 | results_df = results_df.assign(  | 
            ||
| 2205 | capacity=(results_df.capacity * total_missing_factor),  | 
            ||
| 2206 | )  | 
            ||
| 2207 | |||
| 2208 | assert np.isclose(  | 
            ||
| 2209 | results_df.capacity.sum(),  | 
            ||
| 2210 | pv_cap,  | 
            ||
| 2211 | rtol=1e-03,  | 
            ||
| 2212 |     ), f"{results_df.capacity.sum()} != {pv_cap}" | 
            ||
| 2213 | |||
| 2214 | return gpd.GeoDataFrame(  | 
            ||
| 2215 | results_df,  | 
            ||
| 2216 | crs=samples_gdf.crs,  | 
            ||
| 2217 | geometry="geom",  | 
            ||
| 2218 | )  | 
            ||
| 2219 | |||
| 2220 | |||
| 2221 | @timer_func  | 
            ||
| 2222 | def desaggregate_pv(  | 
            ||
| 2223 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 2224 | cap_df: pd.DataFrame,  | 
            ||
| 2225 | **kwargs,  | 
            ||
| 2226 | ) -> gpd.GeoDataFrame:  | 
            ||
| 2227 | """  | 
            ||
| 2228 | Desaggregate PV capacity on buildings within a given grid district.  | 
            ||
| 2229 | Parameters  | 
            ||
| 2230 | -----------  | 
            ||
| 2231 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 2232 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 2233 | cap_df : pandas.DataFrame  | 
            ||
| 2234 | DataFrame with total rooftop capacity per mv grid.  | 
            ||
| 2235 | Other Parameters  | 
            ||
| 2236 | -----------  | 
            ||
| 2237 | prob_dict : dict  | 
            ||
| 2238 | Dictionary with values and probabilities per capacity range.  | 
            ||
| 2239 | cap_share_dict : dict  | 
            ||
| 2240 | Dictionary with share of PV capacity from the total PV capacity within  | 
            ||
| 2241 | capacity ranges.  | 
            ||
| 2242 | building_area_range_dict : dict  | 
            ||
| 2243 | Dictionary with estimated normal building area range per capacity  | 
            ||
| 2244 | range.  | 
            ||
| 2245 | load_factor_dict : dict  | 
            ||
| 2246 | Dictionary with mean roof load factor per capacity range.  | 
            ||
| 2247 | seed : int  | 
            ||
| 2248 | Seed to use for random operations with NumPy and pandas.  | 
            ||
| 2249 | pv_cap_per_sq_m : float, int  | 
            ||
| 2250 | Average expected, installable PV capacity per square meter.  | 
            ||
| 2251 | Returns  | 
            ||
| 2252 | -------  | 
            ||
| 2253 | geopandas.GeoDataFrame  | 
            ||
| 2254 | GeoDataFrame containing OSM building data with desaggregated PV  | 
            ||
| 2255 | plants.  | 
            ||
| 2256 | """  | 
            ||
| 2257 | allocated_buildings_gdf = buildings_gdf.loc[~buildings_gdf.end_of_life]  | 
            ||
| 2258 | |||
| 2259 | building_bus_ids = set(buildings_gdf.bus_id)  | 
            ||
| 2260 | cap_bus_ids = set(cap_df.index)  | 
            ||
| 2261 | |||
| 2262 | logger.debug(  | 
            ||
| 2263 |         f"Bus IDs from buildings: {len(building_bus_ids)}\nBus IDs from capacity: " | 
            ||
| 2264 |         f"{len(cap_bus_ids)}" | 
            ||
| 2265 | )  | 
            ||
| 2266 | |||
| 2267 | if len(building_bus_ids) > len(cap_bus_ids):  | 
            ||
| 2268 | missing = building_bus_ids - cap_bus_ids  | 
            ||
| 2269 | else:  | 
            ||
| 2270 | missing = cap_bus_ids - building_bus_ids  | 
            ||
| 2271 | |||
| 2272 | logger.debug(str(missing))  | 
            ||
| 2273 | |||
| 2274 | bus_ids = np.intersect1d(list(building_bus_ids), list(cap_bus_ids))  | 
            ||
| 2275 | |||
| 2276 | # assert set(buildings_gdf.bus_id.unique()) == set(cap_df.index)  | 
            ||
| 2277 | |||
| 2278 | for bus_id in bus_ids:  | 
            ||
| 2279 | buildings_grid_gdf = buildings_gdf.loc[buildings_gdf.bus_id == bus_id]  | 
            ||
| 2280 | |||
| 2281 | pv_installed_gdf = buildings_grid_gdf.loc[  | 
            ||
| 2282 | ~buildings_grid_gdf.end_of_life  | 
            ||
| 2283 | ]  | 
            ||
| 2284 | |||
| 2285 | pv_installed = pv_installed_gdf.capacity.sum()  | 
            ||
| 2286 | |||
| 2287 | pot_buildings_gdf = buildings_grid_gdf.drop(  | 
            ||
| 2288 | index=pv_installed_gdf.index  | 
            ||
| 2289 | )  | 
            ||
| 2290 | |||
| 2291 | if len(pot_buildings_gdf) == 0:  | 
            ||
| 2292 | logger.error(  | 
            ||
| 2293 |                 f"In grid {bus_id} there are no potential buildings to allocate " | 
            ||
| 2294 | "PV capacity to. The grid is skipped. This message should only "  | 
            ||
| 2295 | "appear doing test runs with few buildings."  | 
            ||
| 2296 | )  | 
            ||
| 2297 | |||
| 2298 | continue  | 
            ||
| 2299 | |||
| 2300 | pv_target = cap_df.at[bus_id, "capacity"] * 1000  | 
            ||
| 2301 | |||
| 2302 |         logger.debug(f"pv_target: {pv_target}") | 
            ||
| 2303 | |||
| 2304 | pv_missing = pv_target - pv_installed  | 
            ||
| 2305 | |||
| 2306 | if pv_missing <= 0:  | 
            ||
| 2307 | logger.info(  | 
            ||
| 2308 |                 f"In grid {bus_id} there is more PV installed ({pv_installed: g}) in " | 
            ||
| 2309 |                 f"status Quo than allocated within the scenario ({pv_target: g}). No " | 
            ||
| 2310 | f"new generators are added."  | 
            ||
| 2311 | )  | 
            ||
| 2312 | |||
| 2313 | continue  | 
            ||
| 2314 | |||
| 2315 | if pot_buildings_gdf.max_cap.sum() < pv_missing:  | 
            ||
| 2316 | logger.error(  | 
            ||
| 2317 |                 f"In grid {bus_id} there is less PV potential (" | 
            ||
| 2318 |                 f"{pot_buildings_gdf.max_cap.sum():g} kW) than allocated PV  capacity " | 
            ||
| 2319 |                 f"({pv_missing:g} kW). The average roof utilization will be very high." | 
            ||
| 2320 | )  | 
            ||
| 2321 | |||
| 2322 | gdf = desaggregate_pv_in_mv_grid(  | 
            ||
| 2323 | buildings_gdf=pot_buildings_gdf,  | 
            ||
| 2324 | pv_cap=pv_missing,  | 
            ||
| 2325 | **kwargs,  | 
            ||
| 2326 | )  | 
            ||
| 2327 | |||
| 2328 |         logger.debug(f"New cap in grid {bus_id}: {gdf.capacity.sum()}") | 
            ||
| 2329 |         logger.debug(f"Installed cap in grid {bus_id}: {pv_installed}") | 
            ||
| 2330 | logger.debug(  | 
            ||
| 2331 |             f"Total cap in grid {bus_id}: {gdf.capacity.sum() + pv_installed}" | 
            ||
| 2332 | )  | 
            ||
| 2333 | |||
| 2334 | if not np.isclose(  | 
            ||
| 2335 | gdf.capacity.sum() + pv_installed, pv_target, rtol=1e-3  | 
            ||
| 2336 | ):  | 
            ||
| 2337 | logger.warning(  | 
            ||
| 2338 |                 f"The desired capacity and actual capacity in grid {bus_id} differ.\n" | 
            ||
| 2339 |                 f"Desired cap: {pv_target}\nActual cap: " | 
            ||
| 2340 |                 f"{gdf.capacity.sum() + pv_installed}" | 
            ||
| 2341 | )  | 
            ||
| 2342 | |||
| 2343 | allocated_buildings_gdf = pd.concat(  | 
            ||
| 2344 | [  | 
            ||
| 2345 | allocated_buildings_gdf,  | 
            ||
| 2346 | gdf,  | 
            ||
| 2347 | ]  | 
            ||
| 2348 | )  | 
            ||
| 2349 | |||
| 2350 |     logger.debug("Desaggregated scenario.") | 
            ||
| 2351 |     logger.debug(f"Scenario capacity: {cap_df.capacity.sum(): g}") | 
            ||
| 2352 | logger.debug(  | 
            ||
| 2353 |         f"Generator capacity: {allocated_buildings_gdf.capacity.sum(): g}" | 
            ||
| 2354 | )  | 
            ||
| 2355 | |||
| 2356 | return gpd.GeoDataFrame(  | 
            ||
| 2357 | allocated_buildings_gdf,  | 
            ||
| 2358 | crs=gdf.crs,  | 
            ||
| 2359 | geometry="geom",  | 
            ||
| 2360 | )  | 
            ||
| 2361 | |||
| 2362 | |||
| 2363 | @timer_func  | 
            ||
| 2364 | def add_buildings_meta_data(  | 
            ||
| 2365 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 2366 | prob_dict: dict,  | 
            ||
| 2367 | seed: int,  | 
            ||
| 2368 | ) -> gpd.GeoDataFrame:  | 
            ||
| 2369 | """  | 
            ||
| 2370 | Randomly add additional metadata to desaggregated PV plants.  | 
            ||
| 2371 | Parameters  | 
            ||
| 2372 | -----------  | 
            ||
| 2373 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 2374 | GeoDataFrame containing OSM buildings data with desaggregated PV  | 
            ||
| 2375 | plants.  | 
            ||
| 2376 | prob_dict : dict  | 
            ||
| 2377 | Dictionary with values and probabilities per capacity range.  | 
            ||
| 2378 | seed : int  | 
            ||
| 2379 | Seed to use for random operations with NumPy and pandas.  | 
            ||
| 2380 | Returns  | 
            ||
| 2381 | -------  | 
            ||
| 2382 | geopandas.GeoDataFrame  | 
            ||
| 2383 | GeoDataFrame containing OSM building data with desaggregated PV  | 
            ||
| 2384 | plants.  | 
            ||
| 2385 | """  | 
            ||
| 2386 | rng = default_rng(seed=seed)  | 
            ||
| 2387 | buildings_gdf = buildings_gdf.reset_index().rename(  | 
            ||
| 2388 |         columns={ | 
            ||
| 2389 | "index": "building_id",  | 
            ||
| 2390 | }  | 
            ||
| 2391 | )  | 
            ||
| 2392 | |||
| 2393 | for (min_cap, max_cap), cap_range_prob_dict in prob_dict.items():  | 
            ||
| 2394 | cap_range_gdf = buildings_gdf.loc[  | 
            ||
| 2395 | (buildings_gdf.capacity >= min_cap)  | 
            ||
| 2396 | & (buildings_gdf.capacity < max_cap)  | 
            ||
| 2397 | ]  | 
            ||
| 2398 | |||
| 2399 | for key, values in cap_range_prob_dict["values"].items():  | 
            ||
| 2400 | if key == "load_factor":  | 
            ||
| 2401 | continue  | 
            ||
| 2402 | |||
| 2403 | gdf = cap_range_gdf.loc[  | 
            ||
| 2404 | cap_range_gdf[key].isna()  | 
            ||
| 2405 | | cap_range_gdf[key].isnull()  | 
            ||
| 2406 | | (cap_range_gdf[key] == "None")  | 
            ||
| 2407 | ]  | 
            ||
| 2408 | |||
| 2409 | key_vals = rng.choice(  | 
            ||
| 2410 | a=values,  | 
            ||
| 2411 | size=len(gdf),  | 
            ||
| 2412 | p=cap_range_prob_dict["probabilities"][key],  | 
            ||
| 2413 | )  | 
            ||
| 2414 | |||
| 2415 | buildings_gdf.loc[gdf.index, key] = key_vals  | 
            ||
| 2416 | |||
| 2417 | return buildings_gdf  | 
            ||
| 2418 | |||
| 2419 | |||
| 2420 | def add_voltage_level(  | 
            ||
| 2421 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 2422 | ) -> gpd.GeoDataFrame:  | 
            ||
| 2423 | """  | 
            ||
| 2424 | Add voltage level derived from generator capacity to the power plants.  | 
            ||
| 2425 | Parameters  | 
            ||
| 2426 | -----------  | 
            ||
| 2427 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 2428 | GeoDataFrame containing OSM buildings data with desaggregated PV  | 
            ||
| 2429 | plants.  | 
            ||
| 2430 | Returns  | 
            ||
| 2431 | -------  | 
            ||
| 2432 | geopandas.GeoDataFrame  | 
            ||
| 2433 | GeoDataFrame containing OSM building data with voltage level per generator.  | 
            ||
| 2434 | """  | 
            ||
| 2435 | |||
| 2436 | def voltage_levels(p: float) -> int:  | 
            ||
| 2437 | if p < 100:  | 
            ||
| 2438 | return 7  | 
            ||
| 2439 | elif p < 200:  | 
            ||
| 2440 | return 6  | 
            ||
| 2441 | elif p < 5500:  | 
            ||
| 2442 | return 5  | 
            ||
| 2443 | elif p < 20000:  | 
            ||
| 2444 | return 4  | 
            ||
| 2445 | elif p < 120000:  | 
            ||
| 2446 | return 3  | 
            ||
| 2447 | return 1  | 
            ||
| 2448 | |||
| 2449 | return buildings_gdf.assign(  | 
            ||
| 2450 | voltage_level=buildings_gdf.capacity.apply(voltage_levels)  | 
            ||
| 2451 | )  | 
            ||
| 2452 | |||
| 2453 | |||
| 2454 | def add_start_up_date(  | 
            ||
| 2455 | buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 2456 | start: pd.Timestamp,  | 
            ||
| 2457 | end: pd.Timestamp,  | 
            ||
| 2458 | seed: int,  | 
            ||
| 2459 | ):  | 
            ||
| 2460 | """  | 
            ||
| 2461 | Randomly and linear add start-up date to new pv generators.  | 
            ||
| 2462 | Parameters  | 
            ||
| 2463 | ----------  | 
            ||
| 2464 | buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 2465 | GeoDataFrame containing OSM buildings data with desaggregated PV  | 
            ||
| 2466 | plants.  | 
            ||
| 2467 | start : pandas.Timestamp  | 
            ||
| 2468 | Minimum Timestamp to use.  | 
            ||
| 2469 | end : pandas.Timestamp  | 
            ||
| 2470 | Maximum Timestamp to use.  | 
            ||
| 2471 | seed : int  | 
            ||
| 2472 | Seed to use for random operations with NumPy and pandas.  | 
            ||
| 2473 | Returns  | 
            ||
| 2474 | -------  | 
            ||
| 2475 | geopandas.GeoDataFrame  | 
            ||
| 2476 | GeoDataFrame containing OSM buildings data with start-up date added.  | 
            ||
| 2477 | """  | 
            ||
| 2478 | rng = default_rng(seed=seed)  | 
            ||
| 2479 | |||
| 2480 | date_range = pd.date_range(start=start, end=end, freq="1D")  | 
            ||
| 2481 | |||
| 2482 | return buildings_gdf.assign(  | 
            ||
| 2483 | start_up_date=rng.choice(date_range, size=len(buildings_gdf))  | 
            ||
| 2484 | )  | 
            ||
| 2485 | |||
| 2486 | |||
| 2487 | @timer_func  | 
            ||
| 2488 | def allocate_scenarios(  | 
            ||
| 2489 | mastr_gdf: gpd.GeoDataFrame,  | 
            ||
| 2490 | valid_buildings_gdf: gpd.GeoDataFrame,  | 
            ||
| 2491 | last_scenario_gdf: gpd.GeoDataFrame,  | 
            ||
| 2492 | scenario: str,  | 
            ||
| 2493 | ):  | 
            ||
| 2494 | """  | 
            ||
| 2495 | Desaggregate and allocate scenario pv rooftop ramp-ups onto buildings.  | 
            ||
| 2496 | Parameters  | 
            ||
| 2497 | ----------  | 
            ||
| 2498 | mastr_gdf : geopandas.GeoDataFrame  | 
            ||
| 2499 | GeoDataFrame containing geocoded MaStR data.  | 
            ||
| 2500 | valid_buildings_gdf : geopandas.GeoDataFrame  | 
            ||
| 2501 | GeoDataFrame containing OSM buildings data.  | 
            ||
| 2502 | last_scenario_gdf : geopandas.GeoDataFrame  | 
            ||
| 2503 | GeoDataFrame containing OSM buildings matched with pv generators from temporal  | 
            ||
| 2504 | preceding scenario.  | 
            ||
| 2505 | scenario : str  | 
            ||
| 2506 | Scenario to desaggrgate and allocate.  | 
            ||
| 2507 | Returns  | 
            ||
| 2508 | -------  | 
            ||
| 2509 | tuple  | 
            ||
| 2510 | geopandas.GeoDataFrame  | 
            ||
| 2511 | GeoDataFrame containing OSM buildings matched with pv generators.  | 
            ||
| 2512 | pandas.DataFrame  | 
            ||
| 2513 | DataFrame containing pv rooftop capacity per grid id.  | 
            ||
| 2514 | """  | 
            ||
| 2515 | cap_per_bus_id_df = cap_per_bus_id(scenario)  | 
            ||
| 2516 | |||
| 2517 | logger.debug(  | 
            ||
| 2518 |         f"cap_per_bus_id_df total capacity: {cap_per_bus_id_df.capacity.sum()}" | 
            ||
| 2519 | )  | 
            ||
| 2520 | |||
| 2521 | last_scenario_gdf = determine_end_of_life_gens(  | 
            ||
| 2522 | last_scenario_gdf,  | 
            ||
| 2523 | SCENARIO_TIMESTAMP[scenario],  | 
            ||
| 2524 | PV_ROOFTOP_LIFETIME,  | 
            ||
| 2525 | )  | 
            ||
| 2526 | |||
| 2527 | buildings_gdf = calculate_max_pv_cap_per_building(  | 
            ||
| 2528 | valid_buildings_gdf,  | 
            ||
| 2529 | last_scenario_gdf,  | 
            ||
| 2530 | PV_CAP_PER_SQ_M,  | 
            ||
| 2531 | ROOF_FACTOR,  | 
            ||
| 2532 | )  | 
            ||
| 2533 | |||
| 2534 | mastr_gdf = calculate_building_load_factor(  | 
            ||
| 2535 | mastr_gdf,  | 
            ||
| 2536 | buildings_gdf,  | 
            ||
| 2537 | )  | 
            ||
| 2538 | |||
| 2539 | probabilities_dict = probabilities(  | 
            ||
| 2540 | mastr_gdf,  | 
            ||
| 2541 | cap_ranges=CAP_RANGES,  | 
            ||
| 2542 | )  | 
            ||
| 2543 | |||
| 2544 | cap_share_dict = cap_share_per_cap_range(  | 
            ||
| 2545 | mastr_gdf,  | 
            ||
| 2546 | cap_ranges=CAP_RANGES,  | 
            ||
| 2547 | )  | 
            ||
| 2548 | |||
| 2549 | load_factor_dict = mean_load_factor_per_cap_range(  | 
            ||
| 2550 | mastr_gdf,  | 
            ||
| 2551 | cap_ranges=CAP_RANGES,  | 
            ||
| 2552 | )  | 
            ||
| 2553 | |||
| 2554 | building_area_range_dict = building_area_range_per_cap_range(  | 
            ||
| 2555 | mastr_gdf,  | 
            ||
| 2556 | cap_ranges=CAP_RANGES,  | 
            ||
| 2557 | min_building_size=MIN_BUILDING_SIZE,  | 
            ||
| 2558 | upper_quantile=UPPER_QUNATILE,  | 
            ||
| 2559 | lower_quantile=LOWER_QUANTILE,  | 
            ||
| 2560 | )  | 
            ||
| 2561 | |||
| 2562 | allocated_buildings_gdf = desaggregate_pv(  | 
            ||
| 2563 | buildings_gdf=buildings_gdf,  | 
            ||
| 2564 | cap_df=cap_per_bus_id_df,  | 
            ||
| 2565 | prob_dict=probabilities_dict,  | 
            ||
| 2566 | cap_share_dict=cap_share_dict,  | 
            ||
| 2567 | building_area_range_dict=building_area_range_dict,  | 
            ||
| 2568 | load_factor_dict=load_factor_dict,  | 
            ||
| 2569 | seed=SEED,  | 
            ||
| 2570 | pv_cap_per_sq_m=PV_CAP_PER_SQ_M,  | 
            ||
| 2571 | )  | 
            ||
| 2572 | |||
| 2573 | allocated_buildings_gdf = allocated_buildings_gdf.assign(scenario=scenario)  | 
            ||
| 2574 | |||
| 2575 | meta_buildings_gdf = frame_to_numeric(  | 
            ||
| 2576 | add_buildings_meta_data(  | 
            ||
| 2577 | allocated_buildings_gdf,  | 
            ||
| 2578 | probabilities_dict,  | 
            ||
| 2579 | SEED,  | 
            ||
| 2580 | )  | 
            ||
| 2581 | )  | 
            ||
| 2582 | |||
| 2583 | return (  | 
            ||
| 2584 | add_start_up_date(  | 
            ||
| 2585 | meta_buildings_gdf,  | 
            ||
| 2586 | start=last_scenario_gdf.start_up_date.max(),  | 
            ||
| 2587 | end=SCENARIO_TIMESTAMP[scenario],  | 
            ||
| 2588 | seed=SEED,  | 
            ||
| 2589 | ),  | 
            ||
| 2590 | cap_per_bus_id_df,  | 
            ||
| 2591 | )  | 
            ||
| 2592 | |||
| 2593 | |||
| 2594 | class EgonPowerPlantPvRoofBuildingScenario(Base):  | 
            ||
| 2595 | __tablename__ = "egon_power_plants_pv_roof_building"  | 
            ||
| 2596 |     __table_args__ = {"schema": "supply"} | 
            ||
| 2597 | |||
| 2598 | index = Column(Integer, primary_key=True, index=True)  | 
            ||
| 2599 | scenario = Column(String)  | 
            ||
| 2600 | bus_id = Column(Integer, nullable=True)  | 
            ||
| 2601 | building_id = Column(Integer)  | 
            ||
| 2602 | gens_id = Column(String, nullable=True)  | 
            ||
| 2603 | capacity = Column(Float)  | 
            ||
| 2604 | einheitliche_ausrichtung_und_neigungswinkel = Column(Float)  | 
            ||
| 2605 | hauptausrichtung = Column(String)  | 
            ||
| 2606 | hauptausrichtung_neigungswinkel = Column(String)  | 
            ||
| 2607 | voltage_level = Column(Integer)  | 
            ||
| 2608 | weather_cell_id = Column(Integer)  | 
            ||
| 2609 | |||
| 2610 | |||
| 2611 | def create_scenario_table(buildings_gdf):  | 
            ||
| 2612 | """Create mapping table pv_unit <-> building for scenario"""  | 
            ||
| 2613 | EgonPowerPlantPvRoofBuildingScenario.__table__.drop(  | 
            ||
| 2614 | bind=engine, checkfirst=True  | 
            ||
| 2615 | )  | 
            ||
| 2616 | EgonPowerPlantPvRoofBuildingScenario.__table__.create(  | 
            ||
| 2617 | bind=engine, checkfirst=True  | 
            ||
| 2618 | )  | 
            ||
| 2619 | |||
| 2620 | buildings_gdf.rename(columns=COLS_TO_RENAME).assign(  | 
            ||
| 2621 | capacity=buildings_gdf.capacity.div(10**3) # kW -> MW  | 
            ||
| 2622 | )[COLS_TO_EXPORT].reset_index().to_sql(  | 
            ||
| 2623 | name=EgonPowerPlantPvRoofBuildingScenario.__table__.name,  | 
            ||
| 2624 | schema=EgonPowerPlantPvRoofBuildingScenario.__table__.schema,  | 
            ||
| 2625 | con=db.engine(),  | 
            ||
| 2626 | if_exists="append",  | 
            ||
| 2627 | index=False,  | 
            ||
| 2628 | )  | 
            ||
| 2629 | |||
| 2630 | |||
| 2631 | def geocode_mastr_data():  | 
            ||
| 2632 | """  | 
            ||
| 2633 | Read PV rooftop data from MaStR CSV  | 
            ||
| 2634 | TODO: the source will be replaced as soon as the MaStR data is available  | 
            ||
| 2635 | in DB.  | 
            ||
| 2636 | """  | 
            ||
| 2637 | mastr_df = mastr_data(  | 
            ||
| 2638 | MASTR_INDEX_COL,  | 
            ||
| 2639 | MASTR_RELEVANT_COLS,  | 
            ||
| 2640 | MASTR_DTYPES,  | 
            ||
| 2641 | MASTR_PARSE_DATES,  | 
            ||
| 2642 | )  | 
            ||
| 2643 | |||
| 2644 | clean_mastr_df = clean_mastr_data(  | 
            ||
| 2645 | mastr_df,  | 
            ||
| 2646 | max_realistic_pv_cap=MAX_REALISTIC_PV_CAP,  | 
            ||
| 2647 | min_realistic_pv_cap=MIN_REALISTIC_PV_CAP,  | 
            ||
| 2648 | seed=SEED,  | 
            ||
| 2649 | rounding=ROUNDING,  | 
            ||
| 2650 | )  | 
            ||
| 2651 | |||
| 2652 | geocoding_df = geocoding_data(clean_mastr_df)  | 
            ||
| 2653 | |||
| 2654 | ratelimiter = geocoder(USER_AGENT, MIN_DELAY_SECONDS)  | 
            ||
| 2655 | |||
| 2656 | geocode_gdf = geocode_data(geocoding_df, ratelimiter, EPSG)  | 
            ||
| 2657 | |||
| 2658 | create_geocoded_table(geocode_gdf)  | 
            ||
| 2659 | |||
| 2660 | |||
| 2661 | def add_weather_cell_id(buildings_gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:  | 
            ||
| 2662 | sql = """  | 
            ||
| 2663 | SELECT building_id, zensus_population_id  | 
            ||
| 2664 | FROM boundaries.egon_map_zensus_mvgd_buildings  | 
            ||
| 2665 | """  | 
            ||
| 2666 | |||
| 2667 | buildings_gdf = (  | 
            ||
| 2668 | buildings_gdf.reset_index()  | 
            ||
| 2669 | .merge(  | 
            ||
| 2670 | right=db.select_dataframe(sql),  | 
            ||
| 2671 | how="left",  | 
            ||
| 2672 | left_on="id",  | 
            ||
| 2673 | right_on="building_id",  | 
            ||
| 2674 | )  | 
            ||
| 2675 |         .set_index("id") | 
            ||
| 2676 | )  | 
            ||
| 2677 | |||
| 2678 | sql = """  | 
            ||
| 2679 | SELECT zensus_population_id, w_id as weather_cell_id  | 
            ||
| 2680 | FROM boundaries.egon_map_zensus_weather_cell  | 
            ||
| 2681 | """  | 
            ||
| 2682 | |||
| 2683 | buildings_gdf = buildings_gdf.merge(  | 
            ||
| 2684 | right=db.select_dataframe(sql),  | 
            ||
| 2685 | how="left",  | 
            ||
| 2686 | on="zensus_population_id",  | 
            ||
| 2687 | )  | 
            ||
| 2688 | |||
| 2689 | if buildings_gdf.weather_cell_id.isna().any():  | 
            ||
| 2690 | raise ValueError(  | 
            ||
| 2691 | f"Following buildings don't have a weather cell id: "  | 
            ||
| 2692 |             f"{buildings_gdf.loc[buildings_gdf.weather_cell_id.isna()].building_id.tolist()}" | 
            ||
| 2693 | )  | 
            ||
| 2694 | |||
| 2695 | return buildings_gdf  | 
            ||
| 2696 | |||
| 2697 | |||
| 2698 | def pv_rooftop_to_buildings():  | 
            ||
| 2699 | """Main script, executed as task"""  | 
            ||
| 2700 | |||
| 2701 | mastr_gdf = load_mastr_data()  | 
            ||
| 2702 | |||
| 2703 | buildings_gdf = load_building_data()  | 
            ||
| 2704 | |||
| 2705 | desagg_mastr_gdf, desagg_buildings_gdf = allocate_to_buildings(  | 
            ||
| 2706 | mastr_gdf, buildings_gdf  | 
            ||
| 2707 | )  | 
            ||
| 2708 | |||
| 2709 | all_buildings_gdf = (  | 
            ||
| 2710 | desagg_mastr_gdf.assign(scenario="status_quo")  | 
            ||
| 2711 | .reset_index()  | 
            ||
| 2712 |         .rename(columns={"geometry": "geom", "EinheitMastrNummer": "gens_id"}) | 
            ||
| 2713 | )  | 
            ||
| 2714 | |||
| 2715 | scenario_buildings_gdf = all_buildings_gdf.copy()  | 
            ||
| 2716 | |||
| 2717 | cap_per_bus_id_df = pd.DataFrame()  | 
            ||
| 2718 | |||
| 2719 | for scenario in SCENARIOS:  | 
            ||
| 2720 |         logger.debug(f"Desaggregating scenario {scenario}.") | 
            ||
| 2721 | (  | 
            ||
| 2722 | scenario_buildings_gdf,  | 
            ||
| 2723 | cap_per_bus_id_scenario_df,  | 
            ||
| 2724 | ) = allocate_scenarios( # noqa: F841  | 
            ||
| 2725 | desagg_mastr_gdf,  | 
            ||
| 2726 | desagg_buildings_gdf,  | 
            ||
| 2727 | scenario_buildings_gdf,  | 
            ||
| 2728 | scenario,  | 
            ||
| 2729 | )  | 
            ||
| 2730 | |||
| 2731 | all_buildings_gdf = gpd.GeoDataFrame(  | 
            ||
| 2732 | pd.concat(  | 
            ||
| 2733 | [all_buildings_gdf, scenario_buildings_gdf], ignore_index=True  | 
            ||
| 2734 | ),  | 
            ||
| 2735 | crs=scenario_buildings_gdf.crs,  | 
            ||
| 2736 | geometry="geom",  | 
            ||
| 2737 | )  | 
            ||
| 2738 | |||
| 2739 | cap_per_bus_id_df = pd.concat(  | 
            ||
| 2740 | [cap_per_bus_id_df, cap_per_bus_id_scenario_df]  | 
            ||
| 2741 | )  | 
            ||
| 2742 | |||
| 2743 | # add weather cell  | 
            ||
| 2744 | all_buildings_gdf = add_weather_cell_id(all_buildings_gdf)  | 
            ||
| 2745 | |||
| 2746 | # export scenario  | 
            ||
| 2747 | create_scenario_table(add_voltage_level(all_buildings_gdf))  | 
            ||
| 2748 |