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