SimAuto Wrapper (SAW)
The SAW (SimAuto Wrapper) class provides complete access to PowerWorld’s SimAuto API.
It is organized into functional mixins for power flow, contingencies, optimization, sensitivity,
transient stability, GIC, ATC, topology, and data management. Access SAW through pw.esa
from PowerWorld.
- class SAW(FileName, early_bind=False, UIVisible=False, CreateIfNotFound=False, UseDefinedNamesInVariables=False, pw_order=False)[source]
Bases:
SAWBase,CaseActionsMixin,DataMixin,ContingencyMixin,GeneralMixin,MatrixMixin,ModifyMixin,PowerflowMixin,RegionsMixin,SensitivityMixin,ScheduledActionsMixin,TopologyMixin,TransientMixin,FaultMixin,ATCMixin,GICMixin,OPFMixin,PVMixin,QVMixin,TimeStepMixin,WeatherMixinInitializes the SimAuto Wrapper (SAW) and establishes a COM connection to PowerWorld Simulator.
- Parameters:
FileName (
str) – Absolute or relative path to the PowerWorld case file (.pwb or .pwx).early_bind (
bool, optional) – If True, uses gencache for faster COM calls (requires admin/write access to site-packages). Defaults to False.UIVisible (
bool, optional) – If True, makes the PowerWorld Simulator application window visible. Defaults to False.CreateIfNotFound (
bool, optional) – Sets the SimAuto property to create new objects during ChangeParameters calls. Defaults to False.UseDefinedNamesInVariables (
bool, optional) – If True, configures the case to use defined names instead of internal IDs. Defaults to False.pw_order (
bool, optional) – If True, disables automatic sorting of DataFrames to match PowerWorld’s internal memory order. Defaults to False.
- Raises:
Exception – If the SimAuto COM server cannot be initialized (e.g., PowerWorld not installed or license issue).
General Program Actions
- class SAWBase(FileName, early_bind=False, UIVisible=False, CreateIfNotFound=False, UseDefinedNamesInVariables=False, pw_order=False)[source]
Initializes the SimAuto Wrapper (SAW) and establishes a COM connection to PowerWorld Simulator.
- Parameters:
FileName (
str) – Absolute or relative path to the PowerWorld case file (.pwb or .pwx).early_bind (
bool, optional) – If True, uses gencache for faster COM calls (requires admin/write access to site-packages). Defaults to False.UIVisible (
bool, optional) – If True, makes the PowerWorld Simulator application window visible. Defaults to False.CreateIfNotFound (
bool, optional) – Sets the SimAuto property to create new objects during ChangeParameters calls. Defaults to False.UseDefinedNamesInVariables (
bool, optional) – If True, configures the case to use defined names instead of internal IDs. Defaults to False.pw_order (
bool, optional) – If True, disables automatic sorting of DataFrames to match PowerWorld’s internal memory order. Defaults to False.
- Raises:
Exception – If the SimAuto COM server cannot be initialized (e.g., PowerWorld not installed or license issue).
- ProcessAuxFile(FileName)[source]
Executes a PowerWorld auxiliary (.aux) file.
Auxiliary files contain script commands or data definitions that PowerWorld can process to modify the case or perform actions.
- RunScriptCommand(Statements)[source]
Executes one or more PowerWorld script statements.
- RunScriptCommand2(Statements, StatusMessage)[source]
Executes script statements and provides a status message for the PowerWorld UI.
This method is similar to RunScriptCommand but also allows displaying a custom message in the PowerWorld Simulator status bar.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If any of the script commands fail.
- exec_aux(aux, use_double_quotes=False)[source]
Executes an auxiliary command string directly.
This method writes the provided aux string to a temporary .aux file and then processes it using ProcessAuxFile.
- exit()[source]
Closes the PowerWorld case, deletes temporary files, and releases the COM object.
This method should be called when the SimAuto session is no longer needed to ensure proper cleanup and resource release.
- set_logging_level(level)[source]
Sets the logging level for the SAW instance logger.
- set_simauto_property(property_name, property_value)[source]
Sets a property on the underlying SimAuto COM object.
This method provides a controlled way to set various SimAuto properties, including validation of property names and value types.
- Parameters:
property_name (
str) – The name of the property to set (e.g., ‘UIVisible’, ‘CurrentDir’, ‘CreateIfNotFound’).property_value (
Union[str,bool]) – The value to assign to the property. The type must match the expected type for the specific property.
- Raises:
ValueError – If the property_name is unsupported, the property_value has an incorrect type, or if CurrentDir is set to an invalid path.
AttributeError – If the property does not exist on the current SimAuto version (e.g., UIVisible on older versions of Simulator).
- update_ui()[source]
Triggers a refresh of the PowerWorld Simulator user interface.
This can be useful after making programmatic changes that might not immediately reflect in the GUI.
- property CreateIfNotFound
- property CurrentDir
- property ProcessID
- property ProgramInformation
Detailed information about the Simulator version and license.
- Type:
Tuple property
- property RequestBuildDate
- SIMAUTO_PROPERTIES = {'CreateIfNotFound': <class 'bool'>, 'CurrentDir': <class 'str'>, 'UIVisible': <class 'bool'>}
- property UIVisible
- class GeneralMixin[source]
Mixin for General Program Actions and Data Interaction.
- CopyFile(old_filename, new_filename)[source]
Copies a file from old_filename to new_filename.
- CreateData(objecttype, fieldlist, valuelist)[source]
Creates a new object of a specified type with initial field values.
- Parameters:
objecttype (
str) – The PowerWorld object type to create (e.g., “Bus”, “Gen”).fieldlist (
List[str]) – A list of internal field names for the new object. This must include all primary key fields.valuelist (
List[str]) – A list of values corresponding to fieldlist for the new object.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., object already exists, invalid parameters).
- Delete(objecttype, filter_name='')[source]
Deletes objects of a specified type, optionally filtered.
- DeleteFile(filename)[source]
Deletes a specified file.
- DeleteState(statename, state_type='USER')[source]
Deletes a previously saved state by its name.
- EnterMode(mode)[source]
Enters PowerWorld Simulator into a specific operating mode.
- Parameters:
mode (
Union[PowerWorldMode,str]) – The mode to enter. Must be PowerWorldMode.RUN, PowerWorldMode.EDIT, or the equivalent strings “RUN” / “EDIT”.- Returns:
- Raises:
ValueError – If mode is not “RUN” or “EDIT”.
PowerWorldError – If the SimAuto call fails.
- GetSubData(objecttype, fieldlist, subdatalist=None, filter_name='')[source]
Retrieves object data including nested SubData sections as a DataFrame.
SubData sections contain structured data like cost curves, reactive capability, or contingency elements that aren’t available through standard CSV exports.
- Parameters:
objecttype (
str) – The PowerWorld object type (e.g., “Gen”, “Load”, “Contingency”).fieldlist (
List[str]) – A list of standard field names to retrieve.subdatalist (
List[str], optional) – SubData section names to include (e.g., [“BidCurve”, “ReactiveCapability”]). Defaults to None (no SubData).filter_name (
str, optional) – A PowerWorld filter name to apply. Defaults to “” (all objects).
- Returns:
DataFrame– DataFrame where standard fields are scalar columns and SubData fields contain lists of lists (each inner list is one row from the SubData section).
Examples
>>> df = saw.GetSubData("Gen", ["BusNum", "GenID"], ["BidCurve"]) >>> for _, row in df.iterrows(): ... print(f"Gen {row['BusNum']}: {len(row['BidCurve'])} bid points")
- ImportData(filename, filetype=FileFormat.CSV, header_line=1, create_if_not_found=False)[source]
Imports data from a file in various formats into PowerWorld Simulator.
- Parameters:
filename (
str) – The path to the data file.filetype (
str) – The format of the file (e.g., “CSV”, “TXT”, “PTI”).header_line (
int, optional) – The line number where the header (column names) is located. Defaults to 1.create_if_not_found (
bool, optional) – If True, attempts to create objects if they don’t exist. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- LoadAux(filename, create_if_not_found=False)[source]
Loads an auxiliary (.aux) file into PowerWorld Simulator.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., file not found, syntax error in aux file).
- LoadAuxDirectory(file_directory, filter_string='', create_if_not_found=False)[source]
Loads multiple auxiliary files from a specified directory.
The auxiliary files will be loaded in alphabetical order by name. This is useful for batch loading configuration files or data updates.
- Parameters:
file_directory (
str) – The directory where the auxiliary files are located.filter_string (
str, optional) – A filter string using Windows wildcard patterns (e.g.,*.aux). If not specified, all files in the directory are loaded. Defaults to “”.create_if_not_found (
bool, optional) – If True, objects that cannot be found will be created while reading DATA sections from the files. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., directory not found).
- LoadCSV(filename, create_if_not_found=False)[source]
Loads a CSV file, typically one formatted similarly to output from SendToExcel.
- LoadData(filename, data_name, create_if_not_found=False)[source]
Loads a named DATA section from another auxiliary file.
This opens the auxiliary file denoted by filename but only reads the specific data section specified, ignoring other sections.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., file or data section not found).
- LoadScript(filename, script_name='')[source]
Loads and runs a script from an auxiliary file.
- LogAdd(text)[source]
Adds a message to the PowerWorld Simulator Message Log.
- LogAddDateTime(label, include_date=True, include_time=True, include_milliseconds=False)[source]
Adds the current date and time to the PowerWorld Simulator Message Log.
Use this action to add a timestamped entry to the message log for tracking when certain operations occur during script execution.
- Parameters:
label (
str) – A string which will appear at the start of the line containing the date/time.include_date (
bool, optional) – If True, includes the date in the log entry. Defaults to True.include_time (
bool, optional) – If True, includes the time in the log entry. Defaults to True.include_milliseconds (
bool, optional) – If True, includes milliseconds in the time. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- LogClear()[source]
Clears all messages from the PowerWorld Simulator Message Log.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- LogSave(filename, append=False)[source]
Saves the contents of the PowerWorld Simulator Message Log to a file.
- LogShow(show=True)[source]
Shows or hides the PowerWorld Simulator Message Log window.
- RenameFile(old_filename, new_filename)[source]
Renames a file from old_filename to new_filename.
- RestoreState(statename, state_type='USER')[source]
Restores a previously saved state by its name.
- SaveData(filename, filetype, objecttype, fieldlist, subdatalist=None, filter_name='', sortfieldlist=None, transpose=False, append=True)[source]
Saves data for specified objects and fields to a file using the SaveData script command.
- Parameters:
filename (
str) – The path to the output file.filetype (
str) – The format of the output file (e.g., “CSV”, “AUX”, “TXT”).objecttype (
str) – The PowerWorld object type (e.g., “Bus”, “Gen”).fieldlist (
List[str]) – A list of internal field names to save.subdatalist (
List[str], optional) – A list of sub-data fields to save (e.g., for time series data). Defaults to None.filter_name (
str, optional) – A PowerWorld filter name to apply to objects. Defaults to an empty string (all).sortfieldlist (
List[str], optional) – A list of fields to sort the output by. Defaults to None.transpose (
bool, optional) – If True, transposes the output data (rows become columns, columns become rows). Defaults to False.append (
bool, optional) – If True, appends data to the file if it exists. If False, overwrites. Defaults to True.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- SaveDataWithExtra(filename, filetype, objecttype, fieldlist, subdatalist=None, filter_name='', sortfieldlist=None, header_list=None, header_value_list=None, transpose=False, append=True)[source]
Saves data with extra user-specified header fields and values.
This method extends SaveData by allowing custom header information to be added to the output file, useful for metadata or tracking.
- Parameters:
filename (
str) – The path to the output file.filetype (
str) – The format of the output file (e.g., “CSV”, “AUX”, “TXT”).objecttype (
str) – The PowerWorld object type (e.g., “Bus”, “Gen”).fieldlist (
List[str]) – A list of internal field names to save.subdatalist (
List[str], optional) – A list of sub-data fields to save. Defaults to None.filter_name (
str, optional) – A PowerWorld filter name to apply to objects. Defaults to an empty string.sortfieldlist (
List[str], optional) – A list of fields to sort the output by. Defaults to None.header_list (
List[str], optional) – A list of custom header names to add to the file. Defaults to None.header_value_list (
List[str], optional) – A list of values corresponding to header_list. Defaults to None.transpose (
bool, optional) – If True, transposes the output data. Defaults to False.append (
bool, optional) – If True, appends data to the file. Defaults to True.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- SaveObjectFields(filename, objecttype, fieldlist)[source]
Saves a list of fields available for the specified objecttype to a file.
- SelectAll(objecttype, filter_name='')[source]
Sets the ‘Selected’ field to YES for objects of a specified type, optionally filtered.
- SendtoExcel(objecttype, fieldlist, filter_name='', use_column_headers=True, workbook='', worksheet='', sortfieldlist=None, header_list=None, header_value_list=None, clear_existing=True, row_shift=0, col_shift=0)[source]
Sends data for specified objects and fields directly to Microsoft Excel with advanced options.
This is an extended version of SendToExcel that provides additional control over Excel output including workbook/worksheet names, sorting, custom headers, and positioning. This method requires Microsoft Excel to be installed on the system.
- Parameters:
objecttype (
str) – The PowerWorld object type (e.g., “Bus”, “Gen”).fieldlist (
List[str]) – A list of internal field names to export.filter_name (
str, optional) – A PowerWorld filter name to apply to objects. Defaults to an empty string (all).use_column_headers (
bool, optional) – If True, includes column headers in the Excel output. Defaults to True.workbook (
str, optional) – The name of the Excel workbook to write to. If empty, a new workbook is created. Defaults to “”.worksheet (
str, optional) – The name of the worksheet within the workbook. If empty, a new worksheet is created. Defaults to “”.sortfieldlist (
List[str], optional) – A list of fields to sort the output by. Defaults to None.header_list (
List[str], optional) – A list of custom header names to add to the Excel output. Defaults to None.header_value_list (
List[str], optional) – A list of values corresponding to header_list. Defaults to None.clear_existing (
bool, optional) – If True, clears existing data in the target worksheet before writing. Defaults to True.row_shift (
int, optional) – Number of rows to shift the output down from the top-left corner. Defaults to 0.col_shift (
int, optional) – Number of columns to shift the output right from the top-left corner. Defaults to 0.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., Excel not installed, invalid parameters).
See also
SendToExcelBasic version with fewer parameters for simple exports.
- SetCurrentDirectory(directory, create_if_not_found=False)[source]
Sets the current working directory for PowerWorld Simulator.
This directory is used for resolving relative file paths in subsequent commands.
- SetData(objecttype, fieldlist, valuelist, filter_name='')[source]
Sets data for specified objects and fields.
This is a generic method for modifying object parameters.
- Parameters:
objecttype (
str) – The PowerWorld object type (e.g., “Bus”, “Gen”).fieldlist (
List[str]) – A list of internal field names to set.valuelist (
List[str]) – A list of values corresponding to fieldlist.filter_name (
str, optional) – A PowerWorld filter name to apply to objects. Defaults to an empty string (all).
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- SetSubData(objecttype, fieldlist, records, subdatatype=None)[source]
Write object data with optional SubData sections to PowerWorld via AUX.
This is the write counterpart to
GetSubData. It constructs an AUX DATA block and processes it, creating or updating objects including their nested SubData sections.- Parameters:
objecttype (
str) – The PowerWorld object type (e.g., “TSContingency”, “Gen”, “Contingency”).fieldlist (
List[str]) – Field names for the parent object’s scalar columns.records (
List[dict]) – Each dict must have keys matchingfieldlistfor scalar values. Ifsubdatatypeis specified, the dict may also contain a key matching each subdata type whose value is a list of lists (each inner list is one row of subdata values).subdatatype (
str,List[str], orNone) – Name(s) of the SubData section(s) (e.g., “CTGElement”, “BidCurve”, or [“BidCurve”, “ReactiveCapability”]). If None, no subdata is written.
Examples
>>> saw.SetSubData( ... "TSContingency", ... ["TSCTGName", "StartTime", "EndTime", "CTGSkip"], ... [{ ... "TSCTGName": "Fault1", ... "StartTime": 0.0, ... "EndTime": 10.0, ... "CTGSkip": "NO", ... "TSContingencyElement": [ ... ["FAULT BUS 1", 1.0], ... ["CLEAR FAULT 1", 1.083], ... ] ... }], ... subdatatype="TSContingencyElement" ... )
- StopAuxFile()[source]
Treats the remainder of the file after this command as a comment.
This includes any script commands inside the present SCRIPT block, as well as all remaining SCRIPT or DATA blocks. Useful for temporarily disabling portions of an auxiliary file.
Note: This command is primarily useful when executing auxiliary files directly, not when using SimAuto programmatically.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- StoreState(statename)[source]
Stores the current state of the PowerWorld case under a given name.
This creates a named snapshot of the case that can be restored later.
- UnSelectAll(objecttype, filter_name='')[source]
Sets the ‘Selected’ field to NO for objects of a specified type, optionally filtered.
Data Interaction
- class DataMixin[source]
Mixin for data retrieval, modification, enumeration, and export.
- ChangeParametersMultipleElement(ObjectType, ParamList, ValueList)[source]
Modifies parameters for multiple objects using a nested list of values.
This method is suitable for updating a moderate number of objects where the data is structured as a list of lists. For very large datasets, ChangeParametersMultipleElementRect is generally more efficient.
- Parameters:
ObjectType (
str) – The PowerWorld object type.ParamList (
List[str]) – A list of internal field names to modify. This list must include the primary key fields for the ObjectType to identify the target objects.ValueList (
List[List[Any]]) – A list of lists, where each inner list contains values for one object. The order of values in each inner list must match ParamList.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- ChangeParametersMultipleElementFlatInput(ObjectType, ParamList, NoOfObjects, ValueList)[source]
Modifies parameters for multiple objects using a flat, 1-D list of values.
This method is an alternative to ChangeParametersMultipleElement for cases where the data is already flattened.
- Parameters:
ObjectType (
str) – The PowerWorld object type.ParamList (
List[str]) – A list of internal field names to modify.NoOfObjects (
int) – The number of objects being updated.ValueList (
List[Any]) – A flat list of values. Its length must be NoOfObjects * len(ParamList). The values are ordered by object, then by parameter within each object.
- Returns:
- Raises:
Error – If ValueList is not a 1-D array (i.e., it’s a list of lists).
PowerWorldError – If the SimAuto call fails.
- ChangeParametersMultipleElementRect(ObjectType, ParamList, df)[source]
Modifies parameters for multiple objects using a pandas DataFrame (rectangular data structure).
This is generally the most efficient way to update a large number of objects at once. The DataFrame must include the primary key fields for the object type to identify which objects to update.
- Parameters:
ObjectType (
str) – The PowerWorld object type.ParamList (
List[str]) – A list of internal field names being updated. These must correspond to the column names in the df.df (
pandas.DataFrame) – A DataFrame containing the data to update. The column names of df must match the ParamList, and it must contain primary key columns.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- ChangeParametersSingleElement(ObjectType, ParamList, Values)[source]
Modifies parameters for a single object in PowerWorld.
This method is used to update specific fields for a single PowerWorld object, identified by its primary key values (which must be included in Values).
- Parameters:
ObjectType (
str) – The PowerWorld object type (e.g., ‘Bus’, ‘Gen’).ParamList (
List[str]) – A list of internal field names to modify. This list must include the primary key fields for the ObjectType to identify the target object.Values (
List[Any]) – A list of values corresponding to the parameters in ParamList. The order and length must match ParamList.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., invalid object type, field name, or value).
- GetCaseHeader(filename=None)[source]
Retrieves the header information from a PowerWorld case file.
- GetFieldList(ObjectType, copy=False)[source]
Retrieves the complete list of available fields for a given PowerWorld object type.
This method queries PowerWorld for all fields associated with an object type and caches the result for performance.
- Parameters:
- Returns:
pandas.DataFrame– A DataFrame containing columns like ‘key_field’, ‘internal_field_name’, ‘field_data_type’, ‘description’, ‘display_name’, and ‘enterable’.- Raises:
PowerWorldError – If the SimAuto call fails (e.g., invalid object type).
- GetParametersMultipleElement(ObjectType, ParamList, FilterName='')[source]
Retrieves parameters for multiple objects of a specific type, optionally filtered.
This method is commonly used to fetch data for all objects of a given type or a subset defined by a PowerWorld filter.
- Parameters:
- Returns:
Union[pandas.DataFrame,None]– A pandas DataFrame where columns correspond to ParamList. Returns None if no objects are found matching the criteria.- Raises:
PowerWorldError – If the SimAuto call fails (e.g., invalid object type or field names).
- GetParametersMultipleElementFlatOutput(ObjectType, ParamList, FilterName='')[source]
Retrieves data for multiple elements in a flat, 1-D output format.
The data is returned as a single tuple of strings, where values for each object are concatenated. This format can be less convenient for direct DataFrame conversion but might be useful for specific parsing needs.
- Parameters:
- Returns:
Union[None,Tuple[str]]– A tuple of strings containing the data. Returns None if no data is found.- Raises:
PowerWorldError – If the SimAuto call fails.
- GetParametersSingleElement(ObjectType, ParamList, Values)[source]
Retrieves parameters for a single object identified by its primary keys.
- Parameters:
ObjectType (
str) – The PowerWorld object type (e.g., ‘Bus’, ‘Gen’).ParamList (
List[str]) – A list of internal field names to retrieve. This list must include the primary key fields for the ObjectType to identify the target object.Values (
List[Any]) – A list containing the primary key values for the object, followed by empty strings or placeholders for other parameters in ParamList if they are not part of the key. The length must match ParamList.
- Returns:
pandas.Series– A pandas Series containing the requested data, indexed by ParamList.- Raises:
AssertionError – If the length of ParamList and Values do not match.
PowerWorldError – If the SimAuto call fails.
- GetParamsRectTyped(ObjectType, ParamList, FilterName='')[source]
Retrieves data in a rectangular format with PowerWorld’s native variant typing preserved.
This method is similar to GetParametersMultipleElement but attempts to preserve the original data types as returned by SimAuto, which can sometimes be more efficient or necessary for specific use cases.
- Parameters:
- Returns:
Union[pandas.DataFrame,None]– A pandas DataFrame containing the requested data. Returns None if no objects found.- Raises:
PowerWorldError – If the SimAuto call fails.
- GetSpecificFieldList(ObjectType, FieldList)[source]
Retrieves detailed metadata for a specific subset of fields for a given object type.
This method provides more detailed information about specific fields, including their display names and whether they are enterable.
- Parameters:
ObjectType (
str) – The PowerWorld object type.FieldList (
List[str]) – A list of internal field names to query metadata for.
- Returns:
pandas.DataFrame– A DataFrame with columns like ‘variablename:location’, ‘field’, ‘column header’, ‘field description’, and ‘enterable’.- Raises:
PowerWorldError – If the SimAuto call fails.
- GetSpecificFieldMaxNum(ObjectType, Field)[source]
Retrieves the maximum index for a field that supports multiple entries (e.g., CustomFloat).
Some PowerWorld fields, like ‘CustomFloat’, can have multiple instances (e.g., ‘CustomFloat:1’, ‘CustomFloat:2’). This method returns the highest available index for such a field.
- ListOfDevices(ObjType, FilterName='')[source]
Retrieves a list of all objects of a specific type and their primary keys.
This method is useful for getting an inventory of all objects of a certain type in the case, or a filtered subset.
- Parameters:
- Returns:
Union[None,pandas.DataFrame]– A pandas DataFrame containing the primary key fields for the objects. Returns None if no objects are found.- Raises:
PowerWorldError – If the SimAuto call fails.
- ListOfDevicesAsVariantStrings(ObjType, FilterName='')[source]
Retrieves a list of devices where primary keys are returned as variant strings.
This method returns the primary keys as a tuple of strings, which might be useful for direct use in other SimAuto commands that expect string identifiers.
- Parameters:
- Returns:
tuple– A tuple of strings, where each string represents the primary key(s) of an object.- Raises:
PowerWorldError – If the SimAuto call fails.
- ListOfDevicesFlatOutput(ObjType, FilterName='')[source]
Retrieves a list of devices in a flat, 1-D output format.
Similar to ListOfDevicesAsVariantStrings, but the output format might differ slightly depending on the SimAuto version.
- SendToExcel(ObjectType, FilterName, FieldList)[source]
Exports data for the specified objects directly to Microsoft Excel.
This method requires Microsoft Excel to be installed on the system.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., Excel not installed, invalid parameters).
Case Actions
- class CaseActionsMixin[source]
Mixin for Case Actions functions.
- CaseDescriptionClear()[source]
Clears the case description.
Removes all text from the case’s description field.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CaseDescriptionSet(text, append=False)[source]
Sets or appends text to the case description.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CloseCase()[source]
Closes the currently open PowerWorld case without exiting the Simulator application.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- DeleteExternalSystem()[source]
Deletes the part of the power system where the ‘Equiv’ field on buses is set to true.
Removes all buses from the case that have their ‘Equiv’ field set to True.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- Equivalence()[source]
Equivalences the power system based on Equiv_Options.
This action applies the equivalence settings configured in PowerWorld to reduce the size of the system model.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- LoadEMS(filename, filetype='AREVAHDB')[source]
Opens an EMS (Energy Management System) file.
- NewCase()[source]
Clears the existing case and opens a new, empty one.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- OpenCase(FileName=None)[source]
Opens a PowerWorld case file.
- Parameters:
FileName (
Union[str,None], optional) – Path to the .pwb or .pwx file. If None, it attempts to reopen the last file path stored in self.pwb_file_path.- Returns:
- Raises:
TypeError – If FileName is None and no previous pwb_file_path is set.
PowerWorldError – If the SimAuto call fails (e.g., file not found).
- OpenCaseType(FileName, FileType, Options=None)[source]
Opens a case file of a specific type (e.g., PTI, GE) with options.
- Parameters:
FileName (
str) – Path to the file. Different sets of optional parameters apply for the PTI and GE file formats. The LoadTransactions and Star bus parameters are available for writing to RAW files. MSLine, VarLimDead, and PostCTGAGC are for writing EPC files. See OpenCase in the Auxiliary File Format PDF for more details on options.FileType (
str) – The file format (e.g., ‘PTI’, ‘GE’, ‘EPC’). Valid options include: PWB, PTI (latest version), PTI23-PTI35, GE (latest version), GE14-GE23, CF, AUX, UCTE, AREVAHDB, OPENNETEMS.Options (
Union[list,str,None], optional) – A list or string of format-specific options. Defaults to None.
- Renumber3WXFormerStarBuses(filename, delimiter='BOTH')[source]
Renumbers 3-winding transformer star buses based on user-specified values in a file.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., file not found, format error).
- RenumberAreas(custom_integer_index=0)[source]
Renumbers Areas using the value in the specified Custom Integer field.
- RenumberBuses(custom_integer_index=1)[source]
Renumbers Buses using the value in the specified Custom Integer field.
- RenumberCase()[source]
Renumbers objects in the case according to the swap list in memory.
This applies any pending renumbering operations that have been configured.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- RenumberMSLineDummyBuses(filename, delimiter='BOTH')[source]
Renumbers dummy buses of multisection lines based on a provided file.
- RenumberSubs(custom_integer_index=2)[source]
Renumbers Substations using the value in the specified Custom Integer field.
- RenumberZones(custom_integer_index=3)[source]
Renumbers Zones using the value in the specified Custom Integer field.
- SaveCase(FileName=None, FileType='PWB', Overwrite=True)[source]
Saves the currently open PowerWorld case to a file.
- Parameters:
FileName (
str, optional) – Path to save the file. If None, the case is saved to its current path, potentially overwriting the original file.FileType (
str, optional) – The file format to save as (e.g., “PWB”, “PTI”, “GE”). Defaults to “PWB”.Overwrite (
bool, optional) – If True, overwrites an existing file at FileName without prompting. Defaults to True.
- Returns:
- Raises:
TypeError – If FileName is None and no case has been opened previously.
PowerWorldError – If the SimAuto call fails (e.g., invalid path, permission issues).
- SaveExternalSystem(filename, filetype='PWB', with_ties=False)[source]
Saves only buses where ‘Equiv’ is set to ‘External’ to a new case file.
This is useful for creating reduced models of external systems.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- SaveMergedFixedNumBusCase(filename, filetype='PWB')[source]
Saves the Merged FixedNumBus case.
This action is typically used after a fixed-number bus merge operation.
- Scale(scale_type, based_on, parameters, scale_marker)[source]
Scales load and generation in the system based on specified criteria.
This action can be used to uniformly adjust load or generation values across the system or specific regions.
- Parameters:
scale_type (
str) – The type of object to scale (“LOAD”, “GEN”, “INJECTIONGROUP”, or “BUSSHUNT”).based_on (
str) – The scaling basis (“MW” for absolute MW/MVAR values, or “FACTOR” for a multiplier).parameters (
List[float]) – A list of values for scaling. If based_on is “MW”, this can be [MW, MVAR] or [MW] for LOAD/INJECTIONGROUP, [MW] for GEN, or [GMW, BCAPMVAR, BREAMVAR] for BUSSHUNT. If based_on is “FACTOR”, this is [Factor]. Can also be a field variable name to use values from another field.scale_marker (
str) – The scope of the scaling (“BUS”, “AREA”, “ZONE”, “OWNER”, or “SYSTEM”).
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- get_version_and_builddate()[source]
Retrieves the PowerWorld Simulator version string and executable build date.
This method queries the ‘PowerWorldSession’ object for its version and build date.
- Returns:
tuple– A tuple containing: - str: The version string of PowerWorld Simulator (e.g., “22.0.0.0”). - datetime.datetime: The build date of the PowerWorld Simulator executable.
Modify Case Objects
- class ModifyMixin[source]
Mixin for modifying case objects.
- AutoInsertTieLineTransactions()[source]
Deletes existing MW transactions and creates new ones based on tie-line flows.
This action automatically generates transactions to represent power transfers across tie-lines between areas.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- BranchMVALimitReorder(filter_name='', limits=None)[source]
Modifies MVA limits for branches, allowing reordering or setting specific limits.
- Parameters:
filter_name (
str, optional) – A PowerWorld filter name to apply to branches. Defaults to an empty string (all branches).limits (
List[str], optional) – A list of 15 strings representing the MVA limits (A through O) to apply. If None, default limits are used.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CalculateRXBGFromLengthConfigCondType(filter_name='')[source]
Recalculates R, X, G, B parameters for transmission lines using the TransLineCalc tool.
This is typically used when line length, configuration, or conductor type changes.
- ChangeSystemMVABase(new_base)[source]
Changes the system MVA base.
This action rescales all per-unit values in the case to reflect the new MVA base.
- ClearSmallIslands()[source]
Identifies the largest island in the system and de-energizes all other smaller islands.
This is useful for simplifying the system or isolating the main connected component.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CreateLineDeriveExisting(from_bus, to_bus, circuit, new_length, branch_id, existing_length=None, zero_g=False)[source]
Creates a new branch derived from an existing one with scaled impedance.
This allows for quickly modeling new lines based on the characteristics of an already defined line, adjusting for length.
- Parameters:
from_bus (
int) – The bus number of the ‘From’ end of the new branch.to_bus (
int) – The bus number of the ‘To’ end of the new branch.circuit (
str) – The circuit identifier for the new branch.new_length (
float) – The length of the new branch.branch_id (
str) – The ID of an existing branch to derive parameters from.existing_length (
float, optional) – The length of the existing branch. If None, PowerWorld will attempt to determine it.zero_g (
bool, optional) – If True, sets the shunt conductance (G) of the new branch to zero. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- DirectionsAutoInsert(source, sink, delete_existing=True, use_area_zone_filters=False)[source]
Auto-inserts directions to the case for transfer analysis.
- Parameters:
source (
str) – The source object type (e.g., ‘AREA’, ‘BUS’, ‘ZONE’).sink (
str) – The sink object type (e.g., ‘AREA’, ‘BUS’, ‘ZONE’).delete_existing (
bool, optional) – If True, deletes existing directions before inserting new ones. Defaults to True.use_area_zone_filters (
bool, optional) – If True, uses Area/Zone filters for auto-insertion. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- DirectionsAutoInsertReference(source_type, reference_object, delete_existing=True, source_filter='', opposite_direction=False)[source]
Auto-inserts directions from multiple source objects to the same ReferenceObject.
- Parameters:
source_type (
str) – The type of source objects (e.g., “BUS”, “AREA”, “ZONE”).reference_object (
str) – The reference object string (e.g., ‘[BUS 100]’, ‘[AREA “LoadZone”]’).delete_existing (
bool, optional) – If True, deletes existing directions before inserting new ones. Defaults to True.source_filter (
str, optional) – A PowerWorld filter name to apply to the source objects. Defaults to an empty string (all).opposite_direction (
bool, optional) – If True, inserts directions in the opposite sense (from reference to sources). Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- InitializeGenMvarLimits()[source]
Initializes all generators to be marked as at Mvar limits or not.
This action typically resets the Mvar limit status of generators based on their current operating point and defined limits.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- InjectionGroupCreate(name, object_type, initial_value, filter_name, append=True)[source]
Creates or modifies an injection group.
- Parameters:
name (
str) – The name of the injection group.object_type (
str) – The type of objects to include in the group (e.g., “Gen”, “Load”, “Bus”).initial_value (
float) – The initial value for the injection group.filter_name (
str) – A PowerWorld filter name to select objects for the group.append (
bool, optional) – If True, appends to an existing group; if False, creates a new one or overwrites. Defaults to True.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- InjectionGroupRemoveDuplicates(preference_filter='')[source]
Removes duplicate injection groups.
- InjectionGroupsAutoInsert()[source]
Inserts injection groups according to the IG_AutoInsert_Options.
Injection groups are used for various analyses, such as PV/QV curves.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- InterfaceAddElementsFromContingency(interface_name, contingency_name)[source]
Adds elements from a contingency to an existing interface.
This can be used to define an interface that monitors elements affected by a specific contingency.
- InterfaceCreate(name, delete_existing, object_type, filter_name)[source]
Creates or modifies an interface with elements of a single object type.
- Parameters:
name (
str) – The name of the interface to create or modify.delete_existing (
bool) – If True, deletes any existing interface with the same name before creating.object_type (
str) – The type of objects to include in the interface (e.g., “Branch”, “Transformer”).filter_name (
str) – A PowerWorld filter name to select objects for the interface.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- InterfaceFlatten(interface_name)[source]
Flattens an interface.
Flattening an interface replaces its complex definition (e.g., based on areas) with a direct list of its constituent branches and transformers.
- InterfaceFlattenFilter(filter_name)[source]
Flattens interfaces that meet a specified filter.
- InterfaceModifyIsolatedElements(filter_name='')[source]
Modifies isolated elements within interfaces.
This action typically removes or adjusts elements in an interface that become isolated from the main system.
- InterfaceRemoveDuplicates(preference_filter='')[source]
Removes duplicate interfaces.
- InterfacesAutoInsert(type_, delete_existing=True, use_filters=False, prefix='', limits='AUTO')[source]
Auto-inserts interfaces based on specified criteria.
Interfaces are used to monitor power flow across boundaries.
- Parameters:
type_ (
str) – The type of interface to auto-insert (e.g., “AREA”, “ZONE”, “OWNER”).delete_existing (
bool, optional) – If True, deletes existing interfaces before auto-inserting new ones. Defaults to True.use_filters (
bool, optional) – If True, uses Area/Zone filters for auto-insertion. Defaults to False.prefix (
str, optional) – A prefix to add to the names of the auto-inserted interfaces. Defaults to “”.limits (
str, optional) – How to set interface limits (“AUTO”, “NONE”, or a specific value). Defaults to “AUTO”.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- MergeBuses(element, filter_name='')[source]
Merges buses based on specified criteria.
- MergeLineTerminals(filter_name='SELECTED')[source]
Merges line terminals.
This action is typically used to simplify the representation of line connections.
- MergeMSLineSections(filter_name='SELECTED')[source]
Eliminates multi-section line records by merging them into single lines.
- Move(element_a, destination, how_much=100.0, abort_on_error=True)[source]
Moves a generator, load, transmission line, or switched shunt.
This action transfers a specified percentage of an element’s value (e.g., MW/Mvar) from one location to another.
- Parameters:
element_a (
str) – The source element string (e.g., ‘[GEN 1]’, ‘[LOAD 2]’).destination (
str) – The destination object string (e.g., ‘[BUS 10]’, ‘[AREA “ZoneA”]’).how_much (
float, optional) – The percentage (0-100) of the element’s value to move. Defaults to 100.0.abort_on_error (
bool, optional) – If True, aborts the operation if an error occurs. Defaults to True.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- ReassignIDs(object_type, field, filter_name='', use_right=False)[source]
Sets IDs of specified objects to the first/last two characters of a specified field.
This is a utility for re-identifying objects based on their attributes.
- Parameters:
object_type (
str) – The type of object to reassign IDs for (e.g., “Load”, “Gen”).field (
str) – The field whose characters will be used for the new ID (e.g., “BusName”).filter_name (
str, optional) – A PowerWorld filter name to apply to objects. Defaults to an empty string (all).use_right (
bool, optional) – If True, uses the last two characters of the field; otherwise, uses the first two. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- Remove3WXformerContainer(filter_name='')[source]
Deletes three-winding transformer container objects, leaving their internal two-winding transformers.
- RenameInjectionGroup(old_name, new_name)[source]
Renames an injection group.
- RotateBusAnglesInIsland(bus_key, value)[source]
Rotates bus angles in an island by a specified value.
This action adjusts the phase angles of all buses within the island containing the specified bus_key.
- SetGenPMaxFromReactiveCapabilityCurve(filter_name='')[source]
Changes generator maximum MW output (PMax) based on its reactive capability curve.
- SetInterfaceLimitToMonitoredElementLimitSum(filter_name='ALL')[source]
Sets interface limits to the sum of its monitored element limits.
This action is useful for ensuring interface limits are consistent with the underlying component limits.
- SetParticipationFactors(method, constant_value, object_str)[source]
Modifies generator participation factors.
Participation factors determine how generators respond to changes in system load or frequency.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- SetScheduledVoltageForABus(bus_id, voltage)[source]
Sets the stored scheduled voltage for a specific bus.
- SplitBus(element, new_bus_number, insert_tie=True, line_open=False, branch_device_type='Line')[source]
Splits a bus into two, optionally inserting a tie line between them.
This action is used to model substation reconfigurations or new bus connections.
- Parameters:
element (
str) – The bus identifier string to split (e.g., ‘[BUS 1]’).new_bus_number (
int) – The bus number for the newly created bus.insert_tie (
bool, optional) – If True, inserts a tie line between the original and new bus. Defaults to True.line_open (
bool, optional) – If True, the inserted tie line (if any) is initially open. Defaults to False.branch_device_type (
str, optional) – The type of branch device to use for the tie line (e.g., “Line”, “Breaker”). Defaults to “Line”.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- SuperAreaAddAreas(name, filter_name)[source]
Adds areas to a Super Area.
Super Areas are collections of regular areas, useful for hierarchical modeling.
- SuperAreaRemoveAreas(name, filter_name)[source]
Removes areas from a Super Area.
- TapTransmissionLine(element, pos_along_line, new_bus_number, shunt_model='CAPACITANCE', treat_as_ms_line=False, update_onelines=False, new_bus_name='')[source]
Taps a transmission line at a specified position to insert a new bus.
This action is used to model new substations or connections along an existing line.
- Parameters:
element (
str) – The transmission line identifier string (e.g.,[BRANCH 1 2 1]).pos_along_line (
float) – The position along the line (0-100%) where the tap is made.new_bus_number (
int) – The bus number for the newly created tapped bus.shunt_model (
str, optional) – The shunt model to use for the new bus (“CAPACITANCE”, “INDUCTANCE”, etc.). Defaults to “CAPACITANCE”.treat_as_ms_line (
bool, optional) – If True, treats the tapped line as a multisection line. Defaults to False.update_onelines (
bool, optional) – If True, attempts to update any open oneline diagrams to reflect the change. Defaults to False.new_bus_name (
str, optional) – A name for the newly created bus. Defaults to an empty string.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- class TopologyMixin[source]
- CloseWithBreakers(object_type, filter_val, only_specified=False, switching_types=None, close_normally_closed=False)[source]
Energize objects by closing associated breakers.
Closes the breakers (or other switching devices) required to energize the specified objects. This is used when working with breaker-level topology models.
This is a wrapper for the
CloseWithBreakersscript command.- Parameters:
object_type (
str) – The type of object to energize (e.g., “GEN”, “BRANCH”, “LOAD”).filter_val (
str) – Filter name or object identifier (e.g., “[1 1]” for Gen at bus 1).only_specified (
bool, optional) – If True, only closes breakers directly associated with the specified object, not all breakers needed for energization. Defaults to False.switching_types (
list, optional) – List of switching device types to close, e.g., [“Breaker”, “Load Break Disconnect”]. Defaults to [“Breaker”].close_normally_closed (
bool, optional) – If True, also closes normally-closed disconnects. Defaults to False.
- Returns:
str– The response from the PowerWorld script command.
See also
OpenWithBreakersDisconnect objects by opening breakers.
- CreateNewAreasFromIslands()[source]
Create permanent areas matching the temporary islands from power flow.
Creates permanent area definitions that match the areas Simulator creates temporarily while solving the power flow. New areas are created if an area is on AGC, spans multiple viable islands, and only one of those islands has more than one area in it.
This is a wrapper for the
CreateNewAreasFromIslandsscript command.- Returns:
str– The response from the PowerWorld script command.
- DetermineBranchesThatCreateIslands(Filter=BranchFilterMode.ALL, StoreBuses=True, SetSelectedOnLines=False)[source]
Determine which branches, if opened, would create electrical islands.
Evaluates each branch to check if its removal causes part of the system to become electrically isolated. Useful for identifying critical transmission lines.
This is a wrapper for the
DetermineBranchesThatCreateIslandsscript command.- Parameters:
Filter (
str, optional) – Which branches to check. Options: “ALL”, “SELECTED”, “AREAZONE”, or a filter name. Defaults to “ALL”.StoreBuses (
bool, optional) – If True, stores the buses in each island to the output. Defaults to True.SetSelectedOnLines (
bool, optional) – If True, sets the Selected field to YES for branches that create islands. Note: this overwrites existing Selected values. Defaults to False.
- Returns:
DataFrame– DataFrame with branch/bus pairs showing which buses would be islanded by each critical branch.- Raises:
PowerWorldError – If the command fails to execute.
- DeterminePathDistance(start, BranchDistMeas=_BranchDistanceMeasure.REACTANCE, BranchFilter=BranchFilterMode.ALL, BusField='CustomFloat:1')[source]
Calculate a distance measure at each bus from a starting location.
Computes how far each bus is from the specified starting group using the chosen distance measure (impedance, length, or nodes). Results are stored in a bus field. Buses in the start group have distance 0, unreachable buses have distance -1.
This is a wrapper for the
DeterminePathDistancescript command.- Parameters:
start (
str) – The starting location. Can be a Bus, Area, Zone, SuperArea, Substation, or Injection Group. Examples: ‘[BUS 1]’, ‘[Area “East”]’, ‘[InjectionGroup “Source”]’.BranchDistMeas (
str, optional) – Distance measure to use. Options: “X” (series reactance), “Z” (impedance magnitude sqrt(R^2+X^2)), “Length”, “Nodes” (count branches), “FixedNumBus”, “SuperBus”, or any branch field variable name. Defaults to “X”.BranchFilter (
str, optional) – Filter for branches that can be traversed. Options: “ALL”, “SELECTED”, “CLOSED”, or a filter name. Defaults to “ALL”.BusField (
str, optional) – Bus field to store the distance results. Defaults to “CustomFloat:1”.
- Returns:
DataFrame– DataFrame containing BusNum and the calculated distance.
- DetermineShortestPath(start, end, BranchDistanceMeasure=_BranchDistanceMeasure.REACTANCE, BranchFilter=BranchFilterMode.ALL)[source]
Calculate the shortest path between two network locations.
Computes the lowest-impedance (or other measure) path between a starting location and an ending location. Returns the buses along the path with cumulative distance from the end to the start.
This is a wrapper for the
DetermineShortestPathscript command.- Parameters:
start (
str) – The starting location. Same format as DeterminePathDistance: ‘[BUS 1]’, ‘[Area “East”]’, etc.end (
str) – The ending location. Same format as start.BranchDistanceMeasure (
str, optional) – Distance measure to use. Options: “X”, “Z”, “Length”, “Nodes”, or any branch field variable name. Defaults to “X”.BranchFilter (
str, optional) – Filter for branches that can be traversed. Options: “ALL”, “SELECTED”, “CLOSED”, or a filter name. Defaults to “ALL”.
- Returns:
DataFrame– DataFrame with columns [BusNum, distance_measure, BusName] listing the path from end to start with cumulative distances.- Raises:
PowerWorldError – If the command fails or no path exists.
- DoFacilityAnalysis(filename, set_selected=False)[source]
Find the minimum cut to isolate a Facility from an External region.
Identifies the minimum number of branches that need to be opened to isolate the Facility (power system device) from the External region. The Facility and External regions must be defined beforehand using the Select Bus Dialog or other automation means.
This is a wrapper for the
DoFacilityAnalysisscript command.- Parameters:
- Returns:
str– The response from the PowerWorld script command.
- ExpandAllBusTopology()[source]
Expand the topology model around all buses.
Expands the topology representation for all buses in the model, showing breaker-level detail where available.
This is a wrapper for the
ExpandAllBusTopologyscript command.- Returns:
str– The response from the PowerWorld script command.
See also
ExpandBusTopologyExpand topology for a specific bus.
- ExpandBusTopology(bus_identifier, topology_type)[source]
Expand the topology model around a specific bus.
Expands the topology representation for a specific bus to show breaker-level detail according to the specified topology type.
This is a wrapper for the
ExpandBusTopologyscript command.- Parameters:
- Returns:
str– The response from the PowerWorld script command.
See also
ExpandAllBusTopologyExpand topology for all buses.
- FindRadialBusPaths(ignore_status=False, treat_parallel_as_not_radial=False, bus_or_superbus='BUS')[source]
Identify radial (dead-end) bus paths in the network.
Scans the network for series of buses that end in a dead-end (radial path) and populates the following fields for involved buses and branches: Radial Path End Number, Radial Path Index, Radial Path Length.
This is a wrapper for the
FindRadialBusPathsscript command.- Parameters:
ignore_status (
bool, optional) – If True, ignores element status when traversing branches. Defaults to False.treat_parallel_as_not_radial (
bool, optional) – If True, treats parallel branches as not radial when traversing. Defaults to False.bus_or_superbus (
str, optional) – Grouping level for traversal. “BUS” or “SUPERBUS”. When using “SUPERBUS”, branches within the same superbus have blank results. Defaults to “BUS”.
- Returns:
str– The response from the PowerWorld script command.
- OpenWithBreakers(object_type, filter_val, switching_types=None, open_normally_open=False)[source]
Disconnect objects by opening associated breakers.
Opens the breakers (or other switching devices) to disconnect the specified objects from the network. This is used when working with breaker-level topology models.
This is a wrapper for the
OpenWithBreakersscript command.- Parameters:
object_type (
str) – The type of object to disconnect (e.g., “GEN”, “BRANCH”, “LOAD”).filter_val (
str) – Filter name or object identifier (e.g., “[1 2 1]” for Branch).switching_types (
list, optional) – List of switching device types to open, e.g., [“Breaker”]. Defaults to [“Breaker”].open_normally_open (
bool, optional) – If True, also opens normally-open disconnects. Defaults to False.
- Returns:
str– The response from the PowerWorld script command.
See also
CloseWithBreakersEnergize objects by closing breakers.
- SaveConsolidatedCase(filename, filetype=FileFormat.PWB, bus_format='Number', truncate_ctg_labels=False, add_comments=False)[source]
Save the full topology model as a consolidated case file.
Exports the complete topology model (including breaker-level detail) into a single consolidated case file.
This is a wrapper for the
SaveConsolidatedCasescript command.- Parameters:
filename (
str) – The file path to save the consolidated case.filetype (
str, optional) – Output file format: “PWB” or “AUX”. Defaults to “PWB”.bus_format (
str, optional) – How to identify buses: “Number” or “Name”. Defaults to “Number”.truncate_ctg_labels (
bool, optional) – If True, truncates contingency labels. Defaults to False.add_comments (
bool, optional) – If True, adds comments for object labels. Defaults to False.
- Returns:
str– The response from the PowerWorld script command.
- SetBusFieldFromClosest(variable_name, bus_filter_set_to, bus_filter_from_these, branch_filter_traverse, branch_dist_meas)[source]
Copy a bus field value from the electrically closest bus.
For buses matching bus_filter_set_to, sets their field value equal to the value from the closest bus that matches bus_filter_from_these, where “closest” is determined by traversing branches according to the specified distance measure.
This is a wrapper for the
SetBusFieldFromClosestscript command.- Parameters:
variable_name (
str) – The bus field to set (and copy from the closest bus).bus_filter_set_to (
str) – Filter specifying which buses should have their field overwritten.bus_filter_from_these (
str) – Filter specifying which buses can be used as sources.branch_filter_traverse (
str) – Filter for branches that can be traversed. Options: “ALL”, “SELECTED”, “CLOSED”, or a filter name.branch_dist_meas (
str) – Distance measure: “X”, “Z”, “Length”, “Nodes”, “FixedNumBus”, “SuperBus”, or a branch field variable name.
- Returns:
str– The response from the PowerWorld script command.
- SetSelectedFromNetworkCut(set_how, bus_on_cut_side, branch_filter='', interface_filter='', dc_line_filter='', energized=True, num_tiers=0, initialize_selected=True, objects_to_select=None, use_area_zone=False, use_kv=False, min_kv=0.0, max_kv=9999.0, lower_min_kv=0.0, lower_max_kv=9999.0)[source]
Set the Selected field of specified object types if they are on the specified side of a network cut.
- Parameters:
set_how (
bool) – How to set the field (True for YES, False for NO).bus_on_cut_side (
str) – Identifier for a bus on the desired side.branch_filter (
str, optional) – Filter for branches defining the cut.interface_filter (
str, optional) – Filter for interfaces defining the cut.dc_line_filter (
str, optional) – Filter for DC lines defining the cut.energized (
bool, optional) – If True, only considers energized elements. Defaults to True.num_tiers (
int, optional) – Number of tiers to traverse. Defaults to 0.initialize_selected (
bool, optional) – If True, initializes Selected field before setting. Defaults to True.objects_to_select (
list, optional) – List of object types to select.use_area_zone (
bool, optional) – If True, uses Area/Zone filters. Defaults to False.use_kv (
bool, optional) – If True, uses kV limits. Defaults to False.min_kv (
float, optional) – Minimum kV. Defaults to 0.0.max_kv (
float, optional) – Maximum kV. Defaults to 9999.0.
- Returns:
str– The response from the PowerWorld script command.
Power Flow
- class PowerflowMixin[source]
- ClearPowerFlowSolutionAidValues()[source]
Clears internal power flow solution aid values.
PowerWorld Simulator maintains several internal flags that track which branches are closed or opened, as well as information to help estimate the generation change needed after making changes to load or generation. This information relates to angle smoothing and generator MW estimation features of the power flow solution.
Typically, this information aids in getting successful power flow solutions. However, in some circumstances you may be using an AUX file to edit information you know is good and would not want PowerWorld to modify the initial bus voltage and angle nor the generator MW outputs before a solution is attempted. Call this command to clear all internally stored information so PowerWorld does not perform these pre-processing steps.
- ConditionVoltagePockets(voltage_threshold, angle_threshold, filter_name=FilterKeyword.ALL)[source]
Finds pockets of buses with bad initial voltage estimates and conditions them.
Identifies pockets of buses bounded by branches that meet the condition that the absolute value of the voltage difference across the branch is greater than
voltage_thresholdor the absolute value of the angle difference is greater thanangle_threshold. The tool then estimates better voltages for buses in each pocket using known good values outside the pocket.- Parameters:
voltage_threshold (
float) – Per-unit voltage difference (absolute value) threshold for identifying branches that bound voltage pockets.angle_threshold (
float) – Angle difference in degrees (absolute value) threshold for identifying branches that bound voltage pockets.filter_name (
str, optional) – Filter specifying which branches to check. Defaults to “ALL”.
- DiffCaseClearBase()[source]
Clears the base case for the difference case comparison abilities of Simulator.
- DiffCaseKeyType(key_type)[source]
Changes the key type used when comparing fields in difference case mode.
- Parameters:
key_type (
str) – Key type to use:PRIMARY,SECONDARY, orLABEL.
- DiffCaseMode(mode)[source]
Changes the mode for difference case comparison.
- Parameters:
mode (
str) – Display mode:PRESENT,BASE,DIFFERENCE, orCHANGE.
- DiffCaseRefresh()[source]
Refreshes the linking between the base case and the present case.
Call this before saving data that identifies objects as being added or removed, especially if any topological differences have been made that affect the comparison.
- DiffCaseSetAsBase()[source]
Sets the present case as the base case for difference case comparison.
- DiffCaseShowPresentAndBase(show)[source]
Toggles ‘Show Present|Base in Difference and Change Mode’.
- DiffCaseWriteBothEPC(filename, ge_file_type='GE19', use_area_zone=False, base_area_zone_meet=True, append=False, export_format='', use_data_maintainer=False)[source]
Saves elements that exist in both base and present cases in GE EPC format.
- Parameters:
filename (
str) – Name of the EPC file to create.ge_file_type (
str, optional) – GE EPC file version (e.g., “GE18”, “GE19”, “PTI33”). Defaults to “GE19”.use_area_zone (
bool, optional) – If True, use Area/Zone/Owner filter. Defaults to False.base_area_zone_meet (
bool, optional) – If True, assume base case meets filters. Defaults to True.append (
bool, optional) – If True, append to existing file. Defaults to False.export_format (
str, optional) – Export format name. Defaults to “”.use_data_maintainer (
bool, optional) – If True, use Data Maintainer filter. Defaults to False.
- DiffCaseWriteCompleteModel(filename, append=False, save_added=True, save_removed=True, save_both=True, key_fields=KeyFieldType.PRIMARY, export_format='', use_area_zone=False, use_data_maintainer=False, assume_base_meet=True, include_clear_pf_aids=True, delete_branches_flip=False)[source]
Creates an auxiliary file with difference case comparison information.
Creates an auxiliary file containing information about objects that have been added or removed when comparing the present case to the base case. Fields that have changed for objects that exist in both cases can also be written. This auxiliary file can then be used to apply these same changes to other cases.
- Parameters:
filename (
str) – Name of the auxiliary file to create.append (
bool, optional) – If True, append to existing file. Defaults to False.save_added (
bool, optional) – If True, save added objects to the file. Defaults to True.save_removed (
bool, optional) – If True, save removed objects to the file. Defaults to True.save_both (
bool, optional) – If True, save changed fields for objects in both cases. Defaults to True.key_fields (
str, optional) – Key field identifiers to use:PRIMARYorSECONDARY. Defaults to “PRIMARY”.export_format (
str, optional) – Name of Auxiliary File Export Format Description to use. Defaults to “”.use_area_zone (
bool, optional) – If True, use Area/Zone/Owner filter for including objects. Defaults to False.use_data_maintainer (
bool, optional) – If True, use Data Maintainer filter. Defaults to False.assume_base_meet (
bool, optional) – If True, assume base case areas/zones/owners meet filters. Defaults to True.include_clear_pf_aids (
bool, optional) – If True, include ClearPowerFlowSolutionAidValues command. Defaults to True.delete_branches_flip (
bool, optional) – If True, treat branches with flipped bus order as removed and added. Defaults to False.
- DiffCaseWriteNewEPC(filename, ge_file_type='GE19', use_area_zone=False, base_area_zone_meet=True, append=False, use_data_maintainer=False)[source]
Saves elements that are new (added) in GE EPC format.
- Parameters:
filename (
str) – Name of the EPC file to create.ge_file_type (
str, optional) – GE EPC file version (e.g., “GE18”, “GE19”, “PTI33”). Defaults to “GE19”.use_area_zone (
bool, optional) – If True, use Area/Zone/Owner filter. Defaults to False.base_area_zone_meet (
bool, optional) – If True, assume base case meets filters. Defaults to True.append (
bool, optional) – If True, append to existing file. Defaults to False.use_data_maintainer (
bool, optional) – If True, use Data Maintainer filter. Defaults to False.
- DiffCaseWriteRemovedEPC(filename, ge_file_type='GE19', use_area_zone=False, base_area_zone_meet=True, append=False, use_data_maintainer=False)[source]
Saves elements that were removed in GE EPC format.
- Parameters:
filename (
str) – Name of the EPC file to create.ge_file_type (
str, optional) – GE EPC file version (e.g., “GE18”, “GE19”, “PTI33”). Defaults to “GE19”.use_area_zone (
bool, optional) – If True, use Area/Zone/Owner filter. Defaults to False.base_area_zone_meet (
bool, optional) – If True, assume base case meets filters. Defaults to True.append (
bool, optional) – If True, append to existing file. Defaults to False.use_data_maintainer (
bool, optional) – If True, use Data Maintainer filter. Defaults to False.
- DoCTGAction(action)[source]
Applies a contingency action without the full contingency analysis framework.
- Parameters:
action (
str) – The contingency action string to execute.
- EstimateVoltages(filter_name)[source]
Estimates voltages and angles at buses meeting the filter.
- Parameters:
filter_name (
str) – Filter specifying which buses should have their voltages estimated.
- GenForceLDC_RCC(filter_name='')[source]
Forces generators onto line drop / reactive current compensation.
- Parameters:
filter_name (
str, optional) – Filter specifying which generators to force. Defaults to all generators.
- GetMinPUVoltage()[source]
Gets the minimum per-unit voltage magnitude in the case.
- Returns:
float– The minimum p.u. voltage.
- InterfacesCalculatePostCTGMWFlows()[source]
Updates Interface MW Flow fields on Contingent Interfaces.
Calculates the post-contingency MW flows for interfaces that have contingent elements defined.
- LoadState()[source]
Loads the last saved state of the PowerWorld case.
- ResetToFlatStart()[source]
Resets all bus voltages to 1.0 per unit and angles to 0.
This is a wrapper for the
ResetToFlatStartscript command.
- SaveGenLimitStatusAction(filename)[source]
Saves Mvar information about generators to a text file.
- Parameters:
filename (
str) – Path to the output text file.
- SaveState()[source]
Saves the current state of the PowerWorld case.
This creates an unnamed snapshot of the case that can be restored later using LoadState.
- SetDoOneIteration(enable=True)[source]
Sets the ‘Do One Iteration’ power flow option.
- Parameters:
enable (
bool, optional) – If True, power flow will only perform one iteration. Defaults to True.
- SetInnerLoopCheckMVars(enable=True)[source]
Sets the ‘Check Mvar Limits Immediately’ power flow option.
- Parameters:
enable (
bool, optional) – If True, the inner loop of the power flow will check Mvar limits before proceeding to the outer loop. Defaults to True.
- SetMVATolerance(tol=0.1)[source]
Sets the MVA Tolerance for Newton-Raphson convergence.
- Parameters:
tol (
float, optional) – The MVA tolerance value. Defaults to 0.1.
- SolvePowerFlow(SolMethod=SolverMethod.RECTNEWT)[source]
Performs a single power flow solution.
If the DC method is selected, the case is switched to DC power flow mode. If one of the other AC methods is selected, the case is switched to AC power flow mode. It may be difficult to solve a case with an AC power flow method once the case has been switched to DC power flow mode.
- Parameters:
SolMethod (
Union[SolverMethod,str], optional) – The solution method to use for the power flow calculation:RECTNEWT: Rectangular Newton-Raphson (default)POLARNEWT: Polar Newton-RaphsonGAUSSSEIDEL: Gauss-SeidelFASTDEC: Fast DecoupledROBUST: Attempts the robust solution processDC: DC power flow (switches case to DC mode)
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails or the power flow does not converge.
- UpdateIslandsAndBusStatus()[source]
Updates islands and bus status without requiring a power flow solution.
Changes to branch and generator status impact islands and whether or not buses are connected. Islands and bus status are always updated at the beginning of a power flow solution if necessary, but this command makes it convenient to update this information without requiring a power flow solution.
- VoltageConditioning()[source]
Performs voltage conditioning based on the Voltage Conditioning tool options.
Uses the configured Voltage Conditioning options to improve initial voltage estimates throughout the network, which can help power flow convergence.
- ZeroOutMismatches(object_type='BUSSHUNT')[source]
Forces mismatches to zero by changing bus shunts or loads.
Bus shunts or loads are changed at each bus that has a mismatch greater than the MVA convergence tolerance so that the mismatch at that bus is forced to zero.
- Parameters:
object_type (
str, optional) – How to adjust the mismatch:BUSSHUNT: Adjust Bus Shunt fields at each bus (default)LOAD: Add a new load at each bus with mismatch (ID starting with Q1)
- class MatrixMixin[source]
- SaveJacobian(jac_filename, jid_filename, file_type='M', jac_form=JacobianForm.RECTANGULAR)[source]
Saves the Jacobian Matrix to a text file or a file formatted for use with Matlab.
- Parameters:
jac_filename (
str) – File in which to save the Jacobian.jid_filename (
str) – File to save a description of what each row and column of the Jacobian represents.file_type (
str, optional) – “M” for Matlab form, “TXT” for text file, “EXPM” for Matlab exponential form. Defaults to “M”.jac_form (
Union[JacobianForm,str], optional) – Jacobian coordinate form. Defaults to JacobianForm.RECTANGULAR.
- SaveYbusInMatlabFormat(filename, include_voltages=False)[source]
Saves the YBus to a file formatted for use with Matlab.
- get_gmatrix(full=False)[source]
Get the GIC conductance matrix (G).
This method calls the GICSaveGMatrix script command to write the G-matrix to a temporary file, then parses that file to construct the matrix in Python. The G-matrix relates GIC currents to earth potentials.
- Parameters:
full (
bool, optional) – If True, returns a dense NumPy array. If False (default), returns a SciPy CSR sparse matrix.- Returns:
Union[numpy.ndarray,scipy.sparse.csr_matrix]– The G-matrix as either a dense NumPy array or a SciPy CSR sparse matrix.- Raises:
PowerWorldError – If the SimAuto call fails or the generated file cannot be parsed.
FileNotFoundError – If the temporary matrix file is not created.
- get_gmatrix_with_ids(full=False)[source]
Get the GIC conductance matrix (G) along with the node ID mapping.
This method returns both the G-matrix and a list of node identifiers that describe what each row/column represents (substations and buses).
- Parameters:
full (
bool, optional) – If True, returns a dense NumPy array. If False (default), returns a SciPy CSR sparse matrix.- Returns:
tuple– A tuple of (G_matrix, node_ids) where: - G_matrix: The G-matrix as either dense array or sparse CSR matrix - node_ids: List of strings describing each node (e.g., “Sub 1”, “Bus 101”)
- get_jacobian(full=False, form=JacobianForm.RECTANGULAR)[source]
Get the power flow Jacobian matrix.
This method calls the SaveJacobian script command to write the Jacobian matrix to a temporary file, then parses that file to construct the matrix in Python. The Jacobian is crucial for Newton-Raphson power flow solutions and sensitivity analysis.
- Parameters:
full (
bool, optional) – If True, returns a dense NumPy array. If False (default), returns a SciPy CSR sparse matrix.form (
Union[JacobianForm,str], optional) – Jacobian coordinate form. Defaults to JacobianForm.RECTANGULAR.
- Returns:
Union[numpy.ndarray,scipy.sparse.csr_matrix]– The Jacobian matrix as either a dense NumPy array or a SciPy CSR sparse matrix.- Raises:
PowerWorldError – If the SimAuto call fails or the generated file cannot be parsed.
FileNotFoundError – If the temporary matrix file is not created.
- get_jacobian_with_ids(full=False, form=JacobianForm.RECTANGULAR)[source]
Get the power flow Jacobian matrix along with row/column ID mapping.
Returns both the Jacobian matrix and a list of identifiers describing what each row/column represents (equation type and bus number, e.g.
'dP 101','dQ 102').- Parameters:
full (
bool, optional) – If True, returns a dense NumPy array. If False (default), returns a SciPy CSR sparse matrix.form (
Union[JacobianForm,str], optional) – Jacobian coordinate form. Defaults to JacobianForm.RECTANGULAR.
- Returns:
tuple– A tuple of (jacobian_matrix, row_ids) where: - jacobian_matrix: The Jacobian as either dense array or sparse CSR matrix - row_ids: List of strings describing each row/column
- get_ybus(full=False, file=None)[source]
Obtain the YBus matrix from PowerWorld.
This method calls the SaveYbusInMatlabFormat script command to write the YBus matrix to a temporary file, then parses that file to construct the matrix in Python.
- Parameters:
full (
bool, optional) – If True, returns a dense NumPy array. If False (default), returns a SciPy CSR sparse matrix.file (
Union[str,None], optional) – Optional path to a pre-existing .mat file containing the YBus matrix. If provided, the file will be parsed directly instead of calling SimAuto to generate a new one. Defaults to None.
- Returns:
Union[numpy.ndarray,scipy.sparse.csr_matrix]– The YBus matrix as either a dense NumPy array or a SciPy CSR sparse matrix.- Raises:
PowerWorldError – If the SimAuto call fails or the generated file cannot be parsed.
Sensitivity Calculations
- class SensitivityMixin[source]
Mixin for sensitivity analysis functions.
- CalculateFlowSense(flow_element, flow_type)[source]
Calculates the sensitivity of the flow of a line or interface to bus injections.
This method determines how much the flow on a specific element changes for a unit change in injection at each bus.
- CalculateLODF(branch, method=LinearMethod.DC, post_closure_lcdf='')[source]
Calculates LODF (Line Outage Distribution Factors) for a specified branch outage.
LODFs quantify how much power flow on other branches changes when a specific branch is outaged.
- Parameters:
branch (
str) – The branch element string to outage/close (e.g., ‘[BRANCH 1 2 1]’).method (
Union[LinearMethod,str], optional) – The linear method to use for calculation (LinearMethod.DC, LinearMethod.DCPS). Defaults to LinearMethod.DC.post_closure_lcdf (
Union[YesNo,str], optional) – Optional parameter (YesNo.YES or YesNo.NO) to include LCDF (Line Closure Distribution Factor) calculation relative to post-closure flow. Defaults to “”.
- Returns:
str– The result of the script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- CalculateLODFAdvanced(include_phase_shifters, file_type, max_columns, min_lodf, number_format, decimal_points, only_increasing, filename, include_islanding=True)[source]
Performs an advanced LODF calculation with various output and filtering options.
- Parameters:
include_phase_shifters (
bool) – If True, includes phase shifters in the LODF calculation.file_type (
str) – The output file type (e.g., “CSV”, “AUX”).max_columns (
int) – Maximum number of columns in the output file.min_lodf (
float) – Minimum LODF value to report.number_format (
str) – Format for numeric output (e.g., “DECIMAL”, “PERCENT”).decimal_points (
int) – Number of decimal points for numeric output.only_increasing (
bool) – If True, only reports increasing LODF values.filename (
str) – The path to the output file.include_islanding (
bool, optional) – If True, includes islanding information in the output. Defaults to True.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
ValueError – If file_type or number_format are invalid.
Notes
This method corresponds to the CalculateLODFAdvanced script command in PowerWorld.
- CalculateLODFMatrix(which_ones, filter_process, filter_monitor, monitor_only_closed=True, linear_method=LinearMethod.DC, filter_monitor_interface='', post_closure_lcdf=True)[source]
Calculates the Line Outage Distribution Factors (LODF) matrix.
This method generates a matrix showing the impact of a set of outages/closures on a set of monitored elements.
- Parameters:
which_ones (
str) – Specifies whether to calculate for “OUTAGES” or “CLOSURES”.filter_process (
str) – A PowerWorld filter name for branches to outage/close.filter_monitor (
str) – A PowerWorld filter name for branches to monitor.monitor_only_closed (
bool, optional) – If True, only monitors initially closed branches. Defaults to True.linear_method (
Union[LinearMethod,str], optional) – The linear method to use (LinearMethod.DC or LinearMethod.DCPS). Defaults to LinearMethod.DC.filter_monitor_interface (
str, optional) – A PowerWorld filter name for interfaces to monitor. Defaults to “”.post_closure_lcdf (
bool, optional) – If True, calculates LCDF (Line Closure Distribution Factor) relative to post-closure flow. Defaults to True.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CalculateLODFScreening(filter_process, filter_monitor, include_phase_shifters, include_open_lines, use_lodf_threshold, lodf_threshold, use_overload_threshold, overload_low, overload_high, do_save_file, file_location, custom_high_lodf=0, custom_high_lodf_line=0, custom_high_overload=0, custom_high_overload_line=0, do_use_ctg_name=False, custom_orig_ctg_name=0)[source]
Performs LODF Screening calculation to identify critical outages and overloads.
This method is used to quickly assess the impact of numerous outages based on LODF and overload thresholds.
- Parameters:
filter_process (
str) – Filter for branches to outage/process.filter_monitor (
str) – Filter for branches to monitor.include_phase_shifters (
bool) – If True, includes phase shifters in the calculation.include_open_lines (
bool) – If True, includes initially open lines in the calculation.use_lodf_threshold (
bool) – If True, applies an LODF threshold for reporting.lodf_threshold (
float) – The LODF threshold value.use_overload_threshold (
bool) – If True, applies an overload threshold for reporting.overload_low (
float) – Lower bound for overload threshold (e.g., 100 for 100% limit).overload_high (
float) – Upper bound for overload threshold.do_save_file (
bool) – If True, saves the screening results to a file.file_location (
str) – The path to the output file if do_save_file is True.custom_high_lodf (
int, optional) – Custom field index for high LODF. Defaults to 0.custom_high_lodf_line (
int, optional) – Custom field index for high LODF line. Defaults to 0.custom_high_overload (
int, optional) – Custom field index for high overload. Defaults to 0.custom_high_overload_line (
int, optional) – Custom field index for high overload line. Defaults to 0.do_use_ctg_name (
bool, optional) – If True, uses contingency name in output. Defaults to False.custom_orig_ctg_name (
int, optional) – Custom field index for original contingency name. Defaults to 0.
- Returns:
- CalculateLossSense(function_type, area_ref='NO', island_ref=IslandReference.EXISTING)[source]
Calculates loss sensitivity at each bus.
Loss sensitivity indicates how much system losses change for a unit injection change at each bus.
- Parameters:
function_type (
str) – The type of function for loss calculation (e.g., “AREA”, “ZONE”, “BUS”).area_ref (
str, optional) – Area reference for calculation (“NO”, or an area name). Defaults to “NO”.island_ref (
str, optional) – Island reference for calculation (“EXISTING”, or an island name). Defaults to “EXISTING”.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CalculatePTDF(seller, buyer, method=LinearMethod.DC)[source]
Calculates the PTDF (Power Transfer Distribution Factor) values between a seller and a buyer.
PTDFs indicate how much power flow on a specific branch changes for a unit power transfer between two points in the system.
- Parameters:
seller (
str) – The seller (source) object string (e.g., ‘[AREA “Top”]’, ‘[BUS 7]’).buyer (
str) – The buyer (sink) object string (e.g., ‘[AREA “Bottom”]’, ‘[BUS 8]’).method (
Union[LinearMethod,str], optional) – The linear method to use for calculation (LinearMethod.AC, LinearMethod.DC, LinearMethod.DCPS). Defaults to LinearMethod.DC.
- Returns:
str– The result of the script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- CalculatePTDFMultipleDirections(store_branches=True, store_interfaces=True, method=LinearMethod.DC)[source]
Calculates PTDF values between all directions specified in the case.
- Parameters:
store_branches (
bool, optional) – If True, stores PTDFs for branches. Defaults to True.store_interfaces (
bool, optional) – If True, stores PTDFs for interfaces. Defaults to True.method (
Union[LinearMethod,str], optional) – The linear method to use for calculation (LinearMethod.DC, LinearMethod.AC, LinearMethod.DCPS). Defaults to LinearMethod.DC.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CalculateShiftFactors(flow_element, direction, transactor, method=LinearMethod.DC)[source]
Calculates Shift Factor Sensitivity values (formerly known as TLRs).
Shift Factors quantify how much power flow on a specific element changes for a unit injection change at a particular transactor (e.g., area, bus).
- Parameters:
flow_element (
str) – The monitored flow element string (e.g., ‘[BRANCH 1 2 1]’, ‘[INTERFACE “name”]’).direction (
str) – The direction of transfer (“BUYER” or “SELLER”).transactor (
str) – The transactor object string (e.g., ‘[AREA “Top”]’, ‘[BUS 7]’).method (
Union[LinearMethod,str], optional) – The linear method to use for calculation (LinearMethod.AC, LinearMethod.DC, LinearMethod.DCPS). Defaults to LinearMethod.DC.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CalculateShiftFactorsMultipleElement(type_element, which_element, direction, transactor, method=LinearMethod.DC)[source]
Calculates Shift Factor Sensitivity values for multiple elements.
This method extends CalculateShiftFactors to apply the calculation across a set of elements defined by type_element and which_element.
- Parameters:
type_element (
str) – The type of element to calculate shift factors for (e.g., “BRANCH”, “INTERFACE”).which_element (
str) – A PowerWorld filter name or “ALL” to specify which elements to include.direction (
str) – The direction of transfer (“BUYER” or “SELLER”).transactor (
str) – The transactor object string (e.g., ‘[AREA “Top”]’, ‘[BUS 7]’).method (
Union[LinearMethod,str], optional) – The linear method to use for calculation (LinearMethod.AC, LinearMethod.DC, LinearMethod.DCPS). Defaults to LinearMethod.DC.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CalculateTapSense(filter_name='')[source]
Forces voltage to tap sensitivity calculation.
This determines how bus voltages respond to changes in transformer tap settings.
- CalculateVoltSelfSense(filter_name='')[source]
Calculates the sensitivity of a bus’s voltage to injections at the same bus.
- CalculateVoltSense(bus_num)[source]
Calculates the sensitivity of a bus’s voltage to injections at all buses.
- CalculateVoltToTransferSense(seller, buyer, transfer_type='P', turn_off_avr=False)[source]
Calculates the sensitivity of bus voltage to power transfer between a seller and buyer.
This helps in understanding voltage impacts of inter-area power exchanges.
- Parameters:
seller (
str) – The seller (source) object string (e.g., ‘[AREA “Top”]’, ‘[BUS 7]’).buyer (
str) – The buyer (sink) object string (e.g., ‘[AREA “Bottom”]’, ‘[BUS 8]’).transfer_type (
str, optional) – The type of transfer (“P” for active power, “Q” for reactive power). Defaults to “P”.turn_off_avr (
bool, optional) – If True, turns off Automatic Voltage Regulators (AVRs) during the calculation. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- LineLoadingReplicatorCalculate(flow_element, injection_group, agc_only, desired_flow, implement, linear_method=LinearMethod.DC, use_load_min_max=True, max_mult=1.0, min_mult=1.0)[source]
Calculates injection changes required to alter a line flow to a desired value.
This tool helps in determining how to adjust generation or load to achieve a target flow on a specific element.
- Parameters:
flow_element (
str) – The flow element string (e.g., ‘[BRANCH 1 2 1]’).injection_group (
str) – The injection group string (e.g., ‘[INJECTIONGROUP “GenGroup”]’).agc_only (
bool) – If True, only considers generators participating in AGC for adjustments.desired_flow (
float) – The desired flow value on the flow_element.implement (
bool) – If True, immediately implements the calculated injection changes.linear_method (
Union[LinearMethod,str], optional) – The linear method to use (LinearMethod.DC, LinearMethod.AC). Defaults to LinearMethod.DC.use_load_min_max (
bool, optional) – If True, respects load min/max limits during adjustments. Defaults to True.max_mult (
float, optional) – Maximum multiplier for adjustments. Defaults to 1.0.min_mult (
float, optional) – Minimum multiplier for adjustments. Defaults to 1.0.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- LineLoadingReplicatorImplement()[source]
Applies the changes calculated by the Line Loading Replicator.
This action modifies the system based on the previously determined injection adjustments.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- SetSensitivitiesAtOutOfServiceToClosest(filter_name='', branch_dist_meas='')[source]
Populates sensitivity values at out-of-service buses by interpolating from the closest in-service buses.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
Contingency Analysis
- class ContingencyMixin[source]
Mixin for contingency analysis functions.
- CTGApply(contingency_name)[source]
Applies the actions defined in a contingency without solving the power flow.
This can be useful for inspecting the network topology changes caused by a contingency before running a full power flow solution.
- CTGAutoInsert()[source]
Auto-inserts contingencies based on the Ctg_AutoInsert_Options configured in PowerWorld.
Prior to calling this action, all options for this action must be specified in the Ctg_AutoInsert_Options object using the SetData method or DATA sections. This typically generates N-1 contingencies for lines, transformers, and generators.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGCalculateOTDF(seller, buyer, linear_method=LinearMethod.DC)[source]
Computes OTDFs (Outage Transfer Distribution Factors) for contingency violations.
This action first performs the same action as CalculatePTDF for the specified seller and buyer. It then goes through all the violations found by the contingency analysis tool and determines the OTDF values for the various contingency/violation pairs.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGClearAllResults()[source]
Deletes all contingency violations and any contingency comparison results from memory.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGCloneMany(filter_name='', prefix='', suffix='', set_selected=False)[source]
Creates copies of multiple contingencies based on a filter.
- Parameters:
filter_name (
str, optional) – A PowerWorld filter name to select contingencies to clone. Defaults to an empty string (all).prefix (
str, optional) – A prefix to add to the names of the cloned contingencies. Defaults to “”.suffix (
str, optional) – A suffix to add to the names of the cloned contingencies. Defaults to “”.set_selected (
bool, optional) – If True, sets the ‘Selected’ field of the cloned contingencies to YES. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGCloneOne(ctg_name, new_ctg_name='', prefix='', suffix='', set_selected=False)[source]
Creates a copy of a single existing contingency.
- Parameters:
ctg_name (
str) – The name of the contingency to clone.new_ctg_name (
str, optional) – The name for the new cloned contingency. If empty, a name is generated. Defaults to “”.prefix (
str, optional) – A prefix to add to the new contingency name. Defaults to “”.suffix (
str, optional) – A suffix to add to the new contingency name. Defaults to “”.set_selected (
bool, optional) – If True, sets the ‘Selected’ field of the cloned contingency to YES. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGComboDeleteAllResults()[source]
Deletes all results associated with contingency combination analysis.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGComboSolveAll(do_distributed=False, clear_all_results=True)[source]
Runs contingency combination analysis for all primary and regular/secondary contingencies.
This performs a more complex analysis by considering the combined impact of multiple outages.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., no primary contingencies defined).
- CTGCompareTwoListsofContingencyResults(controlling, comparison)[source]
Compares two different contingency result lists.
- CTGConvertAllToDeviceCTG(keep_original_if_empty=False)[source]
Converts breaker/disconnect contingencies to device outages.
- CTGConvertToPrimaryCTG(filter_name='', keep_original=True, prefix='', suffix='-Primary')[source]
Converts regular/secondary contingencies to Primary contingencies.
Primary contingencies are typically used as the first level of outages in a combination analysis.
- Parameters:
filter_name (
str, optional) – A PowerWorld filter name to select contingencies to convert. Defaults to an empty string (all).keep_original (
bool, optional) – If True, keeps the original contingency after conversion. Defaults to True.prefix (
str, optional) – A prefix to add to the new primary contingency name. Defaults to “”.suffix (
str, optional) – A suffix to add to the new primary contingency name. Defaults to “-Primary”.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGCreateContingentInterfaces(filter_name, max_option='')[source]
Creates an interface based on contingency violations.
This interface can then be used to monitor elements that are frequently involved in violations.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGCreateExpandedBreakerCTGs()[source]
Converts ‘Open/Close with Breakers’ actions in contingencies into explicit OPEN/CLOSE actions on individual breakers.
This can be useful for more detailed modeling of protection schemes.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGCreateStuckBreakerCTGs(filter_name='', allow_duplicates=False, prefix_name='', include_ctg_label=True, branch_field_name='', suffix_name='STK', prefix_comment='', branch_field_comment='', suffix_comment='')[source]
Creates new contingencies from existing ones that have explicit breaker outages defined, modeling ‘stuck’ breakers.
This is used to simulate scenarios where a breaker fails to operate as intended during a contingency.
- Parameters:
filter_name (
str, optional) – A PowerWorld filter name to select contingencies to process. Defaults to an empty string (all).allow_duplicates (
bool, optional) – If True, allows creation of duplicate contingencies. Defaults to False.prefix_name (
str, optional) – A prefix to add to the new contingency name. Defaults to “”.include_ctg_label (
bool, optional) – If True, includes the original contingency label in the new name. Defaults to True.branch_field_name (
str, optional) – A branch field name to use in the new contingency name. Defaults to “”.suffix_name (
str, optional) – A suffix to add to the new contingency name. Defaults to “STK”.prefix_comment (
str, optional) – A prefix to add to the new contingency comment. Defaults to “”.branch_field_comment (
str, optional) – A branch field name to use in the new contingency comment. Defaults to “”.suffix_comment (
str, optional) – A suffix to add to the new contingency comment. Defaults to “”.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGDeleteWithIdenticalActions()[source]
Deletes contingencies that have identical actions.
This helps in reducing redundancy in the contingency list.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGJoinActiveCTGs(insert_solve_pf, delete_existing, join_with_self, filename='')[source]
Creates new contingencies that are a join of the current active contingency list.
This allows for creating combined contingencies from existing ones.
- Parameters:
insert_solve_pf (
bool) – If True, inserts a SolvePowerFlow action into the new contingencies.delete_existing (
bool) – If True, deletes the original contingencies after joining.join_with_self (
bool) – If True, allows a contingency to be joined with itself (e.g., for N-2 from N-1).filename (
str, optional) – An optional filename to save the new contingencies to. Defaults to an empty string.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGPrimaryAutoInsert()[source]
Auto-inserts Primary Contingencies.
Primary contingencies are typically used as the first level of outages in a combination analysis.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGProcessRemedialActionsAndDependencies(do_delete, filter_name='')[source]
Processes Remedial Actions and their dependencies.
Remedial actions are corrective measures taken after a contingency occurs.
- CTGProduceReport(filename)[source]
Produces a text-based contingency analysis report.
- CTGReadFilePSLF(filename)[source]
Loads a file in the PSLF OTG format and creates contingencies from it.
- CTGReadFilePTI(filename)[source]
Loads a file in the PTI CON format and creates contingencies from it.
- CTGRelinkUnlinkedElements()[source]
Attempts to relink unlinked elements in the contingency records.
This action tries to re-establish connections for elements that might have become unlinked due to topology changes or data inconsistencies.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGRestoreReference()[source]
Resets the system state to the reference state for contingency analysis.
Call this action after running contingencies to restore the system to its baseline condition. The reference state is set by calling CTGSetAsReference.
This command undoes any changes made by contingency actions (e.g., line outages, generator trips) and restores all values to the pre-contingency state.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., no reference state has been set).
See also
CTGSetAsReferenceSets the current state as the reference.
CTGApplyApplies contingency actions without solving.
- CTGSaveViolationMatrices(filename, filetype, use_percentage, object_types_to_report, save_contingency, save_objects, field_list_object_type='', field_list=None, include_unsolvable_ctgs=False)[source]
Saves contingency violations in a matrix format to a file.
This provides a structured output of which contingencies cause violations on which monitored elements.
- Parameters:
filename (
str) – The path to the output file.filetype (
str) – The format of the output file (e.g., “CSVCOLHEADER”, “AUX”).use_percentage (
bool) – If True, reports violations as a percentage of the limit.object_types_to_report (
List[str]) – A list of object types for which to report violations (e.g., [“Branch”, “Bus”]).save_contingency (
bool) – If True, saves contingency information (e.g., name, status).save_objects (
bool) – If True, saves information about the monitored objects.field_list_object_type (
str, optional) – The object type for which field_list applies. Defaults to an empty string.field_list (
List[str], optional) – A list of specific fields to include for the field_list_object_type. Defaults to None.include_unsolvable_ctgs (
bool, optional) – If True, includes information about contingencies that failed to solve. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
ValueError – If field_list is provided without field_list_object_type.
- CTGSetAsReference()[source]
Sets the present system state as the reference for contingency analysis.
This baseline state is used for comparison when evaluating contingency impacts.
- Returns:
- CTGSolve(ctg_name)[source]
Runs a single defined contingency.
Executes the actions defined in a specific contingency and solves the power flow.
- CTGSolveAll(distributed=False, clear_results=True)[source]
Solves all contingencies that are not marked to be skipped.
Iterates through all active contingencies, applies their actions, and solves the power flow for each.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails or any contingency solution diverges.
- CTGSort(sort_field_list=None)[source]
Sorts the contingencies stored in Simulator’s internal data structure.
This is different than sorting contingencies in case information displays in the GUI or sorting data when it is written to an auxiliary file. Contingencies are processed in the order in which they are stored in the internal data structure, and they are not sorted by default; contingencies are added in the order in which they are created. This could be significant for other actions like CTGJoinActiveCTGs if the goal is to join contingencies alphabetically.
- Parameters:
sort_field_list (
List[str], optional) – A list of fields to sort by. If None, sorts alphabetically by contingency name. Format:["fieldname1:+:0", "fieldname2:-:1"]where + is ascending, - is descending, 0 is case insensitive, 1 is case sensitive.- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGVerifyIteratedLinearActions(filename)[source]
Creates a text file that contains validation information for iterated linear actions.
- Parameters:
filename (
str) – The path to the output text file.
- CTGWriteAllOptions(filename, key_field='PRIMARY', use_selected_data_maintainer=False, save_dependencies=False, use_area_zone_filters=False)[source]
Writes out all information related to contingency analysis using concise variable names.
This is a specialized version of CTGWriteResultsAndOptions that uses concise variable names and includes data sections by default.
- Parameters:
filename (
str) – The path to the auxiliary file where the information will be written.key_field (
str, optional) – Identifier to use for the data (“PRIMARY”, “SECONDARY”, “LABEL”). Defaults to “PRIMARY”.use_selected_data_maintainer (
bool, optional) – If True, uses the selected data maintainer. Defaults to False.save_dependencies (
bool, optional) – If True, saves contingency dependencies. Defaults to False.use_area_zone_filters (
bool, optional) – If True, applies Area/Zone filters. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGWriteAuxUsingOptions(filename, append=True)[source]
Writes out information related to contingency analysis as an auxiliary file.
- CTGWriteFilePTI(filename, bus_format='Name12', truncate_labels=True, filter_name='', append=False)[source]
Writes contingencies to a file in the PTI CON format.
- Parameters:
filename (
str) – The path to the output file.bus_format (
str, optional) – The format for bus names (“Name12”, “Number”, etc.). Defaults to “Name12”.truncate_labels (
bool, optional) – If True, truncates contingency labels. Defaults to True.filter_name (
str, optional) – A PowerWorld filter name to apply to contingencies. Defaults to an empty string (all).append (
bool, optional) – If True, appends to the file if it exists. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- CTGWriteResultsAndOptions(filename, options=None, key_field='PRIMARY', use_data_section=False, use_concise=False, use_object_ids='NO', use_selected_data_maintainer=False, save_dependencies=False, use_area_zone_filters=False)[source]
Writes out all information related to contingency analysis to an auxiliary file.
This method provides a comprehensive way to export contingency definitions, results, and options for documentation or further processing.
- Parameters:
filename (
str) – The path to the auxiliary file where the information will be written.options (
List[str], optional) – A list of specific options to include in the output. Defaults to None (all options).key_field (
str, optional) – Identifier to use for the data (“PRIMARY”, “SECONDARY”, “LABEL”). Defaults to “PRIMARY”.use_data_section (
bool, optional) – If True, includes a data section in the auxiliary file. Defaults to False.use_concise (
bool, optional) – If True, uses concise variable names in the output. Defaults to False.use_object_ids (
str, optional) – Specifies how object IDs are handled (“NO”, “YES_MS_3W”). Defaults to “NO”.use_selected_data_maintainer (
bool, optional) – If True, uses the selected data maintainer. Defaults to False.save_dependencies (
bool, optional) – If True, saves contingency dependencies. Defaults to False.use_area_zone_filters (
bool, optional) – If True, applies Area/Zone filters. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
Fault Analysis
- class FaultMixin[source]
Mixin for fault analysis functions.
- FaultAutoInsert()[source]
Inserts multiple fault definitions using the Ctg_AutoInsert_Options object.
Multiple fault definitions are inserted using the options in the Ctg_AutoInsert_Options object that are relevant for fault analysis. Faults can only be inserted for transmission lines or buses.
- FaultClear()[source]
Clears a single fault that has been calculated with the Fault command.
- FaultMultiple(use_dummy_bus=False)[source]
Runs fault analysis on a list of defined faults.
- Parameters:
use_dummy_bus (
bool, optional) – If True, dummy buses are created and inserted at the specified percent location for branch faults, and faults are calculated at the dummy buses. If False, the fault is calculated at the branch terminal bus closest to the specified location. Defaults to False.
- LoadPTISEQData(filename, version=33)[source]
Loads sequence data in the PTI format.
- RunFault(element, fault_type, r=0.0, x=0.0, location=None)[source]
Calculates fault currents for a single fault.
This method simulates a fault at a specified element and calculates the resulting currents and voltages.
- Parameters:
element (
str) – The fault element string (e.g., ‘[BUS 1]’, ‘[BRANCH 1 2 1]’).fault_type (
str) – The type of fault: “SLG” (Single Line to Ground), “LL” (Line to Line), “3PB” (Three Phase Balanced), or “DLG” (Double Line to Ground).r (
float, optional) – Fault resistance in per unit. Defaults to 0.0.x (
float, optional) – Fault reactance in per unit. Defaults to 0.0.location (
float, optional) – Percentage distance (0-100) along the branch for branch faults. Required if element is a branch. Defaults to None.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., invalid element, fault type, or location).
ATC (Available Transfer Capability)
- class ATCMixin[source]
Mixin for ATC analysis functions.
- ATCCreateContingentInterfaces(filter_name='')[source]
Creates an interface based on Transfer Limiter results from an ATC run.
Each Transfer Limiter is comprised of a Limiting Element/Contingency pair. Each interface is then created with contingent elements from the contingency and the Limiting Element included as the monitored element.
- Parameters:
filter_name (
str, optional) – The name of an Advanced Filter. Only objects of type TransferLimiter that meet the named filter will be used to create new interfaces. If blank, all transfer limiters will be used. Defaults to “”.
- ATCDataWriteOptionsAndResults(filename, append=True, key_field=KeyFieldType.PRIMARY)[source]
Writes out all information related to ATC analysis to an auxiliary file.
Saves the same information as the ATCWriteResultsAndOptions script command. The auxiliary file is formatted using the concise format for DATA section headers and variable names. Data is written using DATA sections instead of SUBDATA sections.
Note: This command was named ATCWriteAllOptions prior to December 2021.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- ATCDeleteAllResults()[source]
Deletes all ATC results including TransferLimiter, ATCExtraMonitor, and ATCFlowValue object types.
- ATCDeleteScenarioChangeIndexRange(scenario_change_type, index_range)[source]
Deletes entries within an ATC scenario change type by index.
ATC scenarios are defined by RL (line rating and zone load), G (generator), and I (interface rating) changes.
- Parameters:
scenario_change_type (
str) – “RL”, “G”, or “I” to indicate the scenario change type to delete.index_range (
List[str]) – Comma-delimited list of integer ranges (e.g., [“0-2”, “5”, “7-9”]). The indices start at 0.
- ATCDetermine(seller, buyer, distributed=False, multiple_scenarios=False)[source]
Calculates Available Transfer Capability (ATC) between a specified seller and buyer.
This method initiates an ATC calculation, ramping transfer between the seller and buyer until a system limit is reached.
- Parameters:
seller (
str) – The source object string (e.g., ‘[AREA “Top”]’, ‘[BUS 1]’).buyer (
str) – The sink object string (e.g., ‘[AREA “Bottom”]’, ‘[BUS 2]’).distributed (
bool, optional) – If True, uses the distributed ATC solution method. Defaults to False.multiple_scenarios (
bool, optional) – If True, processes each defined scenario in the case. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., invalid seller/buyer, calculation error).
- ATCDetermineATCFor(rl, g, i, apply_transfer=False)[source]
Determines the ATC for a specific Scenario RL, G, I.
- ATCDetermineMultipleDirections(distributed=False, multiple_scenarios=False)[source]
Calculates ATC for all directions defined within the PowerWorld case.
This method is used when multiple transfer directions have been pre-configured in the Simulator.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., no directions defined, calculation error).
- ATCDetermineMultipleDirectionsATCFor(rl, g, i)[source]
Determines the ATC for Scenario RL, G, I for all defined directions.
- ATCIncreaseTransferBy(amount)[source]
Increases the transfer between the seller and buyer by a specified amount.
- ATCRestoreInitialState()[source]
Restores the initial state for the ATC tool.
Call this action to restore the system to its state before any ATC calculations were performed.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- ATCSetAsReference()[source]
Sets the present system state as the reference state for ATC analysis.
This baseline state is used as the starting point for ATC calculations.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- ATCTakeMeToScenario(rl, g, i)[source]
Sets the present case according to the scenarios along the RL, G, and I axes.
All three parameters must be specified as integers indicating the index of the respective scenario. Indices start at 0.
- ATCWriteAllOptions(filename, append=True, key_field=KeyFieldType.PRIMARY)[source]
Writes out all information related to ATC analysis (deprecated name).
Deprecated since version Use: ATCDataWriteOptionsAndResults instead. This method was renamed in the December 9, 2021 patch of Simulator 22.
- ATCWriteResultsAndOptions(filename, append=True)[source]
Writes out all information related to ATC analysis to an auxiliary file.
This includes Contingency Definitions, Remedial Action Definitions, Limit Monitoring Settings, Solution Options, ATC Options, ATC results, as well as any Model Criteria that are used by the Contingency and Remedial Action Definitions.
- ATCWriteScenarioLog(filename, append=False, filter_name='')[source]
Writes out detailed log information for ATC Multiple Scenarios to a text file.
If no scenarios have been defined, no file will be created; this is not treated as a fatal error.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- ATCWriteScenarioMinMax(filename, filetype=FileFormat.CSV, append=False, fieldlist=None, operation='MIN', operation_field='TransferLimit', group_scenario='NONE')[source]
Writes out TransferLimiter results from multiple scenario ATC calculations.
The results are grouped based on the input parameters, and the minimum, maximum, or minimum and maximum limiter from each group is written to file.
- Parameters:
filename (
str) – Name of output file.filetype (
str, optional) – Output format: “AUX”, “AUXCSV”, “CSV”, “CSVNOHEADER”, “CSVCOLHEADER”. Defaults to “CSV”.append (
bool, optional) – If True, appends to existing file. Defaults to False.fieldlist (
List[str], optional) – List of fields to save. Defaults to None.operation (
str, optional) – Operation to perform on each grouping: “MIN”, “MAX”, or “MINMAX”. Defaults to “MIN”.operation_field (
str, optional) – Field to use for the min/max operation. Must be “TransferLimit” or “ATCExtraMonitor”. Defaults to “TransferLimit”.group_scenario (
str, optional) – How to group scenarios. Use “NONE” to not group, or a scenario type name. Defaults to “NONE”.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- ATCWriteToExcel(worksheet_name, fieldlist=None)[source]
Sends ATC analysis results to an Excel spreadsheet for Multiple Scenarios ATC analysis.
- ATCWriteToText(filename, filetype=FileFormat.TAB, fieldlist=None)[source]
Writes Multiple Scenario ATC analysis results to text files.
- GetATCResults(fields=None)[source]
Retrieves Transfer Limiter results from the case after an ATC calculation.
This method fetches the detailed results of the ATC analysis, including the maximum flow, limiting contingency, and limiting element.
- Parameters:
fields (
List[str], optional) – A list of internal field names to retrieve for the ‘TransferLimiter’ object type. If None, a default set of common fields is retrieved.- Returns:
pandas.DataFrame– A DataFrame containing the requested data for ‘TransferLimiter’ objects.- Raises:
PowerWorldError – If the SimAuto call fails.
GIC (Geomagnetically Induced Current)
- class GICMixin[source]
Mixin for GIC analysis functions.
- GICCalculate(max_field, direction, solve_pf=True)[source]
Calculates the ‘Single Snapshot’ GIC solution for a uniform electric field.
This method computes Geomagnetically Induced Currents (GIC) based on a specified electric field magnitude and direction.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., GIC not enabled, invalid parameters).
- GICClear()[source]
Clears GIC (Geomagnetically Induced Current) values from the case.
This is a wrapper for the
GICClearscript command.- Returns:
- GICLoad3DEfield(file_type, filename, setup_on_load=True)[source]
Loads GIC data, including time-varying electric fields, from a specified file.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails (e.g., file not found, invalid format).
- GICReadFilePSLF(filename)[source]
Reads GIC supplemental data from a GMD text file format.
- Parameters:
filename (
str,) – The name (path) of the file to be loaded, typically with a .GMD extension.- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- GICReadFilePTI(filename)[source]
Reads GIC supplemental data from a GIC text file format.
- Parameters:
filename (
str,) – The name (path) of the file to be loaded, typically with a .GIC extension.- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- GICSaveGMatrix(gmatrix_filename, gmatrix_id_filename)[source]
Saves the GMatrix used with the GIC calculations in a file formatted for use with Matlab.
The G-matrix represents the network’s conductance properties relevant to GIC.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- GICSetupTimeVaryingSeries(start=0.0, end=0.0, delta=0.0)[source]
Creates a set of Branch series DC input voltages for time-varying GIC analysis.
This is done from the Active Event(s) in the “Time-Varying Electric Field Inputs” Calculation Mode.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- GICShiftOrStretchInputPoints(lat_shift=0.0, lon_shift=0.0, mag_scalar=1.0, stretch_scalar=1.0, update_time_varying_series=False)[source]
Scales, shifts, or stretches the active set of Time Varying Electric Field Inputs.
This allows for adjusting the geographic and magnitude characteristics of the time-varying electric field model.
- Parameters:
lat_shift (
float, optional) – Latitude Shift in degrees. Defaults to 0.0.lon_shift (
float, optional) – Longitude Shift in degrees. Defaults to 0.0.mag_scalar (
float, optional) – E-Field Magnitude scalar multiplier. Defaults to 1.0.stretch_scalar (
float, optional) – Geographic Stretch scalar multiplier. Defaults to 1.0.update_time_varying_series (
bool, optional) – If True, updates the time-varying voltage input values after the shift/stretch. Defaults to False.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- GICTimeVaryingAddTime(new_time)[source]
Adds a new time point to the time-varying voltage input series.
- GICTimeVaryingCalculate(the_time, solve_pf=True)[source]
Calculates GIC values using the ‘Time-Varying Series Voltage Inputs’ calculation mode.
This method is used for dynamic GIC analysis where the electric field varies over time.
- GICTimeVaryingDeleteAllTimes()[source]
Deletes all input time-varying voltage input values.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- GICTimeVaryingEFieldCalculate(the_time, solve_pf=True)[source]
Calculates GIC Values using the ‘Time-Varying Electric Field Inputs’ calculation mode.
- GICTimeVaryingElectricFieldsDeleteAllTimes()[source]
Clears all time-varying electric field input values.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- GICWriteFilePSLF(filename, use_filters=False)[source]
Writes GIC supplemental data to a GMD text file format (PSLF).
- GICWriteFilePTI(filename, use_filters=False, version=4)[source]
Writes GIC supplemental data to a GIC text file format (PTI).
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
- GICWriteOptions(filename, key_field=KeyFieldType.PRIMARY)[source]
Writes the current GIC solution options to an auxiliary file.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails.
OPF (Optimal Power Flow) and SCOPF
- class OPFMixin[source]
Mixin for OPF analysis functions.
- InitializePrimalLP(on_success_aux='', on_fail_aux='', create_if_not_found1=False, create_if_not_found2=False)[source]
Clears all structures and results of previous primal LP OPF solutions.
This prepares the system for a new OPF calculation.
- OPFWriteResultsAndOptions(filename)[source]
Writes out all information related to OPF analysis to an auxiliary file.
- SolveFullSCOPF(bc_method='OPF', on_success_aux='', on_fail_aux='', create_if_not_found1=False, create_if_not_found2=False)[source]
Performs a full Security Constrained Optimal Power Flow (SCOPF).
SCOPF finds the least-cost dispatch that satisfies both base-case and contingency constraints.
- Parameters:
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails or the SCOPF does not converge.
- SolvePrimalLP(on_success_aux='', on_fail_aux='', create_if_not_found1=False, create_if_not_found2=False)[source]
Attempts to solve a primal linear programming optimal power flow (LP OPF).
This method finds the least-cost generation dispatch while satisfying system constraints.
- Parameters:
on_success_aux (
str, optional) – Auxiliary file to load if the solution is successful.on_fail_aux (
str, optional) – Auxiliary file to load if the solution is NOT successful.create_if_not_found1 (
bool, optional) – If True, creates objects from on_success_aux if they don’t exist.create_if_not_found2 (
bool, optional) – If True, creates objects from on_fail_aux if they don’t exist.
- Returns:
- Raises:
PowerWorldError – If the SimAuto call fails or the OPF does not converge.
- SolveSinglePrimalLPOuterLoop(on_success_aux='', on_fail_aux='', create_if_not_found1=False, create_if_not_found2=False)[source]
Performs a single optimization iteration of LP OPF.
This is typically used in iterative solution schemes.
PV Analysis
- class PVMixin[source]
Mixin for PV analysis functions.
- PVClear()[source]
Clear all results of the PV (Power-Voltage) study.
This removes all computed results from a previous PV analysis, allowing a fresh study to be performed.
This is a wrapper for the
PVClearscript command.- Returns:
str– The response from the PowerWorld script command.
- PVDataWriteOptionsAndResults(filename, append=True, key_field=KeyFieldType.PRIMARY)[source]
Write all PV analysis information to an auxiliary file.
Saves the same information as
PVWriteResultsAndOptionsbut uses the concise format for DATA section headers and variable names. Data is written using DATA sections instead of SUBDATA sections.This is a wrapper for the
PVDataWriteOptionsAndResultsscript command.- Parameters:
filename (
str) – Name of the auxiliary file to save.append (
bool, optional) – If True, appends results to existing file. If False, overwrites the file. Defaults to True.key_field (
str, optional) – Identifier to use for data. Valid values are “PRIMARY” (bus numbers and primary key fields), “SECONDARY” (bus name and nominal kV), or “LABEL” (device labels). Defaults to “PRIMARY”.
- Returns:
str– The response from the PowerWorld script command.
- PVDestroy()[source]
Destroy the PV study and release resources.
This removes all results and prevents any restoration of the initial state that is stored with the PV study. Use this when you are finished with a PV analysis and want to free memory.
This is a wrapper for the
PVDestroyscript command.- Returns:
str– The response from the PowerWorld script command.
- PVQVTrackSingleBusPerSuperBus()[source]
Reduce monitored buses to one per super bus.
If the topology processing add-on is installed, this examines each monitored value for each bus, determines if that bus is part of a super bus, and selects monitored buses so that only the pnode is monitored. This reduces computational overhead for PV/QV studies.
This is a wrapper for the
PVQVTrackSingleBusPerSuperBusscript command.- Returns:
str– The response from the PowerWorld script command.
- PVRun(source, sink)[source]
Start a PV (Power-Voltage) analysis.
PV analysis incrementally transfers power from a source to a sink to determine the system’s voltage stability limits. The analysis increases the transfer until voltage collapse occurs or limits are reached.
This is a wrapper for the
PVRunscript command.- Parameters:
- Returns:
str– The response from the PowerWorld script command.
- PVSetSourceAndSink(source, sink)[source]
Specify the source and sink elements for the PV study.
Sets up the injection groups that define where power will be incrementally injected (source) and withdrawn (sink) during the PV analysis.
This is a wrapper for the
PVSetSourceAndSinkscript command.- Parameters:
- Returns:
str– The response from the PowerWorld script command.
- PVStartOver()[source]
Start over the PV study from the initial state.
This clears the activity log, clears results, restores the initial state, sets the current state as the new initial state, and initializes the step size. Use this to reset a PV study without destroying it completely.
This is a wrapper for the
PVStartOverscript command.- Returns:
str– The response from the PowerWorld script command.
- PVWriteInadequateVoltages(filename, append=True, inadequate_type='LOW')[source]
Save PV inadequate voltages to a CSV file.
Exports buses with voltage violations identified during the PV study to a CSV file. This helps identify which buses are most vulnerable to voltage collapse.
This is a wrapper for the
PVWriteInadequateVoltagesscript command.- Parameters:
filename (
str) – Name of the CSV file to save.append (
bool, optional) – If True, appends data to existing file. If False, overwrites the file. Defaults to True.inadequate_type (
str, optional) – Type of inadequate voltages to save. Valid values are “LOW” (undervoltage), “HIGH” (overvoltage), or “BOTH”. Defaults to “LOW”.
- Returns:
str– The response from the PowerWorld script command.
- PVWriteResultsAndOptions(filename, append=True)[source]
Write all PV analysis information to an auxiliary file.
Exports complete PV analysis data including Contingency Definitions, Remedial Action Definitions, Solution Options, PV Options, PV results, ATC Extra Monitors, and any Model Criteria used by the Contingency and Remedial Action Definitions.
Dependencies for the PV setup are also included, such as Injection Groups used as seller/buyer and Interfaces used for interface ramping.
This is a wrapper for the
PVWriteResultsAndOptionsscript command.
- RefineModel(object_type, filter_name, action, tolerance)[source]
Refine the system model to fix modeling idiosyncrasies.
This command helps prepare a model for voltage stability analysis by addressing common modeling issues that may cause numerical problems or unrealistic results.
This is a wrapper for the
RefineModelscript command.- Parameters:
- Returns:
str– The response from the PowerWorld script command.
QV Analysis
- class QVMixin[source]
Mixin for QV analysis functions.
- QVDataWriteOptionsAndResults(filename, append=True, key_field=KeyFieldType.PRIMARY)[source]
Write all QV analysis information to an auxiliary file.
Saves the same information as
QVWriteResultsAndOptionsbut uses the concise format for DATA section headers and variable names. Data is written using DATA sections instead of SUBDATA sections.This is a wrapper for the
QVDataWriteOptionsAndResultsscript command.- Parameters:
filename (
str) – Name of the auxiliary file to save.append (
bool, optional) – If True, appends results to existing file. If False, overwrites. Defaults to True.key_field (
str, optional) – Identifier to use for data. “PRIMARY” uses bus numbers and primary key fields. “SECONDARY” uses bus name and nominal kV. “LABEL” uses device labels. Defaults to “PRIMARY”.
- Returns:
str– The response from the PowerWorld script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- QVDeleteAllResults()[source]
Delete all QV results from memory.
Removes all QV analysis results including QVCurve and PWQVResultListContainer object types. Use this to free memory after QV analysis is complete.
This is a wrapper for the
QVDeleteAllResultsscript command.- Returns:
str– The response from the PowerWorld script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- QVRun(filename=None, make_base_solvable=True, write_case_after_solve=False)[source]
Run a QV (Reactive Power-Voltage) analysis.
Performs a QV study for buses whose QVSELECTED field is set to YES. QV analysis varies reactive power injection at monitored buses to determine voltage stability margins. The analysis produces QV curves showing the relationship between reactive power and voltage.
This is a wrapper for the
QVRunscript command.- Parameters:
filename (
str, optional) – Path to a CSV file to save results. If None, a temporary file is used and results are returned as a DataFrame. Defaults to None.make_base_solvable (
bool, optional) – If True, attempts to fix the base case if it is not solvable before running the QV analysis. Defaults to True.write_case_after_solve (
bool, optional) – If True, writes the case file after each QV solve point. Defaults to False.
- Returns:
pandas.DataFrameorNone– If filename is None, returns a DataFrame containing the QV analysis results (voltage vs. reactive power for each bus). Otherwise, returns None.- Raises:
PowerWorldError – If the SimAuto call fails or the QV analysis does not complete.
- QVSelectSingleBusPerSuperBus()[source]
Reduce monitored QV buses to one per pnode (super bus).
When using QV analysis on a full topology model, this modifies the monitored buses so that only one bus is monitored for each pnode. This simplifies analysis and reduces computational load by focusing on representative buses.
This is a wrapper for the
QVSelectSingleBusPerSuperBusscript command.- Returns:
str– The response from the PowerWorld script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- QVWriteCurves(filename, include_quantities=True, filter_name='', append=False)[source]
Save QV curve points to a CSV file.
Exports the QV curve data (voltage vs. reactive power points) for each monitored bus to a comma-separated file.
This is a wrapper for the
QVWriteCurvesscript command.- Parameters:
filename (
str) – Name of the CSV file to save.include_quantities (
bool, optional) – If True, includes any Quantities to Track along with the QV curve points. Defaults to True.filter_name (
str, optional) – Filter applied to QVCurve objects. Empty string selects all curve results. Note: AREAZONE filtering is ignored for QVCurve. Defaults to “” (all curves).append (
bool, optional) – If True, appends data to existing file. If False, overwrites. Defaults to False.
- Returns:
str– The response from the PowerWorld script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- QVWriteResultsAndOptions(filename, append=True)[source]
Write all QV analysis information to an auxiliary file.
Exports complete QV analysis data including Contingency Definitions, Remedial Action Definitions, Solution Options, QV Options, QV results, and any Model Criteria used by Contingency and Remedial Action Definitions.
Dependencies are saved along with definitions, including: Model Conditions, Model Filters, Model Planes, Model Expressions, Model Result Overrides, Interfaces, Injection Groups, Calculated Fields, and Expressions.
This is a wrapper for the
QVWriteResultsAndOptionsscript command.
Regions
- class RegionsMixin[source]
Mixin for Regions functions.
- RegionLoadShapefile(filename, class_name, attribute_names, add_to_open_onelines=False, display_style_name='', delete_existing=False)[source]
Loads shapes from a shapefile.
- Parameters:
filename (
str) – Path to the shapefile.class_name (
str) – The object class to associate with the shapes.attribute_names (
List[str]) – List of attribute names to map.add_to_open_onelines (
bool, optional) – If True, adds shapes to open onelines. Defaults to False.display_style_name (
str, optional) – Name of the display style to use. Defaults to “”.delete_existing (
bool, optional) – If True, deletes existing objects of this class. Defaults to False.
- Returns:
str– The response from the PowerWorld script command.
- RegionRename(old_name, new_name, update_onelines=True)[source]
Renames an existing region.
- RegionRenameClass(old_class, new_class, update_onelines=True, filter_name='')[source]
Changes the class name of regions.
- RegionRenameProper1(old_prop, new_prop, update_onelines=True, filter_name='')[source]
Changes the proper1 name of regions.
- Parameters:
- Returns:
str– The response from the PowerWorld script command.
- RegionRenameProper12Flip(update_onelines=True, filter_name='')[source]
Flips proper1 and proper2 names.
- RegionRenameProper2(old_prop, new_prop, update_onelines=True, filter_name='')[source]
Changes the proper2 name of regions.
- Parameters:
- Returns:
str– The response from the PowerWorld script command.
TS (Transient Stability)
- class TransientMixin[source]
- TSAutoCorrect()[source]
Runs auto correction of parameters for transient stability.
Attempts to automatically fix common model parameter issues.
- TSAutoInsertDistRelay(reach, add_from, add_to, transfer_trip, shape, filter_name)[source]
Inserts DistRelay models on the lines meeting the specified filter.
- TSAutoInsertZPOTT(reach, filter_name)[source]
Inserts ZPOTT models on the lines meeting the specified filter.
- TSAutoSavePlots(plot_names, ctg_names, image_type='JPG', width=800, height=600, font_scalar=1.0, include_case_name=False, include_category=False)[source]
Create and save images of the plots.
- TSCalculateCriticalClearTime(element_or_filter)[source]
Calculate critical clearing time for faults.
- TSCalculateSMIBEigenValues()[source]
Calculate single machine infinite bus eigenvalues.
- TSClearAllModels()[source]
Clears all transient stability models from the case.
- TSClearModelsforObjects(object_type, filter_name='')[source]
Deletes all transient stability models associated with the objects that meet the filter.
- TSClearPlayInSignals()[source]
Deletes all defined PlayIn signals.
This is a wrapper for the
DELETE(PLAYINSIGNAL)script command.
- TSClearResultsFromRAM(ctg_name='ALL', clear_summary=True, clear_events=True, clear_statistics=True, clear_time_values=True, clear_solution_details=True)[source]
Clears all transient stability results from RAM.
This is useful for managing memory when running many simulations.
This is a wrapper for the
TSClearResultsFromRAMscript command.
- TSClearResultsFromRAMAndDisableStorage()[source]
Disables result storage in RAM and clears any existing results.
This is a convenience method that calls
TSResultStorageSetAll(value=False)followed byTSClearResultsFromRAM().
- TSDisableMachineModelNonZeroDerivative(threshold=0.001)[source]
Disable machine models with non-zero state derivatives.
- TSGetResults(mode, contingencies, plots_fields, filename=None, start_time=None, end_time=None)[source]
Retrieves transient stability results.
If filename is None, creates a temporary file, reads the results into DataFrames, deletes the temporary files, and returns (meta, data).
- TSGetVCurveData(filename, filter_name)[source]
Generates V-curve data for synchronous generators.
- TSInitialize()[source]
Initializes the transient stability simulation parameters.
This command must be called before solving a transient stability run. It prepares the simulation engine with the model data.
This is a wrapper for the
TSInitializescript command.
- TSJoinActiveCTGs(time_delay, delete_existing, join_with_self, filename='', first_ctg='Both')[source]
Joins two lists of TSContingency objects.
- TSLoadBPA(filename)[source]
Loads transient stability data stored in the BPA format.
- Parameters:
filename (
str) – Path to the BPA file to load.
- TSLoadGE(filename)[source]
Loads transient stability data stored in the GE DYD format.
- Parameters:
filename (
str) – Path to the GE DYD file to load.
- TSLoadPTI(filename)[source]
Loads transient stability data in the PTI DYR format.
- Parameters:
filename (
str) – Path to the PTI DYR file to load.
- TSLoadRDB(filename, model_type, filter_name='')[source]
Loads a SEL RDB file.
- TSLoadRelayCSV(filename, model_type, filter_name='')[source]
Loads relay data from CSV.
- TSPlotSeriesAdd(plot_name, sub_plot_num, axis_group_num, object_type, field_name, filter_name='', attributes='')[source]
Adds one or multiple plot series to a new or existing plot definition.
- TSResultStorageSetAll(object='ALL', value=True)[source]
Sets the ‘Store results in RAM’ flag for all objects of a given type.
This is a wrapper for the
TSResultStorageSetAllscript command.
- TSRunResultAnalyzer(ctg_name='')[source]
Run the Transient Result Analyzer.
- TSRunUntilSpecifiedTime(ctg_name, stop_time=None, step_size=0.25, steps_in_cycles=True, reset_start_time=False, steps_to_do=0)[source]
Allows manual control of the transient stability run.
- TSSaveBPA(filename, diff_case_modified_only=False)[source]
Saves transient stability data in the BPA IPF format.
- TSSaveDynamicModels(filename, file_type='AUX', object_type='', filter_name='', append=False)[source]
Save dynamics models for specified object types to file.
- TSSaveGE(filename, diff_case_modified_only=False)[source]
Saves transient stability data in the GE DYD format.
- TSSavePTI(filename, diff_case_modified_only=False)[source]
Saves transient stability data in the PTI DYR format.
- TSSaveTwoBusEquivalent(filename, bus_identifier)[source]
Save the two bus equivalent model of a specified bus to a PWB file.
- TSSetPlayInSignals(name, times, signals)[source]
Sets PlayIn signals using an AUX file command.
This method constructs and executes an AUX data block to define transient stability play-in signals.
- Parameters:
name – Name of the PlayIn Signal configuration.
times – 1D NumPy array of time points.
signals – 2D NumPy array of signal values (rows=time, cols=signals).
- TSSetSelectedForTransientReferences(set_what, set_how, object_types, model_types)[source]
Set the Custom Integer field or Selected field for objects referenced in a transient stability model.
- TSSolve(ctgname, start_time=None, stop_time=None, step_size=None, step_in_cycles=False)[source]
Solves a single transient stability contingency.
This is a wrapper for the
TSSolvescript command.- Parameters:
ctgname (
str) – The name of the contingency to solve.start_time (
float, optional) – Start time in seconds. Overrides the contingency’s property.stop_time (
float, optional) – Stop time in seconds. Overrides the contingency’s property.step_size (
float, optional) – Step size (in seconds unless step_in_cycles is True). Overrides the contingency’s property.step_in_cycles (
bool, optional) – If True, step_size is interpreted as cycles rather than seconds. Defaults to False.
- TSSolveAll()[source]
Solves all defined transient contingencies that are not set to skip.
Distributed computing is not enabled by default.
- TSStoreResponse(object_type='ALL', value=True)[source]
Convenience wrapper to toggle transient stability result storage.
This is a high-level wrapper around
TSResultStorageSetAll.
- TSTransferStateToPowerFlow(calculate_mismatch=False)[source]
Transfers the transient stability state to the power flow.
After running a transient stability simulation, this allows the state of the system at the final time step to be loaded into the power flow solver for steady-state analysis.
- Parameters:
calculate_mismatch (
bool, optional) – If True, calculates power mismatch when transferring transient state to the power flow case. Defaults to False (no mismatch calculation).
- TSValidate()[source]
Validates transient stability models and input values.
Useful for examining model errors and warnings when preparing a case for analysis. Validation is done automatically when running transient analysis, so this command does not need to be run manually prior to analysis.
- TSWriteModels(filename, diff_case_modified_only=False)[source]
Saves transient stability dynamic model records to an auxiliary file.
- TSWriteOptions(filename, save_dynamic_model=True, save_stability_options=True, save_stability_events=True, save_results_events=True, save_plot_definitions=True, save_transient_limit_monitors=True, save_result_analyzer_time_window=True, key_field=KeyFieldType.PRIMARY)[source]
Save transient stability option settings to an auxiliary file.
Scheduled Actions
- class ScheduledActionsMixin[source]
Mixin for Scheduled Actions functions.
- ApplyScheduledActionsAt(start_time, end_time='', filter_name='', revert=False)[source]
Applies scheduled actions active during the specified time window.
Scheduled actions are predefined changes (e.g., opening/closing branches, changing generation) that occur at specific times.
- Parameters:
start_time (
str) – The start time of the window (e.g., “01/01/2025 10:00”).end_time (
str, optional) – The end time of the window. If empty, only actions at start_time are applied. Defaults to “”.filter_name (
str, optional) – A PowerWorld filter name to apply to scheduled actions. Defaults to an empty string (all).revert (
bool, optional) – If True, reverts the actions instead of applying them. Defaults to False.
- Returns:
str– The result of the script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- IdentifyBreakersForScheduledActions(identify_from_normal=True)[source]
Identifies breakers for scheduled actions.
This action helps in setting up scheduled actions that involve breaker operations.
- RevertScheduledActionsAt(start_time, end_time='', filter_name='')[source]
Reverts scheduled actions that were active during the specified time window.
This undoes the changes made by ApplyScheduledActionsAt.
- Parameters:
start_time (
str) – The start time of the window (e.g., “01/01/2025 10:00”).end_time (
str, optional) – The end time of the window. If empty, only actions at start_time are reverted. Defaults to “”.filter_name (
str, optional) – A PowerWorld filter name to apply to scheduled actions. Defaults to an empty string (all).
- Returns:
str– The result of the script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- ScheduledActionsSetReference()[source]
Sets the current system state as the reference for scheduled actions.
This reference state is used when applying or reverting scheduled actions to ensure a consistent baseline.
- Returns:
str– The result of the script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- SetScheduleView(view_time, apply_actions=None, use_normal_status=None, apply_window=None)[source]
Sets the View Time for Scheduled Actions.
This allows viewing the system state at a specific point in time, considering all scheduled actions up to that point.
- Parameters:
view_time (
str) – The specific time to view (e.g., “01/01/2025 10:00”).apply_actions (
bool, optional) – If True, applies scheduled actions up to view_time. Defaults to None (uses current setting).use_normal_status (
bool, optional) – If True, uses normal status for elements. Defaults to None (uses current setting).apply_window (
bool, optional) – If True, applies the scheduled window. Defaults to None (uses current setting).
- Returns:
str– The result of the script command.- Raises:
PowerWorldError – If the SimAuto call fails.
- SetScheduleWindow(start_time, end_time, resolution=None, resolution_units=None)[source]
Defines the window of interest for Scheduled Actions.
This sets the time range and resolution for displaying or processing scheduled actions.
- Parameters:
start_time (
str) – The start time of the window (e.g., “01/01/2025 00:00”).end_time (
str) – The end time of the window (e.g., “02/01/2025 00:00”).resolution (
float, optional) – The time step resolution for the window (e.g., 1.0). Defaults to None.resolution_units (
str, optional) – The units for the resolution (“HOURS”, “MINUTES”, “SECONDS”). Defaults to None.
- Returns:
str– The result of the script command.- Raises:
PowerWorldError – If the SimAuto call fails.
Time Step Simulation
- class TimeStepMixin[source]
Mixin for Time Step Simulation functions.
- TIMESTEPSaveInputCSV(filename, field_list, start_time='', end_time='')[source]
Saves input fields to CSV.
- Returns:
str– The result of the script command.
- TIMESTEPSaveSelectedModifyFinish()[source]
Finishes modification of selected objects for saving.
- Returns:
str– The result of the script command.
- TIMESTEPSaveSelectedModifyStart()[source]
Starts modification of selected objects for saving.
- Returns:
str– The result of the script command.
- TimeStepAppendPWW(filename, solution_type='Single Solution')[source]
Appends a PWW file to the Time Step Simulation.
- TimeStepAppendPWWRange(filename, start_time, end_time, solution_type='Single Solution')[source]
Appends a range of timepoints from a PWW file.
- TimeStepAppendPWWRangeLatLon(filename, start_time, end_time, min_lat, max_lat, min_lon, max_lon, solution_type='Single Solution')[source]
Appends a range of timepoints with geographic filtering.
- Returns:
str– The result of the script command.
- TimeStepClearResults(start_time='', end_time='')[source]
Clears Time Step Simulation results.
- TimeStepDeleteAll()[source]
Deletes all time points.
- Returns:
str– The result of the script command.
- TimeStepDoRun(start_time='', end_time='')[source]
Solves the Time Step Simulation.
- TimeStepDoSinglePoint(time_point)[source]
Solves the Time Step Simulation for a single point.
- TimeStepLoadB3D(filename, solution_type='GIC Only (No Power Flow)')[source]
Loads a B3D file.
- Returns:
str– The result of the script command.
- TimeStepLoadPWW(filename, solution_type='Single Solution')[source]
Loads a PWW file into the Time Step Simulation.
- TimeStepLoadPWWRange(filename, start_time, end_time, solution_type='Single Solution')[source]
Loads a range of timepoints from a PWW file.
- Returns:
str– The result of the script command.
- TimeStepLoadPWWRangeLatLon(filename, start_time, end_time, min_lat, max_lat, min_lon, max_lon, solution_type='Single Solution')[source]
Loads a range of timepoints with geographic filtering.
- Returns:
str– The result of the script command.
- TimeStepLoadTSB(filename)[source]
Loads a TSB file.
- Returns:
str– The result of the script command.
- TimeStepResetRun()[source]
Resets the run to the beginning.
- Returns:
str– The result of the script command.
- TimeStepSaveFieldsClear(object_types=None)[source]
Clears save fields for object types.
- Parameters:
object_types (
List[str], optional) – List of object types. If None, clears all.- Returns:
str– The result of the script command.
- TimeStepSaveFieldsSet(object_type, field_list, filter_name=FilterKeyword.ALL)[source]
Sets fields to save during simulation.
- TimeStepSavePWW(filename)[source]
Saves existing weather data to a PWW file.
- Returns:
str– The result of the script command.
- TimeStepSavePWWRange(filename, start_time, end_time)[source]
Saves a range of weather data to a PWW file.
- Returns:
str– The result of the script command.
- TimeStepSaveResultsByTypeCSV(object_type, filename, start_time='', end_time='')[source]
Saves results for a specific object type to CSV.
Weather
- class WeatherMixin[source]
Mixin for Weather functions.
- TemperatureLimitsBranchUpdate(rating_set_precedence='NORMAL', normal_rating_set='DEFAULT', ctg_rating_set='DEFAULT')[source]
Update branch limits based on temperature limit curves.
Updates branch thermal limits using temperature limit curves and weather station temperature data. This allows for dynamic line rating based on ambient conditions.
This is a wrapper for the
TemperatureLimitsBranchUpdatescript command.- Parameters:
rating_set_precedence (
str, optional) – Determines which rating set takes precedence when the same rating set is specified for both normal and CTG curves. Valid values are “NORMAL”, “CTG”, or blank (same as “NORMAL”). Defaults to “NORMAL”.normal_rating_set (
str, optional) – Which limit to update with the normal temperature-dependent limit. Valid values are “DEFAULT” (uses Limit Monitoring Settings), “NO” (don’t update), or “A” through “O”. Defaults to “DEFAULT”.ctg_rating_set (
str, optional) – Which limit to update with the contingency temperature-dependent limit. Valid values are “DEFAULT”, “NO”, or “A” through “O”. Defaults to “DEFAULT”.
- Returns:
str– The response from the PowerWorld script command.
- WeatherLimitsGenUpdate(update_max=True, update_min=True)[source]
Update generator MW limits based on weather data.
Updates generator MW limits using weather limit curves and weather station temperature data. This allows for temperature-dependent generator capacity modeling.
This is a wrapper for the
WeatherLimitsGenUpdatescript command.- Parameters:
- Returns:
str– The response from the PowerWorld script command.
- WeatherPFWModelsRestoreDesignValues()[source]
Restore case values changed by PFWModels to their design values.
Restores the case values (such as generator MaxMW fields) that were changed by
WeatherPFWModelsSetInputsAndApplyback to the design values specified with each PFWModel.This is a wrapper for the
WeatherPFWModelsRestoreDesignValuesscript command.- Returns:
str– The response from the PowerWorld script command.
See also
WeatherPFWModelsSetInputsAndApplyThe method whose changes this restores.
- WeatherPFWModelsSetInputs()[source]
Set inputs for all case PFWModels without applying them.
Sets the inputs for all Power Flow Weather (PFW) models in the case, but does not apply them to the power flow case. Usually these inputs require the availability of weather measurements.
This is a wrapper for the
WeatherPFWModelsSetInputsscript command.- Returns:
str– The response from the PowerWorld script command.
See also
WeatherPFWModelsSetInputsAndApplySets inputs and applies to case.
- WeatherPFWModelsSetInputsAndApply(solve_pf=True)[source]
Set inputs for PFWModels and apply them to the case.
Sets the inputs for all Power Flow Weather (PFW) models and applies them to the power flow case. Usually these inputs require the availability of weather measurements, which can be loaded using
WeatherPWWLoadForDateTimeUTC.When PFWModels are applied, some case values may be changed (e.g., generator MaxMW fields). Use
WeatherPFWModelsRestoreDesignValuesto restore these values to the design values.This is a wrapper for the
WeatherPFWModelsSetInputsAndApplyscript command.- Parameters:
solve_pf (
bool, optional) – If True, solves the power flow using the default method after applying inputs. If False, you can call another solution command (e.g., SolvePowerFlow or SolvePrimalLP). Defaults to True.- Returns:
str– The response from the PowerWorld script command.
See also
WeatherPFWModelsRestoreDesignValuesRestores values changed by this method.
WeatherPWWLoadForDateTimeUTCLoads weather data for a specific time.
- WeatherPWWFileAllMeasValid(filename, field_list, start_time='', end_time='')[source]
Check if a PWW file has valid measurements for specified fields.
Returns true if the specified PWW file: 1) has all the specified fields, and 2) all the measurements for those fields are valid. This command only works with version 2 or greater PWW files.
This is a wrapper for the
WeatherPWWFileAllMeasValidscript command.- Parameters:
filename (
str) – The path to the PWW file to check.field_list (
List[str]) – List of fields to check. At least one field must be provided. Valid fields include: TEMP, DEWPOINT, WINDSPEED, WINDSPEED100, GLOBALHORZIRRAD, DIRECTHORZIRRAD, WINDGUST, SMOKEVERTINT, PRECIPRATE, PRECIPPERCFROZEN.start_time (
str, optional) – Start datetime in ISO8601 format. If provided, only returns true if the PWW file’s starting datetime is at or before this. Defaults to “” (no start time check).end_time (
str, optional) – End datetime in ISO8601 format. If provided, only returns true if the PWW file’s ending datetime is at or after this. Defaults to “” (no end time check).
- Returns:
str– The response from the PowerWorld script command.
- WeatherPWWFileCombine2(source1, source2, dest)[source]
Combine two PWW weather files into one.
Merges two PWW files, provided they have the same weather stations and non-overlapping datetime ranges. The source2 file should be the second file chronologically.
This is a wrapper for the
WeatherPWWFileCombine2script command.- Parameters:
source1 (
str) – Path to the first source file (first chronologically). Must exist. Should have “.pww” extension or no extension.source2 (
str) – Path to the second source file (second chronologically). Must exist. Should have “.pww” extension or no extension.dest (
str) – Path to the destination file. Does not need to exist and can be the same as either source file.
- Returns:
str– The response from the PowerWorld script command.
- WeatherPWWFileGeoReduce(source, dest, min_lat, max_lat, min_lon, max_lon)[source]
Reduce the geographic scope of a PWW file.
Extracts weather data only for the geographic region bounded by the specified latitude and longitude coordinates. Rectangles spanning the international date line are not allowed.
This is a wrapper for the
WeatherPWWFileGeoReducescript command.- Parameters:
source (
str) – Path to the source PWW file. Must exist. Should have “.pww” extension or no extension.dest (
str) – Path to the destination PWW file. Does not need to exist and can be the same as the source file.min_lat (
float) – Minimum latitude for the bounding rectangle. Must be >= -90 and less than max_lat.max_lat (
float) – Maximum latitude for the bounding rectangle. Must be <= 90 and greater than min_lat.min_lon (
float) – Minimum longitude for the bounding rectangle. Must be >= -180 and less than max_lon.max_lon (
float) – Maximum longitude for the bounding rectangle. Must be <= 180 and greater than min_lon.
- Returns:
str– The response from the PowerWorld script command.
- WeatherPWWLoadForDateTimeUTC(iso_datetime)[source]
Load weather data for a specific date and time.
Loads weather data by searching the directory (and optionally subdirectories) set with
WeatherPWWSetDirectory.This is a wrapper for the
WeatherPWWLoadForDateTimeUTCscript command.- Parameters:
iso_datetime (
str) – The desired date and time in ISO8601 format. This should be either a UTC value (e.g., “2024-03-06T18:00Z”) or local time with time zone offset (e.g., “2024-03-06T12:00-06”).- Returns:
str– The response from the PowerWorld script command.
See also
WeatherPWWSetDirectorySets the directory to search for PWW files.
- WeatherPWWSetDirectory(directory, include_subdirs=True)[source]
Set the directory to search for PWW weather files.
Specifies the directory (and optionally its subdirectories) to search when loading weather information from PWW files.
This is a wrapper for the
WeatherPWWSetDirectoryscript command.- Parameters:
- Returns:
str– The response from the PowerWorld script command.
See also
WeatherPWWLoadForDateTimeUTCLoads weather data using this directory.
Type-Safe Enumerations
ESA++ provides enumeration types for common PowerWorld string parameters. Using these enums instead of raw strings provides IDE autocomplete, type checking, and prevents typos.
from esapp.saw import SolverMethod, FilterKeyword, BusType
saw.SolvePowerFlow(SolverMethod.RECTNEWT)
saw.GetParametersMultipleElement("Bus", ["BusNum"], FilterKeyword.ALL)
Power Flow & Matrices
- class SolverMethod(value)[source]
Power flow solution methods.
These are the available solver algorithms for the SolvePowerFlow command.
- DC = 'DC'
DC power flow (linear approximation).
- FASTDEC = 'FASTDEC'
Fast Decoupled method.
- GAUSSSEIDEL = 'GAUSSSEIDEL'
Gauss-Seidel iterative method.
- POLARNEWT = 'POLARNEWT'
Polar Newton-Raphson.
- RECTNEWT = 'RECTNEWT'
Rectangular Newton-Raphson (default).
- ROBUST = 'ROBUST'
Robust solver for difficult cases.
Bus Classification
- class BusType(value)[source]
Power flow bus type from the BusCat field.
The three fundamental bus types that determine which equations a bus contributes to the power flow Jacobian.
- PQ = 'PQ'
- PV = 'PV'
- SLACK = 'Slack'
- class BusCtrl(value)[source]
Voltage control modifier flags from BusCat qualifiers.
Bitwise-combinable flags describing how a bus participates in voltage regulation. A remotely regulated bus with droop control would have
BusCtrl.REMOTE | BusCtrl.DROOP.- DROOP = 2
- LDC = 4
- NONE = 0
- REMOTE = 1
- TOL = 8
Data Filters & Object Types
- class FilterKeyword(value)[source]
Special filter keywords for PowerWorld commands.
These keywords are passed unquoted to PowerWorld, unlike custom filter names which must be quoted.
- ALL = 'ALL'
Select all objects of the type.
- AREAZONE = 'AREAZONE'
Objects in the active area/zone filter.
- SELECTED = 'SELECTED'
Only objects currently selected in PowerWorld.
- class ObjectType(value)[source]
PowerWorld object type identifiers.
These are used for filtering and operations on specific element types.
- AREA = 'AREA'
Control area.
- BRANCH = 'BRANCH'
Branch (line or transformer).
- BUS = 'BUS'
Bus/node.
- BUSSHUNT = 'BUSSHUNT'
Bus shunt.
- GEN = 'GEN'
Generator.
- INJECTIONGROUP = 'INJECTIONGROUP'
Injection group.
- INTERFACE = 'INTERFACE'
Interface (flowgate).
- LINE = 'LINE'
Transmission line specifically.
- LOAD = 'LOAD'
Load.
- OWNER = 'OWNER'
Owner.
- SHUNT = 'SHUNT'
Shunt device.
- SUPERAREA = 'SUPERAREA'
Super area (aggregated).
- SUPERBUS = 'SUPERBUS'
Super bus (aggregated).
- TRANSFORMER = 'TRANSFORMER'
Transformer specifically.
- ZONE = 'ZONE'
Zone.
Boolean & Option Flags
- class YesNo(value)[source]
Boolean flag values for PowerWorld commands.
PowerWorld uses “YES” and “NO” strings for boolean parameters in script commands rather than true/false.
- NO = 'NO'
Negative / disable option.
- YES = 'YES'
Affirmative / enable option.
File Formats
- class FileFormat(value)[source]
File format types for import/export operations.
- AREVAHDB = 'AREVAHDB'
AREVA HDB format.
- AUX = 'AUX'
PowerWorld auxiliary format.
- AUXCSV = 'AUXCSV'
Hybrid auxiliary/CSV format.
- AXD = 'AXD'
Oneline diagram format.
- CF = 'CF'
Custom format.
- CSV = 'CSV'
Comma-separated values.
- CSVCOLHEADER = 'CSVCOLHEADER'
CSV with column headers.
- CSVNOHEADER = 'CSVNOHEADER'
CSV without headers.
- GE = 'GE'
GE EPC format.
- OPENNETEMS = 'OPENNETEMS'
OPENNET EMS format.
- PTI = 'PTI'
PTI/PSS-E format.
- PWB = 'PWB'
PowerWorld case format.
- TAB = 'TAB'
Tab-separated format.
- TXT = 'TXT'
Text format.
- UCTE = 'UCTE'
UCTE format.
Transient Stability
Topology & Sensitivity
- class BranchDistanceMeasure(value)[source]
Branch distance measurement types for topology analysis.
- IMPEDANCE = 'Z'
Use impedance magnitude (Z) as distance measure.
- REACTANCE = 'X'
Use reactance (X) as distance measure.
- class BranchFilterMode(value)[source]
Branch filter modes for topology traversal.
- ALL = 'ALL'
All branches.
- CLOSED = 'CLOSED'
Only closed branches.
- SELECTED = 'SELECTED'
Only selected branches.
- class ScalingBasis(value)[source]
Scaling basis for load/generation scaling operations.
- FACTOR = 'FACTOR'
Multiplier factor.
- MW = 'MW'
Absolute MW/MVAR values.
Case Operations
- class StarBusHandling(value)[source]
Star bus handling options for case append operations.
- MAX = 'MAX'
Map to maximum impedance bus.
- NEAR = 'NEAR'
Map to nearest bus (default).
- class MultiSectionLineHandling(value)[source]
Multi-section line handling options for case append operations.
- EQUIVALENCE = 'EQUIVALENCE'
Convert to equivalent circuits.
- MAINTAIN = 'MAINTAIN'
Maintain multisection line structure (default).
- class OnelineLinkMode(value)[source]
Oneline diagram linking modes.
- LABELS = 'LABELS'
Link objects by labels (default).
- NUMBERS = 'NUMBERS'
Link objects by numbers.
- class ShuntModel(value)[source]
Shunt model types for line tapping operations.
- CAPACITANCE = 'CAPACITANCE'
Capacitive shunt model.
- INDUCTANCE = 'INDUCTANCE'
Inductive shunt model.
Ratings
Field Metadata
- class FieldListColumn(value)[source]
Column names for GetFieldList results.
PowerWorld returns field metadata with these column headers. Different Simulator versions may return different subsets of these columns.
- DESCRIPTION = 'description'
Human-readable description.
- DISPLAY_NAME = 'display_name'
Display name in PowerWorld UI.
- ENTERABLE = 'enterable'
Whether the field can be edited.
- FIELD_DATA_TYPE = 'field_data_type'
Data type of the field.
- INTERNAL_FIELD_NAME = 'internal_field_name'
PowerWorld internal field name.
- KEY_FIELD = 'key_field'
Whether the field is a key field.
- class SpecificFieldListColumn(value)[source]
Column names for GetSpecificFieldList results.
PowerWorld returns specific field metadata with these column headers.
- COLUMN_HEADER = 'column header'
Column header label.
- ENTERABLE = 'enterable'
Whether the field can be edited.
- FIELD = 'field'
Field identifier.
- FIELD_DESCRIPTION = 'field description'
Human-readable description.
- VARIABLENAME_LOCATION = 'variablename:location'
Variable name with location.
Helper Functions
Filter formatting:
- format_filter(filter_name)[source]
Format a filter name for use in PowerWorld commands.
Special filter keywords (SELECTED, AREAZONE, ALL) are passed unquoted, while custom filter names are quoted.
- Parameters:
filter_name (
FilterType) – The filter name to format. Can be a FilterKeyword enum or a string.- Returns:
str– The formatted filter string for use in script commands.
- format_filter_selected_only(filter_name)[source]
Format a filter name, treating only SELECTED as special.
Only SELECTED is passed unquoted; other values including AREAZONE and ALL are quoted like custom filter names.
- Parameters:
filter_name (
FilterType) – The filter name to format.- Returns:
str– The formatted filter string.
- format_filter_areazone(filter_name)[source]
Format a filter name, treating SELECTED and AREAZONE as special.
SELECTED and AREAZONE are passed unquoted; ALL and custom names are quoted.
- Parameters:
filter_name (
FilterType) – The filter name to format.- Returns:
str– The formatted filter string.
Data conversion:
- df_to_aux(fp, df, object_name)[source]
Convert a dataframe to PW aux/axd data section.
- Parameters:
fp (
file) – File handler.df (
pandas.DataFrame) – DataFrame to convert.object_name (
str) – PowerWorld object type.
- create_object_string(object_type, *keys)[source]
Helper to format a PowerWorld object string identifier.
This function creates strings formatted like
[BUS 1]or[BRANCH 1 2 1]which are used to identify objects in SimAuto script commands.
- convert_df_to_variant(df)[source]
Given a DataFrame, convert to a variant array for Rect functions.
- format_list(items, quote_items=False, stringify=False)[source]
Format a Python sequence as a PowerWorld bracketed list.
This is the standard way to pass array parameters to PowerWorld script commands.
- Parameters:
items (
Optional[Sequence]) – The items to format. If None or empty, returns “[]”.quote_items (
bool, optional) – If True, wraps each item in double quotes. Use for string fields like names or labels. Defaults to False.stringify (
bool, optional) – If True, converts each item to string using str(). Use for numeric values or mixed types. Defaults to False.
- Returns:
str– A bracketed list string like “[item1, item2, …]” or “[]”.
Examples
>>> format_list(["BusNum", "BusName"]) '[BusNum, BusName]'
>>> format_list(["Gen1", "Gen2"], quote_items=True) '["Gen1", "Gen2"]'
>>> format_list([1.5, 2.0, 3.5], stringify=True) '[1.5, 2.0, 3.5]'
>>> format_list(None) '[]'
- format_optional(value, quote=True, empty_quoted=False)[source]
Format an optional string parameter for PowerWorld commands.
- Parameters:
- Returns:
str– The formatted parameter string.
Examples
>>> format_optional("MyFilter") '"MyFilter"'
>>> format_optional("") ''
>>> format_optional("", empty_quoted=True) '""'
>>> format_optional("SomeValue", quote=False) 'SomeValue'
- format_optional_numeric(value)[source]
Format an optional numeric parameter for PowerWorld commands.
- Parameters:
value (
Optional[Union[int,float]]) – The numeric value to format. If None, returns an empty string.- Returns:
str– The string representation of the value, or “” if None.
Examples
>>> format_optional_numeric(3.14) '3.14'
>>> format_optional_numeric(None) ''
>>> format_optional_numeric(0) '0'
Exceptions
Exception classes for handling PowerWorld and COM errors.
Exception |
Description |
|---|---|
|
Base class for all ESA++ exceptions |
|
Generic error from PowerWorld following a SimAuto call. Parses error messages to extract source and details. |
|
Raised when a SimAuto feature is not supported for the given object or context (e.g., object types that don’t support |
|
Raised when a command fails due to missing prerequisite data (e.g., no contingencies defined for |
|
Raised when a command requires an unlicensed PowerWorld add-on (e.g., TransLineCalc) |
|
Raised when COM communication fails (SimAuto crash, unresponsive, or invalid function call) |
|
Raised when PowerWorld silently ignores a command (e.g., setting a value outside allowed limits) |
|
Raised when a grid object data query fails (object does not exist in the case) |
|
Raised when there is an issue with field data retrieval or parsing |
|
Raised when parsing an auxiliary file fails |
|
Raised when attempting to access a container that has been deleted |
|
Base class for power flow solution errors |
|
Raised when voltage bifurcation is suspected during power flow |
|
Raised when the power flow solution diverges |
|
Raised when a generator has exceeded a limit during power flow |
|
Raised when a GIC analysis error occurs |
Exception
└── Error (base for all ESA++ exceptions)
├── COMError
├── GridObjDNE
├── FieldDataException
├── AuxParseException
├── ContainerDeletedException
├── GICException
├── PowerFlowException
│ ├── BifurcationException
│ ├── DivergenceException
│ └── GeneratorLimitException
└── PowerWorldError
├── SimAutoFeatureError
├── PowerWorldPrerequisiteError
├── PowerWorldAddonError
└── CommandNotRespectedError
from esapp.saw import SAW, PowerWorldError, PowerWorldPrerequisiteError
try:
saw.CTGSolveAll()
except PowerWorldPrerequisiteError:
print("No contingencies defined - add contingencies first")
except PowerWorldError as e:
print(f"PowerWorld error: {e.message}")
print(f"Source: {e.source}")