### Run MESMO Thermal Grid Optimal Operation (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md An advanced example demonstrating the step-by-step setup and solution of an optimal operation problem for a thermal grid using MESMO. ```Python run_thermal_grid_optimal_operation.py ``` -------------------------------- ### Run MESMO Electric Grid Optimal Operation (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md An advanced example demonstrating the step-by-step setup and solution of an optimal operation problem specifically for an electric grid using MESMO. ```Python run_electric_grid_optimal_operation.py ``` -------------------------------- ### Run MESMO Flexible DER Optimal Operation (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md An advanced example demonstrating the step-by-step setup and solution of an optimal operation problem for flexible Distributed Energy Resources (DERs) using MESMO. ```Python run_flexible_der_optimal_operation.py ``` -------------------------------- ### Recommended MESMO Installation (Conda) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/installation.md This snippet details the recommended steps for installing MESMO using a Conda-based Python distribution. It covers creating a dedicated Conda environment, activating it, and running the development setup script. It also includes an optional step for installing Intel MKL on Intel CPUs for performance. ```Shell cd path_to_mesmo_repository conda create -n mesmo -c conda-forge python=3.10 contextily cvxpy numpy pandas scipy conda activate mesmo python development_setup.py # On Intel CPUs: conda install -c conda-forge "libblas=*=*mkl" ``` -------------------------------- ### Run MESMO Multi-Grid Optimal Operation (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md An advanced example demonstrating the step-by-step setup and solution of an optimal operation problem involving multiple interconnected grids using MESMO. ```Python run_multi_grid_optimal_operation.py ``` -------------------------------- ### Run MESMO Electric Grid Power Flow Single Step (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md An advanced example demonstrating the setup and solution of a single-step electric grid power flow problem using MESMO. ```Python run_electric_grid_power_flow_single_step.py ``` -------------------------------- ### MESMO Installation and Dependencies Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Details the `setup.py` file, which manages MESMO's installation routines and lists external package dependencies. It also mentions `environment.yml` as an alternative installation method. ```Python setup.py ``` ```YAML environment.yml ``` -------------------------------- ### MESMO Example Run Script Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Example run scripts are provided in the 'examples' directory to demonstrate typical use cases of MESMO. These scripts are well-commented and serve as templates for users interacting with MESMO's interfaces. ```Python # Import MESMO modules from mesmo import MESMO # Initialize MESMO mesmo_instance = MESMO() # Load scenario data scenario_data = "data/example_scenario.csv" mesmo_instance.load_scenario(scenario_data) # Define model parameters model_params = { "parameter1": 10, "parameter2": "value" } # Run a simulation results = mesmo_instance.run_simulation(model_params) # Save results mesmo_instance.save_results(results, "results/simulation_output.csv") print("Simulation completed and results saved.") ``` -------------------------------- ### Alternative MESMO Installation (Conda Environment Files) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/installation.md This snippet outlines an alternative installation method for MESMO, useful when encountering compatibility issues. It involves creating a Conda environment from provided YAML files specific to the operating system (Windows, macOS, Ubuntu), activating the environment, and running the development setup. ```Shell cd path_to_mesmo_repository # On Windows: conda env create -f environment-windows-latest.yml # On macOS: conda env create -f environment-macos-latest.yml # On Ubuntu: conda env create -f environment-ubuntu-latest.yml conda activate mesmo python development_setup.py ``` -------------------------------- ### Import MESMO and Utilities Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Imports necessary libraries for MESMO operations, including Plotly for visualization and OS for path management. It also loads the MESMO library itself. ```Python import os import plotly.graph_objects as go import mesmo ``` -------------------------------- ### Install MESMO with Conda Source: https://github.com/mesmo-dev/mesmo/blob/develop/README.md This snippet outlines the steps to install MESMO using a conda-based Python distribution. It includes creating a new conda environment, activating it, and installing necessary dependencies like Python, contextily, cvxpy, numpy, pandas, and scipy. It also covers running a setup script and installing MKL for Intel CPUs. ```Shell cd path_to_mesmo_repository conda create -n mesmo -c conda-forge python=3.10 contextily cvxpy numpy pandas scipy conda activate mesmo python development_setup.py conda install -c conda-forge "libblas=*=*mkl" ``` -------------------------------- ### Import MESMO and NumPy Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Imports the necessary libraries, NumPy for numerical operations and MESMO for optimization functionalities. These are essential for setting up and solving the optimization problem. ```Python import numpy as np import mesmo ``` -------------------------------- ### Initialize Optimization Problem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Initializes an OptimizationProblem object to serve as a container for variables, parameters, constraints, and the objective of an optimization problem. ```Python optimization_problem = mesmo.solutions.OptimizationProblem() ``` -------------------------------- ### Instantiate OptimizationProblem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Creates an instance of the MESMO OptimizationProblem class. This object will serve as a container for all problem definitions, including parameters, variables, constraints, and objectives. ```Python optimization_problem = mesmo.solutions.OptimizationProblem() ``` -------------------------------- ### Launch Results Viewer Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Launches a file explorer window to the specified results path and prints the path to the console. This utility helps users easily access their generated results. ```Python mesmo.utils.launch(results_path) print(f"Results are stored in: {results_path}") ``` -------------------------------- ### Install Documentation Dependencies (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/README.md Installs the necessary Python packages for generating documentation. Requires a Python environment and the repository's requirements file. ```shell pip install -r docs/requirements.txt ``` -------------------------------- ### Build All Documentation Versions (Sphinx) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/README.md Generates documentation for all available versions and branches using sphinx-multiversion. This command assumes Sphinx is installed and configured. ```shell sphinx-multiversion docs docs/_build/html ``` -------------------------------- ### MESMO Additional Data Path Configuration Example Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/configuration_reference.md An example of how to configure additional data directories in MESMO. This allows MESMO to import data from supplementary folders located relative to the project's base directory. ```yaml paths: additional_data: [ ./../supplementary_data, ./../project_data ] ``` -------------------------------- ### Validate MESMO Linear Electric Grid Model (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md A validation script provided for testing and verifying the linear electric grid model implementation within MESMO. ```Python validation_linear_electric_grid_model.py ``` -------------------------------- ### Define Scenario Name and Results Path Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Sets the scenario name to 'tutorial_example' and determines the path for storing results using MESMO's utility function. This helps in organizing output files specific to the defined test case. ```Python scenario_name = 'tutorial_example' results_path = mesmo.utils.get_results_path(__file__, scenario_name) ``` -------------------------------- ### Load MESMO Data and Models Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Loads essential data and model objects required for optimization problems in MESMO. This includes price data, linear electric grid models, and DER models, all identified by the scenario name. ```Python price_data = mesmo.data_interface.PriceData(scenario_name) linear_electric_grid_model_set = mesmo.electric_grid_models.LinearElectricGridModelSet(scenario_name) der_model_set = mesmo.der_models.DERModelSet(scenario_name) ``` -------------------------------- ### Import MESMO and Utilities Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Imports necessary Python libraries for numerical operations, file path management, plotting, and the MESMO framework. Numpy is used for calculations, os for path operations, plotly for visualization, and mesmo for accessing the library's functionalities. ```Python import numpy as np import os import plotly.graph_objects as go import mesmo ``` -------------------------------- ### Instantiate MESMO Operation Problems Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Creates instances of MESMO's NominalOperationProblem and OptimalOperationProblem classes for the specified scenario. These objects are used to perform simulations under nominal conditions and solve optimization problems with custom constraints, respectively. ```Python problem_nominal = mesmo.problems.NominalOperationProblem(scenario_name) problem_optimal = mesmo.problems.OptimalOperationProblem(scenario_name) ``` -------------------------------- ### Python Logging Example Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/contributing.md Illustrates how to use Python's logging module for outputting messages like errors, warnings, and debug information, instead of using print statements. ```Python import logging # Configure logging (basic example) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Example usage logger.error("This is an error message.") logger.warning("This is a warning message.") logger.debug("This is a debug message.") ``` -------------------------------- ### Validate MESMO Electric Grid Power Flow (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md A validation script provided for testing and verifying the accuracy of the electric grid power flow solution implemented in MESMO. ```Python validation_electric_grid_power_flow.py ``` -------------------------------- ### Validate MESMO Electric Grid DLMP Solution (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md A validation script for solving a decentralized DER operation problem using Decentralized Locational Marginal Prices (DLMPs) derived from a centralized problem within MESMO. ```Python validation_electric_grid_dlmp_solution.py ``` -------------------------------- ### Run MESMO Nominal Operation Problem (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Demonstrates setting up and solving a nominal operation problem using the MESMO API. This problem type simulates steady-state power flow for all timesteps based on a nominal operation schedule for Distributed Energy Resources (DERs). ```Python run_api_nominal_operation_problem.py ``` -------------------------------- ### Solve Optimization Problem in Python Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Solves the defined optimization problem by compiling it into a standard form and passing it to an optimization solver. Supports interfaces for Gurobi and CVXPY, with CVXPY serving as a fallback for broader solver compatibility. ```Python optimization_problem.solve() ``` -------------------------------- ### Define Problem Dimension and Parameter Matrix Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Sets the dimension for the optimization problem and generates a random parameter matrix using NumPy. The parameter matrix is a key input for the optimization problem. ```Python dimension = 1000 parameter_matrix = np.random.rand(dimension, dimension) ``` -------------------------------- ### Solve Optimization Problem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Invokes the optimization solver by calling the solve() method on the OptimizationProblem object. This internally generates the LP/QP standard form and passes it to the solver interface (e.g., gurobipy or cvxpy). The solution is stored within the object. ```Python optimization_problem.solve() ``` -------------------------------- ### Solve Nominal Operation Problem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Solves the nominal operation problem and retrieves the results. The `solve()` method initiates the power flow solution for electric and thermal grids, while `get_results()` collects the outcomes into a Results object. ```Python problem_nominal.solve() results_nominal = problem_nominal.get_results() ``` -------------------------------- ### Run MESMO Optimal Operation Problem (Python) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Demonstrates setting up and solving an optimal operation problem using the MESMO API. This problem type optimizes DER and grid operator objectives subject to DER and grid model constraints, also known as optimal dispatch or optimal power flow. ```Python run_api_optimal_operation_problem.py ``` -------------------------------- ### Define Parameter in Optimization Problem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Defines a parameter named 'parameter_matrix' within the optimization problem. This allows the parameter to be referenced and updated easily without redefining the entire problem. ```Python optimization_problem.define_parameter('parameter_matrix', parameter_matrix) ``` -------------------------------- ### Retrieve Optimization Results in Python Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Retrieves the results of the solved optimization problem. Results are returned as a dictionary where keys correspond to variable names. Values are typically pandas DataFrames or Series, indexed by time steps. ```Python results = optimization_problem.get_results() a_vector = results['a_vector'] b_vector = results['b_vector'] ``` -------------------------------- ### MESMO Configuration Module Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Implements functionality for configuration variables, logger setup, and parallel pool initialization. It reads settings from config.yml and config_default.yml, manages logging levels, and handles parallel processing via starmap. ```Python def get_config(): # Declaration of configuration variables pass def get_logger(): # Setup of logger object pass def get_parallel_pool(): # Setup of parallel pool pass ``` -------------------------------- ### Plotting DER Dispatch Comparison Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Creates a comparison plot of DER dispatch schedules between nominal and optimal operation problems using Plotly. It adds scatter traces for both scenarios and saves the figure to a file. ```Python figure = go.Figure() figure.add_trace(go.Scatter( x=results_nominal.der_active_power_vector.index, y=np.abs(np.sum(results_nominal.der_active_power_vector, axis=1)), name='Nominal', line=go.scatter.Line(shape='hv') )) figure.add_trace(go.Scatter( x=results_optimal.der_active_power_vector.index, y=np.abs(np.sum(results_optimal.der_active_power_vector, axis=1)), name='Optimal', line=go.scatter.Line(shape='hv') )) mesmo.utils.write_figure_plotly(figure, os.path.join(results_path, 'comparison')) ``` -------------------------------- ### Define Variables in Optimization Problem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Defines two variables, 'a_vector' and 'b_vector', for the optimization problem. Each variable is defined with an index set that determines its dimension. ```Python optimization_problem.define_variable('a_vector', a_index=range(dimension)) optimization_problem.define_variable('b_vector', b_index=range(dimension)) ``` -------------------------------- ### Retrieve and Update Results Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Instantiates a Results object and updates it with optimization results extracted from model objects using get_optimization_results(). The results are stored as pd.DataFrame or pd.Series and attached to the Results object. ```Python results = mesmo.problems.Results() results.update(linear_electric_grid_model_set.get_optimization_results(optimization_problem)) results.update(der_model_set.get_optimization_results(optimization_problem)) ``` -------------------------------- ### Customize and Solve Optimal Operation Problem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Defines a custom constraint for the optimal operation problem to limit peak DER demand. It calculates peak load from nominal results and applies it as a constraint using the `define_constraint` method. The `solve()` method then runs the optimization, and `get_results()` fetches the optimized outcomes. ```Python for timestep in problem_optimal.timesteps: problem_optimal.optimization_problem.define_constraint( ( 'variable', np.array([np.real(problem_optimal.electric_grid_model.der_power_vector_reference)]), dict(name='der_active_power_vector', timestep=timestep) ), '>=', ( 'constant', 0.95 * np.min(np.sum(results_nominal.der_active_power_vector, axis=1)) ) ) problem_optimal.solve() results_optimal = problem_optimal.get_results() ``` -------------------------------- ### Set Scenario Name and Results Path Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Defines the scenario name for identifying the test case and obtains a unique, timestamped results path using a MESMO utility function. This path is optional for storing results. ```Python scenario_name = 'singapore_6node' results_path = mesmo.utils.get_results_path(__file__, scenario_name) ``` -------------------------------- ### Save Results Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Saves the Results object, which contains DataFrames and Series, as CSV files. Model objects within the Results object are saved as binary PKL files. ```Python results.save(results_path) ``` -------------------------------- ### Define Optimization Problem Components Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Defines the variables, parameters, constraints, and objective for an optimization problem by attaching them to the OptimizationProblem object. This method is provided by model objects like linear electric grid and DER models. The price_data is used for objective definition. ```Python linear_electric_grid_model_set.define_optimization_problem(optimization_problem, price_data) der_model_set.define_optimization_problem(optimization_problem, price_data) ``` -------------------------------- ### Operation Problems in MESMO Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Defines the setup for nominal and optimal operation problems. Includes classes for defining problem workflows, solving them, and retrieving results. The Results class aggregates results from various sub-systems like electric grids and DER models. ```Python from mesmo.problems import NominalOperationProblem, OptimalOperationProblem from mesmo.problems import Results # Example usage (conceptual): # operation_problem = OptimalOperationProblem(der_model_set, electric_grid, ...) # operation_problem.solve() # results = operation_problem.get_results() ``` -------------------------------- ### Define Constraints in Python Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Defines constraints for an optimization problem using a list of tuples and strings. Supports equality, less than or equal to, and greater than or equal to operators. Handles variable and constant terms, including summation and multiplication with factors or matrices. ```Python optimization_problem.define_constraint( ('variable', 1.0, dict(name='b_vector')), '==', ('variable', 'parameter_matrix', dict(name='a_vector')), ) optimization_problem.define_constraint( ('constant', -10.0), '<=' , ('variable', 1.0, dict(name='a_vector')), ) optimization_problem.define_constraint( ('constant', +10.0), '>=' , ('variable', 1.0, dict(name='a_vector')), ) ``` -------------------------------- ### Recreate MESMO Database Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Recreates the internal SQLite database used by MESMO for data processing. This function should be called whenever test case definitions (CSV files) are created or modified to ensure the database reflects the latest data. ```Python mesmo.data_interface.recreate_database() ``` -------------------------------- ### Plot and Save Figure with Plotly Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Uses plotly.graph_objects to create a scatter plot of branch power magnitude and saves the figure to a file using the write_figure_plotly() utility function. It constructs a relative output path using os.path.join() for reproducibility. ```Python figure = go.Figure() figure.add_scatter( x=results.branch_power_magnitude_vector_1.index, y=results.branch_power_magnitude_vector_1.loc[:, [('line', '1', 1)]].values.ravel() ) figure.update_layout( title='Branch Power Magnitude at Line 1 (Phase 1)' ) mesmo.utils.write_figure_plotly(figure, os.path.join(results_path, 'branch_power_line_1_phase_1')) ``` -------------------------------- ### Initialize OptimalOperationProblem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Demonstrates the initialization of the OptimalOperationProblem class, which sets up child objects for electric grid modeling, linear electric grid models, and DER models. It also loads data from a SQLite database and defines initial power flow solutions. ```Python optimal_operation_problem = OptimalOperationProblem() # ... initialization routines load data, define models, and set up optimization problem ``` -------------------------------- ### Initialize NominalOperationProblem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Demonstrates the initialization of the `NominalOperationProblem` class, which internally creates `ElectricGridModel` and `DERModelSet` objects. These, in turn, load data from `database.sqlite` and prepare model matrices and DER models. ```Python problem = NominalOperationProblem() # Initialization routine loads ElectricGridData and DERData, # connects to database.sqlite, and sets up models. ``` -------------------------------- ### Configure CPLEX Optimization Solver Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/configuration_reference.md Sets CPLEX as the optimization solver, interfaced through CVXPY. Requires CPLEX installation as per CVXPY instructions. This configuration is used when CPLEX is not directly interfaced in MESMO. ```yaml optimization: solver_name: cplex solver_interface: cvxpy ``` -------------------------------- ### MESMO Documentation Build Workflow Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md This GitHub Actions workflow automates the building and deployment of MESMO's documentation. It uses Sphinx to build HTML documentation from Markdown files and deploys it to GitHub Pages upon changes to the repository. ```YAML name: Documentation Build on: push: branches: - main jobs: build-and-deploy-docs: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install sphinx sphinx-rtd-theme - name: Build documentation run: | cd docs make html - name: Deploy documentation uses: peaceiris/actions-gh-pages@v3 with: github_token: $secrets.GITHUB_TOKEN publish_dir: ./docs/_build/html ``` -------------------------------- ### Define Objective Term in Python Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/examples.md Defines a single objective term for an optimization problem. Objective terms can be variables or constants, and if multiple are defined, they are summed. Variable terms involve a numerical factor and can include slicing keys. ```Python optimization_problem.define_objective(('variable', 1.0, dict(name='b_vector'))) ``` -------------------------------- ### MESMO Low-Level Interfaces: Electric Grid Modeling (Python, MATLAB) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md MESMO must implement low-level interfaces for researchers, offering granular access to model formulations. This includes obtaining admittance matrices, incidence matrices, performing power flow analysis using fixed-point algorithms, and calculating sensitivity matrices for electric grids. ```Python def get_admittance_matrices(): # Obtain nodal and branch admittance matrices pass def get_incidence_matrices(): # Obtain incidence matrices for the electric grid pass def solve_power_flow(): # Obtain steady state power flow solution via fixed-point algorithm pass def get_sensitivity_matrices(): # Obtain sensitivity matrices of global linear approximate electric grid model pass ``` ```MATLAB function [nodal_Y, branch_Y] = get_admittance_matrices() % Obtain nodal and branch admittance matrices end function incidence = get_incidence_matrices() % Obtain incidence matrices for the electric grid end function solution = solve_power_flow() % Obtain steady state power flow solution via fixed-point algorithm end function sensitivities = get_sensitivity_matrices() % Obtain sensitivity matrices of global linear approximate electric grid model end ``` -------------------------------- ### Python Path Joining Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/contributing.md Demonstrates the recommended way to join path components in Python using os.path.join for cross-platform compatibility. ```Python import os # Correct way to join paths path = os.path.join("x", "y") ``` -------------------------------- ### Solution Interface (Optimization Solvers) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/index.md Provides interfaces for solving convex optimization problems for energy systems using third-party numerical optimization solvers. Enables custom constraints and objective terms for advanced analysis. ```Python import mesmo # Example of using optimization solvers # problem = mesmo.OptimizationProblem() # ... define objective and constraints ... # solver = mesmo.Solver() # solution = solver.solve(problem) ``` -------------------------------- ### Get and Save Results Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Details the process of retrieving simulation results using the `get_results()` method, which transforms `PowerFlowSolution` objects into a `Results` object. The results can then be saved to the file system via the `Results` object's `save()` method. ```Python results = problem.get_results() results.save() # Transforms PowerFlowSolution objects into a Results object # and saves them to the file system. ``` -------------------------------- ### Build Current Documentation Version (Sphinx) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/README.md Generates documentation only for the current version or branch using sphinx-build. This is a simpler build process compared to multi-version builds. ```shell sphinx-build docs docs/_build/html ``` -------------------------------- ### MESMO Foundational Publication: Software Architecture Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/publications.md This foundational publication outlines the software architecture for MESMO, serving as a basis for its implementation and development. It describes requirements for flexible distribution grid demonstrators. ```text This paper served as an outline for the software architecture of MESMO. ``` -------------------------------- ### High-Level Interface (Nominal Operation) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/index.md Offers a high-level interface for nominal operation problems, enabling simulation-based studies of energy systems. This allows for the analysis of system behavior under various scenarios. ```Python import mesmo # Example of nominal operation problem # nominal_problem = mesmo.NominalOperationProblem() # ... configure system components ... # simulation_result = nominal_problem.run_simulation() ``` -------------------------------- ### MESMO Foundational Publication: Review of Operation Methods Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/publications.md This review paper initiated the development of MESMO by examining operation methods and simulation requirements for future smart distribution grids. It provides a broad overview of the field. ```text This review paper initiated the development of MESMO. ``` -------------------------------- ### MESMO Foundational Publication: Synthetic Grid Generation Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/publications.md This publication outlines the synthetic grid model used with MESMO for Singapore-based studies. It discusses synthetic distribution grid generation using power system planning, though the test case is not currently included. ```text This paper outlines the synthetic grid model that was used with MESMO for Singapore-based studies at TUMCREATE. However, the complete synthetic test case is currently not part of this repository. ``` -------------------------------- ### High-Level Interface (Optimal Operation) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/index.md Provides a high-level interface for optimal operation problems, facilitating optimization-based studies. This interface supports decision support for energy system management. ```Python import mesmo # Example of optimal operation problem # optimal_problem = mesmo.OptimalOperationProblem() # ... configure system components and objectives ... # optimization_result = optimal_problem.run_optimization() ``` -------------------------------- ### MESMO Configuration Files Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Explains the role of `config.yml` for user-defined parameters and `config_default.yml` as its counterpart in the MESMO project. `config.yml` is intended for local modifications and is ignored by Git to prevent accidental commits. ```YAML config.yml config_default.yml ``` -------------------------------- ### Solve Nominal Operation Problem Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Explains how to use the `solve()` method of the `NominalOperationProblem` object. This method calculates power flow solutions for each time step by obtaining DER nominal power and using the `ElectricGridModel`. ```Python problem.solve() # This method calculates power flow solutions for each time step, # utilizing starmap() for parallel processing. ``` -------------------------------- ### Thermal Grid Modeling (Optimization) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/index.md Offers linear approximate modeling for optimization-based analysis of thermal grids. Supports radial district heating and cooling systems, using global or local approximation methods. ```Python import mesmo # Example of thermal grid optimization # thermal_grid = mesmo.ThermalGrid() # ... configure grid parameters ... # optimal_operation = thermal_grid.optimize() ``` -------------------------------- ### Electric Grid Modeling (Optimization) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/index.md Provides linear approximate modeling for optimization-based analysis of electric grids. Supports multi-phase and unbalanced AC networks, utilizing global or local approximation techniques. ```Python import mesmo # Example of electric grid optimization # electric_grid = mesmo.ElectricGrid() # ... configure grid parameters ... # optimal_operation = electric_grid.optimize() ``` -------------------------------- ### MESMO Utility Module Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Provides base classes for MESMO objects, optimization problem definitions, parallelization utilities, indexing functions, time logging, timestamp generation, results path creation, and Plotly figure saving. ```Python class ObjectBase: # MESMO object base class pass class ResultsBase: # Results object base class pass class OptimizationProblem: # Optimization problem class pass def starmap(func, iterable): # Parallelization utility function pass def get_index(vector): # Indexing utility function pass def log_time(message): # Log elapsed time pass def get_timestamp(): # Get current time stamp pass def get_results_path(): # Get path for new results folder pass def write_figure_plotly(fig, filename): # Write plotly figures to files pass ``` -------------------------------- ### Electric Grid Modeling (Simulation) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/index.md Implements non-linear modeling for steady-state analysis of electric grids, including nodal voltage, branch flows, and losses. Supports multi-phase and unbalanced AC networks. ```Python import mesmo # Example of electric grid simulation # electric_grid = mesmo.ElectricGrid() # ... configure grid parameters ... # solution = electric_grid.simulate() ``` -------------------------------- ### Power Flow Solution Algorithms in Python Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Provides abstract base classes and implementations for power flow solutions. PowerFlowSolution is an abstract base class, extended by PowerFlowSolutionFixedPoint and PowerFlowSolutionZBus for specific algorithms, and PowerFlowSolutionOpenDSS for OpenDSS-based solutions. ```Python class PowerFlowSolution: # Abstract base class for power flow solutions pass class PowerFlowSolutionFixedPoint(PowerFlowSolution): # Fixed-point solution algorithm pass class PowerFlowSolutionZBus(PowerFlowSolution): # Z-bus solution algorithm pass class PowerFlowSolutionOpenDSS(PowerFlowSolution): # Power flow solution through OpenDSS pass ``` -------------------------------- ### Configure Testing Scenarios Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/configuration_reference.md Defines the scenario names used for automated testing scripts. `scenario_name` is for general testing, while `thermal_grid_scenario_name` is specific to thermal-grid-related tests. ```yaml tests: scenario_name: singapore_6node thermal_grid_scenario_name: singapore_tanjongpagar ``` -------------------------------- ### MESMO High-Level Programmable Interfaces (Python, MATLAB) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md MESMO must provide high-level programmable interfaces in languages like Python or MATLAB for system planners and operators. These interfaces support nominal operation (simulation), optimal operation (cost minimization), and optimal planning (investment and operation cost minimization) problems for district-scale energy systems. ```Python def simulate_nominal_operation(der_power_timeseries): # Simulate nominal operation of the district-scale energy system pass def optimize_operation(constraints, der_operational_constraints): # Optimize operation for cost minimization pass def optimize_planning(capacity_constraints, der_operational_constraints): # Optimize planning for investment and operation cost minimization pass ``` ```MATLAB function simulate_nominal_operation(der_power_timeseries) % Simulate nominal operation of the district-scale energy system end function optimize_operation(constraints, der_operational_constraints) % Optimize operation for cost minimization end function optimize_planning(capacity_constraints, der_operational_constraints) % Optimize planning for investment and operation cost minimization end ``` -------------------------------- ### MESMO Low-Level Interfaces: Thermal Grid Modeling (Python, MATLAB) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md For thermal grid modeling, MESMO's low-level interfaces should provide access to incidence matrices, friction factors, and thermal power flow solutions. Researchers can obtain nodal pressure head, branch flows, pumping losses, and sensitivity matrices for the thermal grid. ```Python def get_thermal_incidence_matrices(): # Obtain nodal and branch incidence matrices for the thermal grid pass def get_friction_factors(): # Obtain friction factors for the thermal grid pass def solve_thermal_power_flow(): # Obtain thermal power flow solution for nodal pressure head, branch flows and pumping losses pass def get_thermal_sensitivity_matrices(): # Obtain sensitivity matrices of global linear approximate thermal grid model pass ``` ```MATLAB function incidence = get_thermal_incidence_matrices() % Obtain nodal and branch incidence matrices for the thermal grid end function factors = get_friction_factors() % Obtain friction factors for the thermal grid end function solution = solve_thermal_power_flow() % Obtain thermal power flow solution for nodal pressure head, branch flows and pumping losses end function sensitivities = get_thermal_sensitivity_matrices() % Obtain sensitivity matrices of global linear approximate thermal grid model end ``` -------------------------------- ### MESMO Operation: Simulation and Optimization (Python, MATLAB) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md MESMO facilitates obtaining and solving nominal operation problems (steady-state simulations) for electric and thermal grids with DERs. It also enables defining and solving numerical optimization problems for combined optimal operation and obtaining DLMPs for both grids. ```Python def solve_mes_nominal_operation(): # Obtain and solve nominal operation problems of electric and thermal grids with DERs pass def solve_mes_optimal_operation(): # Define and solve numerical optimization problem for combined optimal operation pass def get_dlmps(): # Obtain DLMPs for the electric and thermal grids pass ``` ```MATLAB function solution = solve_mes_nominal_operation() % Obtain and solve nominal operation problems of electric and thermal grids with DERs end function solution = solve_mes_optimal_operation() % Define and solve numerical optimization problem for combined optimal operation end function dlmp_values = get_dlmps() % Obtain DLMPs for the electric and thermal grids end ``` -------------------------------- ### Linear Thermal Grid Models and Optimization Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Defines base classes for linear thermal grid models and manages sets of these models for optimization. It includes methods for defining optimization variables, constraints, and objectives, as well as retrieving results. ```Python class LinearThermalGridModel: """Base class for linear thermal grid models.""" pass class LinearThermalGridModelSet: """Set of linear thermal grid models for optimization.""" def define_optimization_variables(self): pass def define_optimization_constraints(self): pass def define_optimization_objective(self): pass def get_optimization_results(self): pass def get_optimization_dlmps(self): pass ``` -------------------------------- ### Loading MESMO Scenarios from CSV Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/data_reference.md MESMO scenarios are defined using CSV files, which are automatically loaded into an SQLite database. This process allows for convenient data processing and querying of scenario definitions, including electric and thermal grid configurations. ```Python import sqlite3 import pandas as pd # Assuming CSV files are in a 'data' directory csv_files = ['scenarios.csv', 'parameters.csv', 'price_timeseries.csv', 'electric_grids.csv'] conn = sqlite3.connect('mesmo_scenario.db') for csv_file in csv_files: try: df = pd.read_csv(csv_file) table_name = csv_file.replace('.csv', '') df.to_sql(table_name, conn, if_exists='replace', index=False) print(f"Successfully loaded {csv_file} into table {table_name}") except FileNotFoundError: print(f"Error: {csv_file} not found.") except Exception as e: print(f"Error loading {csv_file}: {e}") conn.close() ``` -------------------------------- ### Fundamental Electric Grid Models in Python Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Implements fundamental electric grid models using classes like ElectricGridModel, ElectricGridModelDefault, and ElectricGridModelOpenDSS. ElectricGridModel serves as a base class, extended by ElectricGridModelDefault for mathematical definitions and ElectricGridModelOpenDSS for OpenDSS integration. ```Python class ElectricGridModel: # Base class for electric models pass class ElectricGridModelDefault(ElectricGridModel): # Extends base class with mathematical definitions pass class ElectricGridModelOpenDSS(ElectricGridModel): # Implements OpenDSS model interface pass ``` -------------------------------- ### MESMO Python Dependencies Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md This snippet lists the core Python dependencies for the MESMO project. It highlights libraries used for modeling (cobmo, OpenDSSDirect.py), database interaction (sqlite3), visualization (plotly, dash), and optimization (cvxpy, gurobipy). ```Python import cobmo import OpenDSSDirect.py import sqlite3 import plotly import dash import cvxpy import gurobipy ``` -------------------------------- ### Configure Plot File Format and Basemap Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/configuration_reference.md Sets the file format for saving plots (e.g., PNG) and controls whether a basemap layer is added for static grid plots. `add_basemap` requires the 'contextily' library, and `show_basemap_attribution` controls the display of copyright notices. ```yaml plots: file_format: png add_basemap: false show_basemap_attribution: ``` -------------------------------- ### MESMO Foundational Publication: DLMP Decomposition Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/publications.md This publication details the mathematical definitions for a linear global-approximate electric grid modeling method used in MESMO, focusing on decomposition and equilibrium achieving DLMPs. ```text This paper outlines the mathematical definitions for the linear global-approximate electric grid modeling method in MESMO. ``` -------------------------------- ### MESMO Version Control Branching Strategy Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Explains the MESMO project's adherence to the git-flow branching model. It details the purpose and management of `master` (stable releases), `develop` (main development), and `feature` branches for parallel development. ```Git master develop feature/* ``` -------------------------------- ### MESMO Git Repository Configuration Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Covers Git-related configuration files for the MESMO repository, including `.gitignore` to specify untracked files and `.gitmodules` for submodule definitions. ```Git .gitignore .gitmodules ``` -------------------------------- ### MESMO Python Implementation and Thermal Grids Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/change_log.md Covers the project's move to Python as the main implementation language and the addition of thermal grid models, including a linear thermal grid model with optimization capabilities. ```Python from mesmo.thermal_grid_models import LinearThermalGridModel # Example usage (conceptual) # linear_thermal_model = LinearThermalGridModel(...) # linear_thermal_model.define_optimization_variables(...) # linear_thermal_model.define_optimization_constraints(...) ``` -------------------------------- ### Thermal Grid Modeling (Simulation) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/index.md Implements non-linear modeling for steady-state analysis of thermal grids, including nodal pressure head, branch flow, and pump losses. Designed for radial district heating and cooling systems. ```Python import mesmo # Example of thermal grid simulation # thermal_grid = mesmo.ThermalGrid() # ... configure grid parameters ... # solution = thermal_grid.simulate() ``` -------------------------------- ### MESMO Scenario Input Data Format and Interfacing (Python, MATLAB) Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md MESMO requires a coherent scenario input data format for electric grid, thermal grid, and DER models. This format must be well-documented for users and enable interaction with common formats like MATPOWER and OpenDSS. ```Python def define_scenario_input_format(): # Define a coherent scenario input data format pass def interact_with_matpower(): # Enable interacting with MATPOWER format pass def interact_with_opendss(): # Enable interacting with OpenDSS format pass ``` ```MATLAB function define_scenario_input_format() % Define a coherent scenario input data format end function interact_with_matpower() % Enable interacting with MATPOWER format end function interact_with_opendss() % Enable interacting with OpenDSS format end ``` -------------------------------- ### Thermal Grid Model Implementation Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Implements the fundamental thermal grid model, including index sets for nodes, branches, and DERs, along with branch parameter and mapping matrices. ```Python class ThermalGridModel: """Fundamental thermal grid model.""" pass ``` -------------------------------- ### OptimizationProblem in MESMO Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/change_log.md Introduces the `utils.OptimizationProblem` class as the primary interface for defining optimization problems. It supports exporting standard forms for LP/QP and direct interfacing with Gurobi for improved performance. ```Python from mesmo.utils import OptimizationProblem # Example usage (conceptual) # opt_problem = OptimizationProblem(...) # opt_problem.export_lp_qp(...) # opt_problem.solve_with_gurobi(...) ``` -------------------------------- ### CoBMo Git Submodule Integration Source: https://github.com/mesmo-dev/mesmo/blob/develop/docs/architecture.md Describes how the CoBMo toolbox is included in the MESMO project as a Git submodule within the `cobmo` directory. This facilitates integrated development as CoBMo is not available on Python package indexes. ```Git git submodule add cobmo ```