Conditions | 9 |
Total Lines | 313 |
Code Lines | 204 |
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 |
||
312 | def import_mastr() -> None: |
||
313 | """Import MaStR data into database""" |
||
314 | engine = db.engine() |
||
315 | |||
316 | # import geocoded data |
||
317 | cfg = config.datasets()["mastr_new"] |
||
318 | path_parts = cfg["geocoding_path"] |
||
319 | path = Path(*["."] + path_parts).resolve() |
||
320 | path = list(path.iterdir())[0] |
||
321 | |||
322 | deposit_id_geocoding = int(path.parts[-1].split(".")[0].split("_")[-1]) |
||
323 | deposit_id_mastr = cfg["deposit_id"] |
||
324 | |||
325 | if deposit_id_geocoding != deposit_id_mastr: |
||
326 | raise AssertionError( |
||
327 | f"The zenodo (sandbox) deposit ID {deposit_id_mastr} for the MaStR" |
||
328 | f" dataset is not matching with the geocoding version " |
||
329 | f"{deposit_id_geocoding}. Make sure to hermonize the data. When " |
||
330 | f"the MaStR dataset is updated also update the geocoding and " |
||
331 | f"update the egon data bundle. The geocoding can be done using: " |
||
332 | f"https://github.com/RLI-sandbox/mastr-geocoding" |
||
333 | ) |
||
334 | |||
335 | geocoding_gdf = gpd.read_file(path) |
||
336 | |||
337 | # remove failed requests |
||
338 | geocoding_gdf = geocoding_gdf.loc[geocoding_gdf.geometry.is_valid] |
||
339 | |||
340 | EgonMastrGeocoded.__table__.drop(bind=engine, checkfirst=True) |
||
341 | EgonMastrGeocoded.__table__.create(bind=engine, checkfirst=True) |
||
342 | |||
343 | geocoding_gdf.to_postgis( |
||
344 | name=EgonMastrGeocoded.__tablename__, |
||
345 | con=engine, |
||
346 | if_exists="append", |
||
347 | schema=EgonMastrGeocoded.__table_args__["schema"], |
||
348 | index=True, |
||
349 | ) |
||
350 | |||
351 | cfg = config.datasets()["power_plants"] |
||
352 | |||
353 | cols_mapping = { |
||
354 | "all": { |
||
355 | "EinheitMastrNummer": "gens_id", |
||
356 | "EinheitBetriebsstatus": "status", |
||
357 | "Inbetriebnahmedatum": "commissioning_date", |
||
358 | "Postleitzahl": "postcode", |
||
359 | "Ort": "city", |
||
360 | "Gemeinde": "municipality", |
||
361 | "Bundesland": "federal_state", |
||
362 | "Nettonennleistung": "capacity", |
||
363 | "Einspeisungsart": "feedin_type", |
||
364 | }, |
||
365 | "pv": { |
||
366 | "Lage": "site_type", |
||
367 | "Standort": "site", |
||
368 | "Nutzungsbereich": "usage_sector", |
||
369 | "Hauptausrichtung": "orientation_primary", |
||
370 | "HauptausrichtungNeigungswinkel": "orientation_primary_angle", |
||
371 | "Nebenausrichtung": "orientation_secondary", |
||
372 | "NebenausrichtungNeigungswinkel": "orientation_secondary_angle", |
||
373 | "EinheitlicheAusrichtungUndNeigungswinkel": "orientation_uniform", |
||
374 | "AnzahlModule": "module_count", |
||
375 | "zugeordneteWirkleistungWechselrichter": "capacity_inverter", |
||
376 | }, |
||
377 | "wind": { |
||
378 | "Lage": "site_type", |
||
379 | "Hersteller": "manufacturer_name", |
||
380 | "Typenbezeichnung": "type_name", |
||
381 | "Nabenhoehe": "hub_height", |
||
382 | "Rotordurchmesser": "rotor_diameter", |
||
383 | }, |
||
384 | "biomass": { |
||
385 | "Technologie": "technology", |
||
386 | "Hauptbrennstoff": "fuel_name", |
||
387 | "Biomasseart": "fuel_type", |
||
388 | "ThermischeNutzleistung": "th_capacity", |
||
389 | }, |
||
390 | "hydro": { |
||
391 | "ArtDerWasserkraftanlage": "plant_type", |
||
392 | "ArtDesZuflusses": "water_origin", |
||
393 | }, |
||
394 | } |
||
395 | |||
396 | source_files = { |
||
397 | "pv": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_pv"], |
||
398 | "wind": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_wind"], |
||
399 | "biomass": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_biomass"], |
||
400 | "hydro": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_hydro"], |
||
401 | } |
||
402 | target_tables = { |
||
403 | "pv": EgonPowerPlantsPv, |
||
404 | "wind": EgonPowerPlantsWind, |
||
405 | "biomass": EgonPowerPlantsBiomass, |
||
406 | "hydro": EgonPowerPlantsHydro, |
||
407 | } |
||
408 | vlevel_mapping = { |
||
409 | "Höchstspannung": 1, |
||
410 | "UmspannungZurHochspannung": 2, |
||
411 | "Hochspannung": 3, |
||
412 | "UmspannungZurMittelspannung": 4, |
||
413 | "Mittelspannung": 5, |
||
414 | "UmspannungZurNiederspannung": 6, |
||
415 | "Niederspannung": 7, |
||
416 | } |
||
417 | |||
418 | # import locations |
||
419 | locations = pd.read_csv( |
||
420 | WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_location"], |
||
421 | index_col=None, |
||
422 | ) |
||
423 | |||
424 | # import grid districts |
||
425 | mv_grid_districts = db.select_geodataframe( |
||
426 | f""" |
||
427 | SELECT * FROM {cfg['sources']['egon_mv_grid_district']} |
||
428 | """, |
||
429 | epsg=4326, |
||
430 | ) |
||
431 | |||
432 | # import units |
||
433 | technologies = ["pv", "wind", "biomass", "hydro"] |
||
434 | for tech in technologies: |
||
435 | # read units |
||
436 | logger.info(f"===== Importing MaStR dataset: {tech} =====") |
||
437 | logger.debug("Reading CSV and filtering data...") |
||
438 | units = pd.read_csv( |
||
439 | source_files[tech], |
||
440 | usecols=( |
||
441 | ["LokationMastrNummer", "Laengengrad", "Breitengrad", "Land"] |
||
442 | + list(cols_mapping["all"].keys()) |
||
443 | + list(cols_mapping[tech].keys()) |
||
444 | ), |
||
445 | index_col=None, |
||
446 | dtype={"Postleitzahl": str}, |
||
447 | ).rename(columns=cols_mapping) |
||
448 | |||
449 | # drop units outside of Germany |
||
450 | len_old = len(units) |
||
451 | units = units.loc[units.Land == "Deutschland"] |
||
452 | logger.debug( |
||
453 | f"{len_old - len(units)} units outside of Germany dropped..." |
||
454 | ) |
||
455 | |||
456 | # get boundary |
||
457 | boundary = ( |
||
458 | federal_state_data(geocoding_gdf.crs).dissolve().at[0, "geom"] |
||
459 | ) |
||
460 | |||
461 | # filter for SH units if in testmode |
||
462 | if not TESTMODE_OFF: |
||
463 | logger.info( |
||
464 | "TESTMODE: Dropping all units outside of Schleswig-Holstein..." |
||
465 | ) |
||
466 | units = units.loc[units.Bundesland == "SchleswigHolstein"] |
||
467 | |||
468 | # merge and rename voltage level |
||
469 | logger.debug("Merging with locations and allocate voltage level...") |
||
470 | units = units.merge( |
||
471 | locations[["MaStRNummer", "Spannungsebene"]], |
||
472 | left_on="LokationMastrNummer", |
||
473 | right_on="MaStRNummer", |
||
474 | how="left", |
||
475 | ) |
||
476 | # convert voltage levels to numbers |
||
477 | units["voltage_level"] = units.Spannungsebene.replace(vlevel_mapping) |
||
478 | # set voltage level for nan values |
||
479 | units = infer_voltage_level(units) |
||
480 | |||
481 | # add geometry |
||
482 | logger.debug("Adding geometries...") |
||
483 | units = gpd.GeoDataFrame( |
||
484 | units, |
||
485 | geometry=gpd.points_from_xy( |
||
486 | units["Laengengrad"], units["Breitengrad"], crs=4326 |
||
487 | ), |
||
488 | crs=4326, |
||
489 | ) |
||
490 | |||
491 | units["geometry_geocoded"] = ( |
||
492 | units.Laengengrad.isna() | units.Laengengrad.isna() |
||
493 | ) |
||
494 | |||
495 | units.loc[~units.geometry_geocoded, "geometry_geocoded"] = ~units.loc[ |
||
496 | ~units.geometry_geocoded, "geometry" |
||
497 | ].is_valid |
||
498 | |||
499 | units_wo_geom = units["geometry_geocoded"].sum() |
||
500 | |||
501 | logger.debug( |
||
502 | f"{units_wo_geom}/{len(units)} units do not have a geometry!" |
||
503 | " Adding geocoding results." |
||
504 | ) |
||
505 | |||
506 | # determine zip and municipality string |
||
507 | mask = ( |
||
508 | units.Postleitzahl.apply(isfloat) |
||
509 | & ~units.Postleitzahl.isna() |
||
510 | & ~units.Gemeinde.isna() |
||
511 | ) |
||
512 | units["zip_and_municipality"] = np.nan |
||
513 | ok_units = units.loc[mask] |
||
514 | |||
515 | units.loc[mask, "zip_and_municipality"] = ( |
||
516 | ok_units.Postleitzahl.astype(int).astype(str).str.zfill(5) |
||
517 | + " " |
||
518 | + ok_units.Gemeinde.astype(str).str.rstrip().str.lstrip() |
||
519 | + ", Deutschland" |
||
520 | ) |
||
521 | |||
522 | # get zip and municipality from Standort |
||
523 | parse_df = units.loc[~mask] |
||
524 | |||
525 | if not parse_df.empty and "Standort" in parse_df.columns: |
||
526 | init_len = len(parse_df) |
||
527 | |||
528 | logger.info( |
||
529 | f"Parsing ZIP code and municipality from Standort for " |
||
530 | f"{init_len} values for {tech}." |
||
531 | ) |
||
532 | |||
533 | parse_df[["zip_and_municipality", "drop_this"]] = ( |
||
534 | parse_df.Standort.astype(str) |
||
535 | .apply(zip_and_municipality_from_standort) |
||
536 | .tolist() |
||
537 | ) |
||
538 | |||
539 | parse_df = parse_df.loc[parse_df.drop_this] |
||
540 | |||
541 | if not parse_df.empty: |
||
542 | units.loc[ |
||
543 | parse_df.index, "zip_and_municipality" |
||
544 | ] = parse_df.zip_and_municipality |
||
545 | |||
546 | # add geocoding to missing |
||
547 | units = units.merge( |
||
548 | right=geocoding_gdf[["zip_and_municipality", "geometry"]].rename( |
||
549 | columns={"geometry": "temp"} |
||
550 | ), |
||
551 | how="left", |
||
552 | on="zip_and_municipality", |
||
553 | ) |
||
554 | |||
555 | units.loc[units.geometry_geocoded, "geometry"] = units.loc[ |
||
556 | units.geometry_geocoded, "temp" |
||
557 | ] |
||
558 | |||
559 | init_len = len(units) |
||
560 | |||
561 | logger.info( |
||
562 | "Dropping units outside boundary by geometry or without geometry" |
||
563 | "..." |
||
564 | ) |
||
565 | |||
566 | units.dropna(subset=["geometry"], inplace=True) |
||
567 | |||
568 | units = units.loc[units.geometry.within(boundary)] |
||
569 | |||
570 | logger.debug( |
||
571 | f"{init_len - len(units)}/{init_len} " |
||
572 | f"({((init_len - len(units)) / init_len) * 100: g} %) dropped." |
||
573 | ) |
||
574 | |||
575 | # drop unnecessary and rename columns |
||
576 | logger.debug("Reformatting...") |
||
577 | units.drop( |
||
578 | columns=[ |
||
579 | "LokationMastrNummer", |
||
580 | "MaStRNummer", |
||
581 | "Laengengrad", |
||
582 | "Breitengrad", |
||
583 | "Spannungsebene", |
||
584 | "Land", |
||
585 | "temp", |
||
586 | ], |
||
587 | inplace=True, |
||
588 | ) |
||
589 | mapping = cols_mapping["all"].copy() |
||
590 | mapping.update(cols_mapping[tech]) |
||
591 | mapping.update({"geometry": "geom"}) |
||
592 | units.rename(columns=mapping, inplace=True) |
||
593 | units["voltage_level"] = units.voltage_level.fillna(-1).astype(int) |
||
594 | |||
595 | units.set_geometry("geom", inplace=True) |
||
596 | units["id"] = range(0, len(units)) |
||
597 | |||
598 | # change capacity unit: kW to MW |
||
599 | units["capacity"] = units["capacity"] / 1e3 |
||
600 | if "capacity_inverter" in units.columns: |
||
601 | units["capacity_inverter"] = units["capacity_inverter"] / 1e3 |
||
602 | if "th_capacity" in units.columns: |
||
603 | units["th_capacity"] = units["th_capacity"] / 1e3 |
||
604 | |||
605 | # assign bus ids |
||
606 | logger.debug("Assigning bus ids...") |
||
607 | units = units.assign( |
||
608 | bus_id=units.loc[~units.geom.x.isna()] |
||
609 | .sjoin(mv_grid_districts[["bus_id", "geom"]], how="left") |
||
610 | .drop(columns=["index_right"]) |
||
611 | .bus_id |
||
612 | ) |
||
613 | units["bus_id"] = units.bus_id.fillna(-1).astype(int) |
||
614 | |||
615 | # write to DB |
||
616 | logger.info(f"Writing {len(units)} units to DB...") |
||
617 | target_tables[tech].__table__.drop(bind=engine, checkfirst=True) |
||
618 | target_tables[tech].__table__.create(bind=engine, checkfirst=True) |
||
619 | |||
620 | units.to_postgis( |
||
621 | name=target_tables[tech].__tablename__, |
||
622 | con=engine, |
||
623 | if_exists="append", |
||
624 | schema=target_tables[tech].__table_args__["schema"], |
||
625 | ) |
||
626 |