Exemple #1
0
def evalOneMax(individual):  # defining the objective function
    psspy.case(casestudy)
    for i in range(len(busidx0)):
        ierr = psspy.shunt_data(busidx0[i],
                                ID=1,
                                INTGAR=1,
                                REALAR1=0,
                                REALAR2=individual[i])
    psspy.fdns(OPTIONS1=0, OPTIONS5=0, OPTIONS6=1)

    PLOSS = 0
    for i in areas[0]:  # evaluating sum of losses in all areas
        ierr, area_loss = psspy.ardat(iar=i, string='LOSS')
        PLOSS = PLOSS + area_loss.real

    ierr, vpu = psspy.abusreal(-1, string="PU")
    vpu0 = vpu[0]
    JV = 0
    for i in range(nbus):
        if busidx[0][i] in busidx0:
            JV = JV + min(0, Vmin - vpu0[i])**2 + max(
                0, vpu0[i] - Vmax
            )**2  # Adding voltage limit, Vmin < V < Vmax, as a part of objective function
    W1, W2 = 1, 10
    J = W1 * PLOSS + W2 * JV
    # Objective function
    # print("  Loss %s" % PLOSS)

    return J,
Exemple #2
0
def run_savnw_simulation(datapath, outfile1, outfile2, outfile3, prgfile):

    import psspy
    psspy.psseinit()

    savfile = 'Converted_NETS-NYPS 68 Bus System_C.sav'
    snpfile = 'NETS-NYPS 68 Bus System.snp'

    if datapath:
        savfile = os.path.join(datapath, savfile)
        snpfile = os.path.join(datapath,
                               snpfile)  #why produce these two kinds of files?

    psspy.lines_per_page_one_device(1, 90)
    psspy.progress_output(2, prgfile, [0, 0])

    ierr = psspy.case(savfile)
    if ierr:
        psspy.progress_output(1, "", [0, 0])
        print(" psspy.case Error")
        return
    ierr = psspy.rstr(snpfile)
    if ierr:
        psspy.progress_output(1, "", [0, 0])
        print(" psspy.rstr Error")
        return

# fault + line trip
    psspy.strt(0, outfile1)
    psspy.run(0, 1.0, 1000, 1, 0)
    psspy.dist_bus_fault(52, 1, 138.0, [0.0, -0.2E+10])
    psspy.run(0, 1.1, 1000, 1, 0)
    psspy.dist_clear_fault(1)
    psspy.dist_branch_trip(52, 55, '1')
    psspy.run(0, 1.2, 1000, 1, 0)
    psspy.dist_machine_trip(1, '1')
    psspy.run(0, 5.0, 1000, 1, 0)

    # line trip (with faults) + generator trip
    psspy.case(savfile)
    psspy.rstr(snpfile)
    psspy.strt(0, outfile2)
    psspy.run(0, 1.0, 1000, 1, 0)
    psspy.dist_bus_fault(52, 1, 138.0, [0.0, -0.2E+10])
    psspy.run(0, 1.1, 1000, 1, 0)
    psspy.dist_clear_fault(1)
    psspy.run(0, 1.2, 1000, 1, 0)
    psspy.dist_machine_trip(8, '1')
    psspy.run(0, 5.0, 1000, 1, 0)

    psspy.case(savfile)
    psspy.rstr(snpfile)
    psspy.strt(0, outfile3)
    psspy.run(0, 1.0, 1000, 1, 0)
    psspy.dist_branch_trip(32, 33, '1')
    psspy.run(0, 5.0, 1000, 1, 0)

    psspy.lines_per_page_one_device(2, 10000000)
    psspy.progress_output(1, "", [0, 0])
Exemple #3
0
def network():
    """Set up the PSS/E case"""
    cwd = os.path.dirname(__file__)
    casename = os.path.join(cwd, 'cases/simple.sav')
    psspy.psseinit(10)
    psspy.case(casename)

    return {'load_bus': 1, 'gen': 2, 'load': 100.0}
Exemple #4
0
def getGeneratedPower():
    with silence():
        # initialize
        psspy.psseinit()
        # load case
        psspy.case(CASE_STUDY)
    PWR_GEN=[]
    for _id in MACHINE_IDS:
            _, _pmax = psspy.macdat(ibus=_id, id='1', string='PMAX') # find power of machine
            Pgen    =   P_gen*_pmax
            PWR_GEN.append(Pgen)
    return PWR_GEN
def run_savnw_simulation(datapath, outfile1, outfile2, outfile3, prgfile):

    import psspy
    psspy.psseinit()

    savfile = 'savcnv.sav'
    snpfile = 'savnw.snp'

    if datapath:
        savfile = os.path.join(datapath, savfile)
        snpfile = os.path.join(datapath, snpfile)

    psspy.lines_per_page_one_device(1, 90)
    psspy.progress_output(2, prgfile, [0, 0])

    ierr = psspy.case(savfile)
    if ierr:
        psspy.progress_output(1, "", [0, 0])
        print(" psspy.case Error")
        return
    ierr = psspy.rstr(snpfile)
    if ierr:
        psspy.progress_output(1, "", [0, 0])
        print(" psspy.rstr Error")
        return

    psspy.strt(0, outfile1)
    psspy.run(0, 1.0, 1000, 1, 0)
    psspy.dist_bus_fault(154, 1, 230.0, [0.0, -0.2E+10])
    psspy.run(0, 1.05, 1000, 1, 0)
    psspy.dist_clear_fault(1)
    psspy.run(0, 5.0, 1000, 1, 0)

    psspy.case(savfile)
    psspy.rstr(snpfile)
    psspy.strt(0, outfile2)
    psspy.run(0, 1.0, 1000, 1, 0)
    psspy.dist_machine_trip(3018, '1')
    psspy.run(0, 5.0, 1000, 1, 0)

    psspy.case(savfile)
    psspy.rstr(snpfile)
    psspy.strt(0, outfile3)
    psspy.run(0, 1.0, 1000, 1, 0)
    psspy.dist_branch_trip(3005, 3007, '1')
    psspy.run(0, 5.0, 1000, 1, 0)

    psspy.lines_per_page_one_device(2, 10000000)
    psspy.progress_output(1, "", [0, 0])
def load_case(path_to_case, case_name):
    #load the appropriate base case
    Case = path_to_case + case_name
    ##Load the SAV file
    psspy.case(Case)
    #increase iteration limit to 200
    psspy.solution_parameters_4([_i, 200, _i, _i, 10], [
        _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f,
        _f
    ])
    #solve load flow
    #Check that the load flow converged (if it converged: ierr = 0)
    ierr = run_power_flow()

    return
Exemple #7
0
def slurp_single_case(filename, case_letter):
    """
    Slurps a single case and initializes each element.
    Stores each row of data with unique keys in to the database
    """
    if not os.path.isfile(filename):
        print "Could not find file %s" % (filename, )
        raise IOError
    fnam, fext = os.path.splitext(filename)
    print '\nReading %s' % filename

    if 'sav' in fext:
        if app_settings.USE_CASPY and run_in_python('slurp.py', filename):
            # test to see if we can use CASPY or it crashes in a subprocess
            import caspy
            import psse_utils as utils
            case = caspy.Savecase(filename)
            assert case.pssopn[
                'IERR'] is 0, 'Error using caspy to read in %s: Check savecase version!!' % filename
            utils.fix_caspy_case(case)
        else:
            app_settings.USE_CASPY = False
            print 'Could not use Caspy'
            check_pssedongle()
            psspy.case(filename)
    else:
        check_pssedongle()
        app_settings.USE_CASPY = False
        with open(filename, 'r') as fid:
            rawheader = fid.readline()

        pssevers = check_psse_version(rawheader)
        psspy.readrawversion(0, pssevers, filename)

    slurp_con = get_slurp_db_con()
    slurp_con.execute("DELETE FROM slurp%s" % (case_letter, ))

    for e in elements.values():
        param_cnt = slurp_element(e, case_letter, slurp_con)
        elem_cnt = param_cnt / len(e.writables)

        if elem_cnt == 1:
            print 'Read in %s %s element.' % (elem_cnt, e.elem_name)
        else:
            print 'Read in %s %s elements.' % (elem_cnt, e.elem_name)

    slurp_con.commit()
    slurp_con.close()
