esa API Documentation

ESA is a single module package - the only Python file is saw.py. To make it easy to remember, “SAW” is an acronym for “SimAuto Wrapper.” Within the saw module is the SAW class, which is the workhorse of ESA.

esa Package

The following are importable from the top-level esa package:

  • SAW: ESA’s primary class

  • Error: Base Error class for ESA exceptions. This exception is never directly raised.

  • PowerWorldError: Error class for when PowerWorld/SimAuto reports an error.

  • COMError: Error class for when something goes wrong communicating with Windows and/or SimAuto.

  • CommandNotRespectedError: Error class for when a commanded change is not respected by PowerWorld/SimAuto. This exception is only raised via SAW helper methods like change_and_confirm_params_multiple_element

  • __version__: ESA’s version.

esa.saw Module

saw is short for SimAuto Wrapper. This module provides a class, SAW, for interfacing with PowerWorld’s Simulator Automation Server (SimAuto). In addition to the SAW class, there are a few custom error classes, such as PowerWorldError.

PowrWorld’s documentation for SimAuto can be found here

class esa.saw.SAW(FileName, early_bind=False, UIVisible=False, object_field_lookup=('bus', 'gen', 'load', 'shunt', 'branch'), CreateIfNotFound: bool = False, UseDefinedNamesInVariables: bool = False, pw_order=False)[source]

Bases: object

A SimAuto Wrapper in Python

Initialize SimAuto wrapper. The case will be opened, and object fields given in object_field_lookup will be retrieved.

Parameters:
  • FileName – Full file path to .pwb file to open. This will be passed to the SimAuto function OpenCase.

  • early_bind – Whether (True) or not (False) to connect to SimAuto via early binding.

  • UIVisible – Whether or not to display the PowerWorld UI.

  • CreateIfNotFound – Set CreateIfNotFound = True if objects that are updated through the ChangeParameters functions should be created if they do not already exist in the case. Objects that already exist will be updated. Set CreateIfNotFound = False to not create new objects and only update existing ones.

  • object_field_lookup – Listing of PowerWorld objects to initially look up available fields for. Objects not specified for lookup here will be looked up later as necessary.

  • UseDefinedNamesInVariables – Set UseDefinedNamesInVariables to True if you want to have custom field with custom header. Default is False.

  • pw_order – Set pw_order = True if you want to have exact same order as shown in PW Simulator. Default is False, which generally sorts the data in a bus ascending order.

Note that Microsoft recommends early binding in most cases.

POWER_FLOW_FIELDS = {'branch': ['BusNum', 'BusNum:1', 'LineCircuit', 'LineMW', 'LineMW:1', 'LineMVR', 'LineMVR:1'], 'bus': ['BusNum', 'BusName', 'BusPUVolt', 'BusAngle', 'BusNetMW', 'BusNetMVR'], 'gen': ['BusNum', 'GenID', 'GenMW', 'GenMVR'], 'load': ['BusNum', 'LoadID', 'LoadMW', 'LoadMVR'], 'shunt': ['BusNum', 'ShuntID', 'ShuntMW', 'ShuntMVR']}
FIELD_LIST_COLUMNS = ['key_field', 'internal_field_name', 'field_data_type', 'description', 'display_name']
FIELD_LIST_COLUMNS_OLD = ['key_field', 'internal_field_name', 'field_data_type', 'description']
FIELD_LIST_COLUMNS_NEW = ['key_field', 'internal_field_name', 'field_data_type', 'description', 'display_name', 'enterable']
SPECIFIC_FIELD_LIST_COLUMNS = ['variablename:location', 'field', 'column header', 'field description']
SPECIFIC_FIELD_LIST_COLUMNS_NEW = ['variablename:location', 'field', 'column header', 'field description', 'enterable']
SIMAUTO_PROPERTIES = {'CreateIfNotFound': <class 'bool'>, 'CurrentDir': <class 'str'>, 'UIVisible': <class 'bool'>}
exec_aux(aux: str, use_double_quotes: bool = False)[source]

Helper function to execute auxiliary script directly. Skip the hassle to save the aux script to a file and then execute it.

Parameters:
  • aux – Auxiliary script (including data section) to execute.

  • use_double_quotes – Whether to use double quotes or single quotes. Default is False. Change to True will replace all the single quotes with double quotes.

change_and_confirm_params_multiple_element(ObjectType: str, command_df: DataFrame) None[source]

Change parameters for multiple objects of the same type, and confirm that the change was respected by PowerWorld.

Parameters:
  • ObjectType – The type of objects you are changing parameters for.

  • command_df – Pandas DataFrame representing the objects which will have their parameters changed. The columns should be object field variable names, and MUST include the key fields for the given ObjectType (which you can get via the get_key_fields_for_object_type method). Columns which are not key fields indicate parameters to be changed, while the key fields are used internally by PowerWorld to look up objects. Each row of the DataFrame represents a single element.

Raises:

CommandNotRespectedError – if PowerWorld does not actually change the parameters.

Raises:

PowerWorldError: if PowerWorld reports an error.

Returns:

None

change_parameters_multiple_element_df(ObjectType: str, command_df: DataFrame) None[source]

Helper to call ChangeParametersMultipleElement, but uses a DataFrame to determine parameters and values. This method is lighter weight but perhaps “riskier” than the “change_and_confirm_params_multiple_element” method, as no effort is made to ensure PowerWorld respected the given command.

Parameters:
  • ObjectType – The type of objects you are changing parameters for.

  • command_df – Pandas DataFrame representing the objects which will have their parameters changed. The columns should be object field variable names, and MUST include the key fields for the given ObjectType (which you can get via the get_key_fields_for_object_type method). Columns which are not key fields indicate parameters to be changed, while the key fields are used internally by PowerWorld to look up objects. Each row of the DataFrame represents a single element.

clean_df_or_series(obj: DataFrame | Series, ObjectType: str) DataFrame | Series[source]

Helper to cast data to the correct types, clean up strings, and sort DataFrame by BusNum (if applicable/present).

Parameters:
  • obj – DataFrame or Series to clean up. It’s assumed that the object came more or less directly from placing results from calling SimAuto into a DataFrame or Series. This means all data will be strings (even if they should be numeric) and data which should be strings often have unnecessary white space. If obj is a DataFrame (Series), the columns (index) must be existing fields for the given object type (i.e. are present in the ‘internal_field_name’ column of the corresponding DataFrame which comes from calling GetFieldList for the given object type).

  • ObjectType – Object type the data in the DataFrame relates to. E.g. ‘gen’

Raises:
  • ValueError – if the DataFrame (Series) columns (index) are not valid fields for the given object type.

  • TypeError – if the input ‘obj’ is not a DataFrame or Series.

exit()[source]

Clean up for the PowerWorld COM object

get_key_fields_for_object_type(ObjectType: str) DataFrame[source]

Helper function to get all key fields for an object type.

Parameters:

ObjectType – The type of the object to get key fields for.

Returns:

DataFrame with the following columns: ‘internal_field_name’, ‘field_data_type’, ‘description’, and ‘display_name’. The DataFrame will be indexed based on the key field returned by the Simulator, but modified to be 0-based.

This method uses the GetFieldList function, documented here.

It’s also worth looking at the key fields documentation here.

get_key_field_list(ObjectType: str) List[str][source]

Convenience function to get a list of key fields for a given object type.

Parameters:

ObjectType – PowerWorld object type for which you would like a list of key fields. E.g. ‘gen’.

Returns:

List of key fields for the given object type. E.g. [‘BusNum’, ‘GenID’]

get_power_flow_results(ObjectType: str, additional_fields: None | List[str] = None) None | DataFrame[source]

Get the power flow results from SimAuto server.

Parameters:
  • ObjectType – Object type to get results for. Valid types are the keys in the POWER_FLOW_FIELDS class attribute (case insensitive).

  • additional_fields – Pass a list of field names to extend the default attributes in the POWER_FLOW_FIELDS.

Returns:

Pandas DataFrame with the corresponding results, or None if the given ObjectType is not present in the model.

Raises:

ValueError – if given ObjectType is invalid.

get_version_and_builddate() tuple[source]
identify_numeric_fields(ObjectType: str, fields: List | ndarray) ndarray[source]

Helper which looks up PowerWorld internal field names to determine if they’re numeric (True) or not (False).

Parameters:
  • ObjectType – Type of object for which we’re identifying numeric fields. E.g. “Branch” or “gen”

  • fields – List of PowerWorld internal fields names for which we’re identifying if they are or aren’t numeric. E.g. [‘BusNum’, ‘BusNum:1’, ‘LineCircuit’, ‘LineStatus’]

Returns:

Numpy boolean array indicating which of the given fields are numeric. Going along with the example given for “fields”: np.array([True, True, False, False])

set_simauto_property(property_name: str, property_value: str | bool)[source]

Set a SimAuto property, e.g. CreateIfNotFound. The currently supported properties are listed in the SAW.SIMAUTO_PROPERTIES class constant.

PowerWorld Documentation

Parameters:
  • property_name – Name of the property to set, e.g. UIVisible.

  • property_value – Value to set the property to, e.g. False.

get_ybus(full: bool = False, file: str | None = None) ndarray | csr_matrix[source]

Helper to obtain the YBus matrix from PowerWorld (in Matlab sparse matrix format) and then convert to scipy csr_matrix by default. :param full: Convert the csr_matrix to the numpy array (full matrix). :param file: Path to the external Ybus file.

get_branch_admittance()[source]

Helper function to get the branch admittance matrix, usually known as Yf and Yt. :returns: A Yf sparse matrix and a Yt sparse matrix

get_shunt_admittance()[source]

Get shunt admittance Ysh. :return: A Ysh sparse matrix

get_jacobian(full=False)[source]

Helper function to get the Jacobian matrix, by default return a scipy sparse matrix in the csr format :param full: Convert the csr_matrix to the numpy array (full matrix).

to_graph(node: str = 'bus', geographic: bool = False, directed: bool = False, node_attr=None, edge_attr=None) MultiGraph | MultiDiGraph[source]

Generate the graph network model (NetworkX) from the topology. Currently supports the bus-level topology and the inter-substation level topology. Parallel lines (if exist) are preserved in the model.

Parameters:
  • edge_attr – A valid field name(str) or iterable of field names that are used to retrieve values and add them to the graph as edge attributes. All fields belonging to object branch are available.

  • node_attr – A valid field name(str) or iterable of field names that are used to retrieve values and add them to the graph as node attributes. All fields belonging to the node type are available.

  • directed – Whether to convert to a directed graph (based on the direction of real power flow).

  • geographic – Include latitude and longitude in the node’s attributes. If geographic information is unavailable in the case, the latitude and the longitude will be NaN.

  • node – Elements to be represented by nodes. Only ‘bus’ or ‘substation’ is supported.

Returns:

A network graph

DeterminePathDistance(start: str, BranchDistMeas: str = 'X', BranchFilter: str = 'ALL', BusField='CustomFloat:1') DataFrame[source]

Powerworld’s built-in function to calculate a distance measure at each bus in the entire model. The distance measure will represent how far each bus is from the starting group specified. The distance measure can be related to impedance, geographical distance, or simply the number of nodes.

Parameters:
  • start – The starting location. String only. Follow the powerworld auxilliary file document.

  • BranchDistMeas – is either X, Z, Length, Nodes, or a field variable name for a branch.

  • BranchFilter – is either ALL, Selected, Closed, or the name of a branch Advanced Filter.

  • BusField – Optional. Only need to change if the CustomFloat:1 column has been used.

Returns:

A dataframe with bus number and distance measurements.

DetermineBranchesThatCreateIslands(Filter: str = 'ALL', StoreBuses: str = 'YES', SetSelectedOnLines: str = 'NO') DataFrame[source]

