API reference#

Important

This reference is work in progress.

mesmo.api#

Application programming interface (API) module for high-level interface functions to run MESMO.

mesmo.api.run_nominal_operation_problem(scenario_name, recreate_database=True, print_results=False, store_results=True, results_path=None)#

Set up and solve a nominal operation problem for the given scenario.

Parameters:
  • scenario_name (str) –

  • recreate_database (bool) –

  • print_results (bool) –

  • store_results (bool) –

  • results_path (str | None) –

Return type:

Results

mesmo.api.run_optimal_operation_problem(scenario_name, recreate_database=True, print_results=False, store_results=True, results_path=None, solve_method=None)#

Set up and solve an optimal operation problem for the given scenario.

Parameters:
  • scenario_name (str) –

  • recreate_database (bool) –

  • print_results (bool) –

  • store_results (bool) –

  • results_path (str | None) –

  • solve_method (str | None) –

Return type:

Results

mesmo.problems#

Problems module for mathematical optimization and simulation problem type definitions.

class mesmo.problems.Results(**kwargs)#

Bases: ElectricGridOperationResults, ThermalGridOperationResults, DERModelSetOperationResults, ElectricGridDLMPResults, ThermalGridDLMPResults

Results object, which serves as data object to hold structured results variables from solved problems.

class mesmo.problems.ResultsDict#

Bases: Dict[str, Results]

Results dictionary, which serves as collection object for labelled results objects.

class mesmo.problems.ProblemBase#

Bases: ObjectBase

Problem base object, which serves as abstract base class for problem objects.

class mesmo.problems.ProblemDict#

Bases: Dict[str, ProblemBase]

Problem dictionary, which serves as collection object for labelled problem objects.

solve()#

Solve all problems within this ProblemDict.

get_results()#

Get results for all problems within this ProblemDict.

Return type:

ResultsDict

class mesmo.problems.NominalOperationProblem#

Bases: ProblemBase

Nominal operation problem object, consisting of the corresponding electric / thermal grid models, reference power flow solutions and DER model set for the given scenario.

  • The nominal operation problem (alias: simulation problem, power flow problem) represents the simulation problem of the DERs and grids considering the nominal operation schedule for all DERs.

  • The problem formulation is able to consider combined as well as individual operation of thermal and electric grids.

class mesmo.problems.OptimalOperationProblem#

Bases: ProblemBase

Optimal operation problem object, consisting of an optimization problem as well as the corresponding electric / thermal grid models, reference power flow solutions, linear grid models and DER model set for the given scenario.

  • The optimal operation problem (alias: optimal dispatch problem, optimal power flow problem) formulates the optimization problem for minimizing the objective functions of DERs and grid operators subject to the model constraints of all DERs and grids.

  • The problem formulation is able to consider combined as well as individual operation of thermal and electric grids.

Keyword Arguments:

solve_method (str) – Solve method for the optimization problem. If None or ‘default’, it will use the default method of solving a single-shot optimization using the global approximation method. If ‘trust_region’, it will solve iteratively via trust-region method using the local approximation method. Choices: ‘default’, ‘trust_region’, None. Default: None.

solve_trust_region()#

Solves the optimal operation problem via trust-region method. In general, the trust-region based algorithm mitigates the approximation inaccuracy of the underlying linear approximate models. The algorithm improves the approximate solution of the underlying optimization problem in an iterative manner.

Trust-region algorithm is based on the work:

  • [1] Hanif et al. “Decomposition and Equilibrium Achieving Distribution Locational Marginal Prices using the Trust-Region Method” IEEE Transactions on Smart Grid, pp. 1–1, 2018, doi: 10.1109/TSG.2018.2822766.

Trust-region parameters are based on the works:

  • [2] A. M. Giacomoni and B. F. Wollenberg, “Linear programming optimal power flow utilizing a trust region method” in North American Power Symposium 2010, Arlington, TX, USA, Sep. 2010, pp. 1–6, doi: 10.1109/NAPS.2010.5619970.

  • [3] J. Nocedal and S. J. Wright, “Numerical Optimization”, Chapter 4, 2nd ed., New York: Springer, 2006.

mesmo.electric_grid_models#

Electric grid models module.

class mesmo.electric_grid_models.ElectricGridModel#

Bases: ObjectBase

Electric grid model object consisting of the index sets for node names / branch names / der names / phases / node types / branch types, the nodal admittance / transformation matrices, branch admittance / incidence matrices and DER incidence matrices.

Syntax:
  • ElectricGridModel(electric_grid_data): Instantiate electric grid model for given electric_grid_data.

  • ElectricGridModel(scenario_name): Instantiate electric grid model for given scenario_name. The required electric_grid_data is obtained from the database.

Parameters:
Variables:
  • phases (pd.Index) – Index set of the phases.

  • node_names (pd.Index) – Index set of the node names.

  • node_types (pd.Index) – Index set of the node types.

  • line_names (pd.Index) – Index set of the line names.

  • transformer_names (pd.Index) – Index set of the transformer names.

  • branch_names (pd.Index) – Index set of the branch names, i.e., all line names and transformer names.

  • branch_types (pd.Index) – Index set of the branch types.

  • der_names (pd.Index) – Index set of the DER names.

  • der_types (pd.Index) – Index set of the DER types.

  • nodes (pd.Index) – Multi-level / tuple index set of the node types, node names and phases corresponding to the dimension of the node admittance matrices.

  • branches (pd.Index) – Multi-level / tuple index set of the branch types, branch names and phases corresponding to the dimension of the branch admittance matrices.

  • lines (pd.Index) – Multi-level / tuple index set of the branch types, branch names and phases for the lines only.

  • transformers (pd.Index) – Multi-level / tuple index set of the branch types, branch names and phases for the transformers only.

  • ders (pd.Index) – Index set of the DER names, corresponding to the dimension of the DER power vector.

  • node_voltage_vector_reference (np.ndarray) – Node voltage reference / no load vector.

  • branch_power_vector_magnitude_reference (np.ndarray) – Branch power reference / rated power vector.

  • der_power_vector_reference (np.ndarray) – DER power reference / nominal power vector.

  • is_single_phase_equivalent (bool) – Singe-phase-equivalent modelling flag. If true, electric grid is modelled as single-phase-equivalent of three-phase balanced system.

  • node_admittance_matrix (sp.spmatrix) – Nodal admittance matrix.

  • node_transformation_matrix (sp.spmatrix) – Nodal transformation matrix.

  • branch_admittance_1_matrix (sp.spmatrix) – Branch admittance matrix in the ‘from’ direction.

  • branch_admittance_2_matrix (sp.spmatrix) – Branch admittance matrix in the ‘to’ direction.

  • branch_incidence_1_matrix (sp.spmatrix) – Branch incidence matrix in the ‘from’ direction.

  • branch_incidence_2_matrix (sp.spmatrix) – Branch incidence matrix in the ‘to’ direction.

  • der_incidence_wye_matrix (sp.spmatrix) – Load incidence matrix for ‘wye’ DERs.

  • der_incidence_delta_matrix (sp.spmatrix) – Load incidence matrix for ‘delta’ DERs.

  • node_admittance_matrix_no_source (sp.spmatrix) – Nodal admittance matrix from no-source to no-source nodes.

  • node_transformation_matrix_no_source (sp.spmatrix) – Nodal admittance matrix from source to no-source nodes.

  • der_incidence_wye_matrix_no_source (sp.spmatrix) – Incidence matrix from wye-conn. DERs to no-source nodes.

  • der_incidence_delta_matrix_no_source (sp.spmatrix) – Incidence matrix from delta-conn. DERs to no-source nodes.

  • node_voltage_vector_reference_no_source (sp.spmatrix) – Nodal reference voltage vector for no-source nodes.

  • node_voltage_vector_reference_source (sp.spmatrix) – Nodal reference voltage vector for source nodes.

  • node_admittance_matrix_no_source_inverse (sp.spmatrix) – Inverse of no-source nodal admittance matrix.

