| Conditions | 9 |
| Total Lines | 321 |
| Code Lines | 211 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | """Import MaStR dataset and write to DB tables |
||
| 154 | def import_mastr() -> None: |
||
| 155 | """Import MaStR data into database""" |
||
| 156 | engine = db.engine() |
||
| 157 | |||
| 158 | # import geocoded data |
||
| 159 | cfg = config.datasets()["mastr_new"] |
||
| 160 | path_parts = cfg["geocoding_path"] |
||
| 161 | path = Path(*["."] + path_parts).resolve() |
||
| 162 | path = list(path.iterdir())[0] |
||
| 163 | |||
| 164 | deposit_id_geocoding = int(path.parts[-1].split(".")[0].split("_")[-1]) |
||
| 165 | deposit_id_mastr = cfg["deposit_id"] |
||
| 166 | |||
| 167 | if deposit_id_geocoding != deposit_id_mastr: |
||
| 168 | raise AssertionError( |
||
| 169 | f"The zenodo (sandbox) deposit ID {deposit_id_mastr} for the MaStR" |
||
| 170 | f" dataset is not matching with the geocoding version " |
||
| 171 | f"{deposit_id_geocoding}. Make sure to hermonize the data. When " |
||
| 172 | f"the MaStR dataset is updated also update the geocoding and " |
||
| 173 | f"update the egon data bundle. The geocoding can be done using: " |
||
| 174 | f"https://github.com/RLI-sandbox/mastr-geocoding" |
||
| 175 | ) |
||
| 176 | |||
| 177 | geocoding_gdf = gpd.read_file(path) |
||
| 178 | |||
| 179 | # remove failed requests |
||
| 180 | geocoding_gdf = geocoding_gdf.loc[geocoding_gdf.geometry.is_valid] |
||
| 181 | |||
| 182 | EgonMastrGeocoded.__table__.drop(bind=engine, checkfirst=True) |
||
| 183 | EgonMastrGeocoded.__table__.create(bind=engine, checkfirst=True) |
||
| 184 | |||
| 185 | geocoding_gdf.to_postgis( |
||
| 186 | name=EgonMastrGeocoded.__tablename__, |
||
| 187 | con=engine, |
||
| 188 | if_exists="append", |
||
| 189 | schema=EgonMastrGeocoded.__table_args__["schema"], |
||
| 190 | index=True, |
||
| 191 | ) |
||
| 192 | |||
| 193 | cfg = config.datasets()["power_plants"] |
||
| 194 | |||
| 195 | cols_mapping = { |
||
| 196 | "all": { |
||
| 197 | "EinheitMastrNummer": "gens_id", |
||
| 198 | "EinheitBetriebsstatus": "status", |
||
| 199 | "Inbetriebnahmedatum": "commissioning_date", |
||
| 200 | "Postleitzahl": "postcode", |
||
| 201 | "Ort": "city", |
||
| 202 | "Gemeinde": "municipality", |
||
| 203 | "Bundesland": "federal_state", |
||
| 204 | "Nettonennleistung": "capacity", |
||
| 205 | "Einspeisungsart": "feedin_type", |
||
| 206 | }, |
||
| 207 | "pv": { |
||
| 208 | "Lage": "site_type", |
||
| 209 | "Standort": "site", |
||
| 210 | "Nutzungsbereich": "usage_sector", |
||
| 211 | "Hauptausrichtung": "orientation_primary", |
||
| 212 | "HauptausrichtungNeigungswinkel": "orientation_primary_angle", |
||
| 213 | "Nebenausrichtung": "orientation_secondary", |
||
| 214 | "NebenausrichtungNeigungswinkel": "orientation_secondary_angle", |
||
| 215 | "EinheitlicheAusrichtungUndNeigungswinkel": "orientation_uniform", |
||
| 216 | "AnzahlModule": "module_count", |
||
| 217 | "zugeordneteWirkleistungWechselrichter": "capacity_inverter", |
||
| 218 | }, |
||
| 219 | "wind": { |
||
| 220 | "Lage": "site_type", |
||
| 221 | "Hersteller": "manufacturer_name", |
||
| 222 | "Typenbezeichnung": "type_name", |
||
| 223 | "Nabenhoehe": "hub_height", |
||
| 224 | "Rotordurchmesser": "rotor_diameter", |
||
| 225 | }, |
||
| 226 | "biomass": { |
||
| 227 | "Technologie": "technology", |
||
| 228 | "Hauptbrennstoff": "main_fuel", |
||
| 229 | "Biomasseart": "fuel_type", |
||
| 230 | "ThermischeNutzleistung": "th_capacity", |
||
| 231 | }, |
||
| 232 | "hydro": { |
||
| 233 | "ArtDerWasserkraftanlage": "plant_type", |
||
| 234 | "ArtDesZuflusses": "water_origin", |
||
| 235 | }, |
||
| 236 | "combustion": { |
||
| 237 | "Energietraeger": "carrier", |
||
| 238 | "Hauptbrennstoff": "main_fuel", |
||
| 239 | "WeitererHauptbrennstoff": "other_main_fuel", |
||
| 240 | "Technologie": "technology", |
||
| 241 | "ThermischeNutzleistung": "th_capacity", |
||
| 242 | }, |
||
| 243 | } |
||
| 244 | |||
| 245 | source_files = { |
||
| 246 | "pv": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_pv"], |
||
| 247 | "wind": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_wind"], |
||
| 248 | "biomass": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_biomass"], |
||
| 249 | "hydro": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_hydro"], |
||
| 250 | "combustion": WORKING_DIR_MASTR_NEW |
||
| 251 | / cfg["sources"]["mastr_combustion"], |
||
| 252 | } |
||
| 253 | target_tables = { |
||
| 254 | "pv": EgonPowerPlantsPv, |
||
| 255 | "wind": EgonPowerPlantsWind, |
||
| 256 | "biomass": EgonPowerPlantsBiomass, |
||
| 257 | "hydro": EgonPowerPlantsHydro, |
||
| 258 | "combustion": EgonPowerPlantsCombustion, |
||
| 259 | } |
||
| 260 | vlevel_mapping = { |
||
| 261 | "Höchstspannung": 1, |
||
| 262 | "UmspannungZurHochspannung": 2, |
||
| 263 | "Hochspannung": 3, |
||
| 264 | "UmspannungZurMittelspannung": 4, |
||
| 265 | "Mittelspannung": 5, |
||
| 266 | "UmspannungZurNiederspannung": 6, |
||
| 267 | "Niederspannung": 7, |
||
| 268 | } |
||
| 269 | |||
| 270 | # import locations |
||
| 271 | locations = pd.read_csv( |
||
| 272 | WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_location"], |
||
| 273 | index_col=None, |
||
| 274 | ) |
||
| 275 | |||
| 276 | # import grid districts |
||
| 277 | mv_grid_districts = db.select_geodataframe( |
||
| 278 | f""" |
||
| 279 | SELECT * FROM {cfg['sources']['egon_mv_grid_district']} |
||
| 280 | """, |
||
| 281 | epsg=4326, |
||
| 282 | ) |
||
| 283 | |||
| 284 | # import units |
||
| 285 | technologies = ["pv", "wind", "biomass", "hydro", "combustion"] |
||
| 286 | for tech in technologies: |
||
| 287 | # read units |
||
| 288 | logger.info(f"===== Importing MaStR dataset: {tech} =====") |
||
| 289 | logger.debug("Reading CSV and filtering data...") |
||
| 290 | units = pd.read_csv( |
||
| 291 | source_files[tech], |
||
| 292 | usecols=( |
||
| 293 | ["LokationMastrNummer", "Laengengrad", "Breitengrad", "Land"] |
||
| 294 | + list(cols_mapping["all"].keys()) |
||
| 295 | + list(cols_mapping[tech].keys()) |
||
| 296 | ), |
||
| 297 | index_col=None, |
||
| 298 | dtype={"Postleitzahl": str}, |
||
| 299 | ).rename(columns=cols_mapping) |
||
| 300 | |||
| 301 | # drop units outside of Germany |
||
| 302 | len_old = len(units) |
||
| 303 | units = units.loc[units.Land == "Deutschland"] |
||
| 304 | logger.debug( |
||
| 305 | f"{len_old - len(units)} units outside of Germany dropped..." |
||
| 306 | ) |
||
| 307 | |||
| 308 | # get boundary |
||
| 309 | boundary = ( |
||
| 310 | federal_state_data(geocoding_gdf.crs).dissolve().at[0, "geom"] |
||
| 311 | ) |
||
| 312 | |||
| 313 | # filter for SH units if in testmode |
||
| 314 | if not TESTMODE_OFF: |
||
| 315 | logger.info( |
||
| 316 | "TESTMODE: Dropping all units outside of Schleswig-Holstein..." |
||
| 317 | ) |
||
| 318 | units = units.loc[units.Bundesland == "SchleswigHolstein"] |
||
| 319 | |||
| 320 | # merge and rename voltage level |
||
| 321 | logger.debug("Merging with locations and allocate voltage level...") |
||
| 322 | units = units.merge( |
||
| 323 | locations[["MaStRNummer", "Spannungsebene"]], |
||
| 324 | left_on="LokationMastrNummer", |
||
| 325 | right_on="MaStRNummer", |
||
| 326 | how="left", |
||
| 327 | ) |
||
| 328 | # convert voltage levels to numbers |
||
| 329 | units["voltage_level"] = units.Spannungsebene.replace(vlevel_mapping) |
||
| 330 | # set voltage level for nan values |
||
| 331 | units = infer_voltage_level(units) |
||
| 332 | |||
| 333 | # add geometry |
||
| 334 | logger.debug("Adding geometries...") |
||
| 335 | units = gpd.GeoDataFrame( |
||
| 336 | units, |
||
| 337 | geometry=gpd.points_from_xy( |
||
| 338 | units["Laengengrad"], units["Breitengrad"], crs=4326 |
||
| 339 | ), |
||
| 340 | crs=4326, |
||
| 341 | ) |
||
| 342 | |||
| 343 | units["geometry_geocoded"] = ( |
||
| 344 | units.Laengengrad.isna() | units.Laengengrad.isna() |
||
| 345 | ) |
||
| 346 | |||
| 347 | units.loc[~units.geometry_geocoded, "geometry_geocoded"] = ~units.loc[ |
||
| 348 | ~units.geometry_geocoded, "geometry" |
||
| 349 | ].is_valid |
||
| 350 | |||
| 351 | units_wo_geom = units["geometry_geocoded"].sum() |
||
| 352 | |||
| 353 | logger.debug( |
||
| 354 | f"{units_wo_geom}/{len(units)} units do not have a geometry!" |
||
| 355 | " Adding geocoding results." |
||
| 356 | ) |
||
| 357 | |||
| 358 | # determine zip and municipality string |
||
| 359 | mask = ( |
||
| 360 | units.Postleitzahl.apply(isfloat) |
||
| 361 | & ~units.Postleitzahl.isna() |
||
| 362 | & ~units.Gemeinde.isna() |
||
| 363 | ) |
||
| 364 | units["zip_and_municipality"] = np.nan |
||
| 365 | ok_units = units.loc[mask] |
||
| 366 | |||
| 367 | units.loc[mask, "zip_and_municipality"] = ( |
||
| 368 | ok_units.Postleitzahl.astype(int).astype(str).str.zfill(5) |
||
| 369 | + " " |
||
| 370 | + ok_units.Gemeinde.astype(str).str.rstrip().str.lstrip() |
||
| 371 | + ", Deutschland" |
||
| 372 | ) |
||
| 373 | |||
| 374 | # get zip and municipality from Standort |
||
| 375 | parse_df = units.loc[~mask] |
||
| 376 | |||
| 377 | if not parse_df.empty and "Standort" in parse_df.columns: |
||
| 378 | init_len = len(parse_df) |
||
| 379 | |||
| 380 | logger.info( |
||
| 381 | f"Parsing ZIP code and municipality from Standort for " |
||
| 382 | f"{init_len} values for {tech}." |
||
| 383 | ) |
||
| 384 | |||
| 385 | parse_df[["zip_and_municipality", "drop_this"]] = ( |
||
| 386 | parse_df.Standort.astype(str) |
||
| 387 | .apply(zip_and_municipality_from_standort) |
||
| 388 | .tolist() |
||
| 389 | ) |
||
| 390 | |||
| 391 | parse_df = parse_df.loc[parse_df.drop_this] |
||
| 392 | |||
| 393 | if not parse_df.empty: |
||
| 394 | units.loc[ |
||
| 395 | parse_df.index, "zip_and_municipality" |
||
| 396 | ] = parse_df.zip_and_municipality |
||
| 397 | |||
| 398 | # add geocoding to missing |
||
| 399 | units = units.merge( |
||
| 400 | right=geocoding_gdf[["zip_and_municipality", "geometry"]].rename( |
||
| 401 | columns={"geometry": "temp"} |
||
| 402 | ), |
||
| 403 | how="left", |
||
| 404 | on="zip_and_municipality", |
||
| 405 | ) |
||
| 406 | |||
| 407 | units.loc[units.geometry_geocoded, "geometry"] = units.loc[ |
||
| 408 | units.geometry_geocoded, "temp" |
||
| 409 | ] |
||
| 410 | |||
| 411 | init_len = len(units) |
||
| 412 | |||
| 413 | logger.info( |
||
| 414 | "Dropping units outside boundary by geometry or without geometry" |
||
| 415 | "..." |
||
| 416 | ) |
||
| 417 | |||
| 418 | units.dropna(subset=["geometry"], inplace=True) |
||
| 419 | |||
| 420 | units = units.loc[units.geometry.within(boundary)] |
||
| 421 | |||
| 422 | logger.debug( |
||
| 423 | f"{init_len - len(units)}/{init_len} " |
||
| 424 | f"({((init_len - len(units)) / init_len) * 100: g} %) dropped." |
||
| 425 | ) |
||
| 426 | |||
| 427 | # drop unnecessary and rename columns |
||
| 428 | logger.debug("Reformatting...") |
||
| 429 | units.drop( |
||
| 430 | columns=[ |
||
| 431 | "LokationMastrNummer", |
||
| 432 | "MaStRNummer", |
||
| 433 | "Laengengrad", |
||
| 434 | "Breitengrad", |
||
| 435 | "Spannungsebene", |
||
| 436 | "Land", |
||
| 437 | "temp", |
||
| 438 | ], |
||
| 439 | inplace=True, |
||
| 440 | ) |
||
| 441 | mapping = cols_mapping["all"].copy() |
||
| 442 | mapping.update(cols_mapping[tech]) |
||
| 443 | mapping.update({"geometry": "geom"}) |
||
| 444 | units.rename(columns=mapping, inplace=True) |
||
| 445 | units["voltage_level"] = units.voltage_level.fillna(-1).astype(int) |
||
| 446 | |||
| 447 | units.set_geometry("geom", inplace=True) |
||
| 448 | units["id"] = range(0, len(units)) |
||
| 449 | |||
| 450 | # change capacity unit: kW to MW |
||
| 451 | units["capacity"] = units["capacity"] / 1e3 |
||
| 452 | if "capacity_inverter" in units.columns: |
||
| 453 | units["capacity_inverter"] = units["capacity_inverter"] / 1e3 |
||
| 454 | if "th_capacity" in units.columns: |
||
| 455 | units["th_capacity"] = units["th_capacity"] / 1e3 |
||
| 456 | |||
| 457 | # assign bus ids |
||
| 458 | logger.debug("Assigning bus ids...") |
||
| 459 | units = units.assign( |
||
| 460 | bus_id=units.loc[~units.geom.x.isna()] |
||
| 461 | .sjoin(mv_grid_districts[["bus_id", "geom"]], how="left") |
||
| 462 | .drop(columns=["index_right"]) |
||
| 463 | .bus_id |
||
| 464 | ) |
||
| 465 | units["bus_id"] = units.bus_id.fillna(-1).astype(int) |
||
| 466 | |||
| 467 | # write to DB |
||
| 468 | logger.info(f"Writing {len(units)} units to DB...") |
||
| 469 | |||
| 470 | units.to_postgis( |
||
| 471 | name=target_tables[tech].__tablename__, |
||
| 472 | con=engine, |
||
| 473 | if_exists="append", |
||
| 474 | schema=target_tables[tech].__table_args__["schema"], |
||
| 475 | ) |
||
| 476 |