Powerworld’s built-in function to determine the branches whose outage results in island formation. Note that setting the Selected field will overwrite the Selected fields.

Parameters:
  • Filter – This parameter is used to specify which branches are checked

  • StoreBuses – YES to store the buses in the island

  • SetSelectedOnLines – Yes to set the SELECTED field to YES for branches that create islands

Returns:

A dataframe that contains the branch and the island information

DetermineShortestPath(start: str, end: str, BranchDistanceMeasure: str = 'X', BranchFilter: str = 'ALL') DataFrame[source]

Powerworld’s built-in function to calculate the shortest path between a starting group and an ending group. The first bus listed in the dataframe will be in the end grouping and the last bus listed will be the start grouping. The dataframe will have a line for each bus passed.

Parameters:
  • start – same as the starting place for the DeterminePathDistance function

  • end – same as the starting place for the DeterminePathDistance function

  • BranchDistanceMeasure – same as for the DeterminePathDistance function

  • BranchFilter – same as for the DeterminePathDistance function

Returns:

A dataframe with number, distance, and name

get_lodf_matrix(precision: int = 3, ignore_open_branch: bool = True, method: str = 'DC', post: bool = True, raw: bool = False)[source]
Obtain LODF matrix in numpy array or scipy sparse matrix.

By default, it obtains the lodf matrix directly from PW. If size is larger than 1000, then precision will be applied to filter out small values and the result will be returned in scipy sparse matrix.

<<<<<<< HEAD

The line (lines) in “OPEN” status are removed from the returned results, which is aligned with PW GUI. Make sure the line in

>>>>>>> upstream/develop

interest is in “CLOSED” status, or calculate LCDF value instead.

param precision:

number of decimal to keep.

param ignore_open_branch:

Ignore branches are open or not. Set to True to monitor only those branches that are closed. Set to False to monitor branches regardless of their status. Default is True.

param method:

The linear method to be used for the LODF calculation. Default is DC. Change to DCPS would take phase shifter into account. Note: AC is NOT an option for the LODF calculation.

param post:

Set to True to calculate any line closure sensitivies relative to post-closure flow on the line being closed. This is known as the LCDF value. Set to False to calculate any line closure sensitivities based on calculating the flow on the line being closed from pre-closure voltages and angles. This is known as the MLCDF value.

param raw:

Set to True if you want to get the raw LODF matrix (dataframe), which suppose to be exactly the same as the table shown in the PW GUI. Default is False.

returns:

The LODF matrix and a boolean vector to indicate which lines would cause islanding.

get_incidence_matrix()[source]

Obtain the incidence matrix.

Returns:

Incidence matrix

get_shift_factor_matrix(method: str = 'DC')[source]

Calculate the injection shift factor matrix using the auxiliary script CalculateShiftFactorsMultipleElement.

Parameters:

method – The linear method to be used for the calculation. The options are AC, DC or DCPS.

Returns:

A dense float matrix in the numpy array format.

get_shift_factor_matrix_fast()[source]

Calculate the injection shift factor matrix directly using the incidence matrix and the susceptance matrix. This method should be much faster than the PW script command for large cases.

Returns:

A dense float matrix in the numpy array format.

get_ptdf_matrix_fast()[source]

Calculate the power transfer distribution factor natively. This method should be much faster than the PW script command for large cases.

Returns:

A dense float matrix in the numpy array format.

get_lodf_matrix_fast()[source]

Calculate the line outage distribution factor natively. This method should be much faster than the PW script command for large cases.

Returns:

A dense float matrix in the numpy array format.

fast_n1_test()[source]

A pure LODF-based fast N-1 contingency analysis implementation.

Returns:

A boolean value to indicate whether the system is N-1 secure.

fast_n2_islanding_detection()[source]

Quickly identify the N-2 islanding CTGs using LODF

returns: A tuple with the number of islanding CTGs and the islanding matrix

change_to_temperature(T: int | float | ndarray, R25=7.283, R75=8.688)[source]

Change line resistance according to temperature. The default coefficients are from IEEE Std 738-2012. Note: The original case has to be set for 25 degree Celsius.

Parameters:
  • T – Target temperature. If it is a single int or float, then a uniform temperature will be assigned to all the lines; If it is a numpy array, then you need to pass a 2D array with first row being the index of branch and second row being the temperature.

  • R25 – Per unit resistance at 25 Celsius

  • R75 – Per unit resistance at 75 Celsius

run_contingency_analysis(option: str = 'N-1', validate: bool = False)[source]

ESA implementation of fast N-1 and N-2 contingency analysis. The case is expected to have a valid power flow state. Run SolvePowerFlow first if you are not sure.

Parameters:
  • option – Choose between N-1 and N-2 mode

  • validate – Use PW internal CA to validate the result. Default is False.

Returns:

A tuple of system security status (bool) and a matrix showing the result of contingency analysis (if exist)

run_robustness_analysis()[source]

Compute the metric RCF to quantify the robustness of power grids against cascading failures. The RCF metric takes the operational states, the branch’s capacities and the topological structure into account and gives an entropy-based value. The formula is given from the following paper: Koç, Yakup, Martijn Warnier, Robert E. Kooij, and Frances MT Brazier. “An entropy-based metric to quantify the robustness of power grids against cascading failures.” Safety science 59 (2013): 126-134.

Returns:

The RCF value.

run_ecological_analysis(target: str = 'MW', split_generator: bool = True)[source]

This method is leveraging applied ecological network analysis to quantify the varity of robustness of the power system.

Reference: [1] H. Huang, Z. Mao, A. Layton and K. R. Davis, “An Ecological Robustness Oriented Optimal Power Flow for Power Systems’ Survivability,” in IEEE Transactions on Power Systems, doi: 10.1109/TPWRS.2022.3168226. [2] Panyam, V., Huang, H., Davis, K., & Layton, A. (2019). An ecosystem perspective for the design of sustainable power systems. Procedia Cirp, 80, 269-274.