def run_savnw_simulation(datapath, outfile, prgfile):

    import psspy
    psspy.psseinit()

    savfile = 'Converted_NETS-NYPS 68 Bus System_C.sav'
    snpfile = 'NETS-NYPS 68 Bus System.snp'

    if datapath:
        savfile = os.path.join(datapath, savfile)
        snpfile = os.path.join(datapath, snpfile)

    psspy.lines_per_page_one_device(1, 90)
    psspy.progress_output(2, prgfile, [0, 0])  # directly output to file
    #psspy.chsb(0,1,[-1,-1,-1,1,13,0])

    ierr = psspy.case(savfile)
    if ierr:
        psspy.progress_output(1, "", [0, 0])
        print(" psspy.case Error")
        return
    ierr = psspy.rstr(snpfile)
    if ierr:
        psspy.progress_output(1, "", [0, 0])
        print(" psspy.rstr Error")
        return

    # run generator trip automatically
    for i in range(16):
        psspy.case(savfile)
        psspy.rstr(snpfile)
        psspy.strt(0, outfile[i])
        #psspy.chsb(0,1,[-1,-1,-1,1,13,0])
        psspy.run(0, 1.0, 1000, 1, 0)
        psspy.dist_machine_trip(i + 1, '1')
        psspy.run(0, 5.0, 1000, 1, 0)

    psspy.lines_per_page_one_device(
        2, 10000000
    )  #Integer DEVICE Indicates which of the four output devices is to be processed (input;
    #1 for disk files.
    #2 for the report window.
    #3 for the first primary hard copy output device.
    #4 for the second primary hard copy output device.
    psspy.progress_output(1, "", [0, 0])
    return outfile, prgfile
def run_savnw_simulation(datapath, outfile, prgfile):

    import psspy
    psspy.psseinit()

    savfile = 'Converted_NETS-NYPS 68 Bus System_C.sav'
    snpfile = 'NETS-NYPS 68 Bus System.snp'

    if datapath:
        savfile = os.path.join(datapath, savfile)
        snpfile = os.path.join(datapath, snpfile)

    psspy.lines_per_page_one_device(1,90)
    psspy.progress_output(2,prgfile,[0,0]) # directly output to file 
    

    ierr = psspy.case(savfile)
    if ierr:
        psspy.progress_output(1,"",[0,0])
        print(" psspy.case Error")
        return
    ierr = psspy.rstr(snpfile)
    if ierr:
        psspy.progress_output(1,"",[0,0])
        print(" psspy.rstr Error")
        return

    # branches
    ibus,jbus,id=read_rawdata.branch_bus()
    for i,gener in enumerate(all_gener):
        psspy.case(savfile)
        psspy.rstr(snpfile)
        psspy.strt(0,outfile[i]) 
        psspy.run(0, 1.0,1000,1,0)
        dist_branch_fault(ibus[i], jbus[i], id[i])
        psspy.run(0, 1.2,1000,1,0)
        psspy.dist_clear_fault(1)
        psspy.run(0, 5.0,1000,1,0)

    psspy.lines_per_page_one_device(2,10000000)#Integer DEVICE Indicates which of the four output devices is to be processed (input;
    #1 for disk files.
    #2 for the report window.
    #3 for the first primary hard copy output device.
    #4 for the second primary hard copy output device.
    psspy.progress_output(1,"",[0,0])
    return outfile,prgfile
Exemple #10
0
def randdist(argin):
    filename=argin[0]
    percentage=argin[1]
    mode=argin[2]
    shuntctrlmode=0
    if mode!='arbitrary':
        shuntctrlmode=argin[3]
    psspy.case(filename)
    ierr, Qload=psspy.aloadcplx(-1, string="MVAACT")    
    Qload=[x.imag for x in Qload[0]]   
    ierr, tlbuses = psspy.aloadint(string='NUMBER')
    nbus=len(tlbuses[0])
    if mode=='random':
        zoseq=[0,1]*nbus
        sb=random.sample(zoseq,nbus)
    elif mode=='arbitrary':
        abus=argin[3]      # argin[3] in this case is the arbitrary buses to apply the disturbance
        sb=[0]*nbus
        for i in range(len(abus)):
            sb[tlbuses[0].index(abus[i])]=1            
    else:
        sb=[1]*nbus
    for j in range(nbus):
        if sb[j]==1:            
            Qd=Qload[j]+percentage/100.0*abs(Qload[j])
            ierr=psspy.load_data_3(i=tlbuses[0][j],REALAR2=Qd)
    if shuntctrlmode==1:
        for i in tlbuses[0]:
            ierr = psspy.switched_shunt_data_3(i, intgar9=1)
    psspy.fnsl(options1=0,options5=0)
    ierr, voltd = psspy.abusreal(-1, string="PU")        #voltage at buses after disturbance
    argout=[]
    argout.append(voltd)
    argout.append(Qload)
    argout.append(tlbuses)
    return argout;
    else:
        return hypot(x, y), atan2(y, x)


#---------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import math
from itertools import groupby

# PSS/E Saved case
#CASE = r"C:\Program Files\PTI\PSSE32\EXAMPLE\12TH_PLAN_MAR_2017R1.sav"
SAVFILE_LOCATION = r"C:\Program Files (x86)\PTI\PSSE33\EXAMPLE\\"
CASE = r"12TH_PLAN_MAR_2017R1.sav"
psspy.psseinit(9000)
psspy.case(SAVFILE_LOCATION + CASE)

###------------------------
ierr = psspy.bus_data_2(44010, intgar1=4)  #BkroA
ierr = psspy.bus_data_2(44031, intgar1=4)  #RTPSG2
ierr = psspy.bus_data_2(44034, intgar1=4)  #RTPSG3
ierr = psspy.bus_data_2(44035, intgar1=4)  #RTPSG4
ierr = psspy.bus_data_2(44036, intgar1=4)  #KODRG3
ierr = psspy.bus_data_2(44037, intgar1=4)  #KODRG4
ierr = psspy.bus_data_2(44140, intgar1=4)  #CHAS1
ierr = psspy.bus_data_2(44141, intgar1=4)  #RNIGNJ1
ierr = psspy.bus_data_2(44214, intgar1=4)  #RNIGNJ2
ierr = psspy.bus_data_2(44219, intgar1=4)  #GOLA2
ierr = psspy.bus_data_2(44227, intgar1=4)  #RTPS2
ierr = psspy.bus_data_2(44228, intgar1=4)  #MOSB2
ierr = psspy.bus_data_2(44230, intgar1=4)  #CHAS2
Exemple #12
0
        NcClose[0] = sys.argv[-2]
        NcClose[1] = sys.argv[-1]

    # Used for testing

    ##i in range(len(sys.argv)):
    ##    print sys.argv[i]
    ##    print '\n'
    ##print CapControlSign
    ##print '\n'
    ##print CapSubstationName
    ##print '\n'
    ##print CapControl

    # Load the PSSE save case
    psspy.case(testCaseName)
    savecase = (testCaseName)
    psspy.save(savecase)

    # determine the ratio and power flow of transformers
    psspy.bsys(sid=1, numbus=2, buses=bus_num)
    sid = 1
    flag = 2  # 2 = all non-tx branches 4 = all two-winding and non-transformer branches
    entry = 1  #1 = every branch once 2 = every branch from both sides
    ties = 1  # 1 = inside subsystem lines, # 2 = ties only, # 3 = everything
    ierr, ratio = psspy.atrnreal(sid, 2, ties, flag, entry, ['RATIO2'])
    ratio = ratio[0]
    fromflow = []
    for i in range(0, len(bus_num)):
        k = i + 1
        fromflow.append(brnflo(bus_num[1], bus_num[0], str(k)))
Exemple #13
0
redirect.psse2py()
psspy.psseinit(50000)
_i = psspy.getdefaultint()
_f = psspy.getdefaultreal()
_s = psspy.getdefaultchar()

##############################################################################
## Instrucciones para leer los casos de estudio y para simular                        ##
##############################################################################
#ruta= r"C:\mario\trabajos2\viesgo_applus_escenarios_red\simulacion\psse"
ruta = r"C:\David\PSSE_Viesgo"
#CASOraw= ruta + r"RDF_Caso_Base_2019_Pcc_wind10_2.raw"
CASOsav = ruta + r"\RDF_Caso_Base_2019_Pcc_wind10_2.sav"
SALIDALINEA = ruta + r"\Salida.txt"
psspy.case(CASOsav)
#psspy.fnsl([0,0,0,1,1,1,99,0])
#psspy.save(CASOsav)

#Volvemos a simular
psspy.fdns([0, 0, 0, 1, 1, 1, 99, 0])
U = psspy.solv()

#bus_i = 798
#bus_f = 734
#ierr, line_rx = psspy.brndt2( bus_i, bus_f, '1', 'RXZ')

##############################################################################
## Lee los buses del modelo
##############################################################################
ierr, busnumbers = psspy.abusint(sid=-1, string="NUMBER")
     if deg:
          return hypot(x, y), 180.0*atan2(y, x)/pi
     else:
          return hypot(x, y), atan2(y, x)
#---------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import math
from itertools import groupby

# PSS/E Saved case
#CASE = r"C:\Program Files\PTI\PSSE32\EXAMPLE\11TH_PLAN_REV_MAR_2012.sav"
#CASE = r"C:\Program Files\PTI\PSSE32\EXAMPLE\12TH_PLAN_MAR_2017R1.sav"
CASE = r"C:\Program Files (x86)\PTI\PSSE33\EXAMPLE\11TH_PLAN_REV_MAR_2012.sav"
psspy.psseinit(9000)
psspy.case(CASE)

#------------------------
ierr = psspy.bus_data_2(44405, intgar1=4) #BkroA
ierr = psspy.bus_data_2(44010, intgar1=4) #BkroA
ierr, realaro = psspy.two_winding_data(44010, 44405, "1", intgar1=0) #BTPSAG to BkroA
ierr, realaro = psspy.two_winding_data(44200, 44405, "1", intgar1=0) #btps-b to bokaro-a interconnection
ierr = psspy.branch_data(44402, 44405, "1", intgar1=0) #Koderma - BkroA line
ierr = psspy.branch_data(44402, 44405, "2", intgar1=0) #Koderma - BkroA line

# Case specific load changes to be indicated here
# CD as on 28.2.2014
ierr = psspy.load_data_3(44100, realar1=44.6) #BOKARO
ierr = psspy.load_data_3(44101, realar1=24.4) #MOSABANI
ierr = psspy.load_data_3(44102, realar1=123.7) #BURDWAN
ierr = psspy.load_data_3(44103, realar1=43.0) #BELMURI
                       1]  # acceleration sfactor used in the network solution
    integration_step = ts[test - 1]  # Simulation time step[s]

    _i = psspy.getdefaultint()
    _f = psspy.getdefaultreal()
    _s = psspy.getdefaultchar()
    redirect.psse2py()
    psspy.psseinit(50000)

    dVref = 0.05
    POC_VCtrl_Tgt = 1.00
    CON_PPCVref = 10
    VAR_PPCVini = 1

    FileName = f_list[case[test - 1] - 1]
    psspy.case(CasePath + FileName)
    psspy.resq(CasePath + "Tamworth_SMIB.seq")
    psspy.addmodellibrary(CasePath + 'SMASC_E161_SMAPPC_E130_342_IVF150.dll')
    psspy.dyre_new([1, 1, 1, 1], CasePath + "Tamworth_SMIB_E161_E130.dyr", '',
                   '', '')

    OutputFilePath = FigurePath + '05. PoC Vref Step Test' + "\\" + 'Test' + str(
        test +
        18) + '_' + FileName + '_sFac' + str(acceleration) + '_dT' + str(
            integration_step) + '_PoC Vref Step Test.out'
    # Setup Dynamic Simulation parameters
    psspy.dynamics_solution_param_2(
        [n_iteration, _i, _i, _i, _i, _i, _i, _i],
        [acceleration, tolerance, integration_step, _f, _f, _f, _f, _f])
    psspy.fdns([0, 0, 1, 1, 0, 0, 99, 0])
