diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index aba8c0466..f8a2f8e62 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,18 @@ repos: # rev: pylint-2.6.0 # hooks: # - id: pylint +- repo: https://github.com/Lucas-C/pre-commit-hooks + rev: v1.5.5 + hooks: + - id: insert-license + files: \.py$ + exclude: ^tests/ + args: + - --license-filepath + - .license-header.txt + - --comment-style + - "#" + - --no-extra-eol - repo: https://github.com/kynan/nbstripout rev: 0.8.1 hooks: diff --git a/doc/conf.py b/doc/conf.py index 468f0636a..32f1cf9cb 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -1,17 +1,13 @@ -"""This file is part of DINGO, the DIstribution Network GeneratOr. -DINGO is a tool to generate synthetic medium and low voltage power -distribution grids based on open data. - -It is developed in the project open_eGo: https://openegoproject.wordpress.com - -DINGO lives at github: https://github.com/openego/dingo/ -The documentation is available on RTD: https://edisgo.readthedocs.io/en/dev/""" - -__copyright__ = "Reiner Lemoine Institut gGmbH" -__license__ = "GNU Affero General Public License Version 3 (AGPL-3.0)" -__url__ = "https://github.com/openego/eDisGo/blob/dev/LICENSE" -__author__ = "nesnoj, gplssm" - +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later # -*- coding: utf-8 -*- # diff --git a/edisgo/__init__.py b/edisgo/__init__.py index d353280c8..c6f599801 100644 --- a/edisgo/__init__.py +++ b/edisgo/__init__.py @@ -1 +1,12 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from edisgo.edisgo import EDisGo # noqa: F401 diff --git a/edisgo/edisgo.py b/edisgo/edisgo.py index afff39a7f..8770308b3 100755 --- a/edisgo/edisgo.py +++ b/edisgo/edisgo.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import copy @@ -2646,8 +2657,8 @@ def plot_voltage_over_dist( if getattr(v_a, "empty", True) or getattr(v_b, "empty", True): raise RuntimeError( "Voltage results (results.v_res) are empty. " - "Run analyze() with timesteps/snapshots so voltage results " - "are generated." + "Run analyze() with timesteps/snapshots so voltage " + "results are generated." ) # Resolve LV grids (index-based resolution) lv_grids_a = list(self.topology.mv_grid.lv_grids) @@ -2816,8 +2827,8 @@ def _lv_source_bus(lv_grid): def plot_voltage_over_dist_mv(self, mv_id, other, save_as=False, return_data=False): """ - Plot MV voltage over distance to the HV/MV transformer, comparing two - EDisGo objects. + Plot MV voltage over distance to the HV/MV transformer, + comparing two EDisGo objects. Parameters ---------- @@ -2839,8 +2850,8 @@ def plot_voltage_over_dist_mv(self, mv_id, other, save_as=False, return_data=Fal if getattr(v_a, "empty", True) or getattr(v_b, "empty", True): raise RuntimeError( "Voltage results (results.v_res) are empty. " - "Run analyze() with timesteps/snapshots so voltage results " - "are generated." + "Run analyze() with timesteps/snapshots so voltage " + "results are generated." ) mv_a = self.topology.mv_grid mv_b = other.topology.mv_grid diff --git a/edisgo/flex_opt/__init__.py b/edisgo/flex_opt/__init__.py index e69de29bb..668095486 100644 --- a/edisgo/flex_opt/__init__.py +++ b/edisgo/flex_opt/__init__.py @@ -0,0 +1,10 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/edisgo/flex_opt/battery_storage_operation.py b/edisgo/flex_opt/battery_storage_operation.py index 64447a8fd..7c8773d47 100644 --- a/edisgo/flex_opt/battery_storage_operation.py +++ b/edisgo/flex_opt/battery_storage_operation.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import math diff --git a/edisgo/flex_opt/charging_strategies.py b/edisgo/flex_opt/charging_strategies.py index fe1f4c6ac..bad559c51 100644 --- a/edisgo/flex_opt/charging_strategies.py +++ b/edisgo/flex_opt/charging_strategies.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging @@ -224,8 +235,8 @@ def charging_strategy( # "residual" charging # only use charging processes from integrated charging parks charging_processes_df = edisgo_obj.electromobility.charging_processes_df[ - edisgo_obj.electromobility.charging_processes_df.charging_park_id.isin( - target_park_ids + edisgo_obj.electromobility.charging_processes_df.charging_park_id.isin( + target_park_ids ) ] diff --git a/edisgo/flex_opt/check_tech_constraints.py b/edisgo/flex_opt/check_tech_constraints.py index 1a90dc36f..f1b022493 100644 --- a/edisgo/flex_opt/check_tech_constraints.py +++ b/edisgo/flex_opt/check_tech_constraints.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import numpy as np diff --git a/edisgo/flex_opt/costs.py b/edisgo/flex_opt/costs.py index d36fc4893..31cac8c6b 100644 --- a/edisgo/flex_opt/costs.py +++ b/edisgo/flex_opt/costs.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import os @@ -162,9 +173,7 @@ def _get_line_costs(lines_added): ]["quantity"].to_frame() lines_added_unique = lines_added.index.unique() lines_added = ( - lines_added.groupby(level=0) - .sum() - .loc[lines_added_unique, ["quantity"]] + lines_added.groupby(level=0).sum().loc[lines_added_unique, ["quantity"]] ) # use the minimum of quantity and num_parallel, as sometimes lines are added # and in a next reinforcement step removed again, e.g. when feeder is split diff --git a/edisgo/flex_opt/exceptions.py b/edisgo/flex_opt/exceptions.py index 8b2ea17d0..ef587e2a8 100644 --- a/edisgo/flex_opt/exceptions.py +++ b/edisgo/flex_opt/exceptions.py @@ -1,3 +1,15 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + + class Error(Exception): """Base class for exceptions in this module.""" diff --git a/edisgo/flex_opt/heat_pump_operation.py b/edisgo/flex_opt/heat_pump_operation.py index 88cb413e5..e6a0d6fb9 100644 --- a/edisgo/flex_opt/heat_pump_operation.py +++ b/edisgo/flex_opt/heat_pump_operation.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import pandas as pd diff --git a/edisgo/flex_opt/q_control.py b/edisgo/flex_opt/q_control.py index 07183a7d5..466de17c9 100644 --- a/edisgo/flex_opt/q_control.py +++ b/edisgo/flex_opt/q_control.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import numpy as np import pandas as pd diff --git a/edisgo/flex_opt/reinforce_grid.py b/edisgo/flex_opt/reinforce_grid.py index e56eb58b4..5ed4c16c6 100644 --- a/edisgo/flex_opt/reinforce_grid.py +++ b/edisgo/flex_opt/reinforce_grid.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import datetime diff --git a/edisgo/flex_opt/reinforce_measures.py b/edisgo/flex_opt/reinforce_measures.py index 1b0b98512..88eb8fb3c 100644 --- a/edisgo/flex_opt/reinforce_measures.py +++ b/edisgo/flex_opt/reinforce_measures.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging @@ -506,9 +517,9 @@ def reinforce_lines_voltage_issues(edisgo_obj, grid, crit_nodes): else: raise ValueError("Bus not in line buses. Please check.") # change line length and type - edisgo_obj.topology._lines_df.at[ - crit_line_name, "length" - ] = path_length_dict[node_2_3] + edisgo_obj.topology._lines_df.at[crit_line_name, "length"] = ( + path_length_dict[node_2_3] + ) edisgo_obj.topology.change_line_type([crit_line_name], standard_line) lines_changes[crit_line_name] = 1 # TODO: Include switch disconnector diff --git a/edisgo/io/__init__.py b/edisgo/io/__init__.py index e69de29bb..668095486 100644 --- a/edisgo/io/__init__.py +++ b/edisgo/io/__init__.py @@ -0,0 +1,10 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/edisgo/io/db.py b/edisgo/io/db.py index 138ebe735..fa153744c 100644 --- a/edisgo/io/db.py +++ b/edisgo/io/db.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import importlib.util diff --git a/edisgo/io/ding0_import.py b/edisgo/io/ding0_import.py index 326553111..74476dda4 100644 --- a/edisgo/io/ding0_import.py +++ b/edisgo/io/ding0_import.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import os import pandas as pd @@ -45,9 +56,9 @@ def sort_transformer_buses(transformers_df): voltage_bus1 = edisgo_obj.topology.buses_df.loc[ transformers_df.bus1 ].v_nom.values - transformers_df.loc[ - voltage_bus1 > voltage_bus0, ["bus0", "bus1"] - ] = transformers_df.loc[voltage_bus1 > voltage_bus0, ["bus1", "bus0"]].values + transformers_df.loc[voltage_bus1 > voltage_bus0, ["bus0", "bus1"]] = ( + transformers_df.loc[voltage_bus1 > voltage_bus0, ["bus1", "bus0"]].values + ) return transformers_df def sort_hvmv_transformer_buses(transformers_df): diff --git a/edisgo/io/dsm_import.py b/edisgo/io/dsm_import.py index fb0637036..51a8d5446 100644 --- a/edisgo/io/dsm_import.py +++ b/edisgo/io/dsm_import.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging diff --git a/edisgo/io/electromobility_import.py b/edisgo/io/electromobility_import.py index 68c17e214..169ff7f9a 100644 --- a/edisgo/io/electromobility_import.py +++ b/edisgo/io/electromobility_import.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import json @@ -1079,11 +1090,11 @@ def distribute_public_charging_demand(edisgo_obj, **kwargs): idx, "charging_point_id" ] = charging_point_id - available_charging_points_df.loc[ - charging_point_id - ] = edisgo_obj.electromobility.charging_processes_df.loc[ - idx, available_charging_points_df.columns - ].tolist() + available_charging_points_df.loc[charging_point_id] = ( + edisgo_obj.electromobility.charging_processes_df.loc[ + idx, available_charging_points_df.columns + ].tolist() + ) designated_charging_point_capacity_df.at[ charging_park_id, "designated_charging_point_capacity" diff --git a/edisgo/io/generators_import.py b/edisgo/io/generators_import.py index e6dd57265..0db84ab1c 100755 --- a/edisgo/io/generators_import.py +++ b/edisgo/io/generators_import.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging @@ -25,10 +36,14 @@ import geopandas as gpd from egoio.db_tables import model_draft, supply - from edisgo.io.mviews_filters import build_conv_scenario_filter, build_res_scenario_filter from shapely.ops import transform from shapely.wkt import loads as wkt_loads + from edisgo.io.mviews_filters import ( + build_conv_scenario_filter, + build_res_scenario_filter, + ) + if TYPE_CHECKING: from edisgo import EDisGo @@ -125,14 +140,11 @@ def _import_conv_generators(session): orm_conv_generators.capacity.label("p_nom"), orm_conv_generators.voltage_level, orm_conv_generators.fuel.label("generator_type"), - func.ST_AsText( - func.ST_Transform(orm_conv_generators.geom, srid) - ).label("geom"), - ) - .filter( - orm_conv_generators.subst_id - == edisgo_object.topology.mv_grid.id + func.ST_AsText(func.ST_Transform(orm_conv_generators.geom, srid)).label( + "geom" + ), ) + .filter(orm_conv_generators.subst_id == edisgo_object.topology.mv_grid.id) .filter(orm_conv_generators.voltage_level.in_([4, 5])) .filter(orm_conv_generators_version) ) @@ -175,13 +187,11 @@ def _import_res_generators(session): func.ST_AsText( func.ST_Transform(orm_re_generators.rea_geom_new, srid) ).label("geom"), - func.ST_AsText( - func.ST_Transform(orm_re_generators.geom, srid) - ).label("geom_em"), - ) - .filter( - orm_re_generators.subst_id == edisgo_object.topology.mv_grid.id + func.ST_AsText(func.ST_Transform(orm_re_generators.geom, srid)).label( + "geom_em" + ), ) + .filter(orm_re_generators.subst_id == edisgo_object.topology.mv_grid.id) .filter(orm_re_generators_version) ) @@ -305,18 +315,16 @@ def _validate_sample_geno_location(): # Map generator_scenario to full scenario names for mview filter logic scenario_mapping = { - 'nep2035': 'NEP 2035', - 'ego100': 'eGo 100', - 'status_quo': 'Status Quo', - 'sq': 'Status Quo' + "nep2035": "NEP 2035", + "ego100": "eGo 100", + "status_quo": "Status Quo", + "sq": "Status Quo", } - scenario_name = scenario_mapping.get( - generator_scenario.lower(), - generator_scenario - ) + scenario_name = scenario_mapping.get(generator_scenario.lower(), generator_scenario) if oedb_data_source == "model_draft": - # Use base tables from model_draft schema (CamelCase ORM names, without _mview suffix) + # Use base tables from model_draft schema + # (CamelCase ORM names, without _mview suffix) orm_conv_generators = model_draft.__getattribute__("EgoDpSupplyConvPowerplant") orm_re_generators = model_draft.__getattribute__("EgoDpSupplyResPowerplant") @@ -331,7 +339,8 @@ def _validate_sample_geno_location(): elif oedb_data_source == "versioned": data_version = edisgo_object.config["versioned"]["version"] - # Use base tables from supply schema (CamelCase ORM names, without _mview suffix) + # Use base tables from supply schema + # (CamelCase ORM names, without _mview suffix) orm_conv_generators = supply.__getattribute__("EgoDpConvPowerplant") orm_re_generators = supply.__getattribute__("EgoDpResPowerplant") diff --git a/edisgo/io/heat_pump_import.py b/edisgo/io/heat_pump_import.py index 921461514..fc0779a5a 100644 --- a/edisgo/io/heat_pump_import.py +++ b/edisgo/io/heat_pump_import.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import os import random diff --git a/edisgo/io/mviews_filters.py b/edisgo/io/mviews_filters.py index dca543d7a..19b0c2d2f 100644 --- a/edisgo/io/mviews_filters.py +++ b/edisgo/io/mviews_filters.py @@ -1,15 +1,16 @@ -""" -Helper functions to build scenario filters that replicate mview logic. - -These functions create SQLAlchemy filter conditions that match the original -materialized view definitions, allowing direct queries on base tables. - -Author: Generated for mviews replacement -Date: 2025-12-17 -""" - - -def build_conv_scenario_filter(orm_table, scenario, version=None, preversion='v0.3.0'): +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + + +def build_conv_scenario_filter(orm_table, scenario, version=None, preversion="v0.3.0"): """ Build filter conditions for conventional power plants matching mview logic. @@ -31,10 +32,10 @@ def build_conv_scenario_filter(orm_table, scenario, version=None, preversion='v0 """ # Set default versions if version is None: - if scenario in ['NEP 2035', 'eGo 100']: - versions = ['v0.4.2', 'v0.4.4', 'v0.4.5'] + if scenario in ["NEP 2035", "eGo 100"]: + versions = ["v0.4.2", "v0.4.4", "v0.4.5"] else: - versions = ['v0.4.5'] + versions = ["v0.4.5"] else: versions = [version] if isinstance(version, str) else version @@ -45,39 +46,44 @@ def build_conv_scenario_filter(orm_table, scenario, version=None, preversion='v0 ] # Version filter - if hasattr(orm_table, 'version'): + if hasattr(orm_table, "version"): filters.append(orm_table.version.in_(versions)) # Scenario-specific filters - if scenario == 'eGo 100': + if scenario == "eGo 100": # eGo 100: only pumped storage from NEP 2035 - filters.extend([ - orm_table.scenario == 'NEP 2035', - orm_table.fuel == 'pumped_storage', - (orm_table.shutdown == None) | - (orm_table.shutdown >= 2049) - ]) - elif scenario == 'NEP 2035': + filters.extend( + [ + orm_table.scenario == "NEP 2035", + orm_table.fuel == "pumped_storage", + (orm_table.shutdown == None) # noqa: E711 + | (orm_table.shutdown >= 2049), + ] + ) + elif scenario == "NEP 2035": # NEP 2035: exclude hydro, filter by shutdown # Note: OEP doesn't support NOT IN, so we use individual != filters - filters.extend([ - orm_table.scenario == 'NEP 2035', - orm_table.fuel != 'hydro', - orm_table.fuel != 'run_of_river', - orm_table.fuel != 'reservoir', - (orm_table.shutdown == None) | - (orm_table.shutdown >= 2034) - ]) + filters.extend( + [ + orm_table.scenario == "NEP 2035", + orm_table.fuel != "hydro", + orm_table.fuel != "run_of_river", + orm_table.fuel != "reservoir", + (orm_table.shutdown == None) # noqa: E711 + | (orm_table.shutdown >= 2034), + ] + ) else: # Generic scenario filter filters.append(orm_table.scenario == scenario) # Combine all filters with AND from sqlalchemy import and_ + return and_(*filters) -def build_res_scenario_filter(orm_table, scenario, version=None, preversion='v0.3.0'): +def build_res_scenario_filter(orm_table, scenario, version=None, preversion="v0.3.0"): """ Build filter conditions for renewable power plants matching mview logic. @@ -105,11 +111,11 @@ def build_res_scenario_filter(orm_table, scenario, version=None, preversion='v0. # Set default versions if version is None: - if scenario == 'Status Quo': - versions = ['v0.4.4', 'v0.4.5'] + if scenario == "Status Quo": + versions = ["v0.4.4", "v0.4.5"] else: # NEP 2035 uses v0.4.4 and v0.4.5 - versions = ['v0.4.4', 'v0.4.5'] + versions = ["v0.4.4", "v0.4.5"] else: versions = [version] if isinstance(version, str) else version @@ -120,37 +126,34 @@ def build_res_scenario_filter(orm_table, scenario, version=None, preversion='v0. ] # Version filter - if hasattr(orm_table, 'version'): + if hasattr(orm_table, "version"): base_filters.append(orm_table.version.in_(versions)) # Scenario-specific filters - if scenario == 'NEP 2035': + if scenario == "NEP 2035": # NEP 2035 mview is UNION of: # 1. Status Quo generators (solar/wind only, no offshore) # 2. NEP 2035 generators (all types) status_quo_filters = [ - orm_table.scenario == 'Status Quo', - orm_table.generation_type.in_(['solar', 'wind']), - orm_table.generation_subtype != 'wind_offshore' - ] - nep2035_filters = [ - orm_table.scenario == 'NEP 2035' + orm_table.scenario == "Status Quo", + orm_table.generation_type.in_(["solar", "wind"]), + orm_table.generation_subtype != "wind_offshore", ] + nep2035_filters = [orm_table.scenario == "NEP 2035"] # Combine: (Status Quo conditions) OR (NEP 2035 conditions) - scenario_filter = or_( - and_(*status_quo_filters), - and_(*nep2035_filters) - ) + scenario_filter = or_(and_(*status_quo_filters), and_(*nep2035_filters)) base_filters.append(scenario_filter) - elif scenario == 'Status Quo': + elif scenario == "Status Quo": # Status Quo: only solar and wind (excluding offshore) - base_filters.extend([ - orm_table.scenario == 'Status Quo', - orm_table.generation_type.in_(['solar', 'wind']), - orm_table.generation_subtype != 'wind_offshore' - ]) + base_filters.extend( + [ + orm_table.scenario == "Status Quo", + orm_table.generation_type.in_(["solar", "wind"]), + orm_table.generation_subtype != "wind_offshore", + ] + ) else: # Generic scenario filter for other scenarios (like eGo 100) base_filters.append(orm_table.scenario == scenario) diff --git a/edisgo/io/mviews_replacement.py b/edisgo/io/mviews_replacement.py index 556857958..6c1911127 100644 --- a/edisgo/io/mviews_replacement.py +++ b/edisgo/io/mviews_replacement.py @@ -1,17 +1,19 @@ -""" -Replacement functions for deprecated materialized views (mviews) in eDisGo/oedb. - -This module provides functions to replace the deprecated mviews by directly querying -the underlying base tables with appropriate filters. The filter logic is extracted -from the original mview definitions in mviews_definitions.sql. - -Author: Generated for mviews replacement -Date: 2025-12-17 -""" +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +from typing import Literal, Optional import pandas as pd + from sqlalchemy import text -from typing import Optional, Literal class MviewsReplacement: @@ -38,9 +40,9 @@ def get_conv_powerplant( self, scenario: str, version: Optional[str] = None, - preversion: str = 'v0.3.0', - schema: Literal['model_draft', 'data'] = 'data', - table_name: str = 'ego_dp_conv_powerplant' + preversion: str = "v0.3.0", + schema: Literal["model_draft", "data"] = "data", + table_name: str = "ego_dp_conv_powerplant", ) -> pd.DataFrame: """ Load conventional power plant data (replaces ego_dp_conv_powerplant_*_mview). @@ -71,10 +73,10 @@ def get_conv_powerplant( """ # Set default versions based on scenario if version is None: - if scenario in ['NEP 2035', 'eGo 100']: - version_list = ['v0.4.2', 'v0.4.4', 'v0.4.5'] + if scenario in ["NEP 2035", "eGo 100"]: + version_list = ["v0.4.2", "v0.4.4", "v0.4.5"] else: - version_list = ['v0.4.5'] + version_list = ["v0.4.5"] else: version_list = [version] if isinstance(version, str) else version @@ -82,7 +84,7 @@ def get_conv_powerplant( version_filter = "', '".join(version_list) # Base query - selecting all columns from the table - if scenario == 'eGo 100': + if scenario == "eGo 100": # Special case for eGo 100: only pumped storage from NEP 2035 query = f""" SELECT DISTINCT @@ -104,7 +106,7 @@ def get_conv_powerplant( AND preversion = '{preversion}' AND version IN ('{version_filter}') """ - elif scenario == 'NEP 2035': + elif scenario == "NEP 2035": # NEP 2035: exclude hydro plants, filter by shutdown date query = f""" SELECT DISTINCT @@ -132,7 +134,7 @@ def get_conv_powerplant( shutdown, status, fuel, technology, type, eeg, chp, capacity, capacity_uba, chp_capacity_uba, efficiency_data, efficiency_estimate, network_node, voltage, network_operator, name_uba, lat, lon, comment, - geom, voltage_level, subst_id, otg_id, un_id, la_id, scenario, flag, nuts + geom, voltage_level, subst_id, otg_id, un_id, la_id, scenario, flag, nuts # noqa: E501 FROM {schema}.{table_name} WHERE scenario = '{scenario}' AND capacity > 0 @@ -147,9 +149,9 @@ def get_res_powerplant( self, scenario: str, version: Optional[str] = None, - preversion: str = 'v0.3.0', - schema: Literal['model_draft', 'data'] = 'data', - table_name: str = 'ego_dp_res_powerplant' + preversion: str = "v0.3.0", + schema: Literal["model_draft", "data"] = "data", + table_name: str = "ego_dp_res_powerplant", ) -> pd.DataFrame: """ Load renewable power plant data (replaces ego_dp_res_powerplant_*_mview). @@ -180,24 +182,24 @@ def get_res_powerplant( """ # Set default versions based on scenario if version is None: - if scenario == 'Status Quo': - version_list = ['v0.4.4', 'v0.4.5'] + if scenario == "Status Quo": + version_list = ["v0.4.4", "v0.4.5"] else: - version_list = ['v0.4.5'] + version_list = ["v0.4.5"] else: version_list = [version] if isinstance(version, str) else version version_filter = "', '".join(version_list) # Base query with duplicate filtering logic from the mview - if table_name == 'ego_dp_res_powerplant': + if table_name == "ego_dp_res_powerplant": # For ego_dp_res_powerplant: complex duplicate filtering id_column = "id || version" else: # For ego_dp_supply_res_powerplant: simpler duplicate filtering id_column = "id" - if scenario == 'Status Quo': + if scenario == "Status Quo": # Status Quo scenario: only solar and wind (excluding offshore) query = f""" WITH filtered_data AS ( @@ -254,9 +256,9 @@ def get_res_powerplant( def get_loadarea( self, - version: str = 'v0.4.5', - schema: Literal['model_draft', 'data'] = 'data', - table_name: str = 'ego_dp_loadarea' + version: str = "v0.4.5", + schema: Literal["model_draft", "data"] = "data", + table_name: str = "ego_dp_loadarea", ) -> pd.DataFrame: """ Load load area data (replaces ego_dp_loadarea_*_mview). @@ -302,9 +304,9 @@ def get_loadarea( def get_mv_griddistrict( self, - version: str = 'v0.4.5', - schema: Literal['model_draft', 'data'] = 'data', - table_name: str = 'ego_dp_mv_griddistrict' + version: str = "v0.4.5", + schema: Literal["model_draft", "data"] = "data", + table_name: str = "ego_dp_mv_griddistrict", ) -> pd.DataFrame: """ Load MV grid district data (replaces ego_dp_mv_griddistrict_*_mview). @@ -340,7 +342,7 @@ def load_mview_replacement( mview_name: str, scenario: Optional[str] = None, version: Optional[str] = None, - **kwargs + **kwargs, ) -> pd.DataFrame: """ Generic mview replacement loader based on mview name. @@ -372,105 +374,98 @@ def load_mview_replacement( Examples -------- >>> replacer = MviewsReplacement(engine) - >>> data = replacer.load_mview_replacement('ego_dp_conv_powerplant_nep2035_mview') - >>> data = replacer.load_mview_replacement('ego_supply_res_powerplant_ego100_mview') + >>> data = replacer.load_mview_replacement( + ... 'ego_dp_conv_powerplant_nep2035_mview') + >>> data = replacer.load_mview_replacement( + ... 'ego_supply_res_powerplant_ego100_mview') """ # Remove 'mviews.' prefix if present - mview_name = mview_name.replace('mviews.', '') + mview_name = mview_name.replace("mviews.", "") # Determine schema from mview name - if mview_name.startswith('ego_supply_'): - schema = kwargs.get('schema', 'data') - base_prefix = 'ego_dp_supply_' - else: - schema = kwargs.get('schema', 'data') - base_prefix = 'ego_dp_' + schema = kwargs.get("schema", "data") # Parse conventional power plants - if 'conv_powerplant' in mview_name: + if "conv_powerplant" in mview_name: # Extract scenario from name if not provided if scenario is None: - if 'ego100' in mview_name or 'ego_100' in mview_name: - scenario = 'eGo 100' - elif 'nep2035' in mview_name: - scenario = 'NEP 2035' - elif 'sq' in mview_name or 'status' in mview_name: - scenario = 'Status Quo' + if "ego100" in mview_name or "ego_100" in mview_name: + scenario = "eGo 100" + elif "nep2035" in mview_name: + scenario = "NEP 2035" + elif "sq" in mview_name or "status" in mview_name: + scenario = "Status Quo" else: - raise ValueError(f"Cannot determine scenario from mview name: {mview_name}") + raise ValueError( + f"Cannot determine scenario from mview name: {mview_name}" + ) # Determine table name - if mview_name.startswith('ego_supply_'): - table_name = 'ego_dp_supply_conv_powerplant' + if mview_name.startswith("ego_supply_"): + table_name = "ego_dp_supply_conv_powerplant" else: - table_name = 'ego_dp_conv_powerplant' + table_name = "ego_dp_conv_powerplant" return self.get_conv_powerplant( scenario=scenario, version=version, schema=schema, table_name=table_name, - **kwargs + **kwargs, ) # Parse renewable power plants - elif 'res_powerplant' in mview_name: + elif "res_powerplant" in mview_name: if scenario is None: - if 'ego100' in mview_name or 'ego_100' in mview_name: - scenario = 'eGo 100' - elif 'nep2035' in mview_name: - scenario = 'NEP 2035' - elif 'sq' in mview_name or 'status' in mview_name: - scenario = 'Status Quo' + if "ego100" in mview_name or "ego_100" in mview_name: + scenario = "eGo 100" + elif "nep2035" in mview_name: + scenario = "NEP 2035" + elif "sq" in mview_name or "status" in mview_name: + scenario = "Status Quo" else: - raise ValueError(f"Cannot determine scenario from mview name: {mview_name}") + raise ValueError( + f"Cannot determine scenario from mview name: {mview_name}" + ) # Determine table name - if mview_name.startswith('ego_supply_'): - table_name = 'ego_dp_supply_res_powerplant' + if mview_name.startswith("ego_supply_"): + table_name = "ego_dp_supply_res_powerplant" else: - table_name = 'ego_dp_res_powerplant' + table_name = "ego_dp_res_powerplant" return self.get_res_powerplant( scenario=scenario, version=version, schema=schema, table_name=table_name, - **kwargs + **kwargs, ) # Parse load areas - elif 'loadarea' in mview_name: + elif "loadarea" in mview_name: # Extract version from name if not provided if version is None: - if 'v0_4_5' in mview_name or 'v0.4.5' in mview_name: - version = 'v0.4.5' - elif 'v0_4_3' in mview_name or 'v0.4.3' in mview_name: - version = 'v0.4.3' + if "v0_4_5" in mview_name or "v0.4.5" in mview_name: + version = "v0.4.5" + elif "v0_4_3" in mview_name or "v0.4.3" in mview_name: + version = "v0.4.3" else: - version = 'v0.4.5' # default + version = "v0.4.5" # default - return self.get_loadarea( - version=version, - schema=schema, - **kwargs - ) + return self.get_loadarea(version=version, schema=schema, **kwargs) # Parse MV grid districts - elif 'mv_griddistrict' in mview_name: + elif "mv_griddistrict" in mview_name: if version is None: - if 'v0_4_5' in mview_name or 'v0.4.5' in mview_name: - version = 'v0.4.5' - elif 'v0_4_3' in mview_name or 'v0.4.3' in mview_name: - version = 'v0.4.3' + if "v0_4_5" in mview_name or "v0.4.5" in mview_name: + version = "v0.4.5" + elif "v0_4_3" in mview_name or "v0.4.3" in mview_name: + version = "v0.4.3" else: - version = 'v0.4.5' # default + version = "v0.4.5" # default - return self.get_mv_griddistrict( - version=version, - schema=schema, - **kwargs - ) + return self.get_mv_griddistrict(version=version, schema=schema, **kwargs) else: raise ValueError(f"Unsupported mview name pattern: {mview_name}") diff --git a/edisgo/io/powermodels_io.py b/edisgo/io/powermodels_io.py index 5d68f35b3..0a60bbfd2 100644 --- a/edisgo/io/powermodels_io.py +++ b/edisgo/io/powermodels_io.py @@ -1,10 +1,13 @@ -""" -This module provides tools to convert eDisGo representation of the network -topology and timeseries to PowerModels network data format and to retrieve results from -PowerModels OPF in PowerModels network data format to eDisGo representation. -Call :func:`to_powermodels` to retrieve the PowerModels network container and -:func:`from_powermodels` to write OPF results to edisgo object. -""" +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later import json import logging @@ -250,10 +253,10 @@ def from_powermodels( Base value of apparent power for per unit system. Default: 1 MVA. """ - if type(pm_results) == str: + if isinstance(pm_results, str): with open(pm_results) as f: pm = json.loads(json.load(f)) - elif type(pm_results) == dict: + elif isinstance(pm_results, dict): pm = pm_results else: raise ValueError( @@ -363,9 +366,11 @@ def from_powermodels( for flex in df2.columns: abs_error = abs(df2[flex].values - hv_flex_dict[flex].values) rel_error = [ - abs_error[i] / hv_flex_dict[flex].iloc[i] - if ((abs_error > 0.01)[i] & (hv_flex_dict[flex].iloc[i] != 0)) - else 0 + ( + abs_error[i] / hv_flex_dict[flex].iloc[i] + if ((abs_error > 0.01)[i] & (hv_flex_dict[flex].iloc[i] != 0)) + else 0 + ) for i in range(len(abs_error)) ] df2[flex] = rel_error @@ -707,13 +712,17 @@ def _build_gen(edisgo_obj, psa_net, pm, flexible_storage_units, s_base): pf, sign = _get_pf(edisgo_obj, pm, idx_bus, "storage_unit") p_g = max( [ - psa_net.storage_units_t.p_set[inflexible_storage_units[stor_i]].iloc[0], + psa_net.storage_units_t.p_set[ + inflexible_storage_units[stor_i] + ].iloc[0], 0.0, ] ) q_g = min( [ - psa_net.storage_units_t.q_set[inflexible_storage_units[stor_i]].iloc[0], + psa_net.storage_units_t.q_set[ + inflexible_storage_units[stor_i] + ].iloc[0], 0.0, ] ) @@ -841,9 +850,9 @@ def _build_branch(edisgo_obj, psa_net, pm, flexible_storage_units, s_base): pm["branch"][str(stor_i + len(branches.index) + 1)] = { "name": "bss_branch_" + str(stor_i + 1), - "br_r": (0.017 * s_base / (psa_net.buses.v_nom.iloc[idx_bus - 1] ** 2)).round( - 10 - ), + "br_r": ( + 0.017 * s_base / (psa_net.buses.v_nom.iloc[idx_bus - 1] ** 2) + ).round(10), "r": 0.017, "br_x": 0, "f_bus": idx_bus, @@ -958,13 +967,17 @@ def _build_load( pf, sign = _get_pf(edisgo_obj, pm, idx_bus, "storage_unit") p_d = -min( [ - psa_net.storage_units_t.p_set[inflexible_storage_units[stor_i]].iloc[0], + psa_net.storage_units_t.p_set[ + inflexible_storage_units[stor_i] + ].iloc[0], np.float64(0.0), ] ) q_d = -max( [ - psa_net.storage_units_t.q_set[inflexible_storage_units[stor_i]].iloc[0], + psa_net.storage_units_t.q_set[ + inflexible_storage_units[stor_i] + ].iloc[0], np.float64(0.0), ] ) @@ -1049,9 +1062,13 @@ def _build_battery_storage( "pf": pf, "sign": sign, "virtual_branch": str(stor_i + len(branches.index) + 1), - "ps": psa_net.storage_units.p_set.loc[flexible_storage_units[stor_i]].round(20) + "ps": psa_net.storage_units.p_set.loc[flexible_storage_units[stor_i]].round( + 20 + ) / s_base, - "qs": psa_net.storage_units.q_set.loc[flexible_storage_units[stor_i]].round(20) + "qs": psa_net.storage_units.q_set.loc[flexible_storage_units[stor_i]].round( + 20 + ) / s_base, "pmax": psa_net.storage_units.p_nom.loc[ flexible_storage_units[stor_i] diff --git a/edisgo/io/pypsa_io.py b/edisgo/io/pypsa_io.py index 023e5fd69..294e02562 100755 --- a/edisgo/io/pypsa_io.py +++ b/edisgo/io/pypsa_io.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + """ This module provides tools to convert eDisGo representation of the network topology to PyPSA data model. Call :func:`to_pypsa` to retrieve the PyPSA network diff --git a/edisgo/io/storage_import.py b/edisgo/io/storage_import.py index 2ba1716cf..79f0325dc 100644 --- a/edisgo/io/storage_import.py +++ b/edisgo/io/storage_import.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging diff --git a/edisgo/io/timeseries_import.py b/edisgo/io/timeseries_import.py index 8716989ef..adb8ab241 100644 --- a/edisgo/io/timeseries_import.py +++ b/edisgo/io/timeseries_import.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import datetime diff --git a/edisgo/network/__init__.py b/edisgo/network/__init__.py index e69de29bb..668095486 100644 --- a/edisgo/network/__init__.py +++ b/edisgo/network/__init__.py @@ -0,0 +1,10 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/edisgo/network/components.py b/edisgo/network/components.py index d0666bf2d..2579dd964 100644 --- a/edisgo/network/components.py +++ b/edisgo/network/components.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import math import os diff --git a/edisgo/network/dsm.py b/edisgo/network/dsm.py index b03f1a54c..fd8ae7d9c 100644 --- a/edisgo/network/dsm.py +++ b/edisgo/network/dsm.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging diff --git a/edisgo/network/electromobility.py b/edisgo/network/electromobility.py index 6cc5c5687..af6812362 100644 --- a/edisgo/network/electromobility.py +++ b/edisgo/network/electromobility.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import os @@ -913,9 +924,7 @@ def from_csv(self, data_path, edisgo_obj, from_zip_archive=False): df = df.assign(geometry=gpd.GeoSeries.from_wkt(df["geometry"])) try: - df = gpd.GeoDataFrame( - df, geometry="geometry", crs=f"epsg:{epsg}" - ) + df = gpd.GeoDataFrame(df, geometry="geometry", crs=f"epsg:{epsg}") except Exception: logger.warning( @@ -923,9 +932,7 @@ def from_csv(self, data_path, edisgo_obj, from_zip_archive=False): f"EPSG {epsg}. Trying with EPSG 4326 as fallback." ) - df = gpd.GeoDataFrame( - df, geometry="geometry", crs="epsg:4326" - ) + df = gpd.GeoDataFrame(df, geometry="geometry", crs="epsg:4326") if attr == "simbev_config_df": for col in ["start_date", "end_date"]: diff --git a/edisgo/network/grids.py b/edisgo/network/grids.py index 20d50ed74..eb3aedd6d 100644 --- a/edisgo/network/grids.py +++ b/edisgo/network/grids.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations from abc import ABC, abstractmethod diff --git a/edisgo/network/heat.py b/edisgo/network/heat.py index a1318b5a9..9223296de 100644 --- a/edisgo/network/heat.py +++ b/edisgo/network/heat.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging diff --git a/edisgo/network/overlying_grid.py b/edisgo/network/overlying_grid.py index 241768a20..df9339071 100644 --- a/edisgo/network/overlying_grid.py +++ b/edisgo/network/overlying_grid.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging diff --git a/edisgo/network/results.py b/edisgo/network/results.py index 151fbd480..471104034 100755 --- a/edisgo/network/results.py +++ b/edisgo/network/results.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import os diff --git a/edisgo/network/timeseries.py b/edisgo/network/timeseries.py index 835b1f3fa..31c637a88 100644 --- a/edisgo/network/timeseries.py +++ b/edisgo/network/timeseries.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import itertools diff --git a/edisgo/network/topology.py b/edisgo/network/topology.py index a75d0d609..a95bff757 100755 --- a/edisgo/network/topology.py +++ b/edisgo/network/topology.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging diff --git a/edisgo/opf/__init__.py b/edisgo/opf/__init__.py index e69de29bb..668095486 100644 --- a/edisgo/opf/__init__.py +++ b/edisgo/opf/__init__.py @@ -0,0 +1,10 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/edisgo/opf/opf_solutions/__init__.py b/edisgo/opf/opf_solutions/__init__.py index e69de29bb..668095486 100644 --- a/edisgo/opf/opf_solutions/__init__.py +++ b/edisgo/opf/opf_solutions/__init__.py @@ -0,0 +1,10 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/edisgo/opf/powermodels_opf.py b/edisgo/opf/powermodels_opf.py index 85da160a8..294c8af80 100644 --- a/edisgo/opf/powermodels_opf.py +++ b/edisgo/opf/powermodels_opf.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import json import logging import os diff --git a/edisgo/opf/results/__init__.py b/edisgo/opf/results/__init__.py index e69de29bb..668095486 100644 --- a/edisgo/opf/results/__init__.py +++ b/edisgo/opf/results/__init__.py @@ -0,0 +1,10 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/edisgo/opf/results/opf_result_class.py b/edisgo/opf/results/opf_result_class.py index 04442bcb4..d6604ea4f 100644 --- a/edisgo/opf/results/opf_result_class.py +++ b/edisgo/opf/results/opf_result_class.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import os diff --git a/edisgo/opf/timeseries_reduction.py b/edisgo/opf/timeseries_reduction.py index 1b02fd827..6bb690ddf 100644 --- a/edisgo/opf/timeseries_reduction.py +++ b/edisgo/opf/timeseries_reduction.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import numpy as np diff --git a/edisgo/tools/__init__.py b/edisgo/tools/__init__.py index 10191a703..88e790882 100644 --- a/edisgo/tools/__init__.py +++ b/edisgo/tools/__init__.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import os from contextlib import contextmanager diff --git a/edisgo/tools/config.py b/edisgo/tools/config.py index cc34adff4..eaabb1e05 100644 --- a/edisgo/tools/config.py +++ b/edisgo/tools/config.py @@ -1,22 +1,20 @@ -"""This file is part of eDisGo, a python package for distribution network -analysis and optimization. - -It is developed in the project open_eGo: https://openegoproject.wordpress.com - -eDisGo lives on github: https://github.com/openego/edisgo/ -The documentation is available on RTD: https://edisgo.readthedocs.io/en/dev/ - -Based on code by oemof developing group - -This module provides a highlevel layer for reading and writing config files. - -""" - -__copyright__ = "Reiner Lemoine Institut gGmbH" -__license__ = "GNU Affero General Public License Version 3 (AGPL-3.0)" -__url__ = "https://github.com/openego/edisgo/blob/master/LICENSE" -__author__ = "nesnoj, gplssm" - +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later +# This file is part of eDisGo. Copyright belongs to +# Reiner Lemoine Institut gGmbH, authors are recorded in the version control +# history of the file, available from its original location on github: +# https://github.com/openego/eDisGo/. +# SPDX-License-Identifier: AGPL-3.0-or-later +# +# eDisGo st available on RTD: https://edisgo.readthedocs.io. import copy import datetime diff --git a/edisgo/tools/geo.py b/edisgo/tools/geo.py index 79b880a6b..dc937e85e 100755 --- a/edisgo/tools/geo.py +++ b/edisgo/tools/geo.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging diff --git a/edisgo/tools/geopandas_helper.py b/edisgo/tools/geopandas_helper.py index 14066d560..863d5004b 100644 --- a/edisgo/tools/geopandas_helper.py +++ b/edisgo/tools/geopandas_helper.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import os diff --git a/edisgo/tools/logger.py b/edisgo/tools/logger.py index 20514f947..ff6f32cf7 100644 --- a/edisgo/tools/logger.py +++ b/edisgo/tools/logger.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import logging import os import sys diff --git a/edisgo/tools/networkx_helper.py b/edisgo/tools/networkx_helper.py index 38fedfb75..4d7d74c08 100644 --- a/edisgo/tools/networkx_helper.py +++ b/edisgo/tools/networkx_helper.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations from networkx import Graph diff --git a/edisgo/tools/plots.py b/edisgo/tools/plots.py index d1673a860..337a5a460 100644 --- a/edisgo/tools/plots.py +++ b/edisgo/tools/plots.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging diff --git a/edisgo/tools/powermodels_io.py b/edisgo/tools/powermodels_io.py index 1291eb7a7..5ee18e9f7 100644 --- a/edisgo/tools/powermodels_io.py +++ b/edisgo/tools/powermodels_io.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import math import numpy as np diff --git a/edisgo/tools/preprocess_pypsa_opf_structure.py b/edisgo/tools/preprocess_pypsa_opf_structure.py index bb01ca648..eab0a6e63 100644 --- a/edisgo/tools/preprocess_pypsa_opf_structure.py +++ b/edisgo/tools/preprocess_pypsa_opf_structure.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + import numpy as np import pandas as pd @@ -40,9 +51,9 @@ def preprocess_pypsa_opf_structure(edisgo_grid, psa_network, hvmv_trafo=False): # check if generator slack has a fluctuating variable set gen_slack_loc = psa_network.generators.control == "Slack" - psa_network.buses.control.loc[ - psa_network.generators.bus.loc[gen_slack_loc] - ] = "Slack" + psa_network.buses.control.loc[psa_network.generators.bus.loc[gen_slack_loc]] = ( + "Slack" + ) is_fluct = psa_network.generators.fluctuating.loc[gen_slack_loc][0] # check for nan value if is_fluct != is_fluct: diff --git a/edisgo/tools/pseudo_coordinates.py b/edisgo/tools/pseudo_coordinates.py index f2f765a2c..fab9198c4 100644 --- a/edisgo/tools/pseudo_coordinates.py +++ b/edisgo/tools/pseudo_coordinates.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging diff --git a/edisgo/tools/spatial_complexity_reduction.py b/edisgo/tools/spatial_complexity_reduction.py index 0759e9dda..101572472 100644 --- a/edisgo/tools/spatial_complexity_reduction.py +++ b/edisgo/tools/spatial_complexity_reduction.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import copy diff --git a/edisgo/tools/temporal_complexity_reduction.py b/edisgo/tools/temporal_complexity_reduction.py index 8af88a41b..83fbfca9e 100644 --- a/edisgo/tools/temporal_complexity_reduction.py +++ b/edisgo/tools/temporal_complexity_reduction.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging @@ -71,7 +82,7 @@ def _scored_most_critical_loading( crit_lines_score.dropna(how="all").dropna(how="all", axis=1).fillna(0) ) # sort sum in descending order - return crit_lines_score.sum(axis=1).sort_values(ascending=False, kind='stable') + return crit_lines_score.sum(axis=1).sort_values(ascending=False, kind="stable") def _scored_most_critical_voltage_issues( @@ -121,9 +132,9 @@ def _scored_most_critical_voltage_issues( lv_station_buses = [ lv_grid.station.index[0] for lv_grid in edisgo_obj.topology.mv_grid.lv_grids ] - edisgo_obj.topology.buses_df.loc[ - lv_station_buses, "grid_feeder" - ] = lv_station_buses + edisgo_obj.topology.buses_df.loc[lv_station_buses, "grid_feeder"] = ( + lv_station_buses + ) # weight voltage violations with expansion costs costs = _costs_per_feeder(edisgo_obj, lv_station_buses=lv_station_buses) # map feeder costs to buses @@ -143,7 +154,7 @@ def _scored_most_critical_voltage_issues( # drop components and time steps without violations voltage_diff = voltage_diff.dropna(how="all").dropna(how="all", axis=1).fillna(0) # sort sum in descending order - return voltage_diff.sum(axis=1).sort_values(ascending=False, kind='stable') + return voltage_diff.sum(axis=1).sort_values(ascending=False, kind="stable") def _scored_most_critical_loading_time_interval( @@ -514,7 +525,7 @@ def _most_critical_time_interval( crit_timesteps = ( crit_timesteps.iloc[int(time_steps_per_time_interval) - 1 :] .iloc[time_step_day_start::time_steps_per_day] - .sort_values(ascending=False, kind='stable') + .sort_values(ascending=False, kind="stable") ) # get time steps in each time interval - these are set up setting the given time # step to be the end of the respective time interval, as rolling() function gives diff --git a/edisgo/tools/tools.py b/edisgo/tools/tools.py index 9e27ba37c..6ec46a351 100644 --- a/edisgo/tools/tools.py +++ b/edisgo/tools/tools.py @@ -1,3 +1,14 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + from __future__ import annotations import logging @@ -486,9 +497,9 @@ def get_path_length_to_station(edisgo_obj): lv_station = lvgrid.station.index[0] for bus in lvgrid.buses_df.index: lv_path = nx.shortest_path(lv_graph, source=lv_station, target=bus) - edisgo_obj.topology.buses_df.at[ - bus, "path_length_to_station" - ] = len(path) + len(lv_path) + edisgo_obj.topology.buses_df.at[bus, "path_length_to_station"] = ( + len(path) + len(lv_path) + ) return edisgo_obj.topology.buses_df.path_length_to_station diff --git a/edisgo/tools/voltage_over_distance.py b/edisgo/tools/voltage_over_distance.py index d914746cd..dc480b1f3 100644 --- a/edisgo/tools/voltage_over_distance.py +++ b/edisgo/tools/voltage_over_distance.py @@ -1,8 +1,18 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later + # edisgo/tools/voltage_over_distance.py from __future__ import annotations -from edisgo.tools.tools import get_path_length_to_station -from typing import Optional, Tuple + import numpy as np import pandas as pd import plotly.graph_objects as go @@ -18,12 +28,16 @@ def _get_v_res_df(edisgo_obj) -> pd.DataFrame: v_res = getattr(edisgo_obj.results, "v_res", None) if v_res is None: - raise RuntimeError("No voltage results (results.v_res) found. Run edisgo.analyze() first.") + raise RuntimeError( + "No voltage results (results.v_res) found. Run edisgo.analyze() first." + ) return v_res() if callable(v_res) else v_res -def _infer_load_and_feedin_timesteps(edisgo_obj, v_df: Optional[pd.DataFrame] = None) -> Tuple[pd.Timestamp, pd.Timestamp]: +def _infer_load_and_feedin_timesteps( + edisgo_obj, v_df: pd.DataFrame | None = None +) -> tuple[pd.Timestamp, pd.Timestamp]: """ Robust worst-case timestep inference. @@ -48,22 +62,30 @@ def _infer_load_and_feedin_timesteps(edisgo_obj, v_df: Optional[pd.DataFrame] = # If all-NaN, fall back if not row_min.dropna().empty and not row_max.dropna().empty: - t_load = pd.Timestamp(row_min.idxmin()) # worst undervoltage - t_feed = pd.Timestamp(row_max.idxmax()) # worst overvoltage + t_load = pd.Timestamp(row_min.idxmin()) # worst undervoltage + t_feed = pd.Timestamp(row_max.idxmax()) # worst overvoltage return t_load, t_feed # 2) Fallback: residual load from timeseries ts = getattr(edisgo_obj, "timeseries", None) if ts is None: - raise RuntimeError("Cannot infer worst-case timesteps: no voltage results and no timeseries.") + raise RuntimeError( + "Cannot infer worst-case timesteps: no voltage results and no timeseries." + ) loads_p = getattr(ts, "loads_active_power", None) gens_p = getattr(ts, "generators_active_power", None) - if loads_p is None or gens_p is None or len(loads_p.index) == 0 or len(gens_p.index) == 0: + if ( + loads_p is None + or gens_p is None + or len(loads_p.index) == 0 + or len(gens_p.index) == 0 + ): raise RuntimeError( "Cannot infer worst-case timesteps: voltage results are empty and " - "timeseries.loads_active_power / generators_active_power are missing or empty." + "timeseries.loads_active_power / generators_active_power " + "are missing or empty." ) loads_sum = loads_p.sum(axis=1) @@ -71,14 +93,15 @@ def _infer_load_and_feedin_timesteps(edisgo_obj, v_df: Optional[pd.DataFrame] = residual = (loads_sum - gens_sum).dropna() if residual.empty: - raise RuntimeError("Cannot infer worst-case timesteps: residual load series is empty.") + raise RuntimeError( + "Cannot infer worst-case timesteps: residual load series is empty." + ) t_load = pd.Timestamp(residual.idxmax()) t_feed = pd.Timestamp(residual.idxmin()) return t_load, t_feed - def _series_at_t(v_df: pd.DataFrame, t: pd.Timestamp) -> pd.Series: """ Return bus-voltage series at timestep t. If exact t not found, use nearest. @@ -100,15 +123,16 @@ def _series_at_t(v_df: pd.DataFrame, t: pd.Timestamp) -> pd.Series: s.index = s.index.map(str) return s + def build_voltage_over_distance_df( *, buses: pd.Index, dist_a: pd.Series, v_a_load: pd.Series, v_a_feed: pd.Series, - dist_b: Optional[pd.Series] = None, - v_b_load: Optional[pd.Series] = None, - v_b_feed: Optional[pd.Series] = None, + dist_b: pd.Series | None = None, + v_b_load: pd.Series | None = None, + v_b_feed: pd.Series | None = None, ) -> pd.DataFrame: """ Build the DataFrame used for voltage-over-distance plots. @@ -143,6 +167,7 @@ def _mk_df(dist: pd.Series, vv: pd.Series, label: str) -> pd.DataFrame: return pd.concat(parts, ignore_index=True) + def make_voltage_over_distance_figure( *, title: str, @@ -150,13 +175,13 @@ def make_voltage_over_distance_figure( dist_a: pd.Series, v_a_load: pd.Series, v_a_feed: pd.Series, - dist_b: Optional[pd.Series] = None, - v_b_load: Optional[pd.Series] = None, - v_b_feed: Optional[pd.Series] = None, + dist_b: pd.Series | None = None, + v_b_load: pd.Series | None = None, + v_b_feed: pd.Series | None = None, band_low: float, band_high: float, x_label: str = "Path length to station [-]", - df: Optional[pd.DataFrame] = None, + df: pd.DataFrame | None = None, ) -> go.Figure: """ Builds a plotly scatter figure with 4 traces: @@ -176,7 +201,6 @@ def make_voltage_over_distance_figure( v_b_feed=v_b_feed, ) - fig = go.Figure() # tolerance band @@ -196,9 +220,12 @@ def make_voltage_over_distance_figure( mode="markers", name=label, customdata=np.stack([sub["bus"]], axis=-1), - hovertemplate="bus=%{customdata[0]}
path=%{x}
v=%{y:.4f} p.u.", + hovertemplate=( + "bus=%{customdata[0]}
path=%{x}" + "
v=%{y:.4f} p.u." + ), ) - ) + ) fig.update_layout( title=title, xaxis_title=x_label, diff --git a/setup.py b/setup.py index 6f6b94106..2dd4992cc 100644 --- a/setup.py +++ b/setup.py @@ -1,3 +1,13 @@ +# This file is part of eDisGo (Electrical Distribution Grid Optimization), +# a Python package for analyzing flexibility options in distribution grids. +# +# Copyright (c) Reiner Lemoine Institut gGmbH +# Contributors are listed in the version control history: +# https://github.com/openego/eDisGo/ +# +# Documentation: https://edisgo.readthedocs.io/ +# +# SPDX-License-Identifier: AGPL-3.0-or-later """Setup""" import os