Parameters:
  • target – the real, reactive, and apparent power over the system. The default value is MW, which is the real power. Users can change to MVR, which is the reactive power; or MVA, which is the apparent power.

  • split_generator – Choose to split or aggregate multiple generators associated with the same bus. If true, the method will consider the generators’ robustness for each generator.

Results:

it is a list of ecological metrics, including the Ecological Robustness (Reco), the Ascendancy (ASC), the Development Capacity (DC), the Cycled Throughflow (tstc), the Finn Cycling Index (CI) and the Total System Overhead (TSO)

n1_fast(c1_isl, count, lodf, f, lim)[source]

A modified fast N-1 method.

Parameters:
  • c1_isl – Array of islanding lines

  • count – Number of lines

  • lodf – LODF matrix

  • f – Flow on the lines

  • lim – Array of line limits

Returns:

A tuple of N-1 status (bool) and the N-1 result (if exist)

n1_protect(margins, lines, lim)[source]

Adjust line limits to eliminate N-1 contingencies.

Parameters:
  • margins – Array of line loading margins.

  • lines – Array of number of line overloading contingencies.

  • lim – Array of line limits.

Return lim:

Array of line limits after adjustment.

n2_fast(c1_isl, count, lodf, f, lim)[source]

A modified fast N-2 method.

Parameters:
  • c1_isl – Array of islanding lines

  • count – Number of lines

  • lodf – LODF matrix

  • f – Flow on the lines

  • lim – Array of line limits

Returns:

A tuple of N-2 status (bool) and the N-2 result (if exist)

n2_bruteforce(count, A0, lodf, lim, f)[source]

Bruteforce for fast N-2 method

Parameters:
  • count – number of branches

  • A0 – filtered contingencies

  • lodf – LODF matrix

  • lim – branch limits

  • f – branch flow

Returns:

Security status and detailed results

ctg_autoinsert(object_type: str, options: None | dict = None)[source]

Auto insert contingencies.

Parameters:
  • object_type – Object type, e.g. branch.

  • options – Optional. Pass a custom dictionary if you need to modify the Ctg_AutoInsert_Options.

Returns:

List of contingencies.

ctg_solveall()[source]

Solve all of the contingencies that are not marked to be skipped.

Returns:

List of results.

update_ui() None[source]

Re-render the PowerWorld user interface (UI).

Returns:

None

ChangeParameters(ObjectType: str, ParamList: list, Values: list) None[source]

The ChangeParameters function has been replaced by the ChangeParametersSingleElement function. ChangeParameters can still be called as before, but will now just automatically call ChangeParametersSingleElement, and pass on the parameters to that function. Unlike the script SetData and CreateData commands, SimAuto does not have any explicit functions to create elements. Instead this can be done using the ChangeParameters functions by making use of the CreateIfNotFound SimAuto property. Set CreateIfNotFound = True if objects that are updated through the ChangeParameters functions should be created if they do not already exist in the case. Objects that already exist will be updated. Set CreateIfNotFound = False to not create new objects and only update existing ones. The CreateIfNotFound property is global, once it is set to True this applies to all future ChangeParameters calls.

PowerWorld documentation

Parameters:
  • ObjectType – The type of object you are changing parameters for.

  • ParamList – List of object field variable names. Note this MUST include the key fields for the given ObjectType (which you can get via the get_key_fields_for_object_type method).

  • Values – List of values corresponding to the parameters in the ParamList.

ChangeParametersSingleElement(ObjectType: str, ParamList: list, Values: list) None[source]

Set a list of parameters for a single object.

PowerWorld Documentation

Parameters:
  • ObjectType – The type of object you are changing parameters for.

  • ParamList – List of object field variable names. Note this MUST include the key fields for the given ObjectType (which you can get via the get_key_fields_for_object_type method).

  • Values – List of values corresponding to the parameters in the ParamList.

ChangeParametersMultipleElement(ObjectType: str, ParamList: list, ValueList: list) None[source]

Set parameters for multiple objects of the same type.

PowerWorld Documentation

Parameters:
  • ObjectType – The type of object you are changing parameters for.

  • ParamList – Listing of object field variable names. Note this MUST include the key fields for the given ObjectType (which you can get via the get_key_fields_for_object_type method).

  • ValueList – List of lists corresponding to the ParamList. Should have length n, where n is the number of elements you with to change parameters for. Each sub-list should have the same length as ParamList, and the items in the sub-list should correspond 1:1 with ParamList.

Returns:

Result from calling SimAuto, which should always simply be None.

Raises:

PowerWorldError – if PowerWorld reports an error.

ChangeParametersMultipleElementFlatInput(ObjectType: str, ParamList: list, NoOfObjects: int, ValueList: list) None[source]

The ChangeParametersMultipleElementFlatInput function allows you to set parameters for multiple objects of the same type in a case loaded into the Simulator Automation Server. This function is very similar to the ChangeParametersMultipleElement, but uses a single dimensioned array of values as input instead of a multi-dimensioned array of arrays.

It is recommended that you use helper functions like change_parameters_multiple_element_df instead of this one, as it’s simply easier to use.

PowerWorld documentation

Parameters:
  • ObjectType – The type of object you are changing parameters for.

  • ParamList – Listing of object field variable names. Note this MUST include the key fields for the given ObjectType (which you can get via the get_key_fields_for_object_type method).

  • NoOfObjects – An integer number of devices that are passing values for. SimAuto will automatically check that the number of parameters for each device (counted from ParamList) and the number of objects integer correspond to the number of values in value list (counted from ValueList.)

  • ValueList – List of lists corresponding to the ParamList. Should have length n, where n is the number of elements you with to change parameters for. Each sub-list should have the same length as ParamList, and the items in the sub-list should correspond 1:1 with ParamList.

Returns:

Result from calling SimAuto, which should always simply be None.

CloseCase()[source]

Closes case without saving changes.

PowerWorld documentation

GetCaseHeader(filename: str | None = None) Tuple[str][source]

The GetCaseHeader function is used to extract the case header information from the file specified. A tuple of strings containing the contents of the case header or description is returned.