Exemple #16
0
def Run_SIM(x,dyr_file,out_file): #inputs are strings\
	dyre = r"""C:\Users\psse\Desktop\Phylicia\Error and Accuracy Tracking Project Sp18\RTS96\%s""" %dyr_file
	out = r"""C:\Users\psse\Desktop\Phylicia\Error and Accuracy Tracking Project Sp18\RTS96\Channels\opt_%s.out""" %out_file
	print dyr_file
	ierr = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] #checking for errors
	output = StringIO.StringIO()
	with silence(output):
		ierr[0] = psspy.psseinit(200000) #need to have this high, otherwise there are not enough output channels
		ierr[1] = psspy.case(r"""C:\Users\psse\Desktop\Phylicia\Error and Accuracy Tracking Project Sp18\RTS96\RTS96DYN.sav""")
		ierr[2] = psspy.fdns([0,0,0,1,1,0,99,0])
		ierr[3] = psspy.cong(0)
		ierr[4] = psspy.conl(0,1,1,[0,0],[ 100.0,0.0,0.0, 100.0])
		ierr[5] = psspy.conl(0,1,2,[0,0],[ 100.0,0.0,0.0, 100.0])
		ierr[6] = psspy.conl(0,1,3,[0,0],[ 100.0,0.0,0.0, 100.0])
		ierr[7] = psspy.ordr(0)
		ierr[8] = psspy.fact()
		ierr[9] = psspy.tysl(0)
		ierr[10] = psspy.dyre_new([1,1,1,1],dyre,"","","") 
		ierr[11] = psspy.chsb(0,1,[-1,-1,-1,1,13,0]) #record voltage
		ierr[12] = psspy.chsb(0,1,[-1,-1,-1,1,12,0]) #record frequency
		ierr[13] = psspy.chsb(0,1,[-1,-1,-1,1,1,0]) #angle
		ierr[14] = psspy.chsb(0,1,[-1,-1,-1,1,16,0]) #line P & Q
		ierr[15] = psspy.strt_2([0,0],out)
		ierr[16] = psspy.run(0, 0.1,1,1,0)
		#ierr[17] = psspy.dist_branch_fault(217,218,r"""1""",1, 230.0,[0.0,-0.2E+10]) #Line Fault, NaN (network no good)
		#ierr[17] = psspy.dist_bus_fault(211,1, 230.0,[0.0,-0.2E+10]) #bus Fault, NaN (network no good)
		#a = int(x[0])
		#b = int(x[1])
		#ierr[17] = psspy.branch_chng_3(a,b,r"""1""",[0,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f],"") #Line Outage
		x = int(x)
		print "before machine change"
		ierr[17] = psspy.machine_chng_2(x,r"""1""",[0,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) #Generator Outage
		print "after machine change"
		ierr[18] = psspy.change_channel_out_file(out)
		ierr[19] = psspy.run(0, 0.5,1,1,0) #this was 10
		psspy.dist_clear_fault(1)
		psspy.change_channel_out_file(out)
		psspy.run(1, 10.0,1,1,0)
		ierr[20] = psspy.delete_all_plot_channels()
		print "completed simulation"
	
	print ierr 
	run_output = output.getvalue()
	
	current_error = 0
	
	if "Network not converged" in run_output:
		print "Network not converged" #need to have something in if statement otherwise you get an indentation error
		result = 0 #this will go out to a if condition to rerun the program with a different selection of buses at this accuracy
		current_error = 1
		#raise SystemExit #this will quit the program
	elif "NaN" in run_output:
		print "NaN, network is no good"
		result = 0 #this will go out to a if condition to rerun the program with a different selection of buses at this accuracy
		current_error = 1
		#raise SystemExit #this will quit the program
	if current_error == 0 and "INITIAL CONDITIONS CHECK O.K." in run_output:
		print "continuing with study..."
	
        #Gather the data and output to excel
		data = dyntools.CHNF(out) #getting data from channel.out file
		d,e,z=data.get_data() #gathering data from data in dictionary format
	
        #Concatenate data so all data from one simulation is in one file
		c = 1 #must start at 1, not zero
        #Save Frequency and Voltage
		while c < 726: 
			if c < 100: #Record Angle
				v=z[c]
				new_v = ", ".join(str(i) for i in v) #this removes the brackets at the beginning and end of the list so can be processed in matlab 
				a = np.matrix(new_v) #make it into a matrix
				if c ==1:
					ang_all = np.copy(a)
				else: 
					ang_all = np.concatenate((ang_all,a),axis=0) #changed to concatenate vertically to test them all individually
			if c > 99 and c < 173: #Record Frequency
				v=z[c]
				new_v = ", ".join(str(i) for i in v) #this removes the brackets at the beginning and end of the list so can be processed in matlab 
				f = np.matrix(new_v) #make it into a matrix
				if c ==100:
					f_all = np.copy(f)
				else: 
					f_all = np.concatenate((f_all,f),axis=0) #changed to concatenate vertically to test them all individually
			if c > 172 and c < 246: #Record voltage magnitude
				v=z[c]
				new_v = ", ".join(str(i) for i in v) #this removes the brackets at the beginning and end of the list so can be processed in matlab 
				f = np.matrix(new_v) #make it into a matrix
				if c == 173:
					all = np.copy(f)
				else:
					all = np.concatenate((all,f),axis=0) #changed to concatenate vertically to test them all individually
			if c > 245 and c < 726: #Record P and Q
				if float(c/2) == int(c/2): #P , even numbers
					v=z[c]
					new_v = ", ".join(str(i) for i in v) #this removes the brackets at the beginning and end of the list so can be processed in matlab 
					f = np.matrix(new_v) #make it into a matrix
					if c == 246:
						P_all = np.copy(f)
					else:
						P_all = np.concatenate((P_all,f),axis=0) #changed to concatenate vertically to test them all individually
				else: #Q, odd numbers
					v=z[c]
					new_v = ", ".join(str(i) for i in v) #this removes the brackets at the beginning and end of the list so can be processed in matlab 
					f = np.matrix(new_v) #make it into a matrix
					if c == 247:
						Q_all = np.copy(f)
					else:
						Q_all = np.concatenate((Q_all,f),axis=0) #changed to concatenate vertically to test them all individually
			c = c+1
		result = [all, f_all, ang_all, P_all, Q_all] #0 is voltage, 1 is frequency
	return result
       NcClose[1] = sys.argv[-1]

    # Used for testing
    
    ##i in range(len(sys.argv)):
    ##    print sys.argv[i]
    ##    print '\n'
    ##print CapControlSign
    ##print '\n'
    ##print CapSubstationName
    ##print '\n'
    ##print CapControl


    # Load the PSSE save case
    psspy.case(testCaseName)
    savecase = (testCaseName)
    psspy.save(savecase)

    # determine the ratio and power flow of transformers
    psspy.bsys(sid = 1,numbus = 2, buses = bus_num)
    sid = 1
    flag = 2 # 2 = all non-tx branches 4 = all two-winding and non-transformer branches
    entry = 1 #1 = every branch once 2 = every branch from both sides
    ties = 1 # 1 = inside subsystem lines, # 2 = ties only, # 3 = everything
    ierr,ratio = psspy.atrnreal(sid,2,ties,flag,entry,['RATIO2'])
    ratio =ratio[0]
    fromflow = []
    for i in range(0,len(bus_num)):
        k = i + 1
        fromflow.append(brnflo(bus_num[1],bus_num[0],str(k)))
Exemple #18
0
observable_areas = excel_sheet_to_list(configuration_excel,
                                       observable_areas_configuration_sheet)

# Activation of PSSE
PSSE_LOCATION = r"C:\Program Files (x86)\PTI\PSSE33\PSSBIN"
sys.path.append(PSSE_LOCATION)
os.environ['PATH'] = os.environ['PATH'] + ';' + PSSE_LOCATION
import psspy

_f = psspy.getdefaultreal()
_i = psspy.getdefaultint()
_s = psspy.getdefaultchar()

psspy.psseinit(0)

psspy.case(PSSE_model_sav)

#Start of process

psspy.fnsl(powerflow_settings[powerflow_normal]
           )  #lahendus (Full Newton-Raphson/Lock taps/Lock shunts)

#Get inital data for areas

area_parameters = ["LOAD", "GEN", "LOSS", "INT"]

list_of_area_data = []

for area in areas:
    area_row = []
    area_row.append(area[0])
Exemple #19
0
# Prompt for cases to compare.  First case can be .raw or .sav.  Second case
# must be .sav.
print('Compare PSS/e cases.  The first case can be .raw or .sav.  ' + \
      '\nThe second case must be .sav.')
msg='Please enter the path/file.ext for the first case (.raw or .sav) file:'
while not os.path.isfile(case1_file):
    case1_file=input(msg)
    msg="Sorry, I can't find " + case1_file + ".  Try again."

msg='Please enter the path/file.ext for the second saved case (.sav) file:'
while not  os.path.isfile(case2_file):
    case2_file=input(msg)
    msg="Sorry, I can't find " + case1_file + ".  Try again."

#open a case
psspy.case(r"""C:\temp\sum16idctr1p4_v32.sav""")

# define a susbsytem to compare
# bsys() batch defines a bus subsystem 
ierr =psspy.bsys(0,0,[ 0.2, 999.],19,area_list,0,[],0,[],0,[])
if ierr != 0:
    print('Error defining subsystem.')

#Initialize
SID = 0      # subsystem identifier, 0 by default\
All = 0      # 1 = all busses; 0 = busses in subsystem\
APIOpt = 1   # 1 = inititalize, 2 = run comparison, 3 = done (cleanup)
Status = [0,0,0,0],   # List of 4 items.  see help['psspy.diff']
Thrsh = [0.0,0.0,0.0]  # thrsh1: difference threshold (default = 0)
#                      thrsh2: voltage or tap ratio threshold (default = 0)
#                      thrsh3: angle threshold (default = 0)
######input######

percentage = 350
ScaleLoadAtBuses = [314691, 314692, 314693, 314694, 314695]
TransformerRatioChangeStep = 0.007
shunt_bus = [314521, 314519]

######input######

# scale up the load

# silent the output
output = StringIO.StringIO()
with silence(output):
    psspy.case(
        r"""C:\Users\niezj\Desktop\16a_Fall\openECA_proj\LocalVoltageControl20161110\Test2\2019SUM_2013Series_Updated_forLocalVoltageControl.sav"""
    )
    savecase = (
        r"""C:\Users\niezj\Desktop\16a_Fall\openECA_proj\LocalVoltageControl20161110\Test2\2019SUM_2013Series_Updated_forLocalVoltageControl_BenchMark.sav"""
    )
    psspy.save(savecase)
    psspy.case(savecase)

    # determine the ratio and power flow of transformers
    bus_num = [314691, 314692]
    psspy.bsys(sid=1, numbus=2, buses=bus_num)
    sid = 1
    flag = 2  # 2 = all non-tx branches 4 = all two-winding and non-transformer branches
    entry = 1  #1 = every branch once 2 = every branch from both sides
    ties = 1  # 1 = inside subsystem lines, # 2 = ties only, # 3 = everything
    ierr, ratio = psspy.atrnreal(sid, 2, ties, flag, entry, ['RATIO2'])
Exemple #21
0
os.environ['PATH'] += ';' + psspath
psspath = r'C:\Program Files (x86)\PTI\PSSEXplore34\PSSBIN'  # change to the address of your PSSBIN directory on your computer
sys.path.append(psspath)
os.environ['PATH'] += ';' + psspath

import psspy
import redirect
import random

redirect.psse2py()
psspy.psseinit(10000)
casestudy = (
    r'network.sav'
)  # change the address and filename to the network that you want to apply the algorithm
psspy.case(
    casestudy
)  # load psse model defined by casestudy. since ardat function give areal losses we need these IDs to sum up all areal losses to find overall network loss
ierr, areas = psspy.aareaint(-1, 1, 'NUMBER')  # id of areas in the network.
psspy.fdns(
    OPTIONS1=0, OPTIONS5=0,
    OPTIONS6=1)  # run power flow in psse model using decoupled newton method
PLOSS1 = 0
for i in areas[
        0]:  # evaluating sum of losses in all areas, before compensation
    ierr, area_loss = psspy.ardat(iar=i, string='LOSS')
    PLOSS1 = PLOSS1 + area_loss.real

ierr, vpu1 = psspy.abusreal(
    -1, string="PU")  # voltage at all buses, before compensation
vpu01 = vpu1[0]
Exemple #22
0
def QVAnalysis(CASE,ireg,activateplot):

    busno = 44999 # Fictitious generator bus
    genid = 1
    status = 1
    pgen = 0.0 # Fict gen P output
    Qlimit = 9999.0 # Fict. gen Q limit
    pmax = 0.0 # Fict gen P limit
    
    #--------------------------------

    def add_machine():
        psspy.plant_data(busno, intgar1=ireg)
        psspy.machine_data_2(
            busno,
            str(genid),
            intgar1=int(status),
            realar1=pgen,
            realar3=Qlimit,
            realar4=-Qlimit,
            realar5=pmax)

    def get_mvar(i):
        """
        Changes the voltage set point at the synchronous machine
        solves the case
        returns the the new reactive power output of the sync machine.
        """
        psspy.plant_data(busno, realar1=i)
        ierr = psspy.fnsl()
        val = psspy.solved()
        if val == 0:
            ierr, mvar = psspy.macdat(busno, str(genid), 'Q')
            return mvar
        else:
            return None
        
    def get_genExhausted(pv):
        """
        get the number of gen whose reactive power got exhausted.
        """
        genExhausted = []
        GenReactivePowerOutput = getGenReactivePowerOutput(pv)
        GenReactivePowerMax = getGenReactivePowerMax(pv)
        GenReactivePowerMin = getGenReactivePowerMin(pv)
        for i in range(0,len(pv)):
            if GenReactivePowerOutput[i] == GenReactivePowerMax[i] \
               or GenReactivePowerOutput[i] == GenReactivePowerMin[i]:
                genExhausted.append(pv[i])
        return genExhausted
        
    
    psspy.psseinit(12000)
    psspy.case(CASE)
    psspy.solution_parameters_3(intgar2=60) # set number of solution iterations.

    psspy.bus_data_2(busno, intgar1=2, name='TEST')
    psspy.branch_data(i=busno, j=ireg)
    all_bus = findAllBuses()
    pq,pv,slackBus = findAllBusType(all_bus)
    add_machine()

    
    # get gen that exhausted its reactive power    
    genExhausted_old = get_genExhausted(pv) 

    pu = [x for x in np.arange(1.0, 0.2, -0.005)]
    varlist = []
    voltagelist = []
    
    for v in pu:
        res = get_mvar(v)
        if res:
            psspy.save("temp")
            varlist.append(res)
            voltagelist.append(v)
        else:
            break

    # get new gen that exhausted its reactive power
    psspy.case("temp")
    busGenExhausted = []
    genExhausted_new = get_genExhausted(pv)
    for bus in genExhausted_new:
        if bus not in genExhausted_old:
            busGenExhausted.append(bus)
                
    QminIndex = np.argmin(varlist)
    Qmin = varlist[QminIndex]
    Vmin = voltagelist[QminIndex]

    if activateplot == 1:
        plt.plot(voltagelist, varlist, '-o')
        plt.plot(Vmin,Qmin,'ro')
        plt.xlabel('PU')
        plt.ylabel('MVar')
        plt.grid()

    return Qmin,Vmin,busGenExhausted
        swing_gen = []

        for igentmp in range(0, len(vbasecasegenbusno)):
            genbuskeytmp = str(vbasecasegenbusno[igentmp]
                               ) + '-' + vbasecasegenid[igentmp].strip()
            genptmp = vbasecasegenp[igentmp] * vbasecasegenstatus[igentmp]
            basecase_gen_dict.update({genbuskeytmp: genptmp})

            # here we also need to find the swing generators
            if vbasecasegenbusno[igentmp] in swingbus:
                swing_gen.append(genbuskeytmp)

        #---------------------form the base case gen dictionary finished here-------------------------------

        # run ACCC for the new case from SCOPF
        psspy.case(savecase)
        #psspy.read(0,case)
        psspy.fnsl([0, 0, 0, 1, 1, 0, 0, 0])
        #psspy.rawd_2(0,1,[1,1,1,0,0,0,0],0, address + '\\' + caseX +'.raw')

        # creat sub-folder to store all the ACCC results
        caseX = caseX + '_scopf'
        if not os.path.isdir(scopfaddress + '\\' + caseX):
            os.makedirs(scopfaddress + '\\' + caseX)

        acccdfx = scopfaddress + '\\' + caseX + '\\' + caseX + '.dfx'
        accout = scopfaddress + '\\' + caseX + '\\' + caseX + '.acc'
        Zip = scopfaddress + '\\' + caseX + '\\' + caseX + '.zip'
        #Progress = address + '\\' + caseX + '\\' + 'Progress_' + caseX + '.txt'
        #logFile = file(Progress, "a")
        #sys.stdout = logFile
import redirect
import PowerSystemPsseLibrary as pssepylib
import random, pdb
redirect.psse2py()  # redirecting PSS\E output to python)

import numpy
import pdb
import scipy
from scipy import special, optimize
from scipy.sparse import bsr_matrix
from numpy import genfromtxt
from numpy import max

psspy.psseinit(80000)
savecase = 'IEEE_118.sav'
psspy.case(savecase)

import StringIO


@contextmanager
def silence(file_object=None):
    """
    Discard stdout (i.e. write to null device) or
    optionally write to given file-like object.
    """
    if file_object is None:
        file_object = open(os.devnull, 'w')

    old_stdout = sys.stdout
    try:
######input######

percentage = 350
ScaleLoadAtBuses = [314691,314692,314693,314694,314695]
TransformerRatioChangeStep = 0.007
shunt_bus = [314521,314519]

######input######

# scale up the load


# silent the output
output = StringIO.StringIO()
with silence(output):
    psspy.case(r"""C:\Users\niezj\Desktop\16a_Fall\openECA_proj\LocalVoltageControl20161110\Test2\2019SUM_2013Series_Updated_forLocalVoltageControl.sav""")
    savecase = (r"""C:\Users\niezj\Desktop\16a_Fall\openECA_proj\LocalVoltageControl20161110\Test2\2019SUM_2013Series_Updated_forLocalVoltageControl_BenchMark.sav""")
    psspy.save(savecase)
    psspy.case(savecase)

    # determine the ratio and power flow of transformers
    bus_num = [314691,314692]
    psspy.bsys(sid = 1,numbus = 2, buses = bus_num)
    sid = 1
    flag = 2 # 2 = all non-tx branches 4 = all two-winding and non-transformer branches
    entry = 1 #1 = every branch once 2 = every branch from both sides
    ties = 1 # 1 = inside subsystem lines, # 2 = ties only, # 3 = everything
    ierr,ratio = psspy.atrnreal(sid,2,ties,flag,entry,['RATIO2'])

    ratio =ratio[0]
    fromflow = []
os.chdir("..")
cwd = os.getcwd()  # Get the current directory
models = os.path.join(cwd, "Models")  # Name of the folder with the models

# Names of the case files
casefile = os.path.join(models, "Scenario1.sav")
dyrfile = os.path.join(models, "Scenario1.dyr")

# Name of the file where the dynamic simulation output is stored
outputfile = os.path.join(cwd, "output.out")

# Start PSS/E
psspy.psseinit(10000)
#
## Initiation----------------------------------------------------------------------------------------------------------------------------------
psspy.case(casefile)  # Read in the power flow data
psspy.dyre_new([1, 1, 1, 1], dyrfile, "", "", "")

# Convert the loads for dynamic simulation
psspy.cong(0)
psspy.conl(0, 1, 1, [0, 0], [10.0, 10.0, 0.0, 100.0])
psspy.conl(0, 1, 2, [0, 0], [10.0, 10.0, 0.0, 100.0])
psspy.conl(0, 1, 3, [0, 0], [10.0, 10.0, 0.0, 100.0])

# Set the time step for the dynamic simulation
psspy.dynamics_solution_params(realar=[_f, _f, 0.005, _f, _f, _f, _f, _f])

psspy.machine_array_channel([1, 2, 5500])  # Monitor Skien Power (as 5101 Hasle does not have any machine to measure frequency)
psspy.machine_array_channel([2, 7, 5500])  # Monitor Skien Frequency (as 5101 Hasle does not have any machine to measure frequency)

load = load_models.Load(3359)  # Create a load consisting of Ringhals
Exemple #27
0
    savFile = rawFileName + '.sav'
    snpFile = rawFileName + '.snp'


    print('Event: {}'.format(event))
    # get the nominal voltages as well as the fault impedance in ohms
    FaultBusNomVolt = float(BusDataDict[str(FaultBus)].NominalVolt)
    Zbase = FaultBusNomVolt**2/Sbase  # float since Sbase is a float
    Rohm = FaultRpu*Zbase # fault impedance in ohms 
             
    # run simulation till just before the fault
    output = StringIO.StringIO()
    with silence(output):
        # load the sav and snp file
        psspy.case(savFile)
        psspy.rstr(snpFile)
    #output = StringIO.StringIO()
    with silence(output):
        ierr = psspy.strt(0,out_file)
        ierr = psspy.run(0,0.1,1,1,1)
        ierr = psspy.dist_branch_trip(L1Bus1, L1Bus2, L1cktID)

    #output = StringIO.StringIO()
    with silence(output):
        ierr = psspy.run(0,0.2,1,1,1) #fault on time

    outputStr = output.getvalue()
    if "Network not converged" in outputStr:
        print('For ' + event + ':')
        print('Network did not converge between branch 1 trip and fault application, skipping...')
    try:
        sys.stdout = file_object
        yield
    finally:
        sys.stdout = old_stdout



# Read the C# information
inputDataFolder = sys.argv[1]
logsDataFolder = sys.argv[2]
caseName = sys.argv[-2]
testCaseName = sys.argv[-1]

# copy benchmark case as the test case
psspy.case(caseName)
savecase = (testCaseName)
psspy.save(savecase)



os.chdir(inputDataFolder)
for file in glob.glob("2016*.xml"):
        os.remove(file)

os.chdir(logsDataFolder)
for file in glob.glob("2016*.xml"):
        os.remove(file)

# delete all the transformers' input data files starts from the THIRD row
for i in range(0,2):
Exemple #29
0
    )

import os
import sys
PSSE_LOCATION = r'c:/program files/pti/psse32/pssbin'
sys.path.append(PSSE_LOCATION)
os.environ['PATH'] += ';' + PSSE_LOCATION

import psspy
import redirect
redirect.psse2py()

psspy.throwPsseExceptions = True

psspy.psseinit(1000)
psspy.case(savedcase)

ierr, (fromnumber, tonumber) = psspy.abrnint(
    sid=-1,
    flag=3,     # for all in service branches and two winding transformers.
    string=["FROMNUMBER", "TONUMBER"])
ierr, (weights,) = psspy.abrncplx(
    sid=-1,
    flag=3,
    string=["RX"]
    )

def inverse(cplx):
    return 1 / cplx.imag

weights = map(abs, weights)
Exemple #30
0
def randdist(argin):

    filename = argin[0]  # initializing input arguments
    maxdist = argin[1]
    mode = argin[2]
    shuntctrlmode = argin[3]
    capbus = argin[4]
    capstep = argin[5]
    capQ = argin[6]
    pilot = argin[7]
    ndist = argin[8]
    nswitch = argin[9]
    reloadfile = 1
    # By default the network data file will be reloaded at each iteration
    if len(argin) == 11:
        reloadfile = argin[10]
    psspy.case(filename)
    ierr, Qload = psspy.aloadcplx(
        -1, string="MVAACT"
    )  # Qload is the amount of apparent power (P+jQ) for all loads
    Qload = [
        x.imag for x in Qload[0]
    ]  # We just need Reactive power (Q) so we find imaginary part of apparent power
    ierr, tlbuses = psspy.aloadint(
        string='NUMBER'
    )  # tlbuses is all loads' bus nomber, it includes also the compensators that we have added as loads to the network
    nbus = len(tlbuses[0])  # nbus is No. of all load buses
    ncap = len(capbus)
    ierr, busn = psspy.abusint(-1, string='NUMBER')

    npn = len(pilot)

    volt = []
    voltd = []
    vpn = [[0 for x in range(npn)] for y in range(ndist * nswitch)]
    vpnd = [[0 for x in range(npn)] for y in range(ndist * nswitch)]
    dvpn = [[0 for x in range(npn)] for y in range(ndist * nswitch)]
    switch = [[0 for x in range(ncap)] for y in range(ndist * nswitch)]
    for i in range(
            ndist
    ):  # in this loop we generate ndist random distrurbane cases and apply nswitch control actions on each case
        if reloadfile == 1:
            psspy.case(filename)
        percentage = random.random(
        ) * maxdist  # choose randomly the amount of disturbance with maximum of maxdist
        zoseq = [0, 1] * nbus
        if mode == 'random':
            sb = random.sample(
                zoseq, nbus)  # choose randomly loads to apply the disturbance
        if mode == 'all': sb = [1] * nbus
        capQd = [0 for x in range(ncap)]
        for j in range(nbus):  # applying the disturbance
            if sb[j] == 1:
                ##                if not(tlbuses[0][j] in capbus):          # we make sure that no dist. applied on capacitor buses (which are considered also as loads)
                Qd = Qload[j] + percentage / 100.0 * abs(Qload[j])
                ierr = psspy.load_data_3(i=tlbuses[0][j], REALAR2=Qd)
            if tlbuses[0][j] in capbus:
                capidx = capbus.index(tlbuses[0][j])
                if sb[j] == 1:
                    capQd[capidx] = Qd
                else:
                    capQd[capidx] = Qload[j]
        if shuntctrlmode == 1:  # by this option we can unlock all compensators over the network
            for j in tlbuses[0]:
                ierr = psspy.switched_shunt_data_3(j, intgar9=1)

        print '###### DIST(' + str(i) + ') ########'
        psspy.fdns(OPTIONS1=0, OPTIONS5=0,
                   OPTIONS6=1)  # do power flow on the disturbed system
        ierr, v = psspy.abusreal(
            -1, string="PU"
        )  # and measure voltage at all buses after disturbance (there is no option in PSS to measure the voltage of just one bus)

        for j in range(
                nswitch):  # now we apply random cap. switchings nswitch times
            [scb, ss, qss] = capselect(capbus, capstep, capQ)

            print '### ADD CAP ###'
            for k in range(len(scb)):
                scbidx = capbus.index(scb[k])
                switch[i * nswitch + j][scbidx] = ss[k]

                capQd[scbidx] = capQd[scbidx] - ss[k] * qss[k]
                ierr = psspy.load_data_3(i=scb[k], REALAR2=capQd[scbidx])

            print '###### DIST(' + str(i) + ') , ' + 'SWITCHCASE(' + str(
                i * nswitch + j) + ') ########'
            psspy.fdns(OPTIONS1=0, OPTIONS5=0,
                       OPTIONS6=1)  # do power flow on the disturbed system
            ierr, vd = psspy.abusreal(
                -1, string="PU"
            )  # and measure voltage at all buses after disturbance (there is no option in PSS to measure the voltage of just one bus)
            voltd.append(vd)
            volt.append(v)
            for k in range(npn):  # measuring vpn, and vpnd as outputs
                pnidx = busn[0].index(pilot[k])
                vpn[i * nswitch + j][k] = v[0][pnidx]
                vpnd[i * nswitch + j][k] = vd[0][pnidx]
                dvpn[i * nswitch +
                     j][k] = vpnd[i * nswitch + j][k] - vpn[i * nswitch + j][k]
            print '### REMOVE CAP ###'
            for k in range(
                    len(scb)
            ):  # after cap switchings we remove their effect for next switching
                scbidx = capbus.index(scb[k])
                capQd[scbidx] = capQd[scbidx] + ss[k] * qss[k]
                ierr = psspy.load_data_3(i=scb[k], REALAR2=capQd[scbidx])

    return volt, voltd, vpn, vpnd, dvpn, switch
def Initialize_Case(case_file):

	psspy.psseinit(150000) #Initialize size of case, just choose large number
	psspy.case(case_file) #Load example case savnw.sav
     if deg:
          return hypot(x, y), 180.0*atan2(y, x)/pi
     else:
          return hypot(x, y), atan2(y, x)
#---------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import math
from itertools import groupby

# PSS/E Saved case
#CASE = r"C:\Program Files\PTI\PSSE32\EXAMPLE\12TH_PLAN_MAR_2017R1.sav"
SAVFILE_LOCATION = r"C:\Program Files (x86)\PTI\PSSE33\EXAMPLE\\"
CASE = r"12TH_PLAN_MAR_2017R1.sav"
psspy.psseinit(9000)
psspy.case(SAVFILE_LOCATION + CASE)

###------------------------
ierr = psspy.bus_data_2(44010, intgar1=4) #BkroA
ierr = psspy.bus_data_2(44031, intgar1=4) #RTPSG2
ierr = psspy.bus_data_2(44034, intgar1=4) #RTPSG3
ierr = psspy.bus_data_2(44035, intgar1=4) #RTPSG4
ierr = psspy.bus_data_2(44036, intgar1=4) #KODRG3
ierr = psspy.bus_data_2(44037, intgar1=4) #KODRG4
ierr = psspy.bus_data_2(44140, intgar1=4) #CHAS1
ierr = psspy.bus_data_2(44141, intgar1=4) #RNIGNJ1
ierr = psspy.bus_data_2(44214, intgar1=4) #RNIGNJ2
ierr = psspy.bus_data_2(44219, intgar1=4) #GOLA2
ierr = psspy.bus_data_2(44227, intgar1=4) #RTPS2
ierr = psspy.bus_data_2(44228, intgar1=4) #MOSB2
ierr = psspy.bus_data_2(44230, intgar1=4) #CHAS2
import redirect
import PowerSystemPsseLibrary as pssepylib
import random, pdb
redirect.psse2py() # redirecting PSS\E output to python)