static process_line_types_overhead(electric_grid_data)#

Process overhead line type definitions in electric grid data object.

Parameters:

electric_grid_data (ElectricGridData) –

Return type:

ElectricGridData

class mesmo.electric_grid_models.ElectricGridModelDefault(*args, **kwargs)#

Bases: ElectricGridModel

ElectricGridModelDefault is a placeholder for ElectricGridModel for backwards compatibility and will be removed in a future version of MESMO.

class mesmo.electric_grid_models.ElectricGridModelOpenDSS#

Bases: ElectricGridModel

OpenDSS electric grid model object.

  • Instantiate OpenDSS circuit by running generating OpenDSS commands corresponding to given electric_grid_data, utilizing the OpenDSSDirect.py package.

  • The OpenDSS circuit can be accessed with the API of OpenDSSDirect.py: http://dss-extensions.org/OpenDSSDirect.py/opendssdirect.html

  • Due to dependency on OpenDSSDirect.py, creating multiple objects of this type may result in erroneous behavior.

Syntax:
  • ElectricGridModelOpenDSS(electric_grid_data): Initialize OpenDSS circuit model for given electric_grid_data.

  • ElectricGridModelOpenDSS(scenario_name) Initialize OpenDSS circuit model for given scenario_name. The required electric_grid_data is obtained from the database.

Parameters:
Variables:
  • phases (pd.Index) – Index set of the phases.

  • node_names (pd.Index) – Index set of the node names.

  • node_types (pd.Index) – Index set of the node types.

  • line_names (pd.Index) – Index set of the line names.

  • transformer_names (pd.Index) – Index set of the transformer names.

  • branch_names (pd.Index) – Index set of the branch names, i.e., all line names and transformer names.

  • branch_types (pd.Index) – Index set of the branch types.

  • der_names (pd.Index) – Index set of the DER names.

  • der_types (pd.Index) – Index set of the DER types.

  • nodes (pd.Index) – Multi-level / tuple index set of the node types, node names and phases corresponding to the dimension of the node admittance matrices.

  • branches (pd.Index) – Multi-level / tuple index set of the branch types, branch names and phases corresponding to the dimension of the branch admittance matrices.

  • lines (pd.Index) – Multi-level / tuple index set of the branch types, branch names and phases for the lines only.

  • transformers (pd.Index) – Multi-level / tuple index set of the branch types, branch names and phases for the transformers only.

  • ders (pd.Index) – Index set of the DER names, corresponding to the dimension of the DER power vector.

  • node_voltage_vector_reference (np.ndarray) – Node voltage reference / no load vector.

  • branch_power_vector_magnitude_reference (np.ndarray) – Branch power reference / rated power vector.

  • der_power_vector_reference (np.ndarray) – DER power reference / nominal power vector.

  • is_single_phase_equivalent (bool) – Singe-phase-equivalent modelling flag. If true, electric grid is modelled as single-phase-equivalent of three-phase balanced system.

  • circuit_name (str) – Circuit name, stored for validation that the correct OpenDSS model is being accessed.

  • electric_grid_data (mesmo.data_interface.ElectricGridData) – (mesmo.data_interface.ElectricGridData): Electric grid data object, stored for possible reinitialization of the OpenDSS model.

class mesmo.electric_grid_models.ElectricGridDEROperationResults(**kwargs)#

Bases: ResultsBase

class mesmo.electric_grid_models.ElectricGridOperationResults(**kwargs)#

Bases: ElectricGridDEROperationResults

class mesmo.electric_grid_models.ElectricGridDLMPResults(**kwargs)#

Bases: ResultsBase

class mesmo.electric_grid_models.PowerFlowSolutionBase#

Bases: ObjectBase

Power flow solution base object consisting of DER power vector and the corresponding solution for nodal voltage vector / branch power vector and total loss, all complex valued.

class mesmo.electric_grid_models.PowerFlowSolutionFixedPoint#

Bases: PowerFlowSolutionBase

Fixed point power flow solution object.

static check_solution_conditions(electric_grid_model, node_power_vector_wye_initial_no_source, node_power_vector_delta_initial_no_source, node_power_vector_wye_candidate_no_source, node_power_vector_delta_candidate_no_source, node_voltage_vector_initial_no_source)#
Check conditions for fixed-point solution existence, uniqueness and non-singularity for

given power vector candidate and initial point.

  • Conditions are formulated according to: <https://arxiv.org/pdf/1702.03310.pdf>

  • Note the performance issues of this condition check algorithm due to the requirement for matrix inversions / solving of linear equations.

Parameters:
  • electric_grid_model (ElectricGridModel) –

  • node_power_vector_wye_initial_no_source (numpy.ndarray) –

  • node_power_vector_delta_initial_no_source (numpy.ndarray) –

  • node_power_vector_wye_candidate_no_source (numpy.ndarray) –

  • node_power_vector_delta_candidate_no_source (numpy.ndarray) –

  • node_voltage_vector_initial_no_source (numpy.ndarray) –

Return type:

bool

static get_voltage(electric_grid_model, der_power_vector, outer_iteration_limit=100, outer_solution_algorithm='check_solution', power_candidate_iteration_limit=100, power_candidate_reduction_factor=0.5, voltage_iteration_limit=100, voltage_tolerance=0.01)#

Get nodal voltage vector by solving with the fixed point algorithm.

  • Initial DER power vector / node voltage vector must be a valid solution to te fixed-point equation, e.g., a previous solution from a past operation point.

  • Fixed point equation according to: <https://arxiv.org/pdf/1702.03310.pdf>

Parameters:
Return type:

numpy.ndarray

static get_branch_power(electric_grid_model, node_voltage_vector)#

Get branch power vectors by calculating power flow with given nodal voltage.

  • Returns two branch power vectors, where branch_power_vector_1 represents the “from”-direction and branch_power_vector_2 represents the “to”-direction.

Parameters:
  • electric_grid_model (ElectricGridModel) –

  • node_voltage_vector (numpy.ndarray) –

static get_loss(electric_grid_model, node_voltage_vector)#

Get total electric losses with given nodal voltage.

Parameters:
  • electric_grid_model (ElectricGridModel) –

  • node_voltage_vector (numpy.ndarray) –

class mesmo.electric_grid_models.PowerFlowSolutionZBus#

Bases: PowerFlowSolutionFixedPoint

Implicit Z-bus power flow solution object.

static check_solution_conditions(*args, **kwargs)#
Check conditions for fixed-point solution existence, uniqueness and non-singularity for

given power vector candidate and initial point.

  • Conditions are formulated according to: <https://arxiv.org/pdf/1702.03310.pdf>

  • Note the performance issues of this condition check algorithm due to the requirement for matrix inversions / solving of linear equations.

static get_voltage(electric_grid_model, der_power_vector, voltage_iteration_limit=100, voltage_tolerance=0.01, **kwargs)#

Get nodal voltage vector by solving with the implicit Z-bus method.

Parameters:
Return type:

numpy.ndarray

class mesmo.electric_grid_models.PowerFlowSolutionOpenDSS#

Bases: PowerFlowSolutionBase

OpenDSS power flow solution object.

static get_voltage(electric_grid_model)#

Get nodal voltage vector by solving OpenDSS model.

  • OpenDSS model must be readily set up, with the desired power being set for all DERs.

Parameters:

electric_grid_model (ElectricGridModelOpenDSS) –

static get_branch_power()#

Get branch power vectors by solving OpenDSS model.

  • OpenDSS model must be readily set up, with the desired power being set for all DERs.

static get_loss()#

Get total loss by solving OpenDSS model.

  • OpenDSS model must be readily set up, with the desired power being set for all DERs.

class mesmo.electric_grid_models.PowerFlowSolution#

Bases: PowerFlowSolutionFixedPoint

Electric power flow solution object. This object is a wrapper for the default power flow solution method as defined by inheritance. Currently, PowerFlowSolutionFixedPoint is the default method for solving the electric grid power flow.

class mesmo.electric_grid_models.PowerFlowSolutionSet#

Bases: ObjectBase

class mesmo.electric_grid_models.LinearElectricGridModelBase#

Bases: ObjectBase

Abstract linear electric model object, consisting of the sensitivity matrices for voltage / voltage magnitude / squared branch power / active loss / reactive loss by changes in nodal wye power / nodal delta power.

Note

This abstract class only defines the expected variables of linear electric grid model objects, but does not implement any functionality.