PowerWorld documentation

Parameters:

filename – The name of the file you wish to extract the header information from.

Returns:

A tuple of strings containing the contents of the case header or description.

GetFieldList(ObjectType: str, copy=False) DataFrame[source]

Get all fields associated with a given ObjectType.

Parameters:
  • ObjectType – The type of object for which the fields are requested.

  • copy – Whether or not to return a copy of the DataFrame. You may want a copy if you plan to make any modifications.

Returns:

Pandas DataFrame with columns from either SAW.FIELD_LIST_COLUMNS or SAW.FIELD_LIST_COLUMNS_OLD, depending on the version of PowerWorld Simulator being used.

PowerWorld Documentation

GetParametersSingleElement(ObjectType: str, ParamList: list, Values: list) Series[source]

Request values of specified fields for a particular object.

PowerWorld Documentation

Parameters:
  • ObjectType – The type of object you’re retrieving parameters for.

  • ParamList – List of strings indicating parameters to retrieve. Note the key fields MUST be present. One can obtain key fields for an object type via the get_key_fields_for_object_type method.

  • Values – List of values corresponding 1:1 to parameters in the ParamList. Values must be included for the key fields, and the remaining values should be set to 0.

Returns:

Pandas Series indexed by the given ParamList. This Series will be cleaned by clean_df_or_series, so data will be of the appropriate type and strings are cleaned up.

Raises:
  • PowerWorldError – if the object cannot be found.

  • ValueError – if any given element in ParamList is not valid for the given ObjectType.

  • AssertionError – if the given ParamList and Values do not have the same length.

GetParametersMultipleElement(ObjectType: str, ParamList: list, FilterName: str = '') DataFrame | None[source]

Request values of specified fields for a set of objects in the load flow case.

PowerWorld Documentation

Parameters:
  • ObjectType – Type of object to get parameters for.

  • ParamList – List of variables to obtain for the given object type. E.g. [‘BusNum’, ‘GenID’, ‘GenMW’]. One can use the method GetFieldList to get a listing of all available fields. Additionally, you’ll likely want to always return the key fields associated with the objects. These key fields can be obtained via the get_key_fields_for_object_type method.

  • FilterName – Name of an advanced filter defined in the load flow case.

Returns:

Pandas DataFrame with columns matching the given ParamList. If the provided ObjectType is not present in the case, None will be returned.

Raises:
  • PowerWorldError – if PowerWorld reports an error.

  • ValueError – if any parameters given in the ParamList are not valid for the given object type.

TODO: Should we cast None to NaN to be consistent with how

Pandas/Numpy handle bad/missing data?

GetParametersMultipleElementFlatOutput(ObjectType: str, ParamList: list, FilterName: str = '') None | Tuple[str][source]

This function operates the same as the GetParametersMultipleElement function, only with one notable difference. The values returned as the output of the function are returned in a single-dimensional vector array, instead of the multi-dimensional array as described in the GetParametersMultipleElement topic.

It is recommended that you use GetParametersMultipleElement instead, as you’ll receive a DataFrame with correct data types. As this method is extraneous, the output from PowerWorld will be directly returned. This will show you just how useful ESA really is!

Parameters:
  • ObjectType – Type of object to get parameters for.

  • ParamList – List of variables to obtain for the given object type. E.g. [‘BusNum’, ‘GenID’, ‘GenMW’]. One can use the method GetFieldList to get a listing of all available fields. Additionally, you’ll likely want to always return the key fields associated with the objects. These key fields can be obtained via the get_key_fields_for_object_type method.

  • FilterName – Name of an advanced filter defined in the load flow case.

Return:The format of the output array is the following:

[ NumberOfObjectsReturned, NumberOfFieldsPerObject, Ob1Fld1, Ob1Fld2, …, Ob(n)Fld(m-1), Ob(n)Fld(m)] The data is thus returned in a single dimension array, where the parameters NumberOfObjectsReturned and NumberOfFieldsPerObject tell you how the rest of the array is populated. Following the NumberOfObjectsReturned parameter is the start of the data. The data is listed as all fields for object 1, then all fields for object 2, and so on. You can parse the array using the NumberOf… parameters for objects and fields. If the given object type does not exist, the method will return None.

GetParameters(ObjectType: str, ParamList: list, Values: list) Series[source]

This function is maintained in versions of Simulator later than version 9 for compatibility with Simulator version 9. This function will call the GetParametersSingleElement implicitly.

PowerWorld Documentation

Parameters:
  • ObjectType – The type of object you’re retrieving parameters for.

  • ParamList – List of strings indicating parameters to retrieve. Note the key fields MUST be present. One can obtain key fields for an object type via the get_key_fields_for_object_type method.

  • Values – List of values corresponding 1:1 to parameters in the ParamList. Values must be included for the key fields, and the remaining values should be set to 0.

Returns:

Pandas Series indexed by the given ParamList. This Series will be cleaned by clean_df_or_series, so data will be of the appropriate type and strings are cleaned up.

Raises:
  • PowerWorldError – if the object cannot be found.

  • ValueError – if any given element in ParamList is not valid for the given ObjectType.

  • AssertionError – if the given ParamList and Values do not have the same length.

GetSpecificFieldList(ObjectType: str, FieldList: List[str]) DataFrame[source]

The GetSpecificFieldList function is used to return identifying information about specific fields used by an object type. Note that in many cases simply using the GetFieldList method is simpler and gives more information.

PowerWorld Documentation

Parameters:
  • ObjectType – The type of object for which fields are requested.

  • FieldList – A list of strings. Each string represents object field variables, as defined in the section on PowerWorld Object Fields . Specific variablenames along with location numbers can be specified. To return all fields using the same variablename, use “variablename:ALL” instead of the location number that would normally appear after the colon. If all fields should be returned, a single parameter of “ALL” can be used instead of specific variablenames.

Returns:

A Pandas DataFrame with columns given by the class constant SPECIFIC_FIELD_LIST_COLUMNS. There will be a row for each element in the FieldList input unless ‘ALL’ is used in the FieldList. The DataFrame will be sorted alphabetically by the variablenames.

GetSpecificFieldMaxNum(ObjectType: str, Field: str) int[source]

The GetSpecificFieldMaxNum function is used to return the maximum number of a fields that use a particular variablename for a specific object type.

PowerWorld Documentation

Parameters:
  • ObjectType – The type of object for which information is being requested.

  • Field – The variablename for which the maximum number of fields is being requested. This should just be the variablename and should exclude the location number that can be included to indicate different fields that use the same variablename, i.e. do not include the colon and number that can be included when identifying a field.

Returns:

An integer that specifies the maximum number of fields that use the same variablename for a particular object type. Fields are identified in the format variablename:location when multiple fields use the same variablename. The output indicates the maximum number that the location can be. Generally, fields are identified starting from 0 and going up to the maximum number, but keep in mind that values within this range might be skipped and not used to indicate valid fields.

ListOfDevices(ObjType: str, FilterName='') None | DataFrame[source]

Request a list of objects and their key fields. This function is general, and you may be better off running more specific methods like “get_gens”

Parameters:
  • ObjType – The type of object for which you are acquiring the list of devices. E.g. “Shunt,” “Gen,” “Bus,” “Branch,” etc.

  • FilterName – Name of an advanced filter defined in the load flow case open in the automation server. Use the empty string (default) if no filter is desired. If the given filter cannot be found, the server will default to returning all objects in the case of type ObjectType.

Returns:

None if there are no objects of the given type in the model. Otherwise, a DataFrame of key fields will be returned. There will be a row for each object of the given type, and columns for each key field. If the “BusNum” key field is present, the data will be sorted by BusNum.

ListOfDevicesAsVariantStrings(ObjType: str, FilterName='') tuple[source]

While this method is implemented, you are almost certainly better off using ListOfDevices instead. Since this method isn’t particularly useful, no type casting will be performed on the output array. Contrast the results of calling this method with the results of calling ListOfDevices to see just how helpful ESA is!

Description below if from PowerWorld:

This function operates the same as the ListOfDevices function, only with one notable difference. The values returned as the output of the function are returned as Variants of type String. The ListOfDevices function was errantly released returning the values strongly typed as Integers and Strings directly, whereas all other SimAuto functions returned data as Variants of type String. This function was added to also return the data in the same manner. This solved some compatibility issues with some software languages.

Parameters:
  • ObjType – The type of object for which you are acquiring the list of devices.

  • FilterName – The name of an advanced filter defined in the load flow case open in the Simulator Automation Server. If no filter is desired, then simply pass an empty string. If the filter cannot be found, the server will default to returning all objects in the case of type ObjType.

Returns:

Tuple of tuples as documented by PowerWorld for the ListOfDevices function.

ListOfDevicesFlatOutput(ObjType: str, FilterName='') tuple[source]

While this method is implemented, you are almost certainly better off using ListOfDevices instead. Since this method isn’t particularly useful, no type casting, data type changing, or data rearranging will be performed on the output array. Contrast the results of calling this method with the results of calling ListOfDevices to see just how helpful ESA is!

This function operates the same as the ListOfDevices function, only with one notable difference. The values returned as the output of the function are returned in a single-dimensional vector array, instead of the multi-dimensional array as described in the ListOfDevices topic. The function returns the key field values for the device, typically in the order of bus number 1, bus number 2 (where applicable), and circuit identifier (where applicable). These are the most common key fields, but some object types do have other key fields as well.

PowerWorld documentation:

Parameters:
  • ObjType – The type of object for which you are acquiring the list of devices.

  • FilterName – The name of an advanced filter defined in the load flow case open in the Simulator Automation Server. If no filter is desired, then simply pass an empty string. If the filter cannot be found, the server will default to returning all objects in the case of type ObjType.

Returns:

List in the following format: [NumberOfObjectsReturned, NumberOfFieldsPerObject, Ob1Fld1, Ob1Fld2, …, Ob(n)Fld(m-1), Ob(n)Fld(m)]. The data is thus returned in a single dimension array, where the parameters NumberOfObjectsReturned and NumberOfFieldsPerObject tell you how the rest of the array is populated. Following the NumberOfObjectsReturned parameter is the start of the data. The data is listed as all fields for object 1, then all fields for object 2, and so on. You can parse the array using the NumberOf… parameters for objects and fields.

LoadState() None[source]

LoadState is used to load the system state previously saved with the SaveState function. Note that LoadState will not properly function if the system topology has changed due to the addition or removal of the system elements.

PowerWorld documentation

OpenCase(FileName: str | None = None) None[source]

Load PowerWorld case into the automation server.

Parameters:

FileName – Full path to the case file to be loaded. If None, this method will attempt to use the last FileName used to open a case.

Raises:

TypeError – if FileName is None, and OpenCase has never been called before.

PowerWorld documentation

OpenCaseType(FileName: str, FileType: str, Options: list | str | None = None) None[source]
The OpenCaseType function will load a PowerWorld Simulator load
flow file into the Simulator Automation Server. This is similar

to opening a file using the File > Open Case menu option in Simulator.

PowerWorld documentation

Parameters:
  • FileName – Full path to the case file to be loaded. If None, this method will attempt to use the last FileName used to open a case.

  • FileType – The type of case file to be loaded. It can be one of the following strings: PWB, PTI, PTI23, PTI24, PTI25, PTI26, PTI27, PTI28, PTI29, PTI30, PTI31, PTI32, PTI33, GE (means GE18), GE14, GE15, GE17, GE18, GE19, CF, AUX, UCTE, AREVAHDB

  • Options – Optional parameter indicating special load options for PTI and GE file types. See the PowerWorld documentation for more details.

ProcessAuxFile(FileName)[source]

Load a PowerWorld Auxiliary file into SimAuto. This allows you to create a text file (conforming to the PowerWorld Auxiliary file format) that can list a set of data changes and other information for making batch changes in Simulator.