import numpy
import pdb
import scipy
from scipy import special,optimize
from scipy.sparse import bsr_matrix
from numpy import genfromtxt
from numpy import max

psspy.psseinit(80000)
savecase = 'IEEE_118.sav'
psspy.case(savecase)

import StringIO

@contextmanager
def silence(file_object=None):
    """
    Discard stdout (i.e. write to null device) or
    optionally write to given file-like object.
    """
    if file_object is None:
        file_object = open(os.devnull, 'w')

    old_stdout = sys.stdout
    try:
        sys.stdout = file_object
Exemple #34
0
import sys, os
sys.path.append(pssbin_path)
os.environ['PATH'] = (pssbin_path + ';' + os.environ['PATH'])
import psspy, redirect, dyntools, pssplot

# Import PSS/E default
_i = psspy.getdefaultint()
_f = psspy.getdefaultreal()
_s = psspy.getdefaultchar()
redirect.psse2py()

# -------------------------------------------------- #
# initiate
psspy.psseinit(2000)  # 2000 bus at most, this number can be changed
# Load and solve the powerflow case
psspy.case(sav_case)
# configure the solver
psspy.fnsl(options1=0, options5=0)
# sikve the power flow case
iVal = psspy.solved()
if iVal == 0:
    print "Met convergence tolerance"
elif iVal == 1:
    print "The iteration limit exceeded"
elif iVal > 1:
    print "Blown up or others"

# ------------------------------------------------- #
# Dynamic Simulation
# Convert gen & load
# convert generators
    if file_object is None:
        file_object = open(os.devnull, 'w')

    old_stdout = sys.stdout
    try:
        sys.stdout = file_object
        yield
    finally:
        sys.stdout = old_stdout

