<commit_before>import sys
import pandas as pd
from edisgo.flex_opt import check_tech_constraints as checks
from .reinforce_measures import reinforce_branches_current, \
    reinforce_branches_voltage, extend_distribution_substation
import logging

logger = logging.getLogger('edisgo')


def reinforce_grid(network):
    """ Evaluates grid reinforcement needs and performs measures. This function
        is the parent function for all grid reinforcements.

    Parameters
    ----------
    network: edisgo network object
    results: edisgo results object

    Notes
    -----
    Vorgehen laut BW-Studie:
    * getrennte oder kombinierte Betrachtung von NS und MS muss noch entschieden
      werden, BW-Studie führt getrennte Betrachtung durch
    * Reihenfolge der Behebung von Grenzwertverletzungen:
    ** Trafo
    ** Spannung
    ** Leitungen
    * Thermische Belastung:
    ** vorhandene BM werden maximal durch ein weiteres gleiches BM verstärkt
    ** ist das nicht ausreichend, wird das BM durch beliebig viele Standard-
       BM ersetzt
    * Spannungsbandverletztung
    ** Strangauftrennung nach 2/3 der Distanz
    ** danach eventuell weitere Strangauftrennung wenn sinnvoll, sonst parallele
       BM

    Sonstiges:
    * nur Rückspeisefall
    ** NS: 20% Last, 85-100% Einspeisung, BM-Belastung 100%
    ** MS: 30% Last, 85-100% Einspeisung, BM-Belastung 100%
    * Spannungsbandaufteilung wie in Wuppertal Studie
    * bei Spannungsproblemen am Trafo wird nicht Trafo ausgebaut, sondern
      Leistung in der MS

    References
    ----------
    .. [1] dena VNS
    .. [2] Ackermann et al. (RP VNS)

    """

    # STEP 1: reinforce overloaded transformers
    iteration_step = 1

    logger.info('==> Check LV stations')

    # ToDo: check overloading of HV/MV Trafo?
    overloaded_stations = checks.mv_lv_station_load(network)

    # ToDo: remove at some point
    # random overloaded station
    stations = network.mv_grid.graph.nodes_by_attribute('lv_station')
    overloaded_stations = {[_ for _ in stations
                            if len(_.transformers) >= 2][0]: 1400}
    station_2 = [_ for _ in stations if len(_.transformers) >= 1][1]
    overloaded_stations[station_2] = 3000

    # reinforce substations
    transformer_changes = extend_distribution_substation(
        network, overloaded_stations)
    # write added and removed transformers to results.equipment_changes
    for station, transformer_list in transformer_changes['added'].items():
        network.results.equipment_changes = \
            network.results.equipment_changes.append(
                pd.DataFrame(
                    {'iteration_step': [iteration_step] * len(
                        transformer_list),
                     'change': ['added'] * len(transformer_list),
                     'equipment': transformer_list},
                    index=[station] * len(transformer_list)))
    for station, transformer_list in transformer_changes['removed'].items():
        network.results.equipment_changes = \
            network.results.equipment_changes.append(
                pd.DataFrame(
                    {'iteration_step': [iteration_step] * len(
                        transformer_list),
                     'change': ['removed'] * len(transformer_list),
                     'equipment': transformer_list},
                    index=[station] * len(transformer_list)))

    # # if stations have been reinforced: run PF again and check if all
    # # overloading problems for all stations were solved
    # if overloaded_stations:
    #     network.analyze()
    #     overloaded_stations = check_station_load(network)
    #     if overloaded_stations:
    #         logger.error("==> Overloading issues of LV stations were not "
    #                      "solved in the first iteration step.")
    #         sys.exit()

    # STEP 2: reinforce branches due to overloading
    iteration_step += 1

    crit_lines_lv = checks.lv_line_load(network)
    crit_lines_mv = checks.mv_line_load(network)
    crit_lines = {**crit_lines_lv, **crit_lines_mv}

    # do reinforcement
    lines_changes = reinforce_branches_current(network, crit_lines)
    # write added and removed transformers to results.equipment_changes
    network.results.equipment_changes = \
        network.results.equipment_changes.append(
            pd.DataFrame(
                {'iteration_step': [iteration_step] * len(
                    lines_changes['added']),
                 'change': ['added'] * len(lines_changes['added'])},
                index=lines_changes['added']))
    network.results.equipment_changes = \
        network.results.equipment_changes.append(
            pd.DataFrame(
                {'iteration_step': [iteration_step] * len(
                    lines_changes['removed']),<commit_msg>Move substation expansion into if statement<commit_after>import sys
import pandas as pd
from edisgo.flex_opt import check_tech_constraints as checks
from .reinforce_measures import reinforce_branches_current, \
    reinforce_branches_voltage, extend_distribution_substation
import logging

logger = logging.getLogger('edisgo')


def reinforce_grid(network):
    """ Evaluates grid reinforcement needs and performs measures. This function
        is the parent function for all grid reinforcements.

    Parameters
    ----------
    network: edisgo network object
    results: edisgo results object

    Notes
    -----
    Vorgehen laut BW-Studie:
    * getrennte oder kombinierte Betrachtung von NS und MS muss noch entschieden
      werden, BW-Studie führt getrennte Betrachtung durch
    * Reihenfolge der Behebung von Grenzwertverletzungen:
    ** Trafo
    ** Spannung
    ** Leitungen
    * Thermische Belastung:
    ** vorhandene BM werden maximal durch ein weiteres gleiches BM verstärkt
    ** ist das nicht ausreichend, wird das BM durch beliebig viele Standard-
       BM ersetzt
    * Spannungsbandverletztung
    ** Strangauftrennung nach 2/3 der Distanz
    ** danach eventuell weitere Strangauftrennung wenn sinnvoll, sonst parallele
       BM

    Sonstiges:
    * nur Rückspeisefall
    ** NS: 20% Last, 85-100% Einspeisung, BM-Belastung 100%
    ** MS: 30% Last, 85-100% Einspeisung, BM-Belastung 100%
    * Spannungsbandaufteilung wie in Wuppertal Studie
    * bei Spannungsproblemen am Trafo wird nicht Trafo ausgebaut, sondern
      Leistung in der MS

    References
    ----------
    .. [1] dena VNS
    .. [2] Ackermann et al. (RP VNS)

    """

    # STEP 1: reinforce overloaded transformers
    iteration_step = 1

    logger.info('==> Check LV stations')

    # ToDo: check overloading of HV/MV Trafo?
    overloaded_stations = checks.mv_lv_station_load(network)

    # ToDo: remove at some point
    # random overloaded station
    stations = network.mv_grid.graph.nodes_by_attribute('lv_station')
    overloaded_stations = {[_ for _ in stations
                            if len(_.transformers) >= 2][0]: 1400}
    station_2 = [_ for _ in stations if len(_.transformers) >= 1][1]
    overloaded_stations[station_2] = 3000

    if overloaded_stations:
        # reinforce substations
        transformer_changes = extend_distribution_substation(
            network, overloaded_stations)
        # write added and removed transformers to results.equipment_changes
        for station, transformer_list in transformer_changes['added'].items():
            network.results.equipment_changes = \
                network.results.equipment_changes.append(
                    pd.DataFrame(
                        {'iteration_step': [iteration_step] * len(
                            transformer_list),
                         'change': ['added'] * len(transformer_list),
                         'equipment': transformer_list},
                        index=[station] * len(transformer_list)))
        for station, transformer_list in \
                transformer_changes['removed'].items():
            network.results.equipment_changes = \
                network.results.equipment_changes.append(
                    pd.DataFrame(
                        {'iteration_step': [iteration_step] * len(
                            transformer_list),
                         'change': ['removed'] * len(transformer_list),
                         'equipment': transformer_list},
                        index=[station] * len(transformer_list)))

        # # run power flow analysis again and check if all overloading problems
        # # for all stations were solved
        # network.analyze()
        # overloaded_stations = checks.mv_lv_station_load(network)
        # if overloaded_stations:
        #     logger.error("==> Overloading issues of LV stations were not "
        #                  "solved in the first iteration step.")
        #     sys.exit()

    # STEP 2: reinforce branches due to overloading
    iteration_step += 1

    crit_lines_lv = checks.lv_line_load(network)
    crit_lines_mv = checks.mv_line_load(network)
    crit_lines = {**crit_lines_lv, **crit_lines_mv}

    # do reinforcement
    lines_changes = reinforce_branches_current(network, crit_lines)
    # write added and removed transformers to results.equipment_changes
    network.results.equipment_changes = \
        network.results.equipment_changes.append(
            pd.DataFrame(
                {'iteration_step': [iteration_step] * len(
                    lines_changes['added']),
                 'change': ['added'] * len(lines_changes['added'])},
                index=lines_changes['added']))
    network.results.equipment_changes = \
        network.results.equipment_changes.append(
            pd.DataFrame(
                {'iteration_step': [iteration_step] * len(
                    lines_changes['removed']),
{'fraction_non_alphanumeric': 0.08545081967213115, 'fraction_numerical': 0.00860655737704918, 'mean_word_length': 2.4699608958407393, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1344003', 'n_tokens_mistral': 2865, 'n_tokens_neox': 2702, 'n_words': 697}