Parameters:

FileName – Name of auxiliary file to load. Should be a full path.

PowerWorld documentation

RunScriptCommand(Statements)[source]

Execute a list of script statements. The script actions are those included in the script sections of auxiliary files.

PowerWorld documentation

Auxiliary File Format

RunScriptCommand2(Statements: str, StatusMessage: str)[source]

Execute a list of script statements. The script actions are those included in the script sections of auxiliary files. This function differs from RunScriptCommand in that it allows informational messages to be returned from the script execution when the execution is successful.

Output is a boolean value indicating whether the script command was succesful or not. If False is returned, the error message will be returned as defined in Status message input parameter. If True, the Status message will be empty.

PowerWorld documentation

Auxiliary File Format

SaveCase(FileName=None, FileType='PWB', Overwrite=True)[source]

Save the current case to file.

PowerWorld documentation

Parameters:
  • FileName – The name of the file you wish to save as, including file path. If None, the original path which was used to open the case (passed to this class’s initializer) will be used.

  • FileType – String indicating the format of the case file to write out. Here’s what PowerWorld currently supports: * “PTI23”: “PTI33” specific PTI version (raw). * “GE14”: “GE21” GE PSLF version (epc). * “IEEE”: IEEE common format (cf). * “UCTE”: UCTE Data Exchange (uct). * “AUX”: PowerWorld Auxiliary format (aux). * “AUXSECOND”: PowerWorld Auxiliary format (aux) using secondary key fields. * “AUXLABEL”: PowerWorld Auxiliary format (aux) using labels as key field identifiers. * “AUXNETWORK”: PowerWorld Auxiliary format (aux) saving only network data. * “PWB5” through “PWB20”: specific PowerWorld Binary version (pwb). * “PWB”: PowerWorld Binary (most recent) (pwb).

  • Overwrite – Whether (True) or not (False) to overwrite the file if it already exists. If False and the specified file already exists, an exception will be raised.

SaveState() None[source]

SaveState is used to save the current state of the power system. This can be useful if you are interested in comparing various cases, much as the “Difference Flows” feature works in the Simulator application.

PowerWorld documentation

SendToExcel(ObjectType: str, FilterName: str, FieldList) None[source]

Send data from SimAuto to an Excel spreadsheet. While ESA provides this function, we strongly recommend you to use the GetParametersMultipleElement function and save the DataFrame directly to a .csv file using the DataFrame’s to_csv method. The problem with SendToExcel is that it opens (but does not save) an Excel sheet, which requires you to manually save it.

PowerWorld documentation

Parameters:
  • ObjectType – A String describing the type of object for which you are requesting data.

  • FilterName – String with the name of an advanced filter which was previously defined in the case before being loaded in the Simulator Automation Server. If no filter is desired, then simply pass an empty string. If a filter name is passed but the filter cannot be found in the loaded case, no filter is used.

  • FieldList – Variant parameter must either be an array of fields for the given object or the string “ALL”. As an array, FieldList contains an array of strings, where each string represents an object field variable, as defined in the section on PowerWorld Object Variables. If, instead of an array of strings, the single string “ALL” is passed, the Simulator Automation Server will use predefined default fields when exporting the data.

Returns:

None

TSGetContingencyResults(CtgName: str, ObjFieldList: List[str], StartTime: None | int | float = None, StopTime: None | int | float = None) Tuple[None, None] | Tuple[DataFrame, DataFrame][source]

WARNING: This function should only be used after the simulation is run (for example, use this after running script commands TSSolveAll or TSSolve).

On to the main documentation:

The TSGetContingencyResults function is used to read transient stability results into an external program (Python) using SimAuto.

This function is analogous to the script command TSGetResults, where rather than saving out results to a file, the results are passed back directly to the SimAuto COM object and may be further processed by an external program. As with TSGetResults, this function should only be used after the simulation is run (for example, use this after running script commands TSSolveAll or TSSolve).

PowerWorld documentation:

The authors of ESA do not have extensive experience running transient contingencies in PowerWorld, so this method has not been tested as extensively as we would prefer. If your case/code has issues with this method, please file an issue on GitHub.

Parameters:
  • CtgName – The contingency to obtain results from. Only one contingency be obtained at a time.

  • ObjFieldList – A list of strings which may contain plots, subplots, or individual object/field pairs specifying the result variables to obtain. For field name please check here.

  • StartTime – The time in seconds in the simulation to begin retrieving results. If not specified (None), the start time of the simulation is used.

  • StopTime – The time in seconds in the simulation to stop retrieving results. If not specified, the end time of the simulation is used.

Returns:

A tuple containing two DataFrames, “meta” and “data.” Alternatively, if the given CtgName does not exist, a tuple of (None, None) will be returned. The “meta” DataFrame describes the data in the “data” DataFrame, and can be used to map objects to columns in the “data” DataFrame. The “meta” DataFrame’s columns are: [‘ObjectType’, ‘PrimaryKey’, ‘SecondaryKey’, ‘Label’, ‘VariableName’, ‘ColHeader’]. Each row in the “meta” DataFrame corresponds to a column in the “data” DataFrame. So the “meta” row with index label 0 corresponds to the column labeled 0 in the “data” DataFrame, and so forth. Unfortunately, the ObjectType``s that come back from PowerWorld do not always match valid ``ObjectType variable names (e.g. “Generator” comes back as an ObjectType, but attempting to use “Generator” in the GetParametersMultipleElement method results in an error), so ESA’s ability to perform automatic data type transformation is limited. All columns in the “data” DataFrame will be cast to numeric types by pandas.to_numeric. If Pandas cannot determine an appropriate numeric type, the data will be unmodified (i.e., the type will not be changed). In addition to the integer labeled columns which match the “meta” rows, the “data” DataFrame additionally has a “time” column which corresponds to the timestamp (in seconds).

WriteAuxFile(FileName: str, FilterName: str, ObjectType: str, FieldList: list | str, ToAppend=True)[source]

