### Install pytest for running tests Source: https://github.com/e2niee/simbench/blob/develop/doc/about/installation.md Install the pytest framework, which is used to run the simbench test suite. ```bash pip install pytest ``` -------------------------------- ### Install simbench from local files Source: https://github.com/e2niee/simbench/blob/develop/doc/about/installation.md Install simbench from downloaded files when an internet connection is unavailable. Ensure you have downloaded the distribution and navigated to the setup.py directory. ```bash cd %path_to_simbench%simbench-x.x.x ``` ```bash pip install -e . ``` -------------------------------- ### Install simbench using pip Source: https://github.com/e2niee/simbench/blob/develop/doc/about/installation.md Use this command to install simbench directly from the Python Package Index. ```bash pip install simbench ``` -------------------------------- ### Install simbench development version Source: https://github.com/e2niee/simbench/blob/develop/doc/about/installation.md After cloning the repository, install the development version of simbench using pip with the editable flag. ```bash pip install -e . ``` -------------------------------- ### Get SimBench Grid by Code Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Use the `get_simbench_net()` function with a valid SimBench code to load a grid. Different codes specify various grid types, voltage levels, and configurations. ```python sb_code1 = "1-MV-rural--0-sw" # rural MV grid of scenario 0 with full switchs net = sb.get_simbench_net(sb_code1) ``` ```python sb_code2 = "1-HVMV-urban-all-0-no_sw" # urban hv grid with one connected mv grid which has the subnet 2.202 multi_voltage_grid = sb.get_simbench_net(sb_code2) ``` -------------------------------- ### Test simbench installation by importing Source: https://github.com/e2niee/simbench/blob/develop/doc/about/installation.md A basic check to verify that simbench can be imported into your Python environment, indicating that dependencies are likely met. ```python import simbench ``` -------------------------------- ### Get SimBench Network with Profiles Source: https://github.com/e2niee/simbench/blob/develop/doc/profiles.md Retrieves a pandapower network object that includes SimBench profiles. Access the profiles via the `.profiles` attribute of the network object. ```python net = simbench.get_simbench_net(sb_code_info) net.profiles ``` -------------------------------- ### Convert Between SimBench CSV and Pandapower Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_converter_usage.ipynb Demonstrates the full conversion process: reading SimBench CSV files into a pandapower network using `sb.csv2pp` and writing a pandapower network to SimBench CSV files using `sb.pp2csv`. Ensure output paths are correctly specified. ```python # determine relevant paths test_network_path = os.path.join(sb.sb_dir, "test", "converter", "test_network") test_output_folder_path = os.path.join(sb.sb_dir, "test", "converter", "test_network_output_folder") # get the pandapower net from test network csv files net = sb.csv2pp(test_network_path) # convert pp net to csv files sb.pp2csv(net, test_output_folder_path, export_pp_std_types=False) ``` -------------------------------- ### Inspect Load and Renewable Profiles with SimBench Source: https://context7.com/e2niee/simbench/llms.txt Load and inspect the shape and columns of load profiles. Describe renewable profiles to understand their distribution. ```python load_profiles = profiles_s0["load"] print(load_profiles.shape) # (8736, ~60 columns including 'time') print(load_profiles.columns.tolist()[:6]) # Inspect renewable profiles (per-unit scaling factors) ren_profiles = profiles_s0["renewables"] print(ren_profiles.describe()) ``` -------------------------------- ### Build SimBench Code from Parameters Source: https://context7.com/e2niee/simbench/llms.txt Use `get_simbench_code_from_parameters` to construct a SimBench code string from a parameter list. ```python # Build a SimBench code from parameters code = sb.get_simbench_code_from_parameters([1, "MV", "LV", "rural", "1.108", "2", True]) print(code) # '1-MVLV-rural-1.108-2-sw' ``` -------------------------------- ### Get absolute profiles with time as index Source: https://context7.com/e2niee/simbench/llms.txt Converts relative profiles to absolute values using a specified multiplying column and sets the time column as the DataFrame index. Ensure the 'time' column exists for this functionality. ```python import pandas as pd custom_profiles = net.profiles["load"].copy() abs_custom = sb.get_absolute_profiles_from_relative_profiles( net, element="load", multiplying_column="p_mw", relative_profiles=custom_profiles, time_as_index=True ) print(type(abs_custom.index[0])) # timestamp from "time" column ``` -------------------------------- ### Simulate Grid and Store Results Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb This snippet simulates grid behavior over a series of time steps, storing load sums and voltage extrema. It requires a pandapower network object, profiles, and assumes `apply_absolute_values` and `pp.runpp` are available. ```python time_steps = range(96) # set trafo tap position so that no voltage limits are violated net.trafo.tap_pos = 1 # run the time series and store results into a DataFrame results = pd.DataFrame([], index=time_steps, columns=["Load Sum", "min_vm_pu", "max_vm_pu"]) for time_step in time_steps: apply_absolute_values(net, profiles, time_step) pp.runpp(net) results.loc[time_step, "Load Sum"] = net.res_load.p_mw.sum() results.loc[time_step, "min_vm_pu"] = net.res_bus.vm_pu.min() results.loc[time_step, "max_vm_pu"] = net.res_bus.vm_pu.max() ``` -------------------------------- ### Simulate Line Outage and Resupply Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Demonstrates how to simulate a line outage by opening switches and then resupply a feeder by closing switches to create a loop. Finally, it runs a power flow calculation and analyzes the maximum line loading. ```python # let's run a simple power flow calculation while assuming an outage of the first line in feeder 1 outage_line = 1 outage_line_switches = net.switch.index[(net.switch.element == outage_line) & (net.switch.et == "l")] net.switch.loc[outage_line_switches, "closed"] = False # resupply feeder 1 via feeder 5 feeder1_buses = net.bus.index[net.bus.subnet.str.contains("Feeder1")] feeder5_buses = net.bus.index[net.bus.subnet.str.contains("Feeder5")] loop_line_1_5 = net.line.index[net.line.from_bus.isin(feeder1_buses) & net.line.to_bus.isin(feeder5_buses)] loop_switches_1_5 = net.switch.index[(net.switch.element == loop_line_1_5[0]) & (net.switch.et == "l")] net.switch.loc[loop_switches_1_5, "closed"] = True # run a simple power flow pp.runpp(net) # analyze maximal loaded lines feeder_1_5_lines = net.line.subnet.str.contains("Feeder1") | net.line.subnet.str.contains("Feeder5") net.res_line.loading_percent.loc[feeder_1_5_lines].max() # maximal loaded line of Feeder 1 and 5 # -> maximal line loading is less than 100% ``` -------------------------------- ### Check profile completeness with SimBench Source: https://context7.com/e2niee/simbench/llms.txt Utility functions to check if profiles referenced by network elements exist in `net.profiles`. Use `profiles_are_missing` for a quick boolean check or a detailed report. `get_applied_profiles` and `get_available_profiles` help identify used and available profile names. ```python import simbench as sb net = sb.get_simbench_net("1-MV-rural--0-sw") # Quick boolean check: are any required profiles absent? missing = sb.profiles_are_missing(net) assert not missing # All SimBench grids ship with complete profiles print("Any missing profiles:", missing) # False # Detailed missing-profile report per type report = sb.profiles_are_missing(net, return_as_bool=False) # {'load': {'p': set(), 'q': set()}, 'renewables': set(), # 'powerplants': set(), 'storage': set()} # Which profile names are actually used in the sgen table? applied = sb.get_applied_profiles(net, profile_type="renewables") print(sorted(applied)[:5]) # ['PV10', 'PV11', 'PV2', 'WP1', 'WP4'] # Which profile names exist in net.profiles["renewables"]? available = sb.get_available_profiles(net, profile_type="renewables") print(len(available)) # e.g. 27 # Which profiles exist in net.profiles but are NOT used by any element? unused = sb.get_unused_profiles(net, profile_type="renewables") print("Unused renewable profiles:", unused) ``` -------------------------------- ### Load SimBench Grid Data Source: https://github.com/e2niee/simbench/blob/develop/tutorials/EHVHV_powerflow_expl.ipynb Imports necessary libraries and loads the SimBench grid data for the '1-EHVHV-mixed-all-0-no_sw' configuration. This is the initial step for performing power flow analysis on this specific grid. ```python import pandas as pd import matplotlib.pyplot as plt import pandapower as pp import simbench as sb net = sb.get_simbench_net("1-EHVHV-mixed-all-0-no_sw") ``` -------------------------------- ### Run simbench test suite Source: https://github.com/e2niee/simbench/blob/develop/doc/about/installation.md Execute the comprehensive test suite for simbench to ensure all functionalities are working correctly. Tests may pass or be expected to fail (xfail). ```python import simbench.test simbench.test.run_all_tests() ``` -------------------------------- ### Compare Load Profiles Between Scenarios in SimBench Source: https://context7.com/e2niee/simbench/llms.txt Load profiles from different scenarios and calculate the mean absolute difference to verify scenario independence. ```python # Compare load shape between scenarios profiles_s1 = sb.get_all_simbench_profiles(scenario=1) diff = profiles_s0["load"] - profiles_s1["load"] print(diff.abs().mean()) # typically zero — profiles are scenario-independent ``` -------------------------------- ### Retrieve all SimBench profiles for a scenario Source: https://context7.com/e2niee/simbench/llms.txt Loads only the profile DataFrames (load, renewables, power plants, storage) for a given scenario directly from CSV, without loading any grid topology. This is useful for standalone profile analysis. ```python import simbench as sb # Get all profiles for scenario 0 (full year = 8736 quarter-hour steps) profiles_s0 = sb.get_all_simbench_profiles(scenario=0) print(profiles_s0.keys()) # dict_keys(['load', 'renewables', 'powerplants', 'storage']) ``` -------------------------------- ### Load SimBench Grid as Pandapower Network Source: https://context7.com/e2niee/simbench/llms.txt Use `get_simbench_net` to load a SimBench grid by its code or parameter list into a pandapower network object. This object includes load/generation profiles and study cases, ready for power flow analysis. ```python import simbench as sb import pandapower as pp # Load a rural MV grid, scenario 0, with full switch representation net = sb.get_simbench_net("1-MV-rural--0-sw") # Equivalent call using parameter list [version, hv_level, lv_level, hv_type, lv_grid, scenario, breaker_rep] net2 = sb.get_simbench_net([1, "MV", "", "rural", "", 0, True]) assert pp.toolbox.nets_equal(net, net2) # Load an HV+MV multi-voltage grid (urban HV with all connected MV grids), no switches multi_net = sb.get_simbench_net("1-HVMV-urban-all-0-no_sw") # Inspect what the network contains print(net) # This pandapower network includes: # - bus (97 elements) # - load (96 elements) # - sgen (102 elements) # - switch (204 elements) # - ext_grid (1 element) # - line (99 elements) # - trafo (2 elements) # - loadcases (6 elements) # Access the profile and study case data print(net.profiles.keys()) # dict_keys(['load', 'renewables', 'powerplants', 'storage']) print(net.loadcases) # pload qload Wind_p PV_p RES_p Slack_vm # Study Case # hL 1.0 1.000000 0.00 0.00 0.0 1.035 # n1 1.0 1.000000 0.00 0.00 0.0 1.035 # hW 1.0 1.000000 1.00 0.80 1.0 1.035 # lW 0.1 0.122543 1.00 0.80 1.0 1.015 # Run a simple power flow pp.runpp(net) print(f"Max line loading: {net.res_line.loading_percent.max():.1f}%") print(f"Voltage range: {net.res_bus.vm_pu.min():.4f} – {net.res_bus.vm_pu.max():.4f} pu") ``` -------------------------------- ### get_simbench_net Source: https://context7.com/e2niee/simbench/llms.txt Loads a SimBench grid as a pandapower network. Reads the SimBench CSV data corresponding to the given code (or parameter list) and returns a fully configured `pandapowerNet` object including load/generation profiles and predefined study cases. ```APIDOC ## get_simbench_net — Load a SimBench grid as a pandapower network Reads the SimBench CSV data corresponding to the given code (or parameter list) and returns a fully configured `pandapowerNet` object including load/generation profiles (`net.profiles`) and predefined study cases (`net.loadcases`). ```python import simbench as sb import pandapower as pp # Load a rural MV grid, scenario 0, with full switch representation net = sb.get_simbench_net("1-MV-rural--0-sw") # Equivalent call using parameter list [version, hv_level, lv_level, hv_type, lv_grid, scenario, breaker_rep] net2 = sb.get_simbench_net([1, "MV", "", "rural", "", 0, True]) assert pp.toolbox.nets_equal(net, net2) # Load an HV+MV multi-voltage grid (urban HV with all connected MV grids), no switches multi_net = sb.get_simbench_net("1-HVMV-urban-all-0-no_sw") # Inspect what the network contains print(net) # This pandapower network includes: # - bus (97 elements) # - load (96 elements) # - sgen (102 elements) # - switch (204 elements) # - ext_grid (1 element) # - line (99 elements) # - trafo (2 elements) # - loadcases (6 elements) # Access the profile and study case data print(net.profiles.keys()) # dict_keys(['load', 'renewables', 'powerplants', 'storage']) print(net.loadcases) # pload qload Wind_p PV_p RES_p Slack_vm # Study Case # hL 1.0 1.000000 0.00 0.00 0.0 1.035 # n1 1.0 1.000000 0.00 0.00 0.0 1.035 # hW 1.0 1.000000 1.00 0.80 1.0 1.035 # lW 0.1 0.122543 1.00 0.80 1.0 1.015 # Run a simple power flow pp.runpp(net) print(f"Max line loading: {net.res_line.loading_percent.max():.1f}%") print(f"Voltage range: {net.res_bus.vm_pu.min():.4f} – {net.res_bus.vm_pu.max():.4f} pu") ``` ``` -------------------------------- ### Generate Helper SimBench Codes Source: https://context7.com/e2niee/simbench/llms.txt Generate helper SimBench codes for complete datasets or full multi-voltage grids using `complete_data_sb_code` and `complete_grid_sb_code`. ```python # Helper codes for complete dataset or full multi-voltage grid print(sb.complete_data_sb_code(0)) # '1-complete_data-mixed-all-0-sw' print(sb.complete_grid_sb_code(1)) # '1-EHVHVMVLV-mixed-all-1-sw' ``` -------------------------------- ### Parse and build SimBench codes Source: https://context7.com/e2niee/simbench/llms.txt Convert between the human-readable SimBench code string and a 7-element parameter list [version, hv_level, lv_level, hv_type, lv_grid, scenario, breaker_rep]. ```APIDOC ## `get_parameters_from_simbench_code` / `get_simbench_code_from_parameters` ### Description Convert between the human-readable SimBench code string and a 7-element parameter list `[version, hv_level, lv_level, hv_type, lv_grid, scenario, breaker_rep]`. ### Method - `get_parameters_from_simbench_code(code_string)`: Parses a SimBench code string into its component parameters. - `get_simbench_code_from_parameters(parameters_list)`: Builds a SimBench code string from a list of parameters. ### Parameters #### `get_parameters_from_simbench_code` - **code_string** (string) - Required - The SimBench code string to parse. #### `get_simbench_code_from_parameters` - **parameters_list** (list) - Required - A 7-element list containing [version, hv_level, lv_level, hv_type, lv_grid, scenario, breaker_rep]. ### Request Example ```python import simbench as sb # Parse a SimBench code into its component parameters params = sb.get_parameters_from_simbench_code("1-HVMV-urban-2.202-0-sw") print(params) # Expected output: [1, 'HV', 'MV', 'urban', '2.202', '0', True] # Build a SimBench code from parameters code = sb.get_simbench_code_from_parameters([1, "MV", "LV", "rural", "1.108", "2", True]) print(code) # Expected output: '1-MVLV-rural-1.108-2-sw' ``` ### Response #### `get_parameters_from_simbench_code` Success Response - **params** (list) - A 7-element list representing the parsed SimBench code parameters. #### `get_simbench_code_from_parameters` Success Response - **code** (string) - The constructed SimBench code string. ### Helper Functions - `sb.complete_data_sb_code(scenario_id)`: Returns a helper code for the complete dataset. - `sb.complete_grid_sb_code(scenario_id)`: Returns a helper code for the complete multi-voltage grid. ``` -------------------------------- ### Run Time Series Simulation with Pandapower Module Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Utilizes the pandapower timeseries module for running simulations, which is recommended for computational efficiency. This involves setting up an OutputWriter and then calling `run_timeseries`. Ensure `pandapower.timeseries` and `pandapower.timeseries.run_time_series` are imported. ```python import tempfile from pandapower.timeseries import OutputWriter from pandapower.timeseries.run_time_series import run_timeseries # apply ConstControllers sb.apply_const_controllers(net, profiles) # create output writer output_dir = os.path.join(tempfile.gettempdir(), "simbench_time_series_example") if not os.path.exists(output_dir): os.mkdir(output_dir) ow = OutputWriter(net, time_steps, output_path=output_dir, output_file_type=".json") ow.log_variable('res_load', 'p_mw', eval_function=np.sum, eval_name="Load Sum") ow.log_variable('res_bus', 'vm_pu', eval_function=np.min, eval_name="min_vm_pu") ow.log_variable('res_bus', 'vm_pu', eval_function=np.max, eval_name="max_vm_pu") # run timeseries run_timeseries(net, time_steps) ``` -------------------------------- ### Clone simbench development version from GitHub Source: https://github.com/e2niee/simbench/blob/develop/doc/about/installation.md Clone the latest development version of simbench from its GitHub repository. ```bash git clone https://github.com/e2nIEE/simbench.git ``` -------------------------------- ### Low-level SimBench CSV I/O Source: https://context7.com/e2niee/simbench/llms.txt Read SimBench CSV tables into DataFrames or write DataFrames back to CSV files. ```APIDOC ## read_csv_data / write2csv ### Description Read one or all SimBench CSV tables into a dict of DataFrames (or a single DataFrame), and write a dict of DataFrames back to CSV files. ### Usage ```python import simbench as sb from simbench.converter import read_csv_data, write2csv import os data_path = os.path.join(sb.sb_dir, "networks", "1-complete_data-mixed-all-0-sw") # Read all tables csv_data = read_csv_data(data_path, sep=";") print(list(csv_data.keys())) # Read a single named table node_df = read_csv_data(data_path, sep=";", tablename="Node") print(node_df.head()) # Read only the first 96 rows of profile tables csv_data_small = read_csv_data(data_path, sep=";", nrows=96) # Modify and write back csv_data["Load"]["pLoad"] *= 1.1 output_path = "/tmp/modified_grid" os.makedirs(output_path, exist_ok=True) write2csv(output_path, csv_data, sep=";", mode="w") # Append unique data write2csv(output_path, csv_data, sep=";", mode="append_unique", keep="last") ``` ``` -------------------------------- ### Convert Ext Grids to Generators and Set Power Setpoints Source: https://github.com/e2niee/simbench/blob/develop/tutorials/EHVHV_powerflow_expl.ipynb Converts external grids to generators, sets slack to true for the last generator, and assigns active power setpoints to generators, excluding a specific one. ```python # --- convert ext_grids to gen elements and set some assumed active power setpoints nuclear_gens = pp.toolbox.replace_ext_grid_by_gen(net, add_cols_to_keep=["slack_weight"]) net.gen.at[net.gen.index[-1], "slack"] = True gens_with_p_2bset = pd.Index(nuclear_gens).difference([342]) net.gen.loc[gens_with_p_2bset, "p_mw"] = net.gen.loc[gens_with_p_2bset, "max_p_mw"] ``` -------------------------------- ### Compare Load Sum with LV Grid Profiles Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Compares the simulated total active power sum of loads with the provided low-voltage (LV) grid profiles. This requires the 'net' object to contain load profiles and the 'results' DataFrame to be computed. ```python # get LV grid profiles DataFrame load_profile_names = pd.Series(net.profiles["load"].columns) lv_grid_profile_names = list(load_profile_names.loc[load_profile_names.str.contains("lv_") & load_profile_names.str.contains("pload")]Пожалуйста, предоставьте мне полный текст для анализа. Я могу помочь вам с извлечением кода и созданием JSON-документации, но мне нужен исходный текст, содержащий код. ") lv_grid_profiles = net.profiles["load"].loc[time_steps, lv_grid_profile_names] lv_grid_profiles.columns = ["LV rural %i" % i for i in range(1, 4)] + ["LV semiurb 4"] # plot load sum result and LV grid profiles fig, ax1 = plt.subplots() ax2 = ax1.twinx() results.plot(ax=ax1, color='k') lv_grid_profiles.plot(ax=ax2, legend=False) h1, l1 = ax1.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() ax1.legend(h1+h2, l1+l2, loc=2) ax1.set_ylabel("Active power sum [kw]") ax2.set_ylabel("Active power per peak power") ax1.set_xlabel("Timesteps (quarter hours)") plt.show() ``` -------------------------------- ### Parse SimBench Code to Parameters Source: https://context7.com/e2niee/simbench/llms.txt Use `get_parameters_from_simbench_code` to convert a SimBench code string into a list of its constituent parameters. ```python import simbench as sb # Parse a SimBench code into its component parameters params = sb.get_parameters_from_simbench_code("1-HVMV-urban-2.202-0-sw") print(params) # [1, 'HV', 'MV', 'urban', '2.202', '0', True] # version, hv_level, lv_level, hv_type, lv_grid, scenario, breaker_rep ``` -------------------------------- ### SimBench Codes for Complete Data and Grids Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Retrieve SimBench codes for accessing complete simulation data or complete grid representations. These are useful when more than two voltage levels are required. ```python complete_data_sb_codes = ["1-complete_data-mixed-all-%i-sw" % scenario for scenario in [0, 1, 2]] complete_grid_sb_codes = ["1-EHVHVMVLV-mixed-all-%i-sw" % scenario for scenario in [0, 1, 2]] ``` -------------------------------- ### Load Network and Access SGen Profile Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Reloads the SimBench network to ensure no outages are present and accesses the profile name used for the first static generator (sgen). This demonstrates how to identify and retrieve profile information. ```python # load 'net' again to have no outage again net = sb.get_simbench_net(sb_code1) # As an example, the first sgen uses the profile: net.sgen.profile.iloc[0] ``` -------------------------------- ### Retrieve All SimBench Profiles Source: https://context7.com/e2niee/simbench/llms.txt Loads only the profile DataFrames for a given scenario directly from CSV, without loading any grid topology. ```APIDOC ## get_all_simbench_profiles ### Description Retrieve all profiles for a scenario without loading a grid. Loads only the profile DataFrames (load, renewable, power plant, storage) for a given scenario directly from CSV, without loading any grid topology. Useful for standalone profile analysis. ### Usage ```python import simbench as sb # Get all profiles for scenario 0 profiles_s0 = sb.get_all_simbench_profiles(scenario=0) print(profiles_s0.keys()) ``` ``` -------------------------------- ### Configure and Run AC Power Flow with Control Source: https://github.com/e2niee/simbench/blob/develop/tutorials/EHVHV_powerflow_expl.ipynb Sets up continuous tap control for EHV-HV transformers and then runs the AC power flow calculation, including control actions. This is used for detailed analysis considering voltage levels and reactive power. ```python ehv_hv_trafos = sb.voltlvl_idx(net, "trafo", [3], "lv_bus") pp.control.ContinuousTapControl(net, ehv_hv_trafos, 1.0) pp.runpp(net, run_control=True, distributed_slack=True) ``` -------------------------------- ### Import Libraries for SimBench Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Imports essential Python libraries for numerical operations, data manipulation, plotting, and SimBench functionalities. ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import pandapower as pp import pandapower.topology as top import pandapower.plotting as plot import simbench as sb ``` -------------------------------- ### CSV to Pandapower Converter Source: https://context7.com/e2niee/simbench/llms.txt Convert SimBench-format CSV files into a pandapower network, or export a pandapower network back to SimBench CSV files. ```APIDOC ## csv2pp / pp2csv ### Description Convert an external folder of SimBench-format CSV files into a pandapower network, or export any pandapower network back to SimBench CSV files. ### Usage ```python import os import simbench as sb import pandapower.networks as pn # ── CSV → pandapower ─────────────────────────────────────────────────────────── path_to_csv = os.path.join(sb.sb_dir, "networks", "1-complete_data-mixed-all-0-sw") net = sb.csv2pp(path=path_to_csv, sep=";") print(net.bus.shape) # Optionally limit profile rows read net_small = sb.csv2pp(path=path_to_csv, sep=";", nrows=96) # ── pandapower → CSV ─────────────────────────────────────────────────────────── net_export = pn.simple_four_bus_system() output_path = "/tmp/my_simbench_export" os.makedirs(output_path, exist_ok=True) sb.pp2csv( net_export, path=output_path, sep=";", export_pp_std_types=False, drop_inactive_elements=True, mode="w", ) # Re-import to verify round-trip net_reimported = sb.csv2pp(path=output_path, sep=";") print(net_reimported.bus) ``` ``` -------------------------------- ### Plot Simple Grid Topology Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Visualizes the topology of the pandapower network, useful for understanding grid structures like open ring systems. ```python # plot the grid to show the open ring systems plot.simple_plot(net) ``` -------------------------------- ### Check for Missing Profiles Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Asserts that all necessary profiles for the SimBench network are available. This function is crucial for ensuring that time series calculations can be performed without errors due to missing profile data. ```python # check that all needed profiles existent assert not sb.profiles_are_missing(net) ``` -------------------------------- ### List Available SimBench Codes Source: https://context7.com/e2niee/simbench/llms.txt Use `collect_all_simbench_codes` to retrieve a list of all valid SimBench codes. Parameters can filter results by voltage level, grid type, scenario, or switch representation. ```python import simbench as sb # Get every available SimBench code (all voltage levels, all scenarios, all variants) all_codes = sb.collect_all_simbench_codes() print(len(all_codes)) # several hundred codes # Only MV grids without a connected lower voltage level, no switch representation, scenario 1 mv_no_sw_s1 = sb.collect_all_simbench_codes( hv_level="MV", lv_level="", breaker_rep=False, scenario=1 ) print(mv_no_sw_s1) # ['1-MV-rural--1-no_sw', '1-MV-semiurb--1-no_sw', '1-MV-urban--1-no_sw', '1-MV-comm--1-no_sw'] # HV urban grids with all connected MV subgrids, scenario 0 hv_urban_mv_s0 = sb.collect_all_simbench_codes( hv_level="HV", hv_type="urban", lv_level="MV", scenario=0 ) print(hv_urban_mv_s0) # ['1-HVMV-urban-all-0-sw', '1-HVMV-urban-2.203-0-sw', ...] # Rural and urban MV grids, no lower voltage level, scenario 1 rural_urban_mv = sb.collect_all_simbench_codes( hv_level="MV", lv_level="", hv_type=["rural", "urban"], scenario=1, all_data=False ) print(rural_urban_mv) ``` -------------------------------- ### Read and Process Simulation Results Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Reads voltage and load data from JSON files and combines them into a single DataFrame. Ensure the output directory and file paths are correctly specified. ```python vm_pu_file = os.path.join(output_dir, "res_bus", "vm_pu.json") vm_pu = pd.read_json(vm_pu_file) load_p_file = os.path.join(output_dir, "res_load", "p_mw.json") load_p = pd.read_json(load_p_file) result2 = pd.concat([load_p[["Load Sum"]], vm_pu[["min_vm_pu", "max_vm_pu"]]], axis=1) result2.sort_index(inplace=True) ``` -------------------------------- ### Plot Voltage Extrema Over Time Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Visualizes the minimum and maximum voltage per unit (pu) over the simulated time steps. Ensure the 'results' DataFrame is populated with 'min_vm_pu' and 'max_vm_pu' columns. ```python # plot the voltage extrema #plt.rc('text', usetex=True) fig1, ax1 = plt.subplots() results[["min_vm_pu", "max_vm_pu"]].plot(ax=ax1) ax1.set_ylabel("Voltage Extrema [pu]") ax1.set_xlabel("Timesteps (quarter hours)") plt.show() ``` -------------------------------- ### Access Predefined Study Cases Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Displays the predefined study cases available in the pandapower network object. These cases define scaling factors for load and generation. ```python # the predefined study case data are stored in pandapower within net.loadcases net.loadcases ``` -------------------------------- ### Collect All SimBench Codes Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Collect all available SimBench codes. Optionally, filter codes to include only those with a specific lower voltage level. ```python all_simbench_codes = sb.collect_all_simbench_codes() all_simbench_code_with_LV_as_lower_voltage_level = sb.collect_all_simbench_codes(lv_level="LV") ``` -------------------------------- ### Apply Absolute Values and Run Power Flow Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Applies absolute values for a given case or time step, adapts transformer tap positions, and runs a power flow calculation. Logs basic results such as the sum of active powers for static generators and loads. ```python def apply_absolute_values(net, absolute_values_dict, case_or_time_step): for elm_param in absolute_values_dict.keys(): if absolute_values_dict[elm_param].shape[1]: elm = elm_param[0] param = elm_param[1] net[elm].loc[:, param] = absolute_values_dict[elm_param].loc[case_or_time_step] # let's analyze the (n-1)-case apply_absolute_values(net, loadcases, "n1") # adapt trafo tap position net.trafo["tap_pos"] = -1 # run a power flow and log basic results pp.runpp(net) pp.lf_info(net) print(net.res_sgen.p_mw.sum()) print(net.res_load.p_mw.sum()) ``` -------------------------------- ### Convert pandapower network to SimBench CSV Source: https://context7.com/e2niee/simbench/llms.txt Exports a pandapower network object back to SimBench CSV files. Options include skipping unused standard types, dropping inactive elements, and specifying the output mode (overwrite or append). ```python import os import simbench as sb import pandapower.networks as pn # ── pandapower → CSV ─────────────────────────────────────────────────────────── net_export = pn.simple_four_bus_system() output_path = "/tmp/my_simbench_export" os.makedirs(output_path, exist_ok=True) sb.pp2csv( net_export, path=output_path, sep=";", export_pp_std_types=False, # skip unused standard types drop_inactive_elements=True, # only export active, suppliable elements mode="w", # overwrite existing CSVs ) # Re-import to verify round-trip net_reimported = sb.csv2pp(path=output_path, sep=";") print(net_reimported.bus) ``` -------------------------------- ### collect_all_simbench_codes Source: https://context7.com/e2niee/simbench/llms.txt Returns a filtered list of all valid SimBench codes. Accepts parameters to narrow results by voltage level, grid type, scenario, or switch representation. ```APIDOC ## collect_all_simbench_codes — List available SimBench codes Returns a filtered list of all valid SimBench codes. Accepts parameters to narrow results by voltage level, grid type, scenario, or switch representation. ```python import simbench as sb # Get every available SimBench code (all voltage levels, all scenarios, all variants) all_codes = sb.collect_all_simbench_codes() print(len(all_codes)) # several hundred codes # Only MV grids without a connected lower voltage level, no switch representation, scenario 1 mv_no_sw_s1 = sb.collect_all_simbench_codes( hv_level="MV", lv_level="", breaker_rep=False, scenario=1 ) print(mv_no_sw_s1) # ['1-MV-rural--1-no_sw', '1-MV-semiurb--1-no_sw', '1-MV-urban--1-no_sw', '1-MV-comm--1-no_sw'] # HV urban grids with all connected MV subgrids, scenario 0 hv_urban_mv_s0 = sb.collect_all_simbench_codes( hv_level="HV", hv_type="urban", lv_level="MV", scenario=0 ) print(hv_urban_mv_s0) # ['1-HVMV-urban-all-0-sw', '1-HVMV-urban-2.203-0-sw', ...] # Rural and urban MV grids, no lower voltage level, scenario 1 rural_urban_mv = sb.collect_all_simbench_codes( hv_level="MV", lv_level="", hv_type=["rural", "urban"], scenario=1, all_data=False ) print(rural_urban_mv) ``` ``` -------------------------------- ### Collect All SimBench Codes Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Use this function to retrieve a list of all available SimBench codes. Parameters can be provided to filter the results. ```python collect_all_simbench_codes() ``` -------------------------------- ### Display DataFrame Head Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Displays the first few rows of a pandas DataFrame. This is useful for quickly inspecting the structure and content of simulation results. ```python results.head() ``` ```python result2.head() ``` -------------------------------- ### Apply Absolute Values for Low Load High Generation Case Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Applies absolute values for the low load, high generation scenario ('lW'), adapts transformer tap position to 2, and runs a power flow. Asserts that voltage magnitudes in specific feeders remain within the 0.915 to 1.055 pu limits. ```python # let's have a look at the low load high generation (extra high wind) case apply_absolute_values(net, loadcases, "lW") # adapt trafo tap position net.trafo["tap_pos"] = 2 # run a power flow and log basic results pp.runpp(net) pp.lf_info(net) assert net.res_bus.vm_pu.loc[net.bus.index.difference(feeder1_buses.union(feeder5_buses))].max() < 1.055 assert net.res_bus.vm_pu.loc[net.bus.index.difference(feeder1_buses.union(feeder5_buses))].min() > 0.915 ``` -------------------------------- ### Sum of Active Powers (n-1 Case) Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Outputs the sum of active powers for static generators (sgen) and loads (load) in MW for the (n-1) case. This provides a quick overview of the total power consumption and generation. ```text 0.0 17.256 ``` -------------------------------- ### Convert SimBench CSV to pandapower network Source: https://context7.com/e2niee/simbench/llms.txt Converts SimBench-format CSV files from a directory into a pandapower network object. Specify the separator used in the CSV files. The `nrows` parameter can limit the number of profile rows read for faster loading during testing. ```python import os import simbench as sb # ── CSV → pandapower ─────────────────────────────────────────────────────────── # Read CSV files from a local directory (semicolon-separated, as per SimBench format) path_to_csv = os.path.join(sb.sb_dir, "networks", "1-complete_data-mixed-all-0-sw") net = sb.csv2pp(path=path_to_csv, sep=";") print(net.bus.shape) # (num_buses, num_columns) print(net.load.shape) # Optionally limit profile rows read (speeds up loading for testing) net_small = sb.csv2pp(path=path_to_csv, sep=";", nrows=96) ``` -------------------------------- ### Power Flow Results Analysis (n-1 Case) Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Displays detailed power flow results, including maximum and minimum voltages, and maximum transformer and line loadings for the (n-1) case. This output helps in verifying if grid constraints are met. ```text hp.pandapower.toolbox.result_info - INFO: Max voltage in vm_pu: hp.pandapower.toolbox.result_info - INFO: 1.0366719617122484 at busidx 2 (MV1.101 busbar1.1) hp.pandapower.toolbox.result_info - INFO: Min voltage in vm_pu: hp.pandapower.toolbox.result_info - INFO: 0.9520172165178736 at busidx 15 (MV1.101 Bus 15) hp.pandapower.toolbox.result_info - INFO: Max loading trafo in %: hp.pandapower.toolbox.result_info - INFO: 36.2246088399241 loading at trafo 0 (HV1-MV1.101-Trafo1) hp.pandapower.toolbox.result_info - INFO: 36.2246088399241 loading at trafo 1 (HV1-MV1.101-Trafo2) hp.pandapower.toolbox.result_info - INFO: Max loading line in %: hp.pandapower.toolbox.result_info - INFO: 53.858594171083354 loading at line 44 (MV1.101 Line 45) hp.pandapower.toolbox.result_info - INFO: 53.221190845578306 loading at line 45 (MV1.101 Line 46) ``` -------------------------------- ### Round-trip Verification of SimBench Codes Source: https://context7.com/e2niee/simbench/llms.txt Verify the integrity of SimBench code parsing and building by converting a code to parameters and back, asserting the result matches the original. ```python # Round-trip verification original = "1-LV-semiurb5--0-no_sw" parsed = sb.get_parameters_from_simbench_code(original) rebuilt = sb.get_simbench_code_from_parameters(parsed) assert rebuilt == original, f"{rebuilt} != {original}" ``` -------------------------------- ### Inspect SimBench CSV Data Structure Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_converter_usage.ipynb Use `sb.pp2csv_data` to extract data from a pandapower network into a dictionary representing the SimBench CSV structure. This helps in understanding the available element tables. ```python import pandapower.networks as nw import simbench as sb import os # let's have a look at the SimBench csv format appearance net = nw.simple_mv_open_ring_net() csv_data = sb.pp2csv_data(net) list(csv_data.keys()) ``` -------------------------------- ### Profile Completeness Checks Source: https://context7.com/e2niee/simbench/llms.txt Utility functions to inspect profile completeness, check for missing profiles, and retrieve applied, available, or unused profile names. ```APIDOC ## profiles_are_missing / get_applied_profiles / get_available_profiles ### Description Utility functions to inspect which profiles are referenced by element tables and whether corresponding data exist in `net.profiles`, returning sets of profile names or a boolean flag. ### Usage ```python import simbench as sb net = sb.get_simbench_net("1-MV-rural--0-sw") # Quick boolean check: are any required profiles absent? missing = sb.profiles_are_missing(net) print("Any missing profiles:", missing) # Detailed missing-profile report per type report = sb.profiles_are_missing(net, return_as_bool=False) # Which profile names are actually used in the sgen table? applied = sb.get_applied_profiles(net, profile_type="renewables") print(sorted(applied)[:5]) # Which profile names exist in net.profiles["renewables"]? available = sb.get_available_profiles(net, profile_type="renewables") print(len(available)) # Which profiles exist in net.profiles but are NOT used by any element? unused = sb.get_unused_profiles(net, profile_type="renewables") print("Unused renewable profiles:", unused) ``` ``` -------------------------------- ### Display Network Information Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Prints a summary of the pandapower network, including the number of elements in each parameter table. ```python net ``` -------------------------------- ### Write SimBench CSV data Source: https://context7.com/e2niee/simbench/llms.txt Writes a dictionary of DataFrames back to SimBench CSV files. Supports different modes like overwriting ('w'), appending unique entries ('append_unique'), or keeping the last entry in case of duplicates. Ensure the output directory exists. ```python import simbench as sb from simbench.converter import write2csv import os # Modify and write back csv_data["Load"]["pLoad"] *= 1.1 # increase all loads by 10% output_path = "/tmp/modified_grid" os.makedirs(output_path, exist_ok=True) write2csv(output_path, csv_data, sep=";", mode="w") # Append unique data (avoid duplicates by name/voltLvl/subnet) write2csv(output_path, csv_data, sep=";", mode="append_unique", keep="last") ``` -------------------------------- ### Analyze and Plot AC Power Flow Results Source: https://github.com/e2niee/simbench/blob/develop/tutorials/EHVHV_powerflow_expl.ipynb Logs detailed information about the AC power flow results, including voltage magnitudes and branch loadings. It then generates box plots to visualize the distribution of bus voltages and branch loadings. ```python pp.lf_info(net) # --- plot voltages and loadings of the AC power flow results fig, axs = plt.subplots(ncols=2) net.res_bus.vm_pu.rename("bus").plot(kind="box", ax=axs[0]) branch_loadings = pd.concat([ net.res_line.loading_percent, net.res_trafo.loading_percent], axis=1, keys=["line", "trafo"]) branch_loadings.plot(kind="box", ax=axs[1]) axs[0].set_ylabel("vm in pu") axs[1].set_ylabel("loading in %") plt.tight_layout() ``` -------------------------------- ### Set Load and Generator Scaling Source: https://github.com/e2niee/simbench/blob/develop/tutorials/EHVHV_powerflow_expl.ipynb Assumes a simultaneity factor for loads and sgens and adjusts generator active power for power balance in a DC power flow context. Ensure the scaling factor is appropriate for the grid's load characteristics. ```python # Assume a simultaneity factor for loads and sgens scaling = 0.35 # Adjust active power of generators for power balance (DC power flow) # This step ensures total electric power consumption equals total feed-in, # disregarding branch losses initially. # Example: netz.gen_data.loc[netz.gen_data.index, 'p'] *= scaling # Example: netz.load_data.loc[netz.load_data.index, 'p'] *= scaling ``` -------------------------------- ### Calculate Absolute Values for Study Cases Source: https://github.com/e2niee/simbench/blob/develop/tutorials/simbench_grids_basics_and_usage.ipynb Converts relative scaling factors from study cases into absolute power values based on the network's maximum load and generation capacities. This is a prerequisite for running power flow with study cases. ```python # calculate the absolute values: loadcases = sb.get_absolute_values(net, profiles_instead_of_study_cases=False) ```