Skip to content

Restructure eGo class design #180

@ClaraBuettner

Description

@ClaraBuettner

eGo currently calls eTraGo and eDisGo by inheriting from the classes eDisGoResults and eTraGoResults.

These are then executed by this line in eGo. __init__:

eGo/ego/tools/io.py

Lines 225 to 245 in de5294e

class eGo(eDisGoResults):
"""Main eGo module which includs all results and main functionalities.
Returns
-------
network_etrago: :class:`etrago.tools.io.NetworkScenario`
eTraGo network object compiled by :meth:`etrago.appl.etrago`
edisgo.network : :class:`ego.tools.edisgo_integration.EDisGoNetworks`
Contains multiple eDisGo networks
edisgo : :pandas:`pandas.Dataframe<dataframe>`
aggregated results of eDisGo
etrago : :pandas:`pandas.Dataframe<dataframe>`
aggregated results of eTraGo
"""
def __init__(self, jsonpath, *args, **kwargs):
self.jsonpath = jsonpath
super(eGo, self).__init__(self, *args, **kwargs)

Since the eGo class inherits from eDisGoResults, eDisGoResults.__init__ is executed:

eGo/ego/tools/io.py

Lines 192 to 202 in de5294e

class eDisGoResults(eTraGoResults):
"""The ``eDisGoResults`` class create and contains all results
of eDisGo and its network containers.
"""
def __init__(self, *args, **kwargs):
super(eDisGoResults, self).__init__(self, *args, **kwargs)
if self.json_file["eGo"]["eDisGo"] is True:
logger.info("Create eDisGo network")

eDisGoResults inherits from eTraGoResults:

eGo/ego/tools/io.py

Lines 107 to 124 in de5294e

class eTraGoResults(egoBasic):
"""The ``eTraGoResults`` class creates and contains all results
of eTraGo and it's network container for eGo.
Returns
-------
network_etrago: :class:`etrago.tools.io.NetworkScenario`
eTraGo network object compiled by :func:`etrago.appl.etrago`
etrago: :pandas:`pandas.Dataframe<dataframe>`
DataFrame which collects several eTraGo results
"""
def __init__(self, *args, **kwargs):
""" """
super(eTraGoResults, self).__init__(self, *args, **kwargs)
self.etrago = None
logger.info("eTraGo section started")

eTraGoResults then starts the etrago run or imports the data from files. eDisGo is executed afterwards because the eDisGoResults class first initializes eTraGoResults and then runs EDisGoNetworks.

In my opinion this is quite complicated to understand, and it would be easier to directly integrate the calls of etrago and edisgo in the desired order.
It could e.g. look like this:


class eGo:
    """
    Hauptklasse, die eTraGo und eDisGo orchestriert.
    Statt Vererbung wird hier explizit komponiert – 
    man sieht sofort, was in welcher Reihenfolge passiert.
    """

    def __init__(self, jsonpath: str):
        self.jsonpath = jsonpath
        self.json_file = get_scenario_setting(jsonpath=jsonpath)
        self.session = self._connect_db()
        self.scn_name = self.json_file["eTraGo"]["scn_name"]

        # Explizite Ausführungsreihenfolge – auf einen Blick lesbar
        self.etrago = self._setup_etrago()
        self.edisgo = self._setup_edisgo()

        self._total_investment_costs = None
        self._total_operation_costs = None
        self._calculate_investment_cost()

    # ------------------------------------------------------------------ #
    #  eTraGo                                                              #
    # ------------------------------------------------------------------ #

    def _setup_etrago(self):
        """
        eTraGo-Netzwerk aufbauen – drei mögliche Quellen,
        klar als if/elif/else ausgedrückt.
        """
        logger.info("eTraGo section started")
        cfg = self.json_file

        # 1) Ergebnisse aus der Datenbank laden
        if cfg["eGo"]["result_id"] is not None:
            return self._etrago_from_db(cfg)

        # 2) Netzwerk aus CSV importieren
        if cfg["eGo"].get("csv_import_eTraGo"):
            logger.info("Import eTraGo network from csv files")
            return Etrago(csv_folder_name=cfg["eGo"]["csv_import_eTraGo"])

        # 3) eTraGo neu berechnen
        if cfg["eGo"]["eTraGo"] is True:
            logger.info("Create eTraGo network calculated by eGo")
            return run_etrago(args=cfg["eTraGo"], json_path=None)

        return None

    def _etrago_from_db(self, cfg):
        """Hilfsmethode: eTraGo-Netzwerk aus OEDB-Ergebnis rekonstruieren."""
        logger.info("Remove given eTraGo settings from scenario_setting")

        # Einstellungen durch DB-Werte ersetzen
        cfg["eGo"]["eTraGo"] = False
        for key in cfg["eTraGo"]:
            cfg["eTraGo"][key] = "removed by DB recover"
        cfg["eTraGo"]["db"] = self.json_file["eTraGo"]["db"]

        # Metadaten aus DB holen und Settings wiederherstellen
        _pkg = import_module("egoio.db_tables.model_draft")
        orm_meta = getattr(_pkg, "EgoGridPfHvResultMeta")
        self.jsonpath = recover_resultsettings(
            self.session, cfg, orm_meta, cfg["eGo"]["result_id"]
        )
        logger.info(
            "Recovered eTraGo network uses kmeans: {}".format(
                cfg["eTraGo"]["network_clustering_kmeans"]
            )
        )

        network = etrago_from_oedb(self.session, cfg)

        # Disaggregiertes Netzwerk
        if cfg["eTraGo"]["disaggregation"] is not False:
            self._etrago_disaggregated_network = network
        else:
            logger.warning("No disaggregated network found in DB")
            self._etrago_disaggregated_network = None

        return network

    # ------------------------------------------------------------------ #
    #  eDisGo                                                              #
    # ------------------------------------------------------------------ #

    def _setup_edisgo(self):
        """eDisGo-Netzwerk aufbauen, sofern aktiviert."""
        if not self.json_file["eGo"]["eDisGo"]:
            logger.info("No eDisGo network")
            return None

        logger.info("Create eDisGo network")
        etrago_network = (
            self.etrago.disaggregated_network
            if self.etrago is not None
            else None
        )
        return EDisGoNetworks(
            json_file=self.json_file,
            etrago_network=etrago_network,
        )

...

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions