Skip to content

Instantly share code, notes, and snippets.

@jmmauricio
Created June 13, 2015 18:41
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save jmmauricio/1198491fa8223572881a to your computer and use it in GitHub Desktop.
Save jmmauricio/1198491fa8223572881a to your computer and use it in GitHub Desktop.
PowerFactory DigSILENT Python Script to load flow, set variables to save, set event, initialize, run and save results to a txt file
import sys
sys.path.append(r"C:\DigSILENT15p1p7\python")
# import PowerFactory module
import powerfactory
# start PowerFactory in engine mode
app = powerfactory.GetApplication()
user = app.GetCurrentUser()
# activate project
project = app.ActivateProject("Nine Bus System")
prj = app.GetActiveProject()
ldf = app.GetFromStudyCase("ComLdf")
ini = app.GetFromStudyCase('ComInc')
sim = app.GetFromStudyCase('ComSim')
Shc_folder = app.GetFromStudyCase('IntEvt');
terminals = app.GetCalcRelevantObjects("*.ElmTerm")
lines = app.GetCalcRelevantObjects("*.ElmTerm")
syms = app.GetCalcRelevantObjects("*.ElmSym")
Shc_folder.CreateObject('EvtSwitch', 'evento de generacion');
EventSet = Shc_folder.GetContents();
evt = EventSet[0];
evt.time =1.0
evt.p_target = syms[1]
ldf.iopt_net = 0
ldf.Execute()
elmres = app.GetFromStudyCase('Results.ElmRes')
for terminal in terminals:
elmres.AddVars(terminal,'m:u','m:phiu','m:fehz')
for sym in syms:
elmres.AddVars(sym,'s:xspeed')
ini.Execute()
sim.Execute()
evt.Delete()
comres = app.GetFromStudyCase('ComRes');
comres.iopt_csel = 0
comres.iopt_tsel = 0
comres.iopt_locn = 2
comres.ciopt_head = 1
comres.pResult=elmres
comres.f_name = r'C:\Users\jmmauricio\hola.txt'
comres.iopt_exp=4
comres.Execute()
@jmmauricio
Copy link
Author

jmmauricio commented Apr 13, 2020 via email

@alejanpat
Copy link

Awesome help.

I have a question:

I would like to do the same but insted of activating a project, i want to import a raw file (from psse) and then activate that project and perfom the simulation.

I cannot find a command for importing from raw. Any idea? How can i use commands for that purpose?

Thank you in advance

@jmmauricio
Copy link
Author

jmmauricio commented Apr 13, 2020 via email

@Alejanpato
Copy link

Alejanpato commented Apr 13, 2020

Thank you very much for the fast response.

Doing it by using the digsilent interface is much easier, but the simulation is ran externally from a web application:

The application user upload a raw file
The application calls digsilent using Python
digsilent import the raw file, activate the Project and perform simulation
Digsilent return results and the web application shows information

I have everything working but the automation of that task. I can do it manually but makes no sense regarding the application objective.

Any suggestion Will be appreciated.

Alejandro

@jmmauricio
Copy link
Author

jmmauricio commented Apr 13, 2020 via email

@Alejanpato
Copy link

It Works perfectly.

I have just added this line before the last one:

psse.targname= 'name of the new project'

Awesome help. Thank you so much.

@Olliejp
Copy link

Olliejp commented Jun 22, 2020

Hi Juan, thanks for posting this. I actually have a simular issue to one that was mentioned earlier in the thread, where i get an error: "AttributeError: 'NoneType' object has no attribute 'ActivateProject'". I have no idea why I am getting this error... I am using the demo version of the latest Powerfactory version... and wondering if maybe this demo doesnt provide access to the python api... hence I am being returned none...

Here is my code for starting powerfactory in engine mode:

"import sys
import os
sys.path.append(
r"C:\Program Files\DIgSILENT\PowerFactory 2020 SP1B\Python\3.8")
import powerfactory as pf

class PowerFactorySim(object):
def init(self, folder_name='', project_name='Project', study_case_name='Study Case'):
#start powerfactory
self.app = pf.GetApplication()
#activate project
self.project = self.app.ActivateProject(os.path.join(folder_name, project_name))
#activate study case
study_case_folder = self.app.GetProjectFolder('study')
study_case = study_case_folder.GetContents(
study_case_name+'.IntCase')[0]
self.study_case = study_case[0]
self.study_case.Activate"

And then the relevant part of a separate python file I have using to call this method is here:

"import csv
from pfsim import PowerFactorySim

FOLDER_NAME = ''
PROJECT_NAME = '14_bus_EMT.IntPrj'
STUDY_CASE_NAME = 'emt_test_case'
MONITORED_VARIABLES = {
# 'Gen_0008.ElmSym': ['s:phi', 's:speed', 's:fe'],
'*.ElmTerm': ['m:ul:A', 'm:ul:B', 'm:ul:C']
}

sim = PowerFactorySim(
folder_name=FOLDER_NAME,
project_name=PROJECT_NAME,
study_case_name=STUDY_CASE_NAME)"

If you could provide any pointers what so ever I would be so grateful... I am new to powerfactory and currently banging my head against the wall...

@uthpala13092
Copy link

I have a question. I am using DigSILENT 15.1 and python 3.8. I am trying to run power factory both in engine mode and ComPython mode.
I am having trouble in interfacing both the applications.

When running in Compython , I cannot import numpy as np (powerfactory has an older version of python without pip)
When in engine mode , I receive this error :
Traceback (most recent call last):
File "<pyshell#2>", line 1, in
import powerfactory
ImportError: DLL load failed while importing powerfactory: The specified module could not be found.

This is my code 👍

import sys
sys.path.append(r"C:\Program Files (x86)\DIgSILENT\PowerFactory 15.1\python")
import powerfactory

Appreciate if I can get an advice and where I am doing wrong
Thank you

@fidelsmc
Copy link

I have a question. I am using DigSILENT 15.1 and python 3.8. I am trying to run power factory both in engine mode and ComPython mode.
I am having trouble in interfacing both the applications.

When running in Compython , I cannot import numpy as np (powerfactory has an older version of python without pip)
When in engine mode , I receive this error :
Traceback (most recent call last):
File "<pyshell#2>", line 1, in
import powerfactory
ImportError: DLL load failed while importing powerfactory: The specified module could not be found.

This is my code 👍

import sys
sys.path.append(r"C:\Program Files (x86)\DIgSILENT\PowerFactory 15.1\python")
import powerfactory

Appreciate if I can get an advice and where I am doing wrong
Thank you

Try to use python3, this library does not work with 2.x version

@rizky-r-lab
Copy link

I have a question. I am using DigSILENT 15.1 and python 3.8. I am trying to run power factory both in engine mode and ComPython mode.
I am having trouble in interfacing both the applications.

When running in Compython , I cannot import numpy as np (powerfactory has an older version of python without pip)
When in engine mode , I receive this error :
Traceback (most recent call last):
File "<pyshell#2>", line 1, in
import powerfactory
ImportError: DLL load failed while importing powerfactory: The specified module could not be found.

This is my code 👍

import sys
sys.path.append(r"C:\Program Files (x86)\DIgSILENT\PowerFactory 15.1\python")
import powerfactory

Appreciate if I can get an advice and where I am doing wrong
Thank you

DigSilent 15.1 works only with python 3.3. I am currently working in it. However, i have question regarding performance of DigSilent 15.1 with python.
I have created script that run power flow with different conditions of power system. It's work however to retrieve the data it takes very long time (100x more time if i use DigSilent 2020) with same script. What does caused it?

@jmmauricio
Copy link
Author

jmmauricio commented Aug 20, 2021 via email

@SjorsHijgenaar
Copy link

I am using PowerFactory 2020 SP3 (x64), Build 20.0.5.0 (10037) / Rev. 75304 and Python 3.8 on a Windows 10 lapot, installed in C:\python (which has been added to %PATH%).

I'm trying to run a very simple 'HelloWorld' script:

import sys

sys.path.append('C:\\Program Files\\DIgSILENT\\PowerFactory 2020 SP3\\Python\\3.8\\')

import powerfactory as pf

app = pf.GetApplication()
app.PrintPlain("Hello PowerFactory")

I have this code in file powerfactory_main.py. When, In PowerFactory, I add a Python Script (ComPython), point to to the file as External Python Script and hit Execute I get a nice Hello PowerFactory in the Outpput Window of PowerFactory. However, once I open the script in VS Code (v 1.63.2 -user setup), hit Run Python File in Terminal I get the aforementioned error:

AttributeError: 'NoneType' object has no attribute 'PrintPlain'

Does anyone have a clue what's going on here? I can't seem to get the solution from the comments above.

Question: does PowerFactory need to be running?
I see references to "engine mode", but I have no idea what that means.

@Sarah3802
Copy link

Hi Everyone
I have a alot of loads with (parameter characteristic - vector (loads with time series every 15 min. for a time period one year )) in Excel file (.xlsx) and i need to import them using python script. can anbody help me out ???

@rizky-r-lab
Copy link

rizky-r-lab commented Jan 23, 2023

Hi Everyone I have a alot of loads with (parameter characteristic - vector (loads with time series every 15 min. for a time period one year )) in Excel file (.xlsx) and i need to import them using python script. can anbody help me out ???

Hi @Sarah3802 ,
I had created script, but to create Time Characteristics. I will try to convert it, but i don't know it will work or not

First you should get the characteristics folder and scale folder
fold_char = app.GetProjectFolder('chars')
fold_scale = app.GetDataFolder('IntScales')

and then you should create the time scale first by using this code :
time_scale = fold_scale.CreateObject('TriTime', 'time_scale_15_minute_year')
time_scale.unit = 3 #(It means hour per year)
time_scale.scale = [i/4 for i in range(0,24*365*4)]

and then for each loads 👍
for load in loads:
load_scale = fold_char.CreateObject('ChaVec', '{} MW'.format(load.GetAttribute('loc_name')))
load_scale.scale = time_scale #to refer the time scale that we created before
load_scale.vector = #YOUR LOAD CURVE (one dimension array)
load_link = load.CreateObject('ChaRef','plini') # plini refer to Active Power Load Parameter, you can change it as appropriate
load_link.typ_id = load_scale

I hope this help

@Sarah3802
Copy link

Hi Everyone I have a alot of loads with (parameter characteristic - vector (loads with time series every 15 min. for a time period one year )) in Excel file (.xlsx) and i need to import them using python script. can anbody help me out ???

Hi @Sarah3802 , I had created script, but to create Time Characteristics. I will try to convert it, but i don't know it will work or not

First you should get the characteristics folder and scale folder fold_char = app.GetProjectFolder('chars') fold_scale = app.GetDataFolder('IntScales')

and then you should create the time scale first by using this code : time_scale = fold_scale.CreateObject('TriTime', 'time_scale_15_minute_year') time_scale.unit = 3 #(It means hour per year) time_scale.scale = [i/4 for i in range(0,24*365*4)]

and then for each loads 👍 for load in loads: load_scale = fold_char.CreateObject('ChaVec', '{} MW'.format(load.GetAttribute('loc_name'))) load_scale.scale = time_scale #to refer the time scale that we created before load_scale.vector = #YOUR LOAD CURVE (one dimension array) load_link = load.CreateObject('ChaRef','plini') # plini refer to Active Power Load Parameter, you can change it as appropriate load_link.typ_id = load_scale

I hope this help

Thank You so much Sir, its really helpfull, but i'm wondering how can i read data from excel file (.xlsx)?

@SjorsHijgenaar
Copy link

SjorsHijgenaar commented Jan 23, 2023

Thank You so much Sir, its really helpfull, but i'm wondering how can i read data from excel file (.xlsx)?

Is it possible to save it as .csv instead?

@rizky-r-lab
Copy link

As @SjorsHijgenaar , you can use CSV file or if you want easier, you can use pandas module

@Sarah3802
Copy link

I've already converted it, but it looks messy

