### Install and Verify Solvers Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/errors.md Provides instructions for installing common solvers like CBC, Gurobi, and CPLEX, and code to verify their availability. ```bash # For CBC (open-source) conda install -c conda-forge coincbc # For Gurobi (requires license) # Download from https://www.gurobi.com/ # Set environment variables # For CPLEX (requires license) # Install via IBM or conda # For Ipopt (NLP) conda install -c conda-forge ipopt ``` ```python import pyomo.environ as pyo # List available solvers solvers = pyo.SolverFactory('').available() print(f"Available solvers: {solvers}") # Try to construct specific solver try: opt = pyo.SolverFactory('gurobi') print("Gurobi is available") except Exception as e: print(f"Gurobi error: {e}") ``` -------------------------------- ### Workflow Example: Load and Solve UC Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/unit_commitment.md A complete workflow example demonstrating loading data and solving a unit commitment problem with the tight formulation. ```python from egret.data.model_data import ModelData from egret.models.unit_commitment import solve_unit_commitment, create_tight_unit_commitment_model # Load data md = ModelData.read('uc_case.json') # Solve with tight formulation md_results = solve_unit_commitment(md, 'cbc', mipgap=0.001) ``` -------------------------------- ### Install Pyomo with Ipopt Interface Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/INDEX.md Installs Pyomo, which includes an interface for the Ipopt nonlinear solver, using pip. This is a command-line instruction. ```bash pip install pyomo # Includes Ipopt interface ``` -------------------------------- ### Install EGRET Library Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/INDEX.md Install the EGRET library using pip. This command installs the latest stable version. ```bash pip install gridx-egret ``` -------------------------------- ### EGRET Example Workflow Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/parsers.md A comprehensive workflow demonstrating loading different data formats, solving an optimal power flow problem, and saving the results. ```python from egret.data.model_data import ModelData from egret.parsers.matpower_parser import create_ModelData as load_matpower from egret.models.dcopf import solve_dcopf # Load different formats md_ieee = ModelData.read('case14.m') md_pglib = ModelData.read('pglib_uc_case.json') md_prescient = ModelData.read('case.dat', file_type='dat') # Solve OPF on IEEE case results = solve_dcopf(md_ieee, 'cbc') # Examine results for bus_name, bus_dict in results.elements('bus'): print(f"{bus_name}: LMP = ${bus_dict.get('lmp', 'N/A'):.2f}") # Save results results.write('results.json') ``` -------------------------------- ### Example Usage of BasePointType Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Demonstrates creating PTDF DCopf models with different base points. Use FLATSTART for initial linearization or SOLUTION for warm-starts. ```python from egret.model_library.defn import BasePointType from egret.models.dcopf import create_ptdf_dcopf_model md = ModelData.read('case.m') # Use flat start m1, md1 = create_ptdf_dcopf_model(md, base_point=BasePointType.FLATSTART) # Use solution-based base point (for warm-starts) m2, md2 = create_ptdf_dcopf_model(md, base_point=BasePointType.SOLUTION) ``` -------------------------------- ### Example: Single-Period OPF Dispatch Visualization Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/visualization.md Shows how to solve a DC optimal power flow (DCOPF) problem and then visualize the resulting single-period dispatch using `generate_stack_graph`. ```python from egret.data.model_data import ModelData from egret.models.dcopf import solve_dcopf from egret.viz.generate_graphs import generate_stack_graph # Solve OPF md = ModelData.read('case14.m') md_results = solve_dcopf(md, 'cbc') # Show stacked dispatch (single period as stacked) fig = generate_stack_graph(md_results, title='14-Bus System Dispatch') ``` -------------------------------- ### Install CBC Solver via Conda Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/INDEX.md Installs the CBC solver, an open-source MIP solver, using conda. This is a command-line instruction. ```bash conda install -c conda-forge coincbc # CBC ``` -------------------------------- ### Basic DCopf Solve Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/dcopf.md This example demonstrates a basic solve of a DC Optimal Power Flow model using the 'cbc' solver. Ensure ModelData is loaded before calling. ```python from egret.models.dcopf import solve_dcopf from egret.data.model_data import ModelData md = ModelData.read('case14.m') # Basic solve md_results = solve_dcopf(md, 'cbc') ``` -------------------------------- ### ModelData Constructor Examples Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/modeldata.md Demonstrates various ways to initialize a ModelData object, including creating an empty instance, loading from files, creating from a dictionary, and cloning an existing object. ```python from egret.data.model_data import ModelData # Create empty model data md = ModelData() # Load from JSON file md = ModelData('system.json') # Load from MATPOWER file md = ModelData('case14.m') # Create from dictionary data = { 'elements': {'bus': {'B1': {'bus_type': 'PV'}}, 'system': {'reference_bus': 'B1'} } md = ModelData(data) # Clone existing ModelData md_copy = ModelData(md) ``` -------------------------------- ### Install COIN-OR CBC Solver (Anaconda) Source: https://github.com/grid-parity-exchange/egret/blob/main/README.md Install the open-source COIN-OR CBC MIP solver using conda. This is recommended for EGRET users. ```bash conda install -c conda-forge coincbc ``` -------------------------------- ### Example of Time Series Load Data Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Shows a concrete example of a load element with a time-varying active power ('Pl') attribute. The reactive power ('Ql') is constant in this case. ```python load = { 'connected_bus': 'B1', 'Pl': { 'data_type': 'time_series', 'values': {0: 100.0, 1: 110.0, 2: 105.0} }, 'Ql': 20.0 # Scalar for constant reactive load } ``` -------------------------------- ### DCopf Solve Returning Model and Results Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/dcopf.md This example demonstrates how to retrieve both the Pyomo model object and the results object by setting return_model and return_results to True. ```python from egret.models.dcopf import solve_dcopf from egret.data.model_data import ModelData md = ModelData.read('case14.m') # Get model and results for inspection md_results, m, results = solve_dcopf(md, 'cbc', return_model=True, return_results=True) ``` -------------------------------- ### Example: Multi-Period UC Visualization with Custom Labels Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/visualization.md Demonstrates solving a multi-period unit commitment problem and generating a dispatch chart with custom time period labels using `generate_stack_graph`. ```python from egret.data.model_data import ModelData from egret.models.unit_commitment import solve_unit_commitment from egret.viz.generate_graphs import generate_stack_graph import matplotlib.pyplot as plt # Solve UC md = ModelData.read('7-period_uc.json') md_results = solve_unit_commitment(md, 'cbc') # Create time labels time_keys = md_results.data['system']['time_keys'] labels = [f'Hour {h}' for h in range(len(time_keys))] # Generate chart with custom labels fig = generate_stack_graph(md_results, title='7-Hour Unit Commitment', save_figure=True, filename='uc_dispatch.png', time_labels=labels) ``` -------------------------------- ### Example: Generate and Display Dispatch Stack Chart Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/visualization.md Demonstrates loading and solving a unit commitment problem, then generating and displaying a dispatch stack chart using `generate_stack_graph`. Includes saving the figure and accessing plot axes for further modification. ```python from egret.data.model_data import ModelData from egret.models.unit_commitment import solve_unit_commitment from egret.viz.generate_graphs import generate_stack_graph import matplotlib.pyplot as plt # Load and solve unit commitment md = ModelData.read('uc_case.json') md_results = solve_unit_commitment(md, 'cbc') # Generate dispatch stack chart fig = generate_stack_graph(md_results, title='24-Hour Generator Dispatch', save_figure=True, filename='dispatch_stack.pdf') # Display in interactive mode plt.show() # Access figure for additional modifications ax = fig.axes[0] ax.set_xlabel('Hour') ax.set_ylabel('MW') fig.savefig('modified_dispatch.png', dpi=300, bbox_inches='tight') ``` -------------------------------- ### DCopf Solve with Time Limit and Solver Options Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/dcopf.md This example shows how to solve a DCopf model with a specified time limit and custom solver options for 'gurobi'. ```python from egret.models.dcopf import solve_dcopf from egret.data.model_data import ModelData md = ModelData.read('case14.m') # With time limit and solver options md_results = solve_dcopf(md, 'gurobi', timelimit=300.0, options={'MIPGap': 0.01}) ``` -------------------------------- ### Configure Python Path for Solver Discovery Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Set the PYTHONPATH environment variable to help Pyomo discover installed solvers. ```bash # Python path for solver discovery export PYTHONPATH=/path/to/pyomo:$PYTHONPATH ``` -------------------------------- ### Example Usage of DCOPF with Losses Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/other_models.md This snippet shows how to instantiate and use the `create_dcopf_losses_model` function. It involves reading model data and then calling the model creation function. ```python from egret.models.dcopf_losses import create_dcopf_losses_model md = ModelData.read('case.m') m, md = create_dcopf_losses_model(md) ``` -------------------------------- ### Complete Lazy PTDF Workflow Example Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/ptdf_utilities.md Demonstrates a complete workflow for solving a DCOPF model using lazy PTDF constraints. It includes loading data, configuring lazy options, and solving the model. ```python from egret.data.model_data import ModelData from egret.models.dcopf import create_ptdf_dcopf_model, solve_dcopf from egret.common.lazy_ptdf_utils import populate_default_ptdf_options import pyomo.environ as pyo # Load data md = ModelData.read('large_case.m') # Configure lazy constraints ptdf_opts = populate_default_ptdf_options({ 'lazy': True, 'iteration_limit': 100, 'violation_tolerance': 2.0, # MW 'exclude_contingencies': True, 'max_violations_per_iteration': { 'branch': 5, 'interface': 2, 'contingency': 0 } }) # Solve with lazy constraints md_results = solve_dcopf(md, 'cbc', dcopf_model_generator=create_ptdf_dcopf_model, ptdf_options=ptdf_opts) print(f"Converged in {md_results.data['system'].get('iteration_count', 'N/A')} iterations") ``` -------------------------------- ### Example Usage of ApproximationType Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Shows how to create DCopf models using different ApproximationTypes. Use BTHETA for small systems and PTDF for large systems with lazy constraints. ```python from egret.model_library.defn import ApproximationType from egret.models.dcopf import create_btheta_dcopf_model, create_ptdf_dcopf_model # B-theta model for small system m1, md1 = create_btheta_dcopf_model(md) # PTDF model for large system with lazy constraints m2, md2 = create_ptdf_dcopf_model(md) ``` -------------------------------- ### Solve DC Power Flow with Gurobi Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/errors.md Example of attempting to solve a DC optimal power flow problem using the Gurobi solver. ```python results = solve_dcopf(md, 'gurobi') # Error: Solver 'gurobi' not found ``` -------------------------------- ### Populate Default PTDF Options Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/ptdf_utilities.md Initializes PTDF options with default values. Can be used with None to get all defaults or with a partial dictionary to override specific settings. ```python def populate_default_ptdf_options(ptdf_options): ... ``` ```python from egret.common.lazy_ptdf_utils import populate_default_ptdf_options # Use all defaults ptdf_opts = populate_default_ptdf_options(None) # Override specific options ptdf_opts = populate_default_ptdf_options({ 'lazy': True, 'iteration_limit': 50, 'violation_tolerance': 2.0 }) ``` -------------------------------- ### Example Test Output Source: https://github.com/grid-parity-exchange/egret/blob/main/README.md Sample output from the pytest execution, indicating the number of tests passed and the time taken. ```text =================================== test session starts ================================== platform darwin -- Python 3.7.7, pytest-5.4.2, py-1.8.1, pluggy-0.13.0 rootdir: /home/some-user/egret collected 21 items test_unit_commitment.py s.................... [100%] ========================= 20 passed, 1 skipped in 641.80 seconds ========================= ``` -------------------------------- ### Example Usage of FlowType Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Illustrates using FlowType with RIV ACopf models. The RIV model internally uses a current-based formulation. ```python from egret.model_library.defn import FlowType from egret.models.acopf import create_riv_acopf_model # RIV model uses current-based formulation md = ModelData.read('case.m') m, md = create_riv_acopf_model(md) # Uses current formulation internally ``` -------------------------------- ### Test EGRET Unit Commitment Functionality Source: https://github.com/grid-parity-exchange/egret/blob/main/README.md Run the unit commitment tests from the EGRET models/tests sub-directory. This verifies the installation and functionality of the unit commitment module. ```bash pytest test_unit_commitment.py ``` -------------------------------- ### Unit Commitment with PTDF Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Solve a Unit Commitment problem using CBC, incorporating PTDF calculations with lazy constraint generation. This example shows how to apply PTDF options to UC models. ```python from egret.models.unit_commitment import solve_unit_commitment ptdf_opts = populate_default_ptdf_options({ 'lazy': True, 'iteration_limit': 100, 'violation_tolerance': 1.0 }) md_results = solve_unit_commitment(md, 'cbc', ptdf_options=ptdf_opts) ``` -------------------------------- ### Model Data Structure Example Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Defines the nested dictionary structure for representing power system elements and system-level attributes. Use this as a template for defining your system's static data. ```python model_data = { 'elements': { : { : { : , ... }, ... }, ... }, 'system': { : , ... } } ``` -------------------------------- ### Time Series with Multiple Attributes Example Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Shows how to represent time-varying active ('Pl') and reactive ('Ql') power for a load element. Both attributes use the 'time_series' data type. ```python load_dict = { 'connected_bus': 'B2', 'Pl': { 'data_type': 'time_series', 'values': {0: 100, 1: 110, 2: 105} }, 'Ql': { 'data_type': 'time_series', 'values': {0: 30, 1: 33, 2: 31} } } ``` -------------------------------- ### Populate Default PTDF Options Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Initialize PTDF options using a utility function, setting parameters for lazy constraint generation, iteration limits, and violation tolerances. This is a common starting point for PTDF calculations. ```python from egret.common.lazy_ptdf_utils import populate_default_ptdf_options ptdf_options = populate_default_ptdf_options({ 'lazy': False, 'iteration_limit': 100000, 'violation_tolerance': 1.0, 'rel_violation_tolerance': 0.01, 'exclude_contingencies': True, 'exclude_interfaces': False, 'max_violations_per_iteration': { 'branch': 100, 'interface': 10, 'contingency': 0 }, 'force_all_contingencies_initially': False, 'verbose': True }) ``` -------------------------------- ### DCOPF with Lazy PTDF Constraints Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Solve a DCOPF problem using CBC with lazy PTDF constraint generation. This example demonstrates configuring lazy generation parameters like iteration limit and violation tolerance. ```python from egret.models.dcopf import solve_dcopf, create_ptdf_dcopf_model from egret.common.lazy_ptdf_utils import populate_default_ptdf_options md = ModelData.read('large_case.m') # Configure lazy generation ptdf_opts = populate_default_ptdf_options({ 'lazy': True, 'iteration_limit': 50, 'violation_tolerance': 2.0, 'max_violations_per_iteration': { 'branch': 10, 'interface': 0, 'contingency': 0 } }) # Solve with lazy constraints md_results = solve_dcopf(md, 'cbc', dcopf_model_generator=create_ptdf_dcopf_model, ptdf_options=ptdf_opts) ``` -------------------------------- ### Install EGRET Package Source: https://github.com/grid-parity-exchange/egret/blob/main/README.md Install EGRET into your Python environment using pip. This command installs the package in editable mode. ```bash pip install -e . ``` -------------------------------- ### Basic EGRET Usage: Load and Solve DCOPF Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/INDEX.md Demonstrates basic usage of EGRET by loading grid data from a MATPOWER file and solving a DC Optimal Power Flow (DCOPF) problem. Requires the 'cbc' solver. ```python from egret.data.model_data import ModelData from egret.models.dcopf import solve_dcopf # Load grid data md = ModelData.read('case14.m') # Solve optimal power flow results = solve_dcopf(md, 'cbc') # Access results for gen, gen_dict in results.elements('generator'): print(f"{gen}: {gen_dict['pg']} MW") ``` -------------------------------- ### Example Usage of CoordinateType Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Demonstrates using CoordinateType with PSV ACopf models. The PSV formulation internally uses polar coordinates. ```python from egret.model_library.defn import CoordinateType from egret.models.acopf import create_psv_acopf_model # PSV formulation uses polar coordinates md = ModelData.read('case.m') m, md = create_psv_acopf_model(md) # Uses POLAR coordinates internally ``` -------------------------------- ### Initialize ModelData with Supported Types Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/errors.md Demonstrates correct ways to initialize ModelData. Avoid passing unsupported types like lists directly. ```python md = ModelData([1, 2, 3]) # Invalid: list not supported ``` ```python md = ModelData() # Empty md = ModelData(dict_data) # Dictionary md = ModelData('file.json') # File path md = ModelData(other_md) # ModelData object ``` -------------------------------- ### Complete Unit Commitment Configuration Workflow Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Demonstrates a full workflow for Unit Commitment, including data loading, PTDF configuration, solver options, and solving the model. ```python from egret.data.model_data import ModelData from egret.models.unit_commitment import solve_unit_commitment from egret.common.lazy_ptdf_utils import populate_default_ptdf_options # Load data md = ModelData.read('uc_case.json') # Configure PTDF for lazy constraint generation ptdf_opts = populate_default_ptdf_options({ 'lazy': True, 'iteration_limit': 100, 'violation_tolerance': 2.0, 'verbose': True, 'max_violations_per_iteration': { 'branch': 5, 'interface': 0, 'contingency': 0 } }) # Configure solver solver_opts = { 'MIPGap': 0.01, 'TimeLimit': 1800.0, 'Threads': 4 } # Solve results = solve_unit_commitment(md, 'gurobi', mipgap=0.001, timelimit=1800, solver_options=solver_opts, ptdf_options=ptdf_opts) # Inspect results print(f"Objective: ${results.data['system']['total_cost']:,.0f}") ``` -------------------------------- ### Get Generator Attributes Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/modeldata.md Retrieves all generator attributes, indexed by attribute name. Useful for inspecting generator properties like minimum and maximum power. ```python gen_attrs = md.attributes('generator') print(gen_attrs['names']) # ['G1', 'G2', ...] print(gen_attrs['p_min']) # {'G1': 100.0, 'G2': 150.0, ...} print(gen_attrs['p_max']) # {'G1': 500.0, 'G2': 600.0, ...} ``` ```python # Get attributes for in-service generators only gen_attrs = md.attributes('generator', in_service=True) ``` -------------------------------- ### Configure Gurobi Environment Variables Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Set GUROBI_HOME and update the PATH to include Gurobi's binary directory for solver execution. ```bash # Solver-specific settings (Gurobi) export GUROBI_HOME=/path/to/gurobi export PATH=$PATH:$GUROBI_HOME/bin ``` -------------------------------- ### Configure Pyomo Solve Method Options Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Set options for Pyomo's solve method, such as loading solutions and using symbolic labels. Useful for fine-tuning the solver behavior. ```python solve_method_opts = { 'load_solution': True, 'symbolic_solver_labels': False, 'io_options': {'output_fixed_variable_bounds': 'all'} } results = solve_dcopf(md, 'cbc', solve_method_options=solve_method_opts) ``` -------------------------------- ### Solve DC Power Flow with Solver Options Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/errors.md Demonstrates how to solve a DC optimal power flow problem using different solvers and specifying solver options like time limits and MIP gaps. ```python results, m = solve_dcopf(md, 'cbc', return_model=True, return_results=True) # Check solver termination condition print(f"Termination condition: {results.solver.termination_condition}") print(f"Status: {results.solver.status}") # Try with more time results = solve_dcopf(md, 'cbc', timelimit=1800) # 30 minutes # Try with different solver options results = solve_dcopf(md, 'gurobi', options={'MIPGap': 0.1, 'TimeLimit': 600}) ``` -------------------------------- ### Configure CPLEX Environment Variables Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Set CPLEX_STUDIO_DIR and update LD_LIBRARY_PATH for CPLEX solver integration. ```bash # Solver-specific settings (CPLEX) export CPLEX_STUDIO_DIR=/path/to/cplex export LD_LIBRARY_PATH=$CPLEX_STUDIO_DIR/cplex/bin/x86-64_linux:$LD_LIBRARY_PATH ``` -------------------------------- ### Define BasePointType Enum Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Defines base points for PTDF linearization. FLATSTART uses a flat start (all angles 0), while SOLUTION uses the previous solution for warm-starts. ```python from egret.model_library.defn import BasePointType class BasePointType(Enum): FLATSTART = 1 # Flat start (all angles = 0) SOLUTION = 2 # Use previous solution as base point ``` -------------------------------- ### Tune for Quick Solutions with LP Relaxation Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Obtain quick solutions by solving the LP relaxation of the Unit Commitment problem with a specified MIP gap. ```python # Solve LP relaxation md_results = solve_unit_commitment(md, 'cbc', relaxed=True, mipgap=0.05) # 5% gap ``` -------------------------------- ### CBC Solver Options Configuration Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Configure options for the CBC solver, including time limits, thread usage, preprocessing, and cut strategies. This is useful for fine-tuning CBC performance for specific problems. ```python solver_options = { 'timeLimit': 300.0, # Time limit (seconds) 'threads': 4, # Number of threads 'preprocess': True, # Preprocess model 'cuts': 'root' # Cut strategy: 'off', 'root', 'on' } results = solve_dcopf(md, 'cbc', options=solver_options) ``` -------------------------------- ### Basic ACOPF Solve with Default PSV Formulation Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/acopf.md Solves an ACOPF problem using the default PSV formulation with the 'ipopt' solver. Requires importing ModelData and solve_acopf. ```python from egret.models.acopf import solve_acopf from egret.data.model_data import ModelData md = ModelData.read('case14.m') # Solve with PSV formulation (default) md_results = solve_acopf(md, 'ipopt') ``` -------------------------------- ### populate_default_ptdf_options Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/ptdf_utilities.md Initializes a dictionary with default PTDF options. It can be used to set up configuration for lazy constraint generation and other PTDF-related computations. ```APIDOC ## populate_default_ptdf_options ### Description Initialize PTDF options with defaults. ### Method `populate_default_ptdf_options(ptdf_options)` ### Parameters #### Path Parameters - **ptdf_options** (dict or None) - Partial options dict; None treated as {} ### Returns - **dict** - dict with complete options including defaults ### Request Example ```python from egret.common.lazy_ptdf_utils import populate_default_ptdf_options # Use all defaults ptdf_opts = populate_default_ptdf_options(None) # Override specific options ptdf_opts = populate_default_ptdf_options({ 'lazy': True, 'iteration_limit': 50, 'violation_tolerance': 2.0 }) ``` ``` -------------------------------- ### Accessing Dual Variables in Pyomo Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Demonstrates how to access dual variables, such as Locational Marginal Prices (LMPs), from a Pyomo optimization model after importing them using `Suffix.IMPORT`. ```python model.dual = Suffix(direction=Suffix.IMPORT) # Access dual of power balance constraint lmp = model.dual[model.eq_p_balance[bus_name]] ``` -------------------------------- ### Loading and Accessing Model Data Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/types.md Demonstrates how to load model data from a JSON file using `ModelData.read()` and access system attributes and element properties. This is a common starting point for working with Egret models. ```python from egret.data.model_data import ModelData md = ModelData.read('case.json') # Access system attributes ref_bus = md.data['system']['reference_bus'] times = md.data['system']['time_keys'] # [0, 1, 2, ...] for multi-period # Access elements for gen_name, gen_dict in md.elements('generator'): p_min = gen_dict['p_min'] p_max = gen_dict['p_max'] ``` -------------------------------- ### Calculate Locational Marginal Prices (LMP) Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/ptdf_utilities.md Calculates Locational Marginal Prices (LMP) from dual values of a solved Pyomo model. Requires the model, duals, and the name of the power balance constraint. ```python def calculate_LMP(self, model, duals, constraint_name): ... ``` -------------------------------- ### create_soc_relaxation_model() Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/other_models.md Create a Second-Order Cone (SOC) relaxation of ACOPF, providing a convex relaxation of AC optimal power flow. ```APIDOC ## create_soc_relaxation_model() ### Description Create a Second-Order Cone (SOC) relaxation of ACOPF. ### Method ```python def create_soc_relaxation_model(model_data, include_feasibility_slack=False, pw_cost_model='delta'): ... ``` ### Parameters #### Path Parameters - **model_data** (ModelData) - Required - EGRET ModelData object - **include_feasibility_slack** (bool) - Optional - Include slack variables - **pw_cost_model** (str) - Optional - Piecewise cost model ### Request Example ```python from egret.models.ac_relaxations import create_soc_relaxation_model md = ModelData.read('case.m') m, md = create_soc_relaxation_model(md) ``` ``` -------------------------------- ### Solve Unit Commitment Model Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/unit_commitment.md Create and solve a unit commitment model with default settings. Requires EGRET ModelData and a Pyomo solver. ```python from egret.data.model_data import ModelData from egret.models.unit_commitment import solve_unit_commitment # Load multi-period data md = ModelData.read('7-period_uc.json') # Solve with default tight formulation md_results = solve_unit_commitment(md, 'cbc') ``` -------------------------------- ### Create KOW Unit Commitment Model Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/unit_commitment.md Instantiates the Knueven-Ostrowski-Watson (KOW) unit commitment formulation. Accepts model data and optional relaxation and keyword arguments. ```python def create_KOW_unit_commitment_model(model_data, relaxed=False, **kwargs): ... ``` -------------------------------- ### Visualize Unit Commitment Results Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/INDEX.md Solves a Unit Commitment problem and generates a stack graph visualization. Requires importing generate_graphs and solve_unit_commitment. ```python from egret.viz.generate_graphs import generate_stack_graph # Solve and visualize results = solve_unit_commitment(md, 'cbc') fig = generate_stack_graph(results, save_figure=True, filename='dispatch.pdf') ``` -------------------------------- ### Specify Correct File Type for ModelData Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/errors.md Illustrates how to specify the file type when loading data, or rely on EGRET's auto-detection. ```python md = ModelData('data.txt', file_type='xyz') # 'xyz' not valid ``` ```python md = ModelData('data.m', file_type='m') # Specify correct type # Or let EGRET infer from extension md = ModelData('data.m') # Auto-detected as MATPOWER ``` -------------------------------- ### create_scopf_model() Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/other_models.md Create a Security-Constrained OPF model that enforces N-1 contingency constraints. ```APIDOC ## create_scopf_model() ### Description Create a Security-Constrained OPF model. ### Method ```python def create_scopf_model(model_data, contingency_list=None, relaxed_contingency_enforcement=False, include_feasibility_slack=False, include_flow_violation_penalty=False, pw_cost_model='delta'): ... ``` ### Parameters #### Path Parameters - **model_data** (ModelData) - Required - EGRET ModelData object - **contingency_list** (list or None) - Optional - List of contingency branch names (None = all branches) - **relaxed_contingency_enforcement** (bool) - Optional - Relax contingency constraints with penalty - **include_feasibility_slack** (bool) - Optional - Include slack variables - **include_flow_violation_penalty** (bool) - Optional - Add penalty term for flow violations - **pw_cost_model** (str) - Optional - Piecewise cost model ### Request Example ```python from egret.models.scopf import create_scopf_model, solve_scopf md = ModelData.read('case57.m') # SCOPF with all N-1 contingencies md_results = solve_scopf(md, 'gurobi') # SCOPF with specific contingencies md_results = solve_scopf(md, 'gurobi', contingency_list=['L1', 'L2', 'L3']) ``` ``` -------------------------------- ### create_dcopf_bilievel_model Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/other_models.md Creates a bilevel DCOPF model, suitable for transmission planning and market design problems. It allows for various configurations including contingency analysis and slack variable inclusion. ```APIDOC ## create_dcopf_bilievel_model() ### Description Create a bilevel DCOPF model (two-level optimization). ### Method Signature ```python def create_dcopf_bilievel_model(model_data, transmission_scaling_factor=1.0, contingency_list=None, relaxed_contingency_enforcement=False, include_feasibility_slack=False, pw_cost_model='delta'): ... ``` ### Parameters #### Positional Parameters - **model_data** (ModelData) - Required - EGRET ModelData object #### Keyword Parameters - **transmission_scaling_factor** (float) - Optional - Default: 1.0 - Scale transmission capacities - **contingency_list** (list or None) - Optional - Default: None - N-1 contingency list - **relaxed_contingency_enforcement** (bool) - Optional - Default: False - Relax contingency constraints - **include_feasibility_slack** (bool) - Optional - Default: False - Include slack variables - **pw_cost_model** (str) - Optional - Default: 'delta' - Piecewise cost model ### Returns - (model, model_data) tuple ``` -------------------------------- ### Generate and Display Multiple Case Comparison Graphs Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/visualization.md Iterates through multiple case files, solves unit commitment for each, generates a stack graph for dispatch, and displays all generated figures. Requires `ModelData`, `solve_unit_commitment`, and `generate_stack_graph`. ```python from egret.data.model_data import ModelData from egret.models.unit_commitment import solve_unit_commitment from egret.viz.generate_graphs import generate_stack_graph import matplotlib.pyplot as plt cases = ['base_case.json', 'high_wind.json', 'high_demand.json'] figures = {} for case in cases: md = ModelData.read(case) md_results = solve_unit_commitment(md, 'cbc') fig = generate_stack_graph(md_results, title=f'Dispatch: {case}', show_figure=False) figures[case] = fig # Display all figures for case, fig in figures.items(): print(f"Generated figure for {case}") plt.show() ``` -------------------------------- ### Tune for Quick Solutions with Reduced Iteration Limit Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Speed up solutions by reducing the iteration limit for lazy constraints and increasing the violation tolerance. ```python # Or reduce iteration limit ptdf_opts = populate_default_ptdf_options({ 'lazy': True, 'iteration_limit': 10, 'violation_tolerance': 5.0 }) ``` -------------------------------- ### Solve Unit Commitment with Visualization Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/README.md Loads multi-period unit commitment data from a JSON file and solves the problem using the Gurobi solver with a specified MIP gap. Generates and saves a dispatch visualization. ```python from egret.data.model_data import ModelData from egret.models.unit_commitment import solve_unit_commitment from egret.viz.generate_graphs import generate_stack_graph # Load multi-period data md = ModelData.read('7-period_uc.json') # Solve with 1% MIP gap results = solve_unit_commitment(md, 'gurobi', mipgap=0.01) # Visualize dispatch fig = generate_stack_graph(results, title='24-Hour Unit Commitment', save_figure=True, filename='dispatch.pdf') ``` -------------------------------- ### solve_dcopf() Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/dcopf.md Creates and solves a DCOPF model. It takes model data and a solver as input, with options for time limits, solver output, and returning intermediate objects. ```APIDOC ## `solve_dcopf()` Creates and solves a DCOPF model in one call. ### Method ```python def solve_dcopf(model_data, solver, timelimit=None, solver_tee=True, symbolic_solver_labels=False, options=None, dcopf_model_generator=create_btheta_dcopf_model, return_model=False, return_results=False, **kwargs) ``` ### Parameters #### Required Parameters - **model_data** (ModelData) - EGRET ModelData object. - **solver** (str or OptSolver) - Pyomo solver name ('cbc', 'glpk', 'gurobi') or solver instance. #### Optional Parameters - **timelimit** (float or None) - Time limit in seconds; None = no limit. Default: None. - **solver_tee** (bool) - Display solver log output. Default: True. - **symbolic_solver_labels** (bool) - Use symbolic labels for debugging. Default: False. - **options** (dict or None) - Additional solver options. Default: None. - **dcopf_model_generator** (function) - Function to generate the model. Default: `create_btheta_dcopf_model`. - **return_model** (bool) - Return the Pyomo model object. Default: False. - **return_results** (bool) - Return the Pyomo results object. Default: False. - **kwargs** (dict) - Additional arguments passed to model generator. ### Returns - ModelData with results if no flags set. - (ModelData, model) if `return_model=True`. - (ModelData, results) if `return_results=True`. - (ModelData, model, results) if both flags are True. ### Result Attributes #### Generator Attributes - `pg` (float) - Real power generation (MW). #### Bus Attributes - `lmp` (float) - Locational Marginal Price ($/MWh). - `pl` (float) - Real power load (MW). - `va` (float) - Voltage angle (degrees). - `p_balance_violation` (float) - Load shed minus over-generation (MW) (if feasibility slack enabled). #### Branch Attributes - `pf` (float) - Real power flow from-to (MW). #### System Attributes - `total_cost` (float) - Objective function value (total generation cost). - `p_balance_violation` (float) - System-wide power balance violation (MW) (if slack enabled). ### Example ```python from egret.models.dcopf import solve_dcopf from egret.data.model_data import ModelData md = ModelData.read('case14.m') # Basic solve md_results = solve_dcopf(md, 'cbc') # With time limit and solver options md_results = solve_dcopf(md, 'gurobi', timelimit=300.0, options={'MIPGap': 0.01}) # Get model and results for inspection md_results, m, results = solve_dcopf(md, 'cbc', return_model=True, return_results=True) # Generator cost output (MW) for gen_name, gen_dict in md_results.elements('generator'): print(f"{gen_name}: {gen_dict['pg']} MW") # Bus LMP (locational marginal price) for bus_name, bus_dict in md_results.elements('bus'): print(f"{bus_name}: ${bus_dict.get('lmp', 'N/A')}/MWh") ``` ``` -------------------------------- ### Create Bilevel DCOPF Model Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/other_models.md Function to create a bilevel DCOPF model, suitable for transmission planning and market design problems. It accepts model data and various optional parameters for customization. ```python def create_dcopf_bilievel_model(model_data, transmission_scaling_factor=1.0, contingency_list=None, relaxed_contingency_enforcement=False, include_feasibility_slack=False, pw_cost_model='delta'): ... ``` -------------------------------- ### Create SOC Relaxation Model Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/other_models.md Construct a Second-Order Cone (SOC) relaxation of the AC Optimal Power Flow (ACOPF) problem. This provides a convex approximation for solving complex power flow scenarios. ```python from egret.models.ac_relaxations import create_soc_relaxation_model md = ModelData.read('case.m') m, md = create_soc_relaxation_model(md) ``` -------------------------------- ### Clone ModelData at a Valid Time Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/errors.md Demonstrates how to safely clone ModelData at a specific time, checking for time key validity first. ```python md = ModelData('uc.json') md_t = md.clone_at_time(999) # Time 999 doesn't exist ``` ```python valid_times = md.data['system'].get('time_keys', []) print(f"Available times: {valid_times}") if 5 in valid_times: md_t = md.clone_at_time(5) else: print(f"Time 5 not available. Choose from: {valid_times}") ``` -------------------------------- ### Standard PTDF Options Dictionary Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/ptdf_utilities.md A dictionary defining common configuration options for PTDF calculations, including settings for lazy constraint generation, iteration limits, and violation tolerances. ```python ptdf_options = { 'lazy': False, # Enable lazy constraint generation 'iteration_limit': 100000, # Max iterations 'violation_tolerance': 1.0, # MW tolerance for violations 'rel_violation_tolerance': 0.01, # Relative tolerance (%) 'exclude_contingencies': True, # Skip contingency constraints 'exclude_interfaces': False, # Skip interface constraints 'max_violations_per_iteration': { 'branch': 100, # Branch constraints per iteration 'interface': 10, # Interface constraints per iteration 'contingency': 0 # Contingency constraints per iteration }, 'force_all_contingencies_initially': False, 'verbose': True # Detailed iteration output } ``` -------------------------------- ### Calculate Power Flows (PFV) Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/ptdf_utilities.md Calculates power flows from a solved Pyomo model's bus injections. Returns power flow values, contingency flows, and bus angles. ```python def calculate_PFV(self, model): ... ``` -------------------------------- ### Create Compact Unit Commitment Model Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/unit_commitment.md Generates a compact unit commitment model. Similar to the tight formulation, it takes model data and optional relaxation and keyword arguments. ```python def create_compact_unit_commitment_model(model_data, relaxed=False, **kwargs): ... ``` -------------------------------- ### Gurobi Solver Options Configuration Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Set Gurobi solver options such as MIP gap, time limit, threads, algorithm method, presolve level, and logging verbosity. These options allow for detailed control over Gurobi's optimization process. ```python solver_options = { 'MIPGap': 0.01, # MIP optimality gap (1%) 'TimeLimit': 300.0, # Time limit (seconds) 'Threads': 4, # Number of threads 'Method': 0, # Algorithm: -1=auto, 0=primal, 1=dual, 2=barrier 'Presolve': 2, # Presolve level: -1=auto, 0=off, 1=conservative, 2=aggressive 'OutputFlag': 1 # Solver logging } results = solve_dcopf(md, 'gurobi', options=solver_options) ``` -------------------------------- ### Tune for Tight Optimality with Tight MIP Gap Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Achieve tighter optimality by setting a very small MIP gap for the Unit Commitment solver. ```python # Tight MIP gap md_results = solve_unit_commitment(md, 'gurobi', mipgap=0.0001) # 0.01% ``` -------------------------------- ### Lazy Constraint Generation for Large DC OPF Systems Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/INDEX.md Solves a DC OPF using lazy constraint generation for large systems, employing PTDF options. Requires specific imports for model generation and PTDF utilities. ```python from egret.models.dcopf import solve_dcopf, create_ptdf_dcopf_model from egret.common.lazy_ptdf_utils import populate_default_ptdf_options ptdf_opts = populate_default_ptdf_options({ 'lazy': True, 'iteration_limit': 50, 'violation_tolerance': 2.0 }) results = solve_dcopf(md, 'cbc', dcopf_model_generator=create_ptdf_dcopf_model, ptdf_options=ptdf_opts) ``` -------------------------------- ### create_copperplate_dispatch_approx_model() Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/other_models.md Create a copperplate dispatch model with the assumption of no transmission constraints. ```APIDOC ## create_copperplate_dispatch_approx_model() ### Description Create a copperplate (no transmission constraints) dispatch model. ### Method ```python def create_copperplate_dispatch_approx_model(model_data, include_feasibility_slack=False, pw_cost_model='delta'): ... ``` ### Parameters #### Path Parameters - **model_data** (ModelData) - Required - EGRET ModelData object - **include_feasibility_slack** (bool) - Optional - Include slack variables - **pw_cost_model** (str) - Optional - Piecewise cost model ### Request Example ```python from egret.models.copperplate_dispatch import create_copperplate_dispatch_approx_model md = ModelData.read('case.m') m, md = create_copperplate_dispatch_approx_model(md) ``` ``` -------------------------------- ### Ipopt Solver Options Configuration Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Set Ipopt solver options such as print level for verbosity, maximum iterations, and constraint tolerance. These are essential for controlling Ipopt's behavior in non-linear optimization. ```python solver_options = { 'print_level': 3, # Verbosity (0-12) 'max_iter': 3000, # Maximum iterations 'tol': 1e-4 # Constraint tolerance } results = solve_acopf(md, 'ipopt', options=solver_options) ``` -------------------------------- ### create_stochastic_dcopf_model Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/other_models.md Creates a stochastic DCOPF model designed to handle uncertain renewable generation by solving with multiple scenarios. ```APIDOC ## create_stochastic_dcopf_model() ### Description Create stochastic DCOPF for uncertain renewable generation. ### Method Signature ```python def create_stochastic_dcopf_model(model_data, scenario_data, weight_scenarios=None, include_feasibility_slack=False): ... ``` ### Parameters #### Positional Parameters - **model_data** (ModelData) - Required - EGRET ModelData object - **scenario_data** (object) - Required - Scenario data for uncertainty #### Keyword Parameters - **weight_scenarios** (object or None) - Optional - Default: None - Weights for scenarios - **include_feasibility_slack** (bool) - Optional - Default: False - Include slack variables ### Use Case Used for solving with multiple scenarios (wind/solar variability, demand uncertainty). ``` -------------------------------- ### Configure Unit Commitment Generator Parameters Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/configuration.md Pass parameters to the Unit Commitment model generator, including PTDF options and ramp constraints. ```python from egret.models.unit_commitment import solve_unit_commitment results = solve_unit_commitment(md, 'gurobi', # UC model options ptdf_options=ptdf_opts, ramp_constraints=True, no_startup_shutdown_ramp=False) ``` -------------------------------- ### create_compact_unit_commitment_model() Source: https://github.com/grid-parity-exchange/egret/blob/main/_autodocs/api-reference/unit_commitment.md Creates a compact unit commitment model. This formulation offers a balance between solution speed and accuracy for generator scheduling. ```APIDOC ## create_compact_unit_commitment_model() ### Description Creates a compact unit commitment model. This formulation is designed for efficient solving of the dynamic scheduling problem for electric generators. ### Method ```python def create_compact_unit_commitment_model(model_data, relaxed=False, **kwargs): ... ``` ### Parameters #### Path Parameters - **model_data** (ModelData) - Required - EGRET ModelData object with multi-period data #### Query Parameters - **relaxed** (bool) - Optional - Default: False - Relax binary commitment variables to continuous [0,1] #### Request Body - **kwargs** (dict) - Optional - Additional model-specific options ### Returns Pyomo ConcreteModel ```