Calculations Module
The Calculations module contains all the essential classes needed for running
ERACS studies. One of the most essential is the
Calculations.TEracsModule
class. All calculation modules inherit
from this core module, and all “easy” equivalent classes own a reference to
one of those sub-classes (depending on which easy class it is -
Loadflow.TEracsLoadflowEasy
owns an instance of the
Loadflow.TEracsLoadflow
class so it can interact with the Loadflow
DLL, and TEracsLoadflow inherits from Calculations.TEracsModule
).
All “Easy” classes inherit from the generic Calculations.TEracsEasy
class, which exposes this underlying low-level module reference via a
CalculationModule property.
This is important to note because Calculations.TEracsModule
provides all sorts of useful functionality which you may want to use when
running ERACS studies in the Python Interface.
Monitor Window
One property Calculations.TEracsModule
exposes is MonitorWindow,
which is a class that can help interaction with the monitor window. In ERACS
when a Loadflow study is run, a monitor window will appear that logs
information about the study, such as the number of iterations and the
convergence error. This monitor window information can be accessed by Python
too.
Example
By default the Python Interface hides the monitor window because Python scripts
are for automation, and it’d be more useful to log the information rather than
presenting it directly. The example below shows us how we can print out
information from the monitor window for a Loadflow study when using the
Loadflow.TEracsLoadflowEasy
class.
1"""
2This example script shows how to quickly access the monitor
3window information by passing in a callback function for the
4Interface to call whenever there's new information available.
5"""
6from Eracs import Loadflow, Data
7from Eracs.Global import TEracsInformation
8
9def monitor_message(AMsg):
10 """
11 Print out the monitor window message to stdout.
12 """
13 print(AMsg)
14
15def run():
16 """
17 Perform a Loadflow study on the Springfield Road network.
18 """
19 # Create the data object and load the SpringfieldRoad example network
20 data = Data.TEracsData()
21 data.Load(TEracsInformation().ExamplesFolder + "SpringfieldRoad.xml")
22
23 # Create the Loadflow easy object, pass in the callback function, give it the data, and run Loadflow
24 loadflow = Loadflow.TEracsLoadflowEasy()
25 loadflow.CalculationModule.MonitorWindow.LoadMessageCallBackProc(monitor_message)
26 loadflow.SetData(data)
27 loadflow.RunCalc()
28
29if __name__ == "__main__":
30 # Script was executed directly, load data and run Loadflow
31 run()
This example could be taken further by writing the information to a file or database. In the example scripts provided with the interface, the LFExampleComplexGUI.py script uses this callback facility to output Loadflow information to the GUI.
Dialog Prompts
When running ERACS studies, dialog prompts can appear asking for confirmation or warning of problems. Below is a typical dialog box to appear from ERACS…
The Python Interface hides these dialog prompts in the same way and for the same reason as hiding the monitor window. The dialog prompts appearing in our automated scripts will interrupt automation and requires user intervention, so by hiding them instead and setting default responses we can keep our studies automated even when problems arise.
Example
The process for providing a callback for dialog prompts is the same, but this
time we use the Dialogs property which is exposed by
Calculations.TEracsModule
.
1"""
2This example script shows how to quickly access the dialog
3prompt information by passing in callbacks and setting default responses.
4"""
5from Eracs import Loadflow, Data
6from Eracs.Global import TEracsInformation
7
8def get_more_iterations(AMsg):
9 """
10 Print out information relating to the fact that ERACS requested
11 additional iterations.
12 """
13 print("More iterations requested")
14
15def dialog_prompt(AMsg, AReason, AButtons):
16 """
17 Print out the dialog prompt message which appeared.
18 """
19 print(AMsg)
20
21def run():
22 """
23 Perform a Loadflow study on the Springfield Road network.
24 """
25 # Create the data object and load the SpringfieldRoad example network
26 data = Data.TEracsData()
27 data.Load(TEracsInformation().ExamplesFolder + "SpringfieldRoad.xml")
28
29 # Create the Loadflow easy object
30 loadflow = Loadflow.TEracsLoadflowEasy()
31 # Pass in callback functions and set default options
32 loadflow.CalculationModule.Dialogs.GetMoreIterations = 1
33 loadflow.CalculationModule.Dialogs.NumberOfAdditionalIterations = 10
34 loadflow.CalculationModule.Dialogs.ContinueIncompleteConvergence = 10
35 loadflow.CalculationModule.Dialogs.LoadGetMoreIterationsCallBackProc(get_more_iterations)
36 loadflow.CalculationModule.Dialogs.LoadMessageDlgCallBackProc(dialog_prompt)
37 # Set the data object and run the study
38 loadflow.SetData(data)
39 loadflow.RunCalc()
40
41if __name__ == "__main__":
42 # Script was executed directly, load data and run Loadflow
43 run()
This example is very similar to the one for the monitor window, however, the dialogs provide a few different options. We have two different callbacks; one which handles all dialog prompts, and one specifically for iteration requests. Both types would have been displayed but were suppressed by the Python Interface.
For general dialog prompts, the callback is given 3 arguments, the dialog message, the reason for the dialog prompt, and the buttons it displays. To see the possible values for the reasons and buttons, refer to the glossary. The callbacks are for notification only, and doesn’t allow you to modify the response given back to ERACS. For this, we use specially provided properties which are also used in the example code.
GetMoreIterations controls how many times ERACS can request additional iterations before ERACS is instructed to stop iterating and stop the study.
NumberOfAdditionalIterations controls the number of iterations given per iteration request.
ContinueIncompleteConvergence controls how many times ERACS should retry incomplete convergances before being told to stop the study.
An additional callback is provided just for the ‘get more iterations’ requests so that you might be able to add additional logic and modify the aforementioned properties appropriately based on conditions. The other callback is given no arguments.
API
All base logic and classes for ERACS calculations reside in this module. This module should not need to be directly imported by the user into their scripts, since all functionality will be inherited from other ERACS modules.
- CheckData(AMethod)
Use as a decorator method for methods in calculation easy routines to check whether the data object has been assigned
- Parameters
AMethod (method) – The method which is being wrapped.
- Returns
The result of the original method call.
- Raises
TEracsDataError – If no data object is assigned.
- Doctest
>>> class foo: ... def __init__(self, data=None): ... self._Data = data ... ... @CheckData ... def bar(self): ... return True
>>> foo1 = foo() >>> foo1.bar() Traceback (most recent call last): ... Eracs.Global.TEracsDataError: Data object not set for the calculation 'easy' module before call to bar
>>> foo2 = foo(data=True) >>> foo2.bar() True
- CheckDLL(AMethod)
This decorator is used in most/all DLL function calls to make sure the DLL is loaded before trying to call its methods.
- Parameters
AMethod (method) – The method which is being wrapped.
- Returns
The method return, or None.
- Raises
TEracsError – If SetupCalculation wasn’t called first.
TEracsDllError – If DLL has not been loaded.
- Doctest
>>> class foo(): ... def __init__(self, loaded=False): ... self.DllLoaded = loaded ... ... @CheckDLL ... def bar(self): ... return True
>>> foo1 = foo() >>> foo1.bar() Traceback (most recent call last): ... Eracs.Global.TEracsDllError: DLL was not loaded before calling bar
>>> foo2 = foo(loaded=True) >>> foo2.bar() True
- class TEracsModule
This class should not be instantiated. This class is used to load the required DLLs and check the ERACS installation so that the calculation classes can call the exported functions properly…
- Doctest
>>> TEracsModule() Traceback (most recent call last): ... NotImplementedError: _CreateResultObjects method must be overridden by the TEracsModule descendant
- property EracsEnviron
The EracsEnviron being used under the hood for all calculations.
- Type
- Writable
False.
- property DllLoaded
True if the calculation module DLL is loaded and ready for use.
- Type
bool.
- Writable
False.
- property MonitorWindow
Access the monitor window which is written to by ERACS during a study.
- Type
_TEracsMonitorWindow.
- Writable
False.
- property Dialogs
Access the dialogs which are usually displayed by Loadflow but are prevents in the Python Interface so that the Python script is able to continue running uninterrupted.
- Type
_TEracsDialogs.
- Writable
False.
- property VersionNumber
Version number of the calculation module.
- Type
str.
- Writable
False.
- property ProgramNumber
Program number of the calculation.
- Type
int.
- Writable
False.
- Example
1 = Loadflow
- GetResult(AResultTypeCode, AResultDictionary, *args)
Calls the result procedure contained in _ResultProcDictionary to populate the given results object.
- Parameters
AResultTypeCode (str) – The typecode of the result to be retrieved e.g. busbar.
AResultDictionary (dict) – Dictionary to store results inside
- Returns
True if the result object exists for the given typecode. False is returned otherwise.
- Raises
TEracsError – If result typecode is not recognised.
- SetupCalculation(ASetupObject)
Low-level access to SetupCalculation DLL call. The first procedure call when running a study passing in the study setup parameters.
- Parameters
ASetupObject (TEracsEngineInterfaceSetupData) – SetupData object used for passing parameters to the calculation engine.
- SolveCalculation()
Called once all data has been loaded into the calculation engine, this starts the study.
- CalculationCleanUp()
Called once the study is complete (even if it failed). Closes all files and unloads all DLLs.
- GetFileNames(AOutParameterList: list)
Gets the files associated with the calculation (results, data, etc.), must be overridden in descendant class.
- Parameters
AOutparameterList (list) – Empty list.
- Raises
NotImplementedError – Must be overridden by descendant.
- class TEracsModuleLoadflowDependent
This class should not be instantiated. This class is the parent to calculation classes that are dependent on a Loadflow calculation having been performed (Fault, Impedance, etc.).
- Inherits
- PassTDFBlock(ATDFBlockObject)
The first method to be called when running Loadflow dependent studies. This method passes the data from the Loadflow calculation to the module so that it can be quickly and easily accessed (and omitting the slower technique of manually loading all the data to it again like with Loadflow).
- Parameters
ATdfBlockObject (TEracsTdfBlock) – The TDF Block to be passed in.
- GetFileNames(AOutParameterList: list)
- Parameters
AOutParameterProperties – This argument acts as an out parameter. An empty list should be passed in, and the various file names will be appended to the list [lstResults, cdResults, cdData].
- class TEracsCalculationEventEnum(value)
‘INVALIDATED’ event is raised whenever the study results are invalidated because data has changed.
- Inherit
- INVALIDATED = 1
- class TEracsEasy
The base class for all ‘Easy’ high-level calculation classes.
- property CalculationModule
The calculation object. For TEracsLoadflowEasy, this would be an instance of
Loadflow.TEracsLoadflow
.- Type
TEracsLoadflow (if Loadflow, otherwise equivalent classes for other calculation engines used).
- Writable
False.
- Doctest
>>> from Eracs import Loadflow >>> lfEasy = Loadflow.TEracsLoadflowEasy() >>> type(lfEasy.CalculationModule) <class 'Eracs.Loadflow.TEracsLoadflow'>
>>> from Eracs import Fault >>> faEasy = Fault.TEracsFaultEasy() >>> type(faEasy.CalculationModule) <class 'Eracs.Fault.TEracsFault'>
- property ProgressSteps
The amount of steps which make up the progress counter.
- Type
int.
- Writable
False.
- property EracsEnviron
- property NetworkName
Name of the network being used in the study.
- Type
str.
- Writable
True.
- property StateName
Name of the data state being used in the study.
- Type
str.
- Writable
True.
- property UserID
ERACS Username of the person who created the network.
- Type
str.
- Writable
True.
- property ChangeID
ERACS Username of the person who last changed the network.
- Type
str.
- Writable
True.
- property SysDate
System date.
- Type
str.
- Writable
False.
- property ListingFileName
Path to the Listing File generated during a study. The listing file contains data/results for the study.
- Type
str.
- Writable
False.
- property CsvResultFileName
Path to the CSV results file for the study.
- Type
str.
- Writable
False.
- property VersionNumber
Version number for the calculation module.
- Type
str.
- Writable
True.
- property ResultTypecodes
Get a list of all possible result typecodes.
- EventEnum()
Returns the event enum used by the implementing events class. This can be called from anywhere to find out what events are exposed.
- SetData(AEracsDataObject)
Assign a data object to be used during the study.
- Parameters
AEracsDataObject (TEracsData) – A TEracsData object
- Invalidate()
This method can be called in order to mark a study as invalid. This can happen for a number of reasons, for example, when the data object loads a fresh set of data, the results are no longer valid because they’re for the old data. When invalidating a study, the results are cleared. This method is called internally when a new data object is set via
SetData()
, but if the data within the object is refreshed/cleared/loaded, it’s the responsibility of the data handler to invalidate the calculation.- Returns
None.
- AddProgressListener(AHandler)
Add a listener to the Loadflow easy class, this will call the handler throughout the RunCalc method with updates on progress. To be used with the ProgressSteps property.
- Parameters
AHandler (Callable[[int, str], None]) – The function which should be called once progress is made. Two parameters are passed to the function, a step integer representing which step we’re on, and a step description. A return value is not expected and will be ignored.
- RemoveProgressListener(AHandler)
Remove the progress listener. Call this once the study finishes.
- Parameters
AHandler (Callable[[int, str], None]) – The function to remove from the listeners list.
- GetResultsFromTypecode(ATypecode)
Get the list of results from the typecode provided.
- Parameters
ATypecode – The typecode.
- ClearResults()
Clears all result objects ready for a fresh study to begin.
- Raises
NotImplementedError – Must be overridden in descendant class.
- RunCalc()
Overidden by the descendant class and called. This is the main method for running the calculation after a data object has been assigned.
- ResultsInXml(AXmlObject)
Use this method as a callback function for the OpenInBrowserAsSvg method in TEracsData objects. This method will append all results for Loadflow to the given XML object.
- Required
LXML Python library.
- Parameters
AXmlObject – The XML object which should be a <results> element, so that <loadflow>…</> results may be appended.
- Returns
None, it is appending to the XML object.
- OpenResultsInExcel(AFilePath=None, AFileName=None, ASeparateSheets=True, AOpen=True)
Write results of calculation to Excel and open.
- Required
XlsxWriter Python library.
- Parameters
AFilePath (str) – (Optional) File path to Excel file.
AFileName (str) – (Optional) File name of Excel file.
ASeparateSheets (bool) – (Optional) True will write results on separate worksheets.
AOpen (bool) – (Optional) Opens the file after writing.
- Returns
Full file path as string.
- Raises
TEracsError – If XlsxWriter Python Library isn’t installed.
- class TEracsTdfBlock
The TDF Block is used to pass data from Loadflow to another calculation module. The TDF Block is populated when the GetTDFBlock procedure is called inside the Loadflow calculation module, and is passed to another calculation module via the PassTDFBlock procedure.
- property HasData
True if the TDF block contains Loadflow data.
- Type
bool.
- Writable
False.
- property PtrToBlock
Pointer to the beginning of the block of data
- Type
Pointer.
- Writable
False.
- property SizeOfBlock
Size of the array of data in the block.
- Type
int.
- Writable
False.
- LoadFromMemory(APtrToBlock, ASizeOfBlock)
This method will take a pointer and size of the array it points to, and loads that data into a buffer array created inside the method…
- Parameters
APtrToBlock (pointer) – A pointer to an array of bytes for the TDF block
ASizeOfBlock (int) – The size of the array
- SaveToFile(AFileName)
This method will take the TDF Block and store it into a binary file.
- Parameters
AFileName (str) – The filename only, no extension (it’s to be stored in the Temp folder.)
- Raises
TEracsDataError – If the TDFBlock file could not be saved properly.
- LoadFromFile(AFileName)
This method will take a TDF file and store the data into a Python block.
- Parameters
AFileName (str) – The filename only, no extension (loaded from the Temp folder.)
- Raises
TEracsDataError – If file wasn’t found.