Variables:
  • electric_grid_model (ElectricGridModel) – Electric grid model object.

  • power_flow_solution (PowerFlowSolutionBase) – Reference power flow solution object.

  • sensitivity_voltage_by_power_wye_active (sp.spmatrix) – Sensitivity matrix for complex voltage vector by active wye power vector.

  • sensitivity_voltage_by_power_wye_reactive (sp.spmatrix) – Sensitivity matrix for complex voltage vector by reactive wye power vector.

  • sensitivity_voltage_by_power_delta_active (sp.spmatrix) – Sensitivity matrix for complex voltage vector by active delta power vector.

  • sensitivity_voltage_by_power_delta_reactive (sp.spmatrix) – Sensitivity matrix for complex voltage vector by reactive delta power vector.

  • sensitivity_voltage_by_der_power_active (sp.spmatrix) – Sensitivity matrix for complex voltage vector by DER active power vector.

  • sensitivity_voltage_by_der_power_reactive (sp.spmatrix) – Sensitivity matrix for complex voltage vector by DER reactive power vector.

  • sensitivity_voltage_magnitude_by_power_wye_active (sp.spmatrix) – Sensitivity matrix for voltage magnitude vector by active wye power vector.

  • sensitivity_voltage_magnitude_by_power_wye_reactive (sp.spmatrix) – Sensitivity matrix for voltage magnitude vector by reactive wye power vector.

  • sensitivity_voltage_magnitude_by_power_delta_active (sp.spmatrix) – Sensitivity matrix for voltage magnitude vector by active delta power vector.

  • sensitivity_voltage_magnitude_by_power_delta_reactive (sp.spmatrix) – Sensitivity matrix for voltage magnitude vector by reactive delta power vector.

  • sensitivity_voltage_magnitude_by_der_power_active (sp.spmatrix) – Sensitivity matrix for voltage magnitude vector by DER active power vector.

  • sensitivity_voltage_magnitude_by_der_power_reactive (sp.spmatrix) – Sensitivity matrix for voltage magnitude vector by DER reactive power vector.

  • sensitivity_branch_power_1_by_power_wye_active (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 1 (‘from’ direction) by active wye power vector.

  • sensitivity_branch_power_1_by_power_wye_reactive (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 1 (‘from’ direction) by reactive wye power vector.

  • sensitivity_branch_power_1_by_power_delta_active (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 1 (‘from’ direction) by active delta power vector.

  • sensitivity_branch_power_1_by_power_delta_reactive (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 1 (‘from’ direction) by reactive delta power vector.

  • sensitivity_branch_power_1_by_der_power_active (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 1 by DER active power vector.

  • sensitivity_branch_power_1_by_der_power_reactive (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 1 by DER reactive power vector.

  • sensitivity_branch_power_2_by_power_wye_active (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 2 (‘to’ direction) by active wye power vector.

  • sensitivity_branch_power_2_by_power_wye_reactive (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 2 (‘to’ direction) by reactive wye power vector.

  • sensitivity_branch_power_2_by_power_delta_active (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 2 (‘to’ direction) by active delta power vector.

  • sensitivity_branch_power_2_by_power_delta_reactive (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 2 (‘to’ direction) by reactive delta power vector.

  • sensitivity_branch_power_2_by_der_power_active (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 2 by DER active power vector.

  • sensitivity_branch_power_2_by_der_power_reactive (sp.spmatrix) – Sensitivity matrix for complex branch flow power vector 2 by DER reactive power vector.

  • sensitivity_branch_power_1_magnitude_by_power_wye_active (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 1 (‘from’ direction) by active wye power vector.

  • sensitivity_branch_power_1_magnitude_by_power_wye_reactive (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 1 (‘from’ direction) by reactive wye power vector.

  • sensitivity_branch_power_1_magnitude_by_power_delta_active (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 1 (‘from’ direction) by active delta power vector.

  • sensitivity_branch_power_1_magnitude_by_power_delta_reactive (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 1 (‘from’ direction) by reactive delta power vector.

  • sensitivity_branch_power_1_magnitude_by_der_power_active (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 1 by DER active power vector.

  • sensitivity_branch_power_1_magnitude_by_der_power_reactive (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 1 by DER reactive power vector.

  • sensitivity_branch_power_2_magnitude_by_power_wye_active (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 2 (‘to’ direction) by active wye power vector.

  • sensitivity_branch_power_2_magnitude_by_power_wye_reactive (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 2 (‘to’ direction) by reactive wye power vector.

  • sensitivity_branch_power_2_magnitude_by_power_delta_active (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 2 (‘to’ direction) by active delta power vector.

  • sensitivity_branch_power_2_magnitude_by_power_delta_reactive (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 2 (‘to’ direction) by reactive delta power vector.

  • sensitivity_branch_power_2_magnitude_by_der_power_active (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 2 by DER active power vector.

  • sensitivity_branch_power_2_magnitude_by_der_power_reactive (sp.spmatrix) – Sensitivity matrix for branch flow power magnitude vector 2 by DER reactive power vector.

  • sensitivity_loss_active_by_power_wye_active (sp.spmatrix) – Sensitivity matrix for active loss by active wye power vector.

  • sensitivity_loss_active_by_power_wye_reactive (sp.spmatrix) – Sensitivity matrix for active loss by reactive wye power vector.

  • sensitivity_loss_active_by_power_delta_active (sp.spmatrix) – Sensitivity matrix for active loss by active delta power vector.

  • sensitivity_loss_active_by_power_delta_reactive (sp.spmatrix) – Sensitivity matrix for active loss by reactive delta power vector.

  • sensitivity_loss_active_by_der_power_active (sp.spmatrix) – Sensitivity matrix for active loss by DER active power vector.

  • sensitivity_loss_active_by_der_power_reactive (sp.spmatrix) – Sensitivity matrix for active loss by DER reactive power vector.

  • sensitivity_loss_reactive_by_power_wye_active (sp.spmatrix) – Sensitivity matrix for reactive loss by active wye power vector.

  • sensitivity_loss_reactive_by_power_wye_reactive (sp.spmatrix) – Sensitivity matrix for reactive loss by reactive wye power vector.

  • sensitivity_loss_reactive_by_power_delta_active (sp.spmatrix) – Sensitivity matrix for reactive loss by active delta power vector.

  • sensitivity_loss_reactive_by_power_delta_reactive (sp.spmatrix) – Sensitivity matrix for reactive loss by reactive delta power vector.

  • sensitivity_loss_reactive_by_der_power_active (sp.spmatrix) – Sensitivity matrix for reactive loss by DER active power vector.

  • sensitivity_loss_reactive_by_der_power_reactive (sp.spmatrix) – Sensitivity matrix for reactive loss by DER reactive power vector.

class mesmo.electric_grid_models.LinearElectricGridModelGlobal#

Bases: LinearElectricGridModelBase

Linear electric grid model object based on global approximations, consisting of the sensitivity matrices for voltage / voltage magnitude / squared branch power / active loss / reactive loss by changes in nodal wye power / nodal delta power.

Syntax:
  • LinearElectricGridModelGlobal(electric_grid_model, power_flow_solution): Instantiate linear electric grid model object for given electric_grid_model and power_flow_solution.

  • LinearElectricGridModelGlobal(scenario_name): Instantiate linear electric grid model for given scenario_name. The required electric_grid_model is obtained for given scenario_name and the power_flow_solution is obtained for nominal power conditions.

Parameters:
  • electric_grid_model (ElectricGridModel) – Electric grid model object.

  • power_flow_solution (PowerFlowSolutionBase) – Power flow solution object.

  • scenario_name (str) – MESMO scenario name.

Attributes / variables are the same as in LinearElectricGridModelBase.

class mesmo.electric_grid_models.LinearElectricGridModelLocal#

Bases: LinearElectricGridModelBase

Linear electric grid model object based on local approximations, consisting of the sensitivity matrices for voltage / voltage magnitude / squared branch power / active loss / reactive loss by changes in nodal wye power / nodal delta power.

Syntax:
  • LinearElectricGridModelLocal(electric_grid_model, power_flow_solution): Instantiate linear electric grid model object for given electric_grid_model and power_flow_solution.

  • LinearElectricGridModelLocal(scenario_name): Instantiate linear electric grid model for given scenario_name. The required electric_grid_model is obtained for given scenario_name and the power_flow_solution is obtained for nominal power conditions.

Parameters:
  • electric_grid_model (ElectricGridModel) – Electric grid model object.

  • power_flow_solution (PowerFlowSolutionBase) – Power flow solution object.

  • scenario_name (str) – MESMO scenario name.

Attributes / variables are the same as in LinearElectricGridModelBase.

class mesmo.electric_grid_models.LinearElectricGridModelSet#

Bases: ObjectBase

get_der_power_limit_timeseries(der, der_active_power_vector, der_reactive_power_vector, node_voltage_magnitude_vector_minimum=None, node_voltage_magnitude_vector_maximum=None, branch_power_magnitude_vector_maximum=None)#

Calculate power limits for given DER through maximum loadability calculation, subject to nodal voltage and/or branch power limits as well as the dispatch quantities of other DERs.

Methodology (work in progress):
  1. Linear electric grid model equation:
    • 𝒔^𝑏=𝒔^(𝑏,𝑟𝑒𝑓)+𝑴^(𝑠^𝑏,𝑠^𝑑 ) 𝒔^𝑑=𝒔^(𝑏,𝑟𝑒𝑓)+𝑴^(𝑠^𝑏,𝑠^(𝑑,1) ) 𝒔^(𝑑,1)+𝑴^(𝑠^𝑏,𝑠^(𝑑,2) ) 𝒔^(𝑑,2)

    • 𝒔^𝑏 - Branch power vector

    • 𝒔^𝑑 - DER power vector; 𝒔^(𝑑,1) - DER power vector of group 1; 𝒔^(𝑑,2) - DER power vector of group 2

    • 𝑴^(𝑠^𝑏,𝑠^𝑑 ),𝑴^(𝑠^𝑏,𝑠^(𝑑,1) ),𝑴^(𝑠^𝑏,𝑠^(𝑑,2) ) 𝒔^(𝑑,2)- Sensitivity matrices

    • ()^𝑟𝑒𝑓 - Reference value / approximation point

  2. Loadability constraint:
    • 𝒔^(𝑏,𝑟𝑒𝑓)+𝑴^(𝑠^𝑏,𝑠^(𝑑,1) ) 𝒔^(𝑑,1)+𝑴^(𝑠^𝑏,𝑠^(𝑑,2) ) 𝒔^(𝑑,2)≤𝒔^(𝑏,𝑚𝑎𝑥)

    • 𝒔^(𝑏,𝑚𝑎𝑥) - Branch power limit / loading limit

  3. Reformulation for DER maximum power value:
    • 𝑴^(𝑠^𝑏,𝑠^(𝑑,2) ) 𝒔^(𝑑,2)≤𝒔^(𝑏,𝑚𝑎𝑥)−𝒔^(𝑏,𝑟𝑒𝑓)+𝑴^(𝑠^𝑏,𝑠^(𝑑,1) ) 𝒔^(𝑑,1)

    • Assume: 𝒔^(𝑑,2)∈ℝ^(1×1); Then: 𝑴^(𝑠^𝑏,𝑠^(𝑑,2) )∈ℝ^(𝑏×1)

    • 𝒔^(𝑑,2,𝑙𝑎𝑥)=diag(𝑴^(𝑠^𝑏,𝑠^(𝑑,2) ) )^(−1) (𝒔^(𝑏,𝑚𝑎𝑥)−𝒔^(𝑏,𝑟𝑒𝑓)+𝑴^(𝑠^𝑏,𝑠^(𝑑,1) ) 𝒔^(𝑑,1) )

    • With: 𝒔^(𝑑,2,𝑙𝑎𝑥)∈ℝ^(𝑏×1)

    • max((𝒔^(𝑑,2,𝑙𝑎𝑥) )^− )=𝒔^(𝑑,2,𝑚𝑖𝑛)≤𝒔^(𝑑,2)≤𝒔^(𝑑,2,𝑚𝑎𝑥)=min((𝒔^(𝑑,2,𝑙𝑎𝑥) )^+ )

Parameters:
  • ders (tuple) – Index identifier of selected DER. Must be valid entry of electric_grid_model.ders.

  • der_active_power_vector (pd.DataFrame) – DER active power vector as dataframe with timesteps as index and DERs as columns. Must contain all other DERs aside from the selected.

  • der_reactive_power_vector (pd.DataFrame) – DER reactive power vector as dataframe with timesteps as index and DERs as columns. Must contain all other DERs aside from the selected.

  • der (tuple) –

  • node_voltage_magnitude_vector_minimum (numpy.ndarray | None) –

  • node_voltage_magnitude_vector_maximum (numpy.ndarray | None) –

  • branch_power_magnitude_vector_maximum (numpy.ndarray | None) –

Keyword Arguments:
  • node_voltage_magnitude_vector_minimum (np.ndarray) – Minimum nodal voltage limit vector.

  • node_voltage_magnitude_vector_maximum (np.ndarray) – Maximum nodal voltage limit vector.

  • branch_power_magnitude_vector_maximum (np.ndarray) – Maximum branch power limit vector.

Return type:

pandas.DataFrame

mesmo.thermal_grid_models#

Thermal grid models module.

class mesmo.thermal_grid_models.ThermalGridModel(scenario_name)#

Bases: ObjectBase

Thermal grid model object.

Parameters:

scenario_name (str) –

class mesmo.thermal_grid_models.ThermalGridDEROperationResults(**kwargs)#

Bases: ResultsBase

class mesmo.thermal_grid_models.ThermalGridOperationResults(**kwargs)#

Bases: ThermalGridDEROperationResults

class mesmo.thermal_grid_models.ThermalGridDLMPResults(**kwargs)#

Bases: ResultsBase

class mesmo.thermal_grid_models.ThermalPowerFlowSolutionBase#

Bases: ObjectBase

Thermal grid power flow solution object.

class mesmo.thermal_grid_models.ThermalPowerFlowSolutionExplicit#

Bases: ThermalPowerFlowSolutionBase

class mesmo.thermal_grid_models.ThermalPowerFlowSolutionNewtonRaphson#

Bases: ThermalPowerFlowSolutionBase

class mesmo.thermal_grid_models.ThermalPowerFlowSolution#

Bases: ThermalPowerFlowSolutionBase

Thermal grid power flow solution object.

class mesmo.thermal_grid_models.ThermalPowerFlowSolutionSet#

Bases: ObjectBase

class mesmo.thermal_grid_models.LinearThermalGridModel#

Bases: ObjectBase

Linear thermal grid model object.

mesmo.thermal_grid_models.LinearThermalGridModelGlobal#

alias of LinearThermalGridModel

class mesmo.thermal_grid_models.LinearThermalGridModelSet#

Bases: ObjectBase

mesmo.der_models#

Distributed energy resource (DER) models.

class mesmo.der_models.DERModel(der_data, der_name, is_standalone=False)#

Bases: ObjectBase

DER model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

  • is_standalone (bool) –

class mesmo.der_models.DERModelOperationResults(**kwargs)#

Bases: ResultsBase

class mesmo.der_models.FixedDERModel(der_data, der_name, is_standalone=False)#

Bases: DERModel

Fixed DER model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

  • is_standalone (bool) –

class mesmo.der_models.ConstantPowerModel(der_data, der_name, **kwargs)#

Bases: FixedDERModel

Constant power DER model object, representing der_type=”constant_power”.

  • The constant power model is a basic placeholder DER model that only requires minimum DER definition input.

  • The nominal active / reactive / thermal power of this DER is applied as constant value in its nominal power timeseries.

  • This is the fallback DER model for DERs that are defined with missing / empty der_type value.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.FixedLoadModel(der_data, der_name, **kwargs)#

Bases: FixedDERModel

Fixed load model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.FixedEVChargerModel(der_data, der_name, **kwargs)#

Bases: FixedDERModel

EV charger model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.FixedGeneratorModel(der_data, der_name, **kwargs)#

Bases: FixedDERModel

Fixed generator model object, representing a generic generator with fixed nominal output.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.FlexibleDERModel(der_data, der_name, is_standalone=False)#

Bases: DERModel

Flexible DER model, e.g., flexible load, object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

  • is_standalone (bool) –

class mesmo.der_models.FlexibleLoadModel(der_data, der_name, **kwargs)#

Bases: FlexibleDERModel

Flexible load model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.FlexibleEVChargerModel(der_data, der_name, **kwargs)#

Bases: FlexibleDERModel

Flexible EV charger model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.FlexibleGeneratorModel(der_data, der_name, **kwargs)#

Bases: FlexibleDERModel

Fixed generator model object, representing a generic generator with fixed nominal output.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.StorageModel(der_data, der_name, **kwargs)#

Bases: FlexibleDERModel

Energy storage model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.FlexibleBuildingModel(der_data, der_name, **kwargs)#

Bases: FlexibleDERModel

Flexible load model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.CoolingPlantModel(der_data, der_name, **kwargs)#

Bases: FlexibleDERModel

Cooling plant model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.HeatingPlantModel(der_data, der_name, **kwargs)#

Bases: FlexibleDERModel

Heating plant model object.

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.FlexibleCHP(der_data, der_name, **kwargs)#

Bases: FlexibleDERModel

Parameters:
  • der_data (DERData) –

  • der_name (str) –

class mesmo.der_models.DERModelSetOperationResults(**kwargs)#

Bases: ElectricGridDEROperationResults

class mesmo.der_models.DERModelSet#

Bases: DERModelSetBase

DER model set object.

mesmo.der_models.make_der_model(der_name, der_data, is_standalone=False)#

Factory method for DER models, makes appropriate DER model type for given der_name.

Parameters:
  • der_name (str) –

  • der_data (DERData) –

Return type:

DERModel

mesmo.data_interface#

Database interface.

mesmo.data_interface.recreate_database()#

Recreate SQLITE database from SQL schema file and CSV files in the data path / additional data paths.

mesmo.data_interface.connect_database()#

Connect to the database and return connection handle.

Return type:

Connection

class mesmo.data_interface.ScenarioData(scenario_name, database_connection=None)#

Bases: ObjectBase

Scenario data object.

Parameters:

scenario_name (str) –

parse_parameters_column(column)#

Parse parameters into one column of a dataframe.

  • Replace strings that match parameter_name with parameter_value.

  • Other strings are are directly parsed into numbers.

  • If a string doesn’t match any match parameter_name and cannot be parsed, it is replaced with NaN.

  • Expects column to be passed as np.ndarray rather than directly as pd.Series (for performance reasons).

Parameters:

column (numpy.ndarray) –

parse_parameters_dataframe(dataframe, excluded_columns=None)#

Parse parameters into a dataframe.

  • Applies parse_parameters_column for all string columns.

  • Columns in excluded_columns are not parsed. By default this includes _name, _type, connection columns.

Parameters:
  • dataframe (pandas.DataFrame) –

  • excluded_columns (list | None) –

class mesmo.data_interface.DERData#

Bases: ObjectBase

DER data object.

class mesmo.data_interface.ElectricGridData(scenario_name, database_connection=None)#

Bases: ObjectBase

Electric grid data object.

Parameters:

scenario_name (str) –

class mesmo.data_interface.ThermalGridData(scenario_name, database_connection=None)#

Bases: ObjectBase

Thermal grid data object.

Parameters:

scenario_name (str) –

class mesmo.data_interface.PriceData#

Bases: ObjectBase

Price data object.

copy()#

Return a copy of this object. A new object will be created with a copy of the calling object’s attributes. Modifications to the attributes of the copy will not be reflected in the original object.

mesmo.solutions#

Solution problems / methods / algorithms module

class mesmo.solutions.OptimizationProblem#

Bases: ObjectBase

Optimization problem object class, which allows the definition and solution of convex optimization problems. The optimization problem object serves as a container for the parameters, variables, constraints and objective terms. The object provides methods for defining variables, parameters, constraints and objectives as well as methods for solving the numerical optimization problem and obtaining results for variables, objective value and dual values.

  • This documentation assumes a fundamental understanding of convex optimization. As a general reference on this topic, refer to: S. P. Boyd and L. Vandenberghe, Convex optimization. Cambridge University Press, 2004. Available at: https://web.stanford.edu/~boyd/cvxbook/

  • The optimization problem object currently supports convex optimization problems in the form of 1) linear program (LP) or 2) quadratic program (QP) with only linear constraints.

  • The solve method currently implements interfaces to 1) Gurobi and 2) CVXPY, where the latter is a high-level convex optimization interface, which in turn allows interfacing further third-party solvers. The intention is to implement more direct solver interfaces on a as-need basis (please raise an issue!), as these interfaces are assumed to allow higher performance than CVXPY for large-scale problems. However, CVXPY is kept as a fallback to allow a high degree of compatibility with various solvers.

The optimization problem object internally translates optimizations into LP / QP standard form. Where the following formulation is assumed for the standard form:

\[\begin{split}\begin{align} \min_{\boldsymbol{x}} \quad & \boldsymbol{c}^{\intercal} \boldsymbol{x} + \frac{1}{2} \boldsymbol{x}^{\intercal} \boldsymbol{Q} \boldsymbol{x} + d \\ \text{s.t.} \quad & \boldsymbol{A} \boldsymbol{x} \leq \boldsymbol{b} \quad : \ \boldsymbol{\mu} \end{align}\end{split}\]

The vectors \(\boldsymbol{x}\) and \(\boldsymbol{\mu}\) are the variable vector and associated constraint dual variable vector. The matrix \(\boldsymbol{A}\) defines the linear constraint coefficients, whereas the matrix \(\boldsymbol{Q}\) defines quadradtic objective coefficients. The vectors \(\boldsymbol{b}\) and \(\boldsymbol{c}\) define constant constraint terms and linear objective coefficients. Lastly, the scalar \(d\) defines the constant objective term. Note that the scalar \(d\) represents a slight abuse of the standard form to include constant objective term, which may prove useful for comparing objective values across different problem definitions.

Example

Consider the following optimization problem:

\[\begin{split}\begin{align} \min_{\boldsymbol{a},\boldsymbol{b}} \quad & \sum_{i=1}^{n=1000} b_i \\ \text{s.t.} \quad & \boldsymbol{b} = \boldsymbol{a} \cdot \boldsymbol{P} \\ & -10 \leq \boldsymbol{a} \leq +10 \end{align}\end{split}\]

The matrix \(\boldsymbol{P} \in \mathbb{R}^{n \times n}\) is an abitrary parameter matrix. The vectors \(\boldsymbol{a}, \boldsymbol{b} \in \mathbb{R}^{n \times 1}\) are decision variable vectors. The symbol \(n\) defines the problem dimension. This problem can be defined and solved with the optimization problem interface as follows:

# Instantiate optimization problem.
optimization_problem = mesmo.solutions.OptimizationProblem()

# Define optimization parameters.
optimization_problem.define_parameter('parameter_matrix', parameter_matrix)

# Define optimization variables.
optimization_problem.define_variable('a_vector', a_index=range(dimension))
optimization_problem.define_variable('b_vector', b_index=range(dimension))

# Define optimization constraints.
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')),
)

# Define optimization objective.
optimization_problem.define_objective(('variable', 1.0, dict(name='b_vector')))

# Solve optimization problem.
optimization_problem.solve()

# Obtain results.
results = optimization_problem.get_results()
a_vector = results['a_vector']
b_vector = results['b_vector']

This example is also available as standalone script at: examples/run_general_optimization_problem.py

define_variable(name, variable_type='continuous', **keys)#

Define decision variable with given name and key set.

  • Variables are defined by passing a name string and index key sets. The variable dimension is determined by the dimension of the index key sets. Accepted key set values are 1) lists, 2) tuples, 3) numpy arrays, 4) pandas index objects and 5) range objects.

  • If multiple index key sets are passed, the variable dimension is determined as the cartesian product of the key sets. However, note that variables always take the shape of column vectors in constraint and objective definitions. That means, multiple key sets are not interpreted as array dimensions.

  • The variable type can be defined with the keyword argument variable_type as either ‘continuous’, ‘integer’ or ‘binary’. The variable type defaults to ‘continuous’.

Parameters:
  • name (str) –

  • variable_type (str) –

define_parameter(name, value)#

Define constant parameters with given name and numerical value.

  • Numerical values can be numerical value can be real-valued 1) float, 2) numpy array and 3) scipy sparse matrix.

  • Defining parameters is optional. – Numerical values can also be directly passed in the constraints / objective definitions. However, using parameters allows updating the numerical values of the problem without re-defining the complete problem.

Parameters:
  • name (str) –

  • value (float | numpy.ndarray | scipy.sparse.spmatrix) –

define_constraint(*elements, **kwargs)#

Define linear constraint for given list of constraint elements.

  • Constraints are defined as list of tuples and strings, where tuples are either 1) variable terms or 2) constant terms and strings represent operators (==, <= or >=). If multiple variable and constant terms are on either side of the operator, these are interpreted as summation of the variables / constants.

  • Constant terms are tuples in the form (‘constant’, numerical value), where the numerical value can be real-valued 1) float, 2) numpy array, 3) scipy sparse matrix or 4) a parameter name string. The numerical value is expected to represent a column vector with appropriate size matching the constraint dimension. If a float value is given as numerical value, the value is multiplied with a column vector of ones of appropriate size.

  • Variable terms are tuples in the form (‘variable’, numerical factor, dict(name=variable name, keys…)), where the numerical factor can be real-valued 1) float, 2) numpy array, 3) scipy sparse matrix or 4) a parameter name string. The numerical factor is multiplied with the variable vector and is expected to represent a matrix of appropriate size for the multiplication. If a float value is given as numerical factor, the value is multiplied with a identity matrix of appropriate size. Keys can be optionally given to select / slice a portion of the variable vector. Note that variables always take the shape of column vectors.

Parameters:

elements (str | Tuple[str, str | float | numpy.ndarray | scipy.sparse.spmatrix] | Tuple[str, str | float | numpy.ndarray | scipy.sparse.spmatrix, dict]) –

define_objective(*elements, **kwargs)#

Define objective terms for the given list of objective elements.

  • Objective terms are defined as list of tuples, where tuples are either 1) variable terms or 2) constant terms. Each term is expected to evaluate to a scalar value. If multiple variable and constant terms are defined, these are interpreted as summation of the variables / constants.

  • Constant terms are tuples in the form (‘constant’, numerical value), where the numerical value can be 1) float value or 2) a parameter name string.

  • Variable terms are tuples in the form (‘variable’, numerical factor, dict(name=variable name, keys…)), where the numerical factor can be 1) float value, 2) numpy array, 3) scipy sparse matrix or 4) a parameter name string. The numerical factor is multiplied with the variable vector and is expected to represent a matrix of appropriate size for the multiplication, such that the multiplication evaluates to a scalar. If a float value is given as numerical factor, the value is multiplied with a row vector of ones of appropriate size. Keys can be optionally given to select / slice a portion of the variable vector. Note that variables always take the shape of column vectors.

Parameters:

elements (str | Tuple[str, str | float | numpy.ndarray | scipy.sparse.spmatrix] | Tuple[str, str | float | numpy.ndarray | scipy.sparse.spmatrix, dict] | Tuple[str, str | float | numpy.ndarray | scipy.sparse.spmatrix, dict, dict]) –

get_variable_index(name, raise_empty_index_error=False, **keys)#

Utility method for obtaining a variable integer index vector for given variable name / keys.

Parameters:
  • name (str) –

  • raise_empty_index_error (bool) –

get_variable_keys(name, **keys)#

Utility method for obtaining a variable key dataframe for given variable name / keys.

  • This intended for debugging / inspection of the key value order, e.g. such that numerical factors can be constructed accordingly.

Parameters:

name (str) –

get_a_matrix()#

Obtain \(\boldsymbol{A}\) matrix for the standard-form problem (see OptimizationProblem).

Return type:

scipy.sparse.csr_matrix

get_b_vector()#

Obtain \(\boldsymbol{b}\) vector for the standard-form problem (see OptimizationProblem).

Return type:

numpy.ndarray

get_c_vector()#

Obtain \(\boldsymbol{c}\) vector for the standard-form problem (see OptimizationProblem).

Return type:

numpy.ndarray

get_q_matrix()#

Obtain \(\boldsymbol{Q}\) matrix for the standard-form problem (see OptimizationProblem).

Return type:

scipy.sparse.spmatrix

get_d_constant()#

Obtain \(d\) value for the standard-form problem (see OptimizationProblem).

Return type:

float

solve()#

Solve the optimization problem.

  • The solve method compiles the standard form of the optimization problem (see OptimizationProblem) and passes the standard-form problem to the optimization solver interface.

  • The solve method currently implements interfaces to 1) Gurobi and 2) CVXPY, where the latter is a high-level convex optimization interface, which in turn allows interfacing further third-party solvers. The intention is to implement more direct solver interfaces on a as-need basis (please raise an issue!), as these interfaces are assumed to allow higher performance than CVXPY for large-scale problems. However, CVXPY is kept as a fallback to allow a high degree of compatibility with various solvers.

  • The choice of solver and solver interface can be controlled through the config parameters optimization > solver_name and optimization > solver_interface (see mesmo/config_default.yml).

The default workflow of the solve method is as follows:

  1. Obtain problem definition through selected solver interface via get_cvxpy_problem() or get_gurobi_problem().

  2. Solve optimization problem and obtain standard-form results via solve_cvxpy() or solve_gurobi(). The standard-form results include the 1) \(\boldsymbol{x}\) variable vector value, 2) \(\boldsymbol{\mu}\) dual vector value and 3) objective value, which are stored into the object attributes x_vector, mu_vector and objective.

  3. Obtain results with respect to the original problem formulation via get_results() and get_duals(). These results are 1) decision variable values and 2) constraint dual values, which are stored into the object attributes results and duals.

Low-level customizations of the problem definition are possible, e.g. definition of quadratic constraints or second-order conic (SOC) constraints via the solver interfaces, with the following workflow.

  1. Obtain problem definition through selected solver interface via get_cvxpy_problem() or get_gurobi_problem().

  2. Customize problem definitions, e.g. add custom constraints directly with the Gurobi or CVXPY interfaces.

  3. Solve optimization problem and obtain standard-form results via solve_cvxpy() or solve_gurobi().

  4. Obtain results with respect to the original problem formulation via get_results() and get_duals().

get_gurobi_problem()#

Obtain standard-form problem via Gurobi direct interface.

Return type:

(gurobipy.Model, gurobipy.MVar, gurobipy.MConstr, gurobipy.MQuadExpr)

solve_gurobi(gurobipy_problem, x_vector, constraints, objective)#

Solve optimization problem via Gurobi direct interface.

Parameters:
  • gurobipy_problem (gurobipy.Model) –

  • x_vector (gurobipy.MVar) –

  • constraints (gurobipy.MConstr) –

  • objective (gurobipy.MQuadExpr) –

Return type:

gurobipy.Model

get_cvxpy_problem()#

Obtain standard-form problem via CVXPY interface.

Return type:

(cvxpy.Variable, List[Union[cvxpy.NonPos, cvxpy.Zero, cvxpy.SOC, cvxpy.PSD]], cvxpy.Expression)

solve_cvxpy(x_vector, constraints, objective)#

Solve optimization problem via CVXPY interface.

Parameters:
  • x_vector (cvxpy.Variable) –

  • constraints (List[cvxpy.NonPos | cvxpy.Zero | cvxpy.SOC | cvxpy.PSD]) –

  • objective (cvxpy.Expression) –

Return type:

cvxpy.Problem

solve_highs()#

Solve optimization problem via SciPy HiGHS interface.

Return type:

scipy.optimize.OptimizeResult

get_results(x_vector=None)#

Obtain results for decisions variables.

  • Results are returned as dictionary with keys corresponding to the variable names that have been defined.

Parameters:

x_vector (cvxpy.Variable | numpy.ndarray | None) –

Return type:

dict

get_duals()#

Obtain results for constraint dual variables.

  • Duals are returned as dictionary with keys corresponding to the constraint names that have been defined.

Return type:

dict

evaluate_objective(x_vector)#

Utility function for evaluating the objective value for a given \(x\) vector value.

Parameters:

x_vector (numpy.ndarray) –

Return type:

float

mesmo.utils#

Utility functions module.

class mesmo.utils.ObjectBase#

Bases: object

MESMO object base class, which extends the Python object base class.

  • Requires all attributes, i.e. parameters or object variables, to be defined with type declaration at the beginning of the class definition. Setting a value to an attribute which has not been defined will raise a warning. This is to ensure consistent definition structure of MESMO classes.

  • String representation of the object is the concatenation of the string representation of all its attributes. Thus, printing the object will print all its attributes.

Example

Attributes should be defined in the beginning of the class definition as follows:

class ExampleClass(ObjectBase):

    example_attribute1: str
    example_attribute2: pd.DataFrame

In this case, example_attribute1 and example_attribute2 are valid attributes of the class.

copy()#

Return a copy of this object. A new object will be created with a copy of the calling object’s attributes. Modifications to the attributes of the copy will not be reflected in the original object.

class mesmo.utils.ResultsBase(**kwargs)#

Bases: ObjectBase

Results object base class.

save(results_path)#

Store results to files at given results path.

  • Each results variable / attribute will be stored as separate file with the attribute name as file name.

  • Pandas Series / DataFrame are stored to CSV.

  • Other objects are stored to pickle binary file (PKL).