output = StringIO.StringIO()
with silence(output):

    psspy.psseinit(80000)             # initialize PSS\E in python
    savecase = 'IEEE 57 bus.sav'
    psspy.case(savecase)


    # find all the buses
    psspy.bsys(0,0,[0.0,0.0],1,[1],0,[],0,[],0,[])
    ierr,all_bus = psspy.abusint(0,1,['number'])
    bus_num = all_bus[0]

    #List of all machines
    psspy.bsys(sid = 1,numbus = len(bus_num), buses = bus_num)
    ierr,machine_bus = psspy.amachint(1,1,['NUMBER'])
    machine_bus = machine_bus[0]
    ierr,machine_id =  psspy.amachchar(1,1,['ID'])
    machine_id = machine_id[0]

    #List of all Gen
Exemple #36
0
os.environ['PATH'] = (r"C:\Program Files (x86)\PTI\PSSE32\PSSBIN;"
                      + os.environ['PATH'])

#add the the above line 


#Here is the macro script
import psspy
import redirect
_i=psspy.getdefaultint()
_f=psspy.getdefaultreal()
_s=psspy.getdefaultchar()
redirect.psse2py()
import pssdb
psspy.psseinit(80000)
psspy.case(r"""psse.sav""")
psspy.resq(r""" psse.seq""")
psspy.lines_per_page_one_device(1,60)
psspy.report_output(2,r"""report.txt""",[0,0])
psspy.flat([1,1,1,0],[0.0,0.0])
psspy.seqd([0,0])
psspy.sequence_network_setup(0)
psspy.scmu(1,[0,0,0,0,0,0,0],[0.0,0.0,0.0,0.0,0.0],"")
psspy.scmu(2,[7,1082,0,0,0,0,0],[0.0,0.0,0.0,0.0,0.0],"")
psspy.scmu(3,[7,1082,0,0,0,0,0],[0.0,0.0,0.0,0.0,0.0],"")
psspy.sequence_network_setup(0)
#end of script

# add below line to show the report
f=open("report.txt",'r')
for line in f.readlines():
    import redirect
    redirect.psse2py()

    # Silence Type
    # 0. silence all outputs
    # 1. silence all outputs but restore them in a log file
    # 2. silence all output and put them in a StringIO object, release them as required
    SilenceType = 0
    if SilenceType == 0:

        # silence all outputs
        print "Choose Silence Type 0: silence all outputs\n"
        with silence():
            psspy.psseinit(10000)
            # Load and solve the powerflow case
            ierr = psspy.case(sav_case)
            iVal = psspy.solved()

    elif SilenceType == 1:

        # redirect output into the log file
        print "Choose Silence Type 1: silence all outputs and restore them in 'psse_logfile.log'\n"
        psse_log = open('psse_logfile.log', 'w')
        with silence(psse_log):
            psspy.psseinit(10000)
            # Load and solve the powerflow case
            ierr = psspy.case(sav_case)
            iVal = psspy.solved()

    elif SilenceType == 2:
    GridInfoPath = "F:/PosDoc Projects/11_Industrial Projects/HuaWei/WISF/" + "D_" + LoadScenario + "/"
    HuaweiModelPath = "F:/PosDoc Projects/11_Industrial Projects/HuaWei/WISF/D_HuaweiModels/"

    FigurePath = "F:/PosDoc Projects/11_Industrial Projects/HuaWei/WISF/R_Results/"
    TestName = "5.2.5.5_contingency"

    if LoadScenario == "SummerPeakLoad":
        file_name = "SummerHi-20171219-153047-34-SystemNormal"
    if LoadScenario == "SummerLowLoad":
        file_name = "SummerLowNormal-20161225-040047"
    if LoadScenario == "SimplifiedSystem":
        file_name = "WISF_ADD"
    # start simulation
    OutputFilePath = ProgramPath + str(fault_type) + "SimulationOutput4.outx"
    TimeShift = 0
    psspy.case(GridInfoPath + file_name + ".sav")
    # psspy.rstr(GridInfoPath+file_name+".snp")
    psspy.resq(GridInfoPath + "/" + file_name + ".seq")
    psspy.dyre_new([1, 1, 1, 1], GridInfoPath + "/" + file_name + ".dyr", "",
                   "", "")
    psspy.addmodellibrary(HuaweiModelPath + 'HWS2000_psse34.dll')
    psspy.addmodellibrary(HuaweiModelPath + 'MOD_GPM_PPC_V13_34.dll')
    psspy.addmodellibrary(HuaweiModelPath + 'MOD_GPM_SB_V7.dll')
    psspy.dynamics_solution_param_2([_i, _i, _i, _i, _i, _i, _i, _i],
                                    [0.300, _f, 0.001, 0.004, _f, _f, _f, _f])
    psspy.machine_data_2(
        500, r"""1""", [_i, _i, _i, _i, _i, _i],
        [90, _f, _f, _f, 96.8, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f])
    psspy.fnsl([0, 0, 0, 1, 1, 1, 99, 0])

    psspy.bus_frequency_channel([1, 1000], r"""System frequency""")
 import sys
 sys.path.append('C:\Program Files (x86)\PTI\PSSEXplore34\PSSBIN'
                 )  #make this point to the pssbin directory
 os.environ['PATH'] = (r'C:\Program Files (x86)\PTI\PSSEXplore34\PSSBIN;' +
                       os.environ['PATH'])
 import redirect
 redirect.psse2py()
 import psspy
 psspy.throwPsseExceptions = True
 nbuses = 50
 #max no of buses
 pathname = r"C:\Users\Narasimham\Desktop\Sevenbus\Loads"  #path of the folder containing the solved base case
 casefile = os.path.join(pathname,
                         "7Bus_conv.sav")  #use the solved base case
 ierr = psspy.psseinit(nbuses)
 psspy.case(casefile)
 for i in range(2, 26):
     print('Changing additional loads...')
     psspy.load_chng_4(1,
                       '1',
                       realar1=sheet.cell(row=i, column=2).value,
                       realar2=0.01 * sheet.cell(row=i, column=2).value)
     psspy.load_chng_4(3,
                       '1',
                       realar1=sheet.cell(row=i, column=3).value,
                       realar2=0.01 * sheet.cell(row=i, column=3).value)
     psspy.load_chng_4(4,
                       '1',
                       realar1=sheet.cell(row=i, column=4).value,
                       realar2=0.01 * sheet.cell(row=i, column=4).value)
     psspy.load_chng_4(5,
Exemple #40
0
indexControl = 16

databaseOCandLabels = 'database_OC_PostControl_' + str(indexControl) + '.csv'
if os.path.isfile(databaseOCandLabels):
    os.remove(databaseOCandLabels)

secure = []
Vol_violation = []
insecure_index = []

output = StringIO.StringIO()
with silence(output):
    with open(databaseOCandLabels, 'a') as f1:
        for i in range(0, len(GeneratedOC)):
            psspy.case('ieee118bus_divided_basecase.sav')

            #trip a line
            fromBus = 15
            toBus = 33
            dist_branch_trip(fromBus, toBus)

            #Apply Control
            control_cap([0, 1, 0, 0, 0, 0])

            #change load operating points
            load_change_region1 = GeneratedOC[i][0]
            load_change_region2 = GeneratedOC[i][1]
            load_change_region3 = GeneratedOC[i][2]

            loadIncrement_region1 = LoadIncreaseMW(load_bus_region[0],
Exemple #41
0
 def __init__(self, studyCase):
     '''
     Constructor
     '''
     psspy.psseinit(1000)
     psspy.case(studyCase)