The WriteAuxFile function can be used to write data from the case in the Simulator Automation Server to a PowerWorld Auxiliary file. The name of an advanced filter which was PREVIOUSLY DEFINED in the case before being loaded in the Simulator Automation Server. If no filter is desired, then simply pass an empty string. If a filter name is passed but the filter cannot be found in the loaded case, no filter is used.

PowerWorld documentation

SolvePowerFlow(SolMethod: str = 'RECTNEWT') None[source]

Run the SolvePowerFlow command.

Parameters:

SolMethod – Solution method to be used for the Power Flow calculation. Case insensitive. Valid options are: ‘RECTNEWT’ - Rectangular Newton-Raphson ‘POLARNEWTON’ - Polar Newton-Raphson ‘GAUSSSEIDEL’ - Gauss-Seidel ‘FASTDEC’ - Fast Decoupled ‘ROBUST’ - Attempt robust solution process ‘DC’ - DC power flow

See Auxiliary File Format.pdf for more details.

OpenOneLine(filename: str, view: str = '', FullScreen: str = 'NO', ShowFull: str = 'NO', LinkMethod: str = 'LABELS', Left: float = 0.0, Top: float = 0.0, Width: float = 0.0, Height: float = 0.0) None[source]

Use this function to open a oneline diagram. This function can be used to associate onelines with a PWB file.

Parameters:
  • filename – The file name of the oneline diagram to open.

  • view – The view name that should be opened. Pass an empty string to denote no specific view.

  • FullScreen – Set to YES or NO. YES means that the oneline diagram will be open in full screen mode. If this parameter is not specified, then NO is assumed.

  • ShowFull – Optional parameter. Set to YES to open the oneline and apply the Show Full option. Set to NO to open the oneline and leave the oneline as is. Default is NO if not specified.

  • LinkMethod – Optional Parameter that controls oneline linking. LABELS, NAMENOMKV, and NUMBER will link using the respective key fields.

  • Left – Optional with default of 0. Value between 0 and 100 that indicates the location of the left edge of the oneline as a percentage of the Simulator/Retriever window width.

  • Top – Optional with default of 0. Value between 0 and 100 that indicates the top edge of the oneline as a percentage of the Simulator/Retriever window height.

  • Width – Optional with default of 0. Value between 0 and 100 that indicates the width of the oneline as a percentage of the Simulator/Retriever window width.

  • Height – Optional with default of 0. Value between 0 and 100 that indicates the height of the oneline as a percentage of the Simulator/Retriever window height.

Returns:

None

CloseOneline(OnelineName: str = '') None[source]

Use this action to close an open oneline diagram without saving it. If the name is omitted, the last focused oneline diagram will be closed.

Parameters:

OnelineName – The name of the oneline diagram to close.

Returns:

None

property CreateIfNotFound

The CreateIfNotFound property of the Simulator Automation Server is useful when you are changing data with the ChangeParameters functions. Set the attribute through the set_simauto_property method.

property CurrentDir: str

The CurrentDir property of the Simulator Automation Server allows you to retrieve or set the working directory for the currently running SimulatorAuto process. This is most useful if using relative filenames (e.g. "relativename.aux" versus r"C:\Program Files\PowerWorld\Workingbosultename.aux") when specifying files. Set this property through the set_simauto_property method.

property ProcessID: int

The ProcessID property of the Simulator Automation Server allows you to retrieve the process ID of the currently running SimulatorAuto process, as can also be seen through the Task Manager in Windows. This information can be useful if a forced shutdown of the SimulatorAuto object is needed, as all calls to the SimulatorAuto object are synchronous. This means the SimulatorAuto object will not be destroyed until all calls, no matter the time of execution, have completed.

property RequestBuildDate: int

The RequestBuildDate property of the Simulator Automation Server allows you to retrieve the build date of the PowerWorld Simulator executable currently running with the SimulatorAuto process. The property returns an integer value that represents a date. This information is useful for verifying the release version of the executable.

After contacting PowerWorld, it seems the integer comes back according to Delphi date conventions, which counts days since December 30th, 1899.

property UIVisible: bool

Get the UIVisible property of the Simulator Automation Server which indicates the visibility of the user interface for Simulator. Default behavior is to not show the user interface while using SimAuto. Set this property through the set_simauto_property method.

property ProgramInformation: tuple | bool

Get the Program Information property of the Simulator Automation Server which returns information about the version of PowerWorld Simulator run by the current instance of SimAuto. This property returns a variant array of variant arrays. The order of each array within the main array is subject to change and additional arrays may be added in the future. The first entry of each array will indicate what type of information is in the array. The order of entries within each array will not change. Set this property through the set_simauto_property method.

esa.saw.df_to_aux(fp, df, object_name: str)[source]

Convert a dataframe to PW aux/axd data section.

Parameters:
  • fp – file handler

  • df – dataframe

  • object_name – object type

esa.saw.convert_to_windows_path(p)[source]

Given a path, p, convert it to a Windows path.

esa.saw.convert_list_to_variant(list_in: list) VARIANT[source]

Given a list, convert to a variant array.

Parameters:

list_in – Simple one-dimensional Python list, e.g. [1, ‘a’, 7]

esa.saw.convert_nested_list_to_variant(list_in: list) List[VARIANT][source]

Given a list of lists, convert to a variant array.

Parameters:

list_in – List of lists, e.g. [[1, ‘1’], [1, ‘2’], [2, ‘1’]]

exception esa.saw.Error[source]

Bases: Exception

Base class for exceptions in this module.

exception esa.saw.PowerWorldError[source]

Bases: Error

Raised when PowerWorld reports an error following a SimAuto call.

exception esa.saw.COMError[source]

Bases: Error

Raised when attempting to call a SimAuto function results in an error.

exception esa.saw.CommandNotRespectedError[source]

Bases: Error

Raised if a command sent into PowerWorld is not respected, but PowerWorld itself does not raise an error. This exception should be used with helpers that double-check commands.