@Sarah3802
Copy link

i would like to read data from excel using the module “pandas”, i found that i can use

import pandas as pd
pandas.read_excel('File_name','sheet name')

The data will then be returned into a DataFrame. The DataFrame has the advantage of providing easy access to columns and rows. But, i'm not able to map the header in the Excel file with a load object in PowerFactory, can someone help me here ?

@rizky-r-lab
Copy link

the easiest one will be the column header has the same name with load name in PowerFactory. And then you can map it like this:
loads_data = app.GetRelevantObjects('*.ElmLod')
for load in loads_data:
try:
load_curve = df[load.GetAttribute('loc_name']
except:
print(f'load curve for {load.GetAttribute('loc_name']} not found') #catching error because load name is not in data

@midhunagarapati
Copy link

Is there a way to extract multiple parameters of all synchronous machines at a time and write to a csv file?

@rizky-r-lab
Copy link

@midhunagarapati , what parameter do you want to extract? If it's just static parameter like inertia, time constant or etc, the easiest one is directly use GUI of powerfactory through Network Model Manager. Chose Generator, and then go through flexible tab.
You can define the parameter in there.

@midhunagarapati
Copy link

@rizky-r-lab I want to extract simulation RMS parameters like transient reactances and change them according to the size of the machine

@Lorias-Jak
Copy link

i searched for a long time now to find all attributes a element can have. Is there a list i didnt know about?

the easiest one will be the column header has the same name with load name in PowerFactory. And then you can map it like this: loads_data = app.GetRelevantObjects('*.ElmLod') for load in loads_data: try: load_curve = df[load.GetAttribute('loc_name'] except: print(f'load curve for {load.GetAttribute('loc_name']} not found') #catching error because load name is not in data

@BRYZERIAN
Copy link

Hi. I want to know if someone can help me in a issue that I´m having on Digsilent 2023... I want to know if it is posible to modify a setpoint value of a controller of a STATCOM during a RMS simulation; specifically when one specific line trips off (Meaning that the system would be running in N-1 condittions), for instance, at that moment when N-1 scenario occurs, instead of a setpoint value of 1 pu voltage at certain busbar, the statcom change that setpoint to look up for 0.98 pu. voltage.... Please if you can help me I´ll appreciate it.

@Sarah3802
Copy link

Sarah3802 commented Aug 22, 2023

Hi Everyone, did anybody know how can i create static generator objects in my project and then need to read date from csv file in order to give every photovoltic (static generator) their power and other properties??

@missto98
Copy link

Hello, . I'm trying to implement rms simulation via python code and I ran into a problem. I want to extract the value of a variable at a specific moment in time, but I don't know how to do it. can someone help me please? Regards!

@Sina833
Copy link

Sina833 commented Sep 24, 2023

Hi
I want to add a shunt element to a bus. How can I do it?
Thanks.

@ashbravo
Copy link

When I close powerfactory, I run the following python script:
import sys sys.path.append( r"C:\Program Files\DIgSILENT\PowerFactory 2022\Python\3.10") if __name__ == "__main__": import powerfactory app = powerfactory.GetApplication() if app is None: raise Exception('getting Powerfactory application failed')

Error reported:
Process finished with exit code -1073741819 (0xC0000005)

Tried many methods to no avail, if you have a similar situation and successfully solved it, or if you have other suggestions, please let me know, thank you for your help, it is greatly appreciated

@GermanAntonioFuentesTapias

import os
os.environ["PATH"]=r"C:\DIgSILENT\PF 2023_SP5"+os.environ["PATH"]
import sys
sys.path.append(r"C:\DIgSILENT\PF 2023_SP5\Python\3.8")

#IMPORTAR LA APLICACION

try:

import powerfactory as pf


app = pf.GetApplication()


app.Show()   

outputWindow = app.GetOutputWindow()
outputWindow.Print(pf.OutputWindow.MessageType.Plain, "Hello World!")

except Exception as e:

print("Error corregir",e)

Only close powerfactory, If powerfactory is run, Engine mode with Digrcom.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment