### Quick Start: Run Voltage Initializer Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/voltage_initializer.md A basic example demonstrating how to initialize the network, set parameters, and run the voltage initializer. Ensure AMPL and Knitro are in your PATH and the config.yml is set up. ```python import pypowsybl as pp import pypowsybl.voltage_initializer as v_init params = v_init.VoltageInitializerParameters() n = pp.network.create_eurostag_tutorial_example1_network() some_gen_id = n.get_generators().iloc[0].name params.add_constant_q_generators([some_gen_id]) some_2wt_id = n.get_2_windings_transformers().iloc[0].name params.add_variable_two_windings_transformers([some_2wt_id]) params.set_objective(VoltageInitializerObjective.SPECIFIC_VOLTAGE_PROFILE) results = v_init.run(n, params) results.apply_all_modification(n) print(results.status()) print(results.indicators()) ``` -------------------------------- ### Install Documentation Requirements Source: https://github.com/powsybl/pypowsybl/blob/main/docs/README.md Install the necessary Python packages for building the documentation. This should be done once. ```bash pip install -r ../requirements.txt ``` -------------------------------- ### Build PyPowSyBl from Source Source: https://github.com/powsybl/pypowsybl/blob/main/README.md Clone the repository, set JAVA_HOME to your GraalVM installation, and install dependencies. Then, install PyPowSyBl using pip. ```bash git clone https://github.com/powsybl/pypowsybl.git cd powsybl export JAVA_HOME= pip install --upgrade setuptools pip pip install -r requirements.txt pip install . ``` -------------------------------- ### Simple Dynawo Simulation Example Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/dynamic.md Complete example demonstrating how to run a dynamic simulation with Dynawo using Pypowsybl. This includes loading a network, defining model mappings, event mappings, output variables, simulation parameters, and running the simulation. ```python import pypowsybl.dynamic as dyn import pypowsybl as pp from pandas import DataFrame # load a network network = pp.network.create_eurostag_tutorial_example1_network() # dynamic mapping model_mapping = dyn.ModelMapping() # get dynamic model categories dataframe model_mapping.get_categories_information() # get all supported model information dataframe model_mapping.get_supported_models_information() # or filtered by category model_mapping.get_supported_models_information('SynchronizedGenerator') # can be written with kwargs... model_mapping.add_base_load(static_id='LOAD', parameter_set_id='LAB', model_name='LoadAlphaBeta') # and so on # or dataframe gen_df = DataFrame.from_records( index='static_id', columns=['static_id', 'parameter_set_id', 'model_name'], data=[('GEN', 'GENPV', 'GeneratorPV')]) model_mapping.add_synchronized_generator(gen_df) # can also be created with the proper category model_mapping.add_dynamic_model(category_name='SynchronizedGenerator' static_id='GEN2', parameter_set_id='GENPQ', model_name='GeneratorPQ') # events mapping event_mapping = dyn.EventMapping() event_mapping.add_disconnection(static_id='GEN', start_time=10) # can also be created with the proper event name event_mapping.add_event_model(event_name='Disconnect', static_id='NHV1_NHV2_1', start_time=10, disconnect_only='ONE') # curves mapping variables_mapping = dyn.OutputVariableMapping() variables_mapping.add_curves("LOAD", ["load_PPu", "load_QPu"]) variables_mapping.add_final_state_values('NGEN', 'Upu_value') # and so on # simulations parameters parameters = dyn.Parameters(start_time=0, stop_time=50) sim = dyn.Simulation() # running the simulation results = sim.run(network, model_mapping, event_mapping, variables_mapping, parameters) # getting the results results.status() results.status_text() # error description if the simulation fails results.curves() # dataframe containing the mapped curves results.final_state_values() # dataframe containing the mapped final state values results.timeline() # dataframe containing the simulation timeline ``` -------------------------------- ### Dynawo Configuration Example Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/dynamic.md Example configuration for Dynawo integration in the pypowsybl config file. Ensure PATH_TO_DYNAWO is set correctly. ```yaml+jinja dynamic-simulation-default-parameters: startTime: 0 stopTime: 30 dynawo: homeDir: PATH_TO_DYNAWO debug: true dynawo-simulation-default-parameters: parametersFile: ./models.par network.parametersFile: ./network.par network.parametersId: "1" solver.type: IDA solver.parametersFile: ./solver.par solver.parametersId: "1" ``` -------------------------------- ### Install PyPowSyBl Source: https://github.com/powsybl/pypowsybl/blob/main/README.md Install PyPowSyBl using pip. Ensure you have an up-to-date version of pip and setuptools. ```bash pip install --upgrade setuptools pip ``` ```bash pip install pypowsybl ``` -------------------------------- ### Provider Specific Parameters Example Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/loadflow.md Demonstrates how to set provider-specific parameters as strings. Ensure all values, including numbers and booleans, are represented as strings. ```python provider_parameters={'someStringParam' : 'myStringValue', 'someIntegerParam' : '42'} provider_parameters={'someDoubleParam' : '1.23', 'someOtherDoubleParam' : '4.56E-2'} provider_parameters={'someBooleanParam' : 'true'} provider_parameters={'someStringListParam' : 'value1,value2,value3'} ``` -------------------------------- ### Basic Logging Configuration Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/logging.md Enable basic logging and set the 'powsybl' logger level to INFO. This is a simple way to start seeing logs. ```python import logging logging.basicConfig() logging.getLogger('powsybl').setLevel(logging.INFO) ``` -------------------------------- ### Install pypowsybl-jupyter Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Install the pypowsybl-jupyter package to enable Jupyter widget integration for network visualization. ```bash pip install pypowsybl_jupyter jupyter lab ``` -------------------------------- ### Install PyPowsybl using pip Source: https://github.com/powsybl/pypowsybl/blob/main/docs/getting_started.md Install the latest released version of PyPowsybl from PyPI. For building from sources, refer to the GitHub repository. ```bash pip install pypowsybl ``` -------------------------------- ### Create Empty Network Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Initialize an empty network object to start building a network from scratch. ```python n = Network() ``` -------------------------------- ### Install PyPowSyBl in Developer Mode Source: https://github.com/powsybl/pypowsybl/blob/main/README.md Install PyPowSyBl in editable mode for development. Optionally, build the C extension with debug symbols. ```bash pip install -e . # or, to build the C extension with debug symbols: python setup.py build --debug develop --user ``` -------------------------------- ### Basic Short-Circuit Setup and Fault Definition Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/shortcircuit.md This snippet demonstrates the initialization of a network, configuration of short-circuit parameters, and the definition of fault locations and characteristics. It sets up a transient short-circuit study with specific fault parameters on buses and branches. ```python >>> import pypowsybl as pp >>> import pypowsybl.network as pn >>> import pandas as pd >>> # create a network >>> n = pn.create_four_substations_node_breaker_network() >>> # sets some short-circuit parameters >>> pars = pp.shortcircuit.Parameters(with_feeder_result = False, with_limit_violations = False, study_type = pp.shortcircuit.ShortCircuitStudyType.TRANSIENT) >>> # create a short-circuit analysis context >>> sc = pp.shortcircuit.create_analysis() >>> # create a bus fault on the first two buses >>> buses = n.get_buses() >>> branches = n.get_branches() >>> sc.set_faults(id = ['fault_1', 'fault_2'], element_id = [buses.index[0], branches.index[0]], r = [1, 1], x = [2, 2], ) ``` -------------------------------- ### Import pypowsybl module Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/flowdecomposition.md Import the pypowsybl library to start using its functionalities. ```python import pypowsybl as pp ``` -------------------------------- ### Create DC Sensitivity Analysis and Add Branch Flow Factor Matrix (Zone to Zone) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md This example shows how to compute the sensitivity of a branch's active power flow to an active power transfer between two defined country zones using DC sensitivity analysis. It involves setting up zones and specifying the branch and zones for the sensitivity calculation. ```python >>> zone_fr = pp.sensitivity.create_country_zone(n, 'FR') >>> zone_de = pp.sensitivity.create_country_zone(n, 'DE') >>> params = pp.loadflow.Parameters(distributed_slack=False) >>> sa = pp.sensitivity.create_dc_analysis() >>> sa.set_zones([zone_fr, zone_de]) >>> sa.add_branch_flow_factor_matrix(['BBE2AA1 FFR3AA1 1'], ['FR', 'DE'], 'm') >>> results = sa.run(n, params) >>> m = results.get_sensitivity_matrix('m') BBE2AA1 FFR3AA1 1 FR -0.708461 DE -0.451820 ``` -------------------------------- ### Topological Coloring in Network Visualization Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Apply topological coloring to distinguish electrical nodes by setting `topological_coloring` to True. This example also demonstrates updating switches. ```python >>> network = pn.create_four_substations_node_breaker_network() >>> network.update_switches(id="S1VL2_COUPLER",open=True) >>> param = pn.SldParameters(topological_coloring = True) >>> network.get_single_line_diagram('S1VL2', parameters = param) ``` -------------------------------- ### Get Single Line Diagram (VL2) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Generate a single line diagram for a specified voltage level to visualize network topology. This is useful for verifying element placement. ```python n.get_single_line_diagram('VL2') ``` -------------------------------- ### Install Native Image to Library Directory Source: https://github.com/powsybl/pypowsybl/blob/main/cpp/pypowsybl-java/CMakeLists.txt Conditionally copies the built native image library to the CMAKE_LIBRARY_OUTPUT_DIRECTORY after the native-image target has been built. This ensures the library is available in the expected location for the project. ```cmake if(DEFINED CMAKE_LIBRARY_OUTPUT_DIRECTORY) add_custom_command(TARGET native-image POST_BUILD ${POWSYBL_CPP_INSTALL_EXTRA_COMMAND} COMMAND ${CMAKE_COMMAND} -E copy ${PYPOWSYBL_JAVA_BIN_DIR}/${PYPOWSYBL_JAVA_LIB} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) endif(DEFINED CMAKE_LIBRARY_OUTPUT_DIRECTORY) ``` -------------------------------- ### Get Single Line Diagram (VL1) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Generate a single line diagram for a specified voltage level to visualize network topology. This is useful for verifying element placement. ```python n.get_single_line_diagram('VL1') ``` -------------------------------- ### Customize Network Visualization with SldParameters Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Use SldParameters to customize the appearance of single-line diagrams. This example shows how to disable node information and enable topological coloring. ```python >>> network = pp.network.create_ieee14() >>> result = pp.loadflow.run_ac(network) >>> network.get_single_line_diagram('VL4',parameters = pp.network.SldParameters(use_name = False, center_name = False, diagonal_label = False, nodes_infos = False, tooltip_enabled = False, topological_coloring = True, component_library = 'Convergence')) ``` -------------------------------- ### Retrieve PST Range Action Results Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/rao.md Get results specifically for PST range actions. ```python rao_result.get_remedial_actions_results(remedial_action_type="pst_range") ``` -------------------------------- ### Flow decomposition with loop flows and fallback to DC load flow Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/flowdecomposition.md Example demonstrating loop flows from peripheral areas. If AC load flow does not converge, it falls back to DC load flow by default, setting AC reference values to NaN and disabling rescaling for affected lines. ```python network = pp.Network() # Add branches and loads to create imbricated zones # ... (network definition code) ... decomposition = pp.FlowDecomposition(network) results = decomposition.run( flow_decomposition_parameters=pp.FlowDecompositionParameters(fallback_to_dc=True) ) print(results) ``` -------------------------------- ### Get Single Line Diagram for VL2 Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Draws the single line diagram for the VL2 voltage level. Use this to verify network configurations. ```python >>> n.get_single_line_diagram('VL2') ``` -------------------------------- ### Import CRAC with Creation Parameters Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/rao.md Import CRAC data from a JSON file, providing a separate JSON file for creation parameters to guide the interpretation of native business data. ```python crac = Crac.from_file_source(network, "path/to/crac.json", creation_parameters_file="path/to/parameters.json") ``` -------------------------------- ### Define a Switch Closing Remedial Action Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/security.md This example shows how to define a remedial action to close a specific switch. This action can be later incorporated into an operator strategy. ```python >>> sa.add_switch_action('SwitchAction', 'S4VL1_BBS_LD6_DISCONNECTOR', True) ``` -------------------------------- ### Discover Available Network Extensions Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Lists the names of available network extensions and inspects the schema of a specific extension. Use `get_extensions_names()` to get a list of all extension names and `get_extensions_information()` to view attribute details for each. ```python >>> available_extensions = pp.network.get_extensions_names() >>> available_extensions[0:5] ['activePowerControl', 'branchObservability', 'busbarSectionPosition', 'cgmesMetadataModels', 'coordinatedReactiveControl'] ``` ```python >>> extensions_information = pp.network.get_extensions_information() >>> extensions_information.loc['twoWindingsTransformerPhaseAngleClock', 'attributes'] 'index : id (str), phase_angle_clock (int)' ``` -------------------------------- ### Specify Objective Function and Distance Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/voltage_initializer.md Set the objective function for the voltage initializer and the corresponding objective distance. This guides the optimization process towards a desired outcome. ```python import pypowsybl as pp import pypowsybl.voltage_initializer as v_init params = v_init.VoltageInitializerParameters() params.set_objective(va.VoltageInitializerObjective.SPECIFIC_VOLTAGE_PROFILE) params.set_objective_distance(1.3) ``` -------------------------------- ### Set Max Heap Memory for GraalVM Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/advanced_parameters.md Pass a specific value for maximum allowed memory (Xmx) to SubstrateVM using the GRAALVM_OPTIONS environment variable before running a Python script. This example sets the maximum heap to 1GB. ```bash GRAALVM_OPTIONS="-Xmx1G" python ``` ```python import logging logging.basicConfig() logging.getLogger('powsybl').setLevel(logging.DEBUG) import pypowsybl as pp DEBUG:powsybl:Max heap is 1086 MB ``` -------------------------------- ### Add Selective Limit Reductions Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/security.md Apply limit reductions selectively based on parameters like duration, country, and voltage. This example reduces temporary current limits by 0.9 for specific network elements. ```python sa..add_limit_reductions(limit_type='CURRENT', permanent=False, temporary=True, value=0.9, min_temporary_duration=300, country='FR', min_voltage=90, max_voltage=225) ``` -------------------------------- ### CRAC Creation Parameters for NC Profiles Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/rao.md Example JSON structure for CRAC creation parameters when importing from NC profiles. This includes timestamp, region EIC code, TSOs, curative instants, borders, and restricted curative batches. ```json { "crac-factory": "CracImplFactory", "extensions": { "NcCracCreatorParameters": { "timestamp": "2026-04-27T16:58:00Z", "capacity-calculation-region-eic-code": "10Y1001C--00095L", "tsos-which-do-not-use-patl-in-final-state": [ "REE" ], "curative-instants": [ { "name": "curative 1", "application-time": 300 }, { "name": "curative 2", "application-time": 600 }, { "name": "curative 3", "application-time": 1200 } ], "borders": [ { "name": "ES-FR", "eic": "10YDOM--ES-FR--D", "default-for-tso": "RTE" }, { "name": "ES-PT", "eic": "10YDOM--ES-PT--T", "default-for-tso": "REN" } ], "restricted-curative-batches-per-tso": { "REE": [ "curative 1", "curative 2" ], "REN": [ "curative 1" ] } } } } ``` -------------------------------- ### Navigate to Docs Directory Source: https://github.com/powsybl/pypowsybl/blob/main/docs/README.md Change the current directory to the 'docs' folder to prepare for building the documentation. ```bash cd docs ``` -------------------------------- ### Build HTML Documentation (Makefile) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/README.md An alternative method to build the HTML documentation using the make html command. ```bash make html ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/powsybl/pypowsybl/blob/main/docs/README.md Generate the HTML version of the documentation. The -a flag ensures all files are rebuilt. ```bash sphinx-build -a . _build/html ``` -------------------------------- ### Preview HTML Documentation Source: https://github.com/powsybl/pypowsybl/blob/main/docs/README.md Open the generated HTML documentation in the Firefox browser. The files are located in the '_build/html' directory. ```bash firefox _build/html/index.html ``` -------------------------------- ### Retrieve Global RAO Result Status Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/rao.md Get the overall status of the RAO run, which can be DEFAULT, FAILURE, or PARTIAL_FAILURE. ```python rao_result.get_global_status() ``` -------------------------------- ### Import PyPowSyBl and Run Load Flow Source: https://github.com/powsybl/pypowsybl/blob/main/README.md Import the pypowsybl library, create an IEEE 14 buses network, and run an AC load flow computation. The results include convergence status and iteration count. ```python import pypowsybl as pp ``` ```python n = pp.network.create_ieee14() results = pp.loadflow.run_ac(n) print(results) ``` -------------------------------- ### Build LaTeX PDF Documentation Source: https://github.com/powsybl/pypowsybl/blob/main/docs/README.md Generate the documentation in LaTeX format and then compile it into a PDF. ```bash make latexpdf ``` -------------------------------- ### Retrieve Non-PST Range Action Results Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/rao.md Get results for remedial actions that are range actions but not PST range actions. ```python rao_result.get_remedial_actions_results(remedial_action_type="range") ``` -------------------------------- ### Create and Move Injection to Empty Zone Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md Shows how to create an empty zone and transfer an injection into it. ```python >>> zone_fict = pp.sensitivity.create_empty_zone('FICT') >>> zone_fr.move_injection_to(zone_fict, 'DDE3AA1 _generator') >>> zone_fict.injections_ids ['DDE3AA1 _generator'] ``` -------------------------------- ### Create DC Sensitivity Analysis and Add Branch Flow Factor Matrix (Zone to Slack) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md This snippet demonstrates how to set up a DC sensitivity analysis, define a country zone, and compute the sensitivity of a specific branch's active power flow to an injection increase from that zone. Load flow parameters are adjusted to disable slack distribution. ```python >>> n = pp.network.load('simple-eu.uct') >>> zone_de = pp.sensitivity.create_country_zone(n, 'DE') >>> params = pp.loadflow.Parameters(distributed_slack=False) >>> sa = pp.sensitivity.create_dc_analysis() >>> sa.set_zones([zone_de]) >>> sa.add_branch_flow_factor_matrix(['BBE2AA1 FFR3AA1 1'], ['DE'], 'm') >>> results = sa.run(n, params) >>> m = results.get_sensitivity_matrix('m') BBE2AA1 FFR3AA1 1 DE -0.45182 ``` -------------------------------- ### Get Single Line Diagram for VL1 Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Draws the single line diagram for the VL1 voltage level. This is useful for visualizing network changes. ```python >>> n.get_single_line_diagram('VL1') ``` -------------------------------- ### Create Zones from GLSK File (All Areas) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md Loads a network and creates a list of sensitivity zones from a UCTE GLSK file, including all areas defined within the file for a specific timestamp. ```python >>> n = pp.network.load('simple-eu.uct') >>> zones = pp.sensitivity.create_zones_from_glsk_file(n, 'glsk_sample.xml', datetime.datetime(2019, 1, 8, 0, 0)) >>> params = pp.loadflow.Parameters(distributed_slack=False) >>> sa = pp.sensitivity.create_dc_analysis() >>> sa.set_zones(zones) >>> sa.add_branch_flow_factor_matrix(['BBE2AA1 FFR3AA1 1'], ['10YCB-GERMANY--8'], 'm') >>> results = sa.run(n, params) ``` -------------------------------- ### Add Limit Reductions to Security Analysis Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/security.md Use add_limit_reductions to detect limit violations on lower operational limits. This example reduces all current limits by 0.8. ```python >>> n = pp.network.create_eurostag_tutorial_example1_network() >>> sa = pp.security.create_analysis() >>> sa.add_single_element_contingency('NHV1_NHV2_1', 'First contingency') >>> sa.add_limit_reductions(limit_type='CURRENT', permanent=True, temporary=True, value=0.8) >>> sa_result = sa.run_ac(n) >>> sa_result.limit_violations["limit_reduction"].unique() [0.8] ``` -------------------------------- ### Add Switches for Line Connection Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Set up disconnectors and breakers on both ends of a voltage level to prepare for connecting a line. ```python dis_vl1_1 = n.create_disconnector(busbar_section=bbs1, name='D_VL1_1', switch_state='open') dis_vl1_2 = n.create_disconnector(busbar_section=bbs2, name='D_VL1_2', switch_state='open') breaker_vl1 = n.create_breaker(busbar_section=bbs1, name='BR_VL1') dis_vl2_1 = n.create_disconnector(busbar_section=bbs4, name='D_VL2_1', switch_state='closed') breaker_vl2 = n.create_breaker(busbar_section=bbs4, name='BR_VL2') ``` -------------------------------- ### Multiple Zone Sensitivities with DC Analysis Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md This snippet illustrates how to perform a comprehensive DC sensitivity analysis by defining multiple country zones and calculating sensitivities for various zone-to-slack and zone-to-zone transfers across specified border lines. It demonstrates setting up multiple zones and adding matrices for different transfer types. ```python >>> zone_fr = pp.sensitivity.create_country_zone(n, 'FR') >>> zone_de = pp.sensitivity.create_country_zone(n, 'DE') >>> zone_be = pp.sensitivity.create_country_zone(n, 'BE') >>> zone_nl = pp.sensitivity.create_country_zone(n, 'NL') >>> params = pp.loadflow.Parameters(distributed_slack=False) >>> sa = pp.sensitivity.create_dc_analysis() >>> sa.set_zones([zone_fr, zone_de, zone_be, zone_nl]) >>> sa.add_branch_flow_factor_matrix(['BBE2AA1 FFR3AA1 1', 'FFR2AA1 DDE3AA1 1'], ['FR', ('FR', 'DE'), ('DE', 'FR'), 'NL'], 'm') >>> result = sa.run(n, params) >>> m = result.get_sensitivity_matrix('m') BBE2AA1 FFR3AA1 1 FFR2AA1 DDE3AA1 1 FR -0.708461 0.291539 FR -> DE -0.256641 0.743359 DE -> FR 0.256641 -0.743359 NL -0.225206 -0.225206 ``` -------------------------------- ### Get Bus Data as Pandas DataFrame Source: https://github.com/powsybl/pypowsybl/blob/main/README.md Retrieve bus data from a created network as a Pandas DataFrame for easy analysis. This includes voltage magnitude and angle. ```python buses = n.get_buses() print(buses) ``` -------------------------------- ### Run Documentation Tests Source: https://github.com/powsybl/pypowsybl/blob/main/docs/README.md Execute the tests embedded within the documentation using the make doctest command. ```bash make doctest ``` -------------------------------- ### Default SldParameters for Network Visualization Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Generate a single-line diagram with default SldParameters. Ensure the pypowsybl.network module is imported. ```python >>> import pypowsybl.network as pn >>> param = pn.SldParameters() #default parameters >>> network.get_single_line_diagram('VL4', parameters = param) ``` -------------------------------- ### Get Single Line Diagram for VL3 Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Retrieve and visualize the single-line diagram for the voltage level VL3. This helps in confirming the placement of components like two-winding transformers. ```python >>> n.get_single_line_diagram('VL3') ``` -------------------------------- ### Load Network with Post Processors Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Load a network from a zip file and apply specified post-processors after import. The zip file can contain supported network formats. ```python network = pp.network.load('mycgmes.zip', post_processors=['replaceTieLinesByLines']) ``` -------------------------------- ### Switch Back to Initial Network Variant Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Return to a previously saved network state by switching back to the 'InitialState' variant. This allows comparison of changes made in other variants. ```python >>> network.switch_variant(name='InitialState') ``` -------------------------------- ### Get Lines Data from Network Source: https://github.com/powsybl/pypowsybl/blob/main/docs/getting_started.md Retrieve a Pandas DataFrame containing information about all lines in the network. Note that flow values may be NaN until a load flow is computed. ```python lines_df = network.get_lines() ``` -------------------------------- ### Get Default Network Area Diagram Profile Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Retrieves the default profile for network area diagrams, useful for updating specific labels while retaining default settings for others. ```python >>> default_profile = network.get_default_nad_profile() ``` -------------------------------- ### Set Current Unit and Display Feeder Info Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Configure both the current unit (e.g., 'A') and display current feeder information simultaneously. ```python >>> param = pn.SldParameters(display_current_feeder_info = True, current_unit = "A") >>> network.get_single_line_diagram('VL4', parameters = param) ``` -------------------------------- ### Calculate X-Node Sensitivity Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md Calculates the sensitivity of an X-Node by adding its corresponding dangling line as an injection to a zone, setting up a DC analysis, and running the analysis to get the sensitivity matrix. ```python >>> zone_x.add_injection('NNL2AA1 XXXXXX11 1') >>> sa = pp.sensitivity.create_dc_analysis() >>> sa.set_zones([zone_x]) >>> sa.add_branch_flow_factor_matrix(['BBE2AA1 FFR3AA1 1'], ['X'], 'm') >>> result = sa.run(n) >>> result.get_sensitivity_matrix('m') BBE2AA1 FFR3AA1 1 X 0.176618 ``` -------------------------------- ### Create Country Zone with Default Weighting Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md Creates a sensitivity zone for a country using the default behavior, which is to use the generator active power target as the weight. ```python >>> zone_de = pp.sensitivity.create_country_zone(n, 'DE') ``` -------------------------------- ### Import Pypowsybl Dynamic Module Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/dynamic.md Import the necessary modules for network and dynamic simulations. ```python import pypowsybl.network as pn import pypowsybl.dynamic as dyn ``` -------------------------------- ### Create and Switch to a New Network Variant Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Manage different network states by creating new variants. Clone an existing variant to preserve the initial state before making changes. ```python >>> network.create_variant(name='MyVariant', clone_from='InitialState') ``` ```python >>> network.switch_variant(name='MyVariant') ``` -------------------------------- ### Update Selected Limits Group for a Line Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Use the `update_lines` method to change the selected limits group for a specific line. This example demonstrates changing the selected group for 'LINE1' to 'OTHER_GROUP'. ```python >>> net.update_lines(id='LINE1', 'selected_limits_group_2'='OTHER_GROUP') ``` ```python >>> net.get_operational_limits(all_attributes=True, show_inactive_sets=True) element_type side name type value acceptable_duration fictitious group_name selected element_id LINE1 LINE TWO permanent_limit CURRENT 1000 -1 False DEFAULT False LINE1 LINE TWO 10' CURRENT 1200 600 False DEFAULT False LINE1 LINE TWO 1' CURRENT 1500 60 False DEFAULT False LINE1 LINE TWO permanent_limit CURRENT 1100 -1 False OTHER_GROUP True ``` -------------------------------- ### Create Country Zone with Load P0 Weighting Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md Creates a sensitivity zone for a country, using the load active power target (P0) as the weight. ```python >>> zone_de = pp.sensitivity.create_country_zone(n, 'DE', pp.sensitivity.ZoneKeyType.LOAD_P0) ``` -------------------------------- ### Get Displayed Voltage Levels Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Retrieve a list of voltage levels displayed in a network area diagram based on an input voltage level and depth. Requires a Powsybl network object. ```python >>> network = pp.network.create_ieee300() >>> list_vl = network.get_network_area_diagram_displayed_voltage_levels('VL1', 1) ``` -------------------------------- ### Load Network with Geographical Data Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Load a network from a zip file, enabling the CGMES GL profile import to include graphical layout data for substations and lines. ```python >>> network = pp.network.load('MicroGridTestConfiguration_T4_BE_BB_Complete_v2.zip', {'iidm.import.cgmes.post-processors': 'cgmesGLImport'}) ``` -------------------------------- ### Move Injection Between Zones Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md Demonstrates how to move an injection from one country zone to another and observe the updated injection lists. ```python >>> zone_fr = pp.sensitivity.create_country_zone(n, 'FR') >>> zone_fr.injections_ids ['FFR1AA1 _generator', 'FFR2AA1 _generator', 'FFR3AA1 _generator'] >>> zone_de = pp.sensitivity.create_country_zone(n, 'DE') >>> zone_de.injections_ids ['DDE1AA1 _generator', 'DDE2AA1 _generator', 'DDE3AA1 _generator'] >>> zone_de.move_injection_to(zone_fr, 'DDE3AA1 _generator') >>> zone_fr.injections_ids ['FFR1AA1 _generator', 'FFR2AA1 _generator', 'FFR3AA1 _generator', 'DDE3AA1 _generator'] >>> zone_de.injections_ids ['DDE1AA1 _generator', 'DDE2AA1 _generator'] ``` -------------------------------- ### Run Linting Inspection Source: https://github.com/powsybl/pypowsybl/blob/main/README.md Check code quality and style using pylint on the PyPowSyBl project. ```bash pylint pypowsybl ``` -------------------------------- ### Retrieve Remedial Action Results Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/rao.md Get a DataFrame containing information about activated remedial actions, including optimized instant, contingency, and activation details. For range actions, optimized tap or set point is also provided. ```python rao_result.get_remedial_actions_results() ``` -------------------------------- ### Load Network from File Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Load a network model from a file. Supported formats include XIIDM. Specific import parameters can be provided as a dictionary. ```python >>> network = pp.network.load('my-network.xiidm') ``` ```python network = pp.network.load('ieee14.raw', {'psse.import.ignore-base-voltage': 'true'}) ``` -------------------------------- ### Create Single Line Diagram SVG Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Use this to create a single line diagram in SVG format from a substation or voltage level. Ensure the network object is initialized. ```python >>> network = pp.network.create_ieee14() >>> network.write_single_line_diagram_svg('VL4', 'vl4.svg') ``` -------------------------------- ### Create Substations Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Add substations to the network. Arguments can be provided as a DataFrame or named arguments. ```python s1 = n.create_substation(name='S1') s2 = n.create_substation(name='S2') ``` -------------------------------- ### Import Load Flow Module Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/loadflow.md Import the necessary modules for running load flows. This is the first step before any load flow operations. ```python import pypowsybl.network as pn import pypowsybl.loadflow as lf ``` -------------------------------- ### Flow decomposition with a Phase-Shifting Transformer (PST) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/flowdecomposition.md Illustrates flow decomposition on a network containing a PST with a non-neutral tap position. An equivalent null load is used to simulate the PST's effect. ```python network = pp.Network() # Define PST and equivalent load # ... (network definition with PST and BLOAD 11) ... decomposition = pp.FlowDecomposition(network) results = decomposition.run() print(results) ``` -------------------------------- ### Generate Multi-Substation Single Line Diagram Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Create a single-line diagram SVG file for multiple substations. This is a beta feature. ```python >>> network = pp.network.create_ieee14() >>> result = pp.loadflow.run_ac(network) >>> network.write_matrix_multi_substation_single_line_diagram_svg([['S1', 'S2'],['S3','S4']], 's1_s2_s3_s4.svg') ``` -------------------------------- ### Run AC Security Analysis with Voltage Angle Limits Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/security.md This snippet demonstrates how to set up a network, define voltage angle limits, create a security analysis object, add a contingency, and run an AC security analysis. It then filters the results to show voltage angle violations. ```python >>> network = pp.network.create_eurostag_tutorial_example1_network() >>> network.create_voltage_angle_limits( ... id='NHV1_NHV2_1_ANGLE', ... from_element_id='NHV1_NHV2_1', ... from_side='ONE', ... to_element_id='NHV1_NHV2_1', ... to_side='TWO', ... low_limit=-5.0, ... high_limit=5.0, ... ) >>> sa = pp.security.create_analysis() >>> sa.add_single_element_contingency('NHV1_NHV2_1', 'First contingency') >>> sa_result = sa.run_ac(network) >>> angle_violations = sa_result.limit_violations[ ... sa_result.limit_violations['limit_type'].isin(['LOW_VOLTAGE_ANGLE', 'HIGH_VOLTAGE_ANGLE']) ... ] ``` -------------------------------- ### Basic flow decomposition with contingencies and monitored lines Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/flowdecomposition.md Perform a flow decomposition by defining a network, adding contingencies, and specifying monitored lines. The results include flow decomposition and reference values. ```python network = pp.Network() # Define contingencies contingencies = [ pp.Contingency(id="C1", elements=[ pp.Branch.from_string("1"), pp.Branch.from_string("2"), ]) ] # Define monitored lines monitored_lines = [ pp.Branch.from_string("1"), pp.Branch.from_string("2"), ] # Create a flow decomposition object decomposition = pp.FlowDecomposition(network) # Run the flow decomposition results = decomposition.run( contingencies=contingencies, monitored_elements=monitored_lines, flow_decomposition_parameters=pp.FlowDecompositionParameters(loss_compensation=False) ) print(results) ``` -------------------------------- ### Enable Tooltips in Network Visualization Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Activate tooltips that display component names when hovering over them by setting `tooltip_enabled` to True. ```python >>> param = pn.SldParameters(tooltip_enabled = True) >>> network.get_single_line_diagram('VL4', parameters = param) ``` -------------------------------- ### Create a Network from IEEE 9-bus Test Case Source: https://github.com/powsybl/pypowsybl/blob/main/docs/getting_started.md Instantiate a Network object using a predefined test case. This is the primary data structure for network analysis. ```python from powsybl import Network network = Network.from_ieee_9_bus_test_case() ``` -------------------------------- ### Configure AMPL and Solver Log Levels Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/voltage_initializer.md Specify the log level for AMPL and the solver. Adjust these settings to control the verbosity of the output during the solving process. ```python import pypowsybl as pp import pypowsybl.voltage_initializer as v_init params = v_init.VoltageInitializerParameters() params.set_log_level_ampl(va.VoltageInitializerLogLevelAmpl.ERROR) params.set_log_level_solver(va.VoltageInitializerLogLevelSolver.EVERYTHING) ``` -------------------------------- ### Create SVG with Load Flow Results Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Generate a single line diagram SVG that includes active and reactive power results from a load flow calculation. Run the load flow before writing the diagram. ```python >>> network = pp.network.create_ieee14() >>> result = pp.loadflow.run_ac(network) >>> network.write_single_line_diagram_svg('VL4', 'vl4.svg') ``` -------------------------------- ### Add Substations from DataFrame Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Populate the network with substations defined in a pandas DataFrame. Ensure the DataFrame has 'name' and 'substation' columns. ```python data = { 'name': ['S1', 'S2'], 'substation': ['S1', 'S2'] } dfs = pd.DataFrame(data) n.create_substation(dfs) ``` -------------------------------- ### Create Country Zone with Generator Max P Weighting Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md Creates a sensitivity zone for a country, using the generator maximum active power as the weight. ```python >>> zone_de = pp.sensitivity.create_country_zone(n, 'DE', pp.sensitivity.ZoneKeyType.GENERATOR_MAX_P) ``` -------------------------------- ### Custom Log Format Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/logging.md Configure logging with a more readable format, including timestamp, log level, and message. ```python logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') ``` -------------------------------- ### Run RAO Voltage and Angle Monitoring Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/rao.md Perform voltage and angle monitoring using the RAO monitoring API. Voltage monitoring can be run directly, while angle monitoring optionally accepts a GLSK file. ```python result_with_voltage_monitoring = rao_runner.run_voltage_monitoring(crac, network, rao_result) >>> monitoring_glsk = RaoGlsk.from_file_source(str(DATA_DIR.joinpath("rao/GlskB45test.xml"))) >>> result_with_angle_monitoring = rao_runner.run_angle_monitoring(crac, network, rao_result, monitoring_glsk=monitoring_glsk) ``` -------------------------------- ### Arrange Substation Diagrams with Matrix Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Use a matrix to define the arrangement of substation diagrams in a grid. An empty string in the matrix creates an empty spot in the grid. ```python >>> network.get_matrix_multi_substation_single_line_diagram([['S1', 'S2'],['S3','S4']]) ``` -------------------------------- ### Manage Transformer Phase-Angle Clock Extension Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Demonstrates the workflow for creating, reading, updating, and removing the 'twoWindingsTransformerPhaseAngleClock' extension. This involves using `create_extensions`, `get_extensions`, `update_extensions`, and `remove_extensions` methods. ```python >>> network = pp.network.create_ieee14() >>> transformer_id = network.get_2_windings_transformers().index[0] >>> network.create_extensions( ... 'twoWindingsTransformerPhaseAngleClock', ... id=transformer_id, ... phase_angle_clock=5, ... ) ``` ```python >>> phase_angle_clock = network.get_extensions('twoWindingsTransformerPhaseAngleClock').loc[transformer_id] >>> phase_angle_clock.phase_angle_clock 5 ``` ```python >>> network.update_extensions( ... 'twoWindingsTransformerPhaseAngleClock', ... id=transformer_id, ... phase_angle_clock=11, ... ) ``` ```python >>> network.get_extensions('twoWindingsTransformerPhaseAngleClock').loc[transformer_id].phase_angle_clock 11 ``` ```python >>> network.remove_extensions('twoWindingsTransformerPhaseAngleClock', [transformer_id]) >>> network.get_extensions('twoWindingsTransformerPhaseAngleClock').empty True ``` -------------------------------- ### Create Topology for Voltage Level Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Creates the basic topology for a voltage level, including busbar sections and coupling devices (breakers and disconnectors). ```python >>> n.create_topology(voltage_level='VL3', bbs_count=2, breaker_sections=[1], disconnector_sections=[2]) ``` -------------------------------- ### Adding monitored elements with automatic selection (Interconnections) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/flowdecomposition.md Use an automatic adder function to include interconnections in the N state as monitored elements. Be cautious with large networks due to potential performance impact. ```python network = pp.Network() adder = pp.FlowDecompositionAdder() adder.add_monitored_elements_interconnections( states=pp.State.N ) decomposition = pp.FlowDecomposition(network, adders=adder) results = decomposition.run() print(results) ``` -------------------------------- ### Create Country Zone with Explicit Generator Target P Weighting Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md Creates a sensitivity zone for a country, explicitly specifying the generator active power target as the weight. ```python >>> zone_de = pp.sensitivity.create_country_zone(n, 'DE', pp.sensitivity.ZoneKeyType.GENERATOR_TARGET_P) ``` -------------------------------- ### Add Switches for Load Connection Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Create disconnectors and breakers to properly connect a load to a busbar section. Note the state of the switches (open/closed). ```python dis1 = n.create_disconnector(busbar_section=bbs1, name='D1', switch_state='closed') dis2 = n.create_disconnector(busbar_section=bbs2, name='D2', switch_state='open') dis3 = n.create_disconnector(busbar_section=bbs3, name='D3', switch_state='open') breaker = n.create_breaker(busbar_section=bbs1, name='BR1') ``` -------------------------------- ### Update Network from File Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Update a network with data from a specific file, such as an EQ or SSH file. This method allows for partial updates to existing network data. ```python >>> network = pp.network.load('network_EQ.xml') >>> network.get_generators()["target_p"]["GEN"] numpy.nan >>> network.update_from_file('network_SSH.xml') >>> network.get_generators()["target_p"]["GEN"] 10.0 ``` -------------------------------- ### Use FlatDesign Component Library Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Change the component library for the single-line diagram to 'FlatDesign' by setting `component_library`. ```python >>> network = pn.create_ieee14() >>> param = pn.SldParameters(component_library = "FlatDesign") >>> network.get_single_line_diagram('VL4', parameters = param) ``` -------------------------------- ### Retrieve Generic Cost Results Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/rao.md Obtain generic cost results, including functional cost, virtual cost, and their sum, for each optimized instant. The optimized instant serves as the index. ```python rao_result.get_generic_cost_results() ``` -------------------------------- ### Generate Network Area Diagram (Force Layout) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Generate a network area diagram using the default automatic force layout. ```python >>> network.write_network_area_diagram('be.svg') ``` -------------------------------- ### Configure Plausible Voltage Limits Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/voltage_initializer.md Set the minimum and maximum plausible voltage limits for the ACOPF solving. These values define the acceptable range for bus voltages. ```python import pypowsybl as pp import pypowsybl.voltage_initializer as v_init params = v_init.VoltageInitializerParameters() params.set_min_plausible_low_voltage_limit(0.45) params.set_max_plausible_high_voltage_limit(1.2) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/powsybl/pypowsybl/blob/main/README.md Execute unit tests for PyPowSyBl using pytest. ```bash pytest tests ``` -------------------------------- ### Display Component Names in Network Visualization Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network_visualization.md Customize the single-line diagram to display component names instead of IDs by setting `use_name` to True. ```python >>> param = pn.SldParameters(use_name = True) >>> network.get_single_line_diagram('VL4', parameters = param) ``` -------------------------------- ### Create Zone from GLSK Data (Specific Area) Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/sensitivity.md Loads GLSK file data and creates a single sensitivity zone using specific injections and shift keys for a given country and timestamp. ```python >>> n = pp.network.load('simple-eu.uct') >>> glsk_document = pp.glsk.load('glsk_sample.xml') >>> t_start = glsk_document.get_gsk_time_interval_start() >>> t_end = glsk_document.get_gsk_time_interval_end() >>> de_generators = glsk_document.get_points_for_country(n, '10YCB-GERMANY--8', t_start) >>> de_shift_keys = glsk_document.get_glsk_factors(n, '10YCB-GERMANY--8', t_start) >>> zone_de = pp.sensitivity.create_zone_from_injections_and_shift_keys('10YCB-GERMANY--8', de_generators, de_shift_keys) ``` -------------------------------- ### Create Busbar Sections Source: https://github.com/powsybl/pypowsybl/blob/main/docs/user_guide/network.md Add busbar sections to voltage levels. These represent the physical busbars in a node/breaker configuration. ```python bbs1 = n.create_busbar_section(voltage_level=vl1, name='BBS1') bbs2 = n.create_busbar_section(voltage_level=vl1, name='BBS2') bbs3 = n.create_busbar_section(voltage_level=vl1, name='BBS3') bbs4 = n.create_busbar_section(voltage_level=vl2, name='BBS4') ```