Conditions | 10 |
Total Lines | 228 |
Code Lines | 155 |
Lines | 12 |
Ratio | 5.26 % |
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:
Complex classes like data.datasets.power_plants.mastr.import_mastr() 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 | """Import MaStR dataset and write to DB tables |
||
172 | def import_mastr() -> None: |
||
173 | """Import MaStR data into database""" |
||
174 | |||
175 | def infer_voltage_level( |
||
176 | units_gdf: gpd.GeoDataFrame, |
||
177 | ) -> gpd.GeoDataFrame: |
||
178 | """ |
||
179 | Infer nan values in voltage level derived from generator capacity to |
||
180 | the power plants. |
||
181 | |||
182 | Parameters |
||
183 | ----------- |
||
184 | units_gdf : geopandas.GeoDataFrame |
||
185 | GeoDataFrame containing units with voltage levels from MaStR |
||
186 | Returnsunits_gdf: gpd.GeoDataFrame |
||
187 | ------- |
||
188 | geopandas.GeoDataFrame |
||
189 | GeoDataFrame containing units all having assigned a voltage level. |
||
190 | """ |
||
191 | |||
192 | View Code Duplication | def voltage_levels(p: float) -> int: |
|
193 | if p <= 100: |
||
194 | return 7 |
||
195 | elif p <= 200: |
||
196 | return 6 |
||
197 | elif p <= 5500: |
||
198 | return 5 |
||
199 | elif p <= 20000: |
||
200 | return 4 |
||
201 | elif p <= 120000: |
||
202 | return 3 |
||
203 | return 1 |
||
204 | |||
205 | units_gdf["voltage_level_inferred"] = False |
||
206 | mask = units_gdf.voltage_level.isna() |
||
207 | units_gdf.loc[mask, "voltage_level_inferred"] = True |
||
208 | units_gdf.loc[mask, "voltage_level"] = units_gdf.loc[ |
||
209 | mask |
||
210 | ].Nettonennleistung.apply(voltage_levels) |
||
211 | |||
212 | return units_gdf |
||
213 | |||
214 | engine = db.engine() |
||
215 | cfg = egon.data.config.datasets()["power_plants"] |
||
216 | |||
217 | cols_mapping = { |
||
218 | "all": { |
||
219 | "EinheitMastrNummer": "gens_id", |
||
220 | "EinheitBetriebsstatus": "status", |
||
221 | "Inbetriebnahmedatum": "commissioning_date", |
||
222 | "Postleitzahl": "postcode", |
||
223 | "Ort": "city", |
||
224 | "Bundesland": "federal_state", |
||
225 | "Nettonennleistung": "capacity", |
||
226 | "Einspeisungsart": "feedin_type", |
||
227 | }, |
||
228 | "pv": { |
||
229 | "Lage": "site_type", |
||
230 | "Nutzungsbereich": "usage_sector", |
||
231 | "Hauptausrichtung": "orientation_primary", |
||
232 | "HauptausrichtungNeigungswinkel": "orientation_primary_angle", |
||
233 | "Nebenausrichtung": "orientation_secondary", |
||
234 | "NebenausrichtungNeigungswinkel": "orientation_secondary_angle", |
||
235 | "EinheitlicheAusrichtungUndNeigungswinkel": "orientation_uniform", |
||
236 | "AnzahlModule": "module_count", |
||
237 | "zugeordneteWirkleistungWechselrichter": "capacity_inverter", |
||
238 | }, |
||
239 | "wind": { |
||
240 | "Lage": "site_type", |
||
241 | "Hersteller": "manufacturer_name", |
||
242 | "Typenbezeichnung": "type_name", |
||
243 | "Nabenhoehe": "hub_height", |
||
244 | "Rotordurchmesser": "rotor_diameter", |
||
245 | }, |
||
246 | "biomass": { |
||
247 | "Technologie": "technology", |
||
248 | "Hauptbrennstoff": "fuel_name", |
||
249 | "Biomasseart": "fuel_type", |
||
250 | "ThermischeNutzleistung": "th_capacity", |
||
251 | }, |
||
252 | "hydro": { |
||
253 | "ArtDerWasserkraftanlage": "plant_type", |
||
254 | "ArtDesZuflusses": "water_origin", |
||
255 | }, |
||
256 | } |
||
257 | |||
258 | source_files = { |
||
259 | "pv": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_pv"], |
||
260 | "wind": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_wind"], |
||
261 | "biomass": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_biomass"], |
||
262 | "hydro": WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_hydro"], |
||
263 | } |
||
264 | target_tables = { |
||
265 | "pv": EgonPowerPlantsPv, |
||
266 | "wind": EgonPowerPlantsWind, |
||
267 | "biomass": EgonPowerPlantsBiomass, |
||
268 | "hydro": EgonPowerPlantsHydro, |
||
269 | } |
||
270 | vlevel_mapping = { |
||
271 | "Höchstspannung": 1, |
||
272 | "UmspannungZurHochspannung": 2, |
||
273 | "Hochspannung": 3, |
||
274 | "UmspannungZurMittelspannung": 4, |
||
275 | "Mittelspannung": 5, |
||
276 | "UmspannungZurNiederspannung": 6, |
||
277 | "Niederspannung": 7, |
||
278 | } |
||
279 | |||
280 | # import locations |
||
281 | locations = pd.read_csv( |
||
282 | WORKING_DIR_MASTR_NEW / cfg["sources"]["mastr_location"], |
||
283 | index_col=None, |
||
284 | ) |
||
285 | |||
286 | # import grid districts |
||
287 | mv_grid_districts = db.select_geodataframe( |
||
288 | f""" |
||
289 | SELECT * FROM {cfg['sources']['egon_mv_grid_district']} |
||
290 | """, |
||
291 | epsg=4326, |
||
292 | ) |
||
293 | |||
294 | # import units |
||
295 | technologies = ["pv", "wind", "biomass", "hydro"] |
||
296 | for tech in technologies: |
||
297 | # read units |
||
298 | print(f"===== Importing MaStR dataset: {tech} =====") |
||
299 | print(" Reading CSV and filtering data...") |
||
300 | units = pd.read_csv( |
||
301 | source_files[tech], |
||
302 | usecols=( |
||
303 | ["LokationMastrNummer", "Laengengrad", "Breitengrad", "Land"] |
||
304 | + list(cols_mapping["all"].keys()) |
||
305 | + list(cols_mapping[tech].keys()) |
||
306 | ), |
||
307 | index_col=None, |
||
308 | dtype={"Postleitzahl": str}, |
||
309 | ).rename(columns=cols_mapping) |
||
310 | |||
311 | # drop units outside of Germany |
||
312 | len_old = len(units) |
||
313 | units = units.loc[units.Land == "Deutschland"] |
||
314 | print(f" {len_old-len(units)} units outside of Germany dropped...") |
||
315 | |||
316 | # filter for SH units if in testmode |
||
317 | if not TESTMODE_OFF: |
||
318 | print( |
||
319 | """ TESTMODE: |
||
320 | Dropping all units outside of Schleswig-Holstein... |
||
321 | """ |
||
322 | ) |
||
323 | units = units.loc[units.Bundesland == "SchleswigHolstein"] |
||
324 | |||
325 | # merge and rename voltage level |
||
326 | print(" Merging with locations and allocate voltage level...") |
||
327 | units = units.merge( |
||
328 | locations[["MaStRNummer", "Spannungsebene"]], |
||
329 | left_on="LokationMastrNummer", |
||
330 | right_on="MaStRNummer", |
||
331 | how="left", |
||
332 | ) |
||
333 | # convert voltage levels to numbers |
||
334 | units["voltage_level"] = units.Spannungsebene.replace(vlevel_mapping) |
||
335 | # set voltage level for nan values |
||
336 | units = infer_voltage_level(units) |
||
337 | |||
338 | # add geometry |
||
339 | print(" Adding geometries...") |
||
340 | units = gpd.GeoDataFrame( |
||
341 | units, |
||
342 | geometry=gpd.points_from_xy( |
||
343 | units["Laengengrad"], units["Breitengrad"], crs=4326 |
||
344 | ), |
||
345 | crs=4326, |
||
346 | ) |
||
347 | units_wo_geom = len( |
||
348 | units.loc[(units.Laengengrad.isna() | units.Laengengrad.isna())] |
||
349 | ) |
||
350 | print( |
||
351 | f" {units_wo_geom}/{len(units)} units do not have a geometry!" |
||
352 | ) |
||
353 | |||
354 | # drop unnecessary and rename columns |
||
355 | print(" Reformatting...") |
||
356 | units.drop( |
||
357 | columns=[ |
||
358 | "LokationMastrNummer", |
||
359 | "MaStRNummer", |
||
360 | "Laengengrad", |
||
361 | "Breitengrad", |
||
362 | "Spannungsebene", |
||
363 | "Land", |
||
364 | ], |
||
365 | inplace=True, |
||
366 | ) |
||
367 | mapping = cols_mapping["all"].copy() |
||
368 | mapping.update(cols_mapping[tech]) |
||
369 | mapping.update({"geometry": "geom"}) |
||
370 | units.rename(columns=mapping, inplace=True) |
||
371 | units["voltage_level"] = units.voltage_level.fillna(-1).astype(int) |
||
372 | |||
373 | units.set_geometry("geom", inplace=True) |
||
374 | units["id"] = range(0, len(units)) |
||
375 | |||
376 | # change capacity unit: kW to MW |
||
377 | units["capacity"] = units["capacity"] / 1e3 |
||
378 | if "capacity_inverter" in units.columns: |
||
379 | units["capacity_inverter"] = units["capacity_inverter"] / 1e3 |
||
380 | if "th_capacity" in units.columns: |
||
381 | units["th_capacity"] = units["th_capacity"] / 1e3 |
||
382 | |||
383 | # assign bus ids |
||
384 | print(" Assigning bus ids...") |
||
385 | units = units.assign( |
||
386 | bus_id=units.loc[~units.geom.x.isna()] |
||
387 | .sjoin(mv_grid_districts[["bus_id", "geom"]], how="left") |
||
388 | .drop(columns=["index_right"]) |
||
389 | .bus_id |
||
390 | ) |
||
391 | units["bus_id"] = units.bus_id.fillna(-1).astype(int) |
||
392 | |||
393 | # write to DB |
||
394 | print(f" Writing {len(units)} units to DB...") |
||
395 | units.to_postgis( |
||
396 | name=target_tables[tech].__tablename__, |
||
397 | con=engine, |
||
398 | if_exists="append", |
||
399 | schema=target_tables[tech].__table_args__["schema"], |
||
400 | ) |
||
401 |