Parameters:

results_path (str) –

load(results_path)#

Load results from given path.

Parameters:

results_path (str) –

mesmo.utils.starmap(function, argument_sequence, keyword_arguments=None)#

Utility function to execute a function for a sequence of arguments, effectively replacing a for-loop. Allows running repeated function calls in-parallel, based on Python’s multiprocessing module.

  • If configuration parameter run_parallel is set to True, execution is passed to starmap of multiprocessing pool, hence running the function calls in parallel.

  • Otherwise, execution is passed to itertools.starmap, which is the non-parallel equivalent.

Parameters:
  • function (Callable) –

  • argument_sequence (Iterable[tuple]) –

  • keyword_arguments (dict | None) –

Return type:

list

mesmo.utils.chunk_dict(dict_in, chunk_count=4)#

Divide dictionary into equally sized chunks.

Parameters:
  • dict_in (dict) –

  • chunk_count (int) –

mesmo.utils.chunk_list(list_in, chunk_count=4)#

Divide list into equally sized chunks.

Parameters:
  • list_in (Iterable | Sized) –

  • chunk_count (int) –

mesmo.utils.ray_iterator(objects)#

Utility iterator for a list of parallelized ray objects.

  • This iterator enables progress reporting with tqdm in ray_get().

Parameters:

objects (list) –

mesmo.utils.ray_get(objects)#

Utility function for parallelized execution of a list of ray objects.

  • This function enables the parallelized execution with built-in progress reporting.

Parameters:

objects (list) –

mesmo.utils.ray_starmap(function_handle, argument_sequence)#

Utility function to provide an interface similar to itertools.starmap for ray.

  • This replicates the starmap interface of the multiprocessing API, which ray also supports, but allows for additional modifications, e.g. progress reporting via ray_get().

Parameters:
  • function_handle (Callable) –

  • argument_sequence (list) –

mesmo.utils.log_time(label, log_level='debug', logger_object=<Logger mesmo.utils (INFO)>)#

Log start / end message and time duration for given label.

  • When called with given label for the first time, will log start message.

  • When called subsequently with the same / previously used label, will log end message and time duration since logging the start message.

  • The log level for start / end messages can be given as keyword argument, By default, messages are logged as debug messages.

  • The logger object can be given as keyword argument. By default, uses utils.logger as logger.

  • Start message: “Starting label.”

  • End message: “Completed label in duration seconds.”

Parameters:
  • label (str) – Label for the start / end message.

  • log_level (str) –

  • logger_object (Logger) –

Keyword Arguments:
  • log_level (str) – Log level to which the start / end messages are output. Choices: ‘debug’, ‘info’. Default: ‘debug’.

  • logger_object (logging.logger.Logger) – Logger object to which the start / end messages are output. Default: utils.logger.

mesmo.utils.get_index(index_set, raise_empty_index_error=True, **levels_values)#

Utility function for obtaining the integer index array for given index set / level / value list combination.

Syntax:
  • get_index(electric_grid_model.nodes, node_type='source', phase=1): Get index array for entries in index set electric_grid_model.nodes with given node_type and phase.

Parameters:
  • index_set (pd.Index) – Index set, e.g., electric_grid_model.nodes.

  • raise_empty_index_error (bool) –

Keyword Arguments:
  • raise_empty_index_error (bool) – If true, raise an exception if obtained index array is empty. This is the default behavior, because it is usually caused by an invalid level / value combination.

  • level (value) – All other keyword arguments are interpreted as level / value combinations, where level must correspond to a level name of the index set.

mesmo.utils.get_element_phases_array(element)#

Utility function for obtaining the list of connected phases for given element data.

Parameters:

element (pandas.Series) –

mesmo.utils.get_element_phases_string(element)#

Utility function for obtaining the OpenDSS phases string for given element data.

Parameters:

element (pandas.Series) –

mesmo.utils.get_inverse_with_zeros(array)#

Obtain the inverse of an array, but do not take the inverse of zero values to avoid numerical errors.

  • Takes the inverse of an array and replaces the inverse of any zero values with zero, thus avoiding inf or nan values in the inverse.

Parameters:

array (numpy.ndarray) –

Return type:

numpy.ndarray

mesmo.utils.get_timestamp(time=None)#

Generate formatted timestamp string, e.g., for saving results with timestamp.

Parameters:

time (datetime | None) –

Return type:

str

mesmo.utils.get_results_path(base_name, scenario_name=None)#

Generate results path, which is a new subfolder in the results directory. The subfolder name is assembled of the given base name, scenario name and current timestamp. The new subfolder is created on disk along with this.

  • Non-alphanumeric characters are removed from base_name and scenario_name.

  • If is a script file path or __file__ is passed as base_name, the base file name without extension will be taken as base name.

Parameters:
  • base_name (str) –

  • scenario_name (str | None) –

Return type:

str

mesmo.utils.get_alphanumeric_string(string)#

Create lowercase alphanumeric string from given string, replacing non-alphanumeric characters with underscore.

Parameters:

string (str) –

mesmo.utils.get_plotly_mapbox_zoom_center(longitudes, latitudes, width_to_height=2.0)#

Get optimal zoom and centering for a plotly mapbox plot, given lists of longitude and latitude values.

Parameters:
  • longitudes (tuple) – Longitude component of each location.

  • latitudes (tuple) – Latitude component of each location.

  • width_to_height (float) –

Keyword Arguments:

width_to_height (float) – Expected ratio of final graph’s with to height, used to select the constrained axis.

Returns:

Zoom value from 1 to 20. dict: Center position with ‘lon’ and ‘lat’ keys.

Return type:

float

mesmo.utils.launch(path)#

Launch the file at given path with its associated application. If path is a directory, open in file explorer.

mesmo.utils.write_figure_plotly(figure, results_path, file_format='png', width=1000, height=500)#

Utility function for writing / storing plotly figure to output file. File format can be given with file_format keyword argument, otherwise the default is obtained from config parameter plots/file_format.

  • results_path should be given as file name without file extension, because the file extension is appended automatically based on given file_format.

  • Valid file formats: ‘png’, ‘jpg’, ‘jpeg’, ‘webp’, ‘svg’, ‘pdf’, ‘html’, ‘json’

Parameters:
  • figure (plotly.graph_objects.Figure) –

  • results_path (str) –

mesmo.utils.OptimizationProblem()#

mesmo.utils.OptimizationProblem is a placeholder for mesmo.solutions.OptimizationProblem for backwards compatibility and will be removed in a future version of MESMO.

Return type:

OptimizationProblem

mesmo.config#

Configuration module.

mesmo.config.get_config()#

Load the configuration dictionary.

  • Default configuration is obtained from ./mesmo/config_default.yml.

  • Custom configuration is obtained from ./config.yml and overwrites the respective default configuration.

  • ./ denotes the repository base directory.

Return type:

dict

mesmo.config.get_logger(name)#

Generate logger with given name.

Parameters:

name (str) –

Return type:

Logger

mesmo.config.get_parallel_pool()#

Create multiprocessing / parallel computing pool.

  • Number of parallel processes / workers defaults to number of CPU threads as returned by os.cpu_count().

Return type:

Pool