Ejemplo n.º 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,
Ejemplo n.º 2
0
def Convert_Dynamic():
	psspy.fdns([0,0,0,1,1,0,99,0]) #Solve fixed slope decoupled newton raphson	
	psspy.cong(0) #Convert our generators using Zsource (Norton Equiv)
	psspy.conl(0,1,1,[0,0],[ 100.0,00.0,00.0, 100.0]) #Convert our loads (represent active power as 100% constant current type, reactive power as 100% constant impedance type.)
	psspy.conl(0,1,2,[0,0],[ 100.0,00.0,00.0, 100.0]) #Convert our loads
	psspy.conl(0,1,3,[0,0],[ 100.0,00.0,00.0, 100.0]) #Convert our loads
	psspy.ordr(0) #Order network for matrix operations
	psspy.fact() #Factorize admittance matrix
	psspy.tysl(0) #Solution for Switching Studies
def run_power_flow():
    #ierr = psspy.fdns([1,0,0,1,1,0,0,0])
    #ierr = psspy.fdns([1,0,0,1,1,0,0,0])
    #ierr = psspy.fdns([1,0,1,1,1,0,0,0])

    ierr = psspy.fdns([0, 0, 0, 1, 1, 0, 0, 0])
    ierr = psspy.fdns([1, 0, 0, 1, 1, 0, 0, 0])
    ierr = psspy.fdns([1, 0, 1, 1, 1, 0, 0, 0])

    return ierr
Ejemplo n.º 4
0
    def _initialize_psse(self):
        redirect.psse2py()
        psspy.psseinit(1000)

        # Read load flow and dynamic files
        psspy.read(0, self.raw_file)
        psspy.dyre_new([1, 1, 1, 1], self.dyr_file, "", "", "")
        psspy.fdns([0, 0, 0, 1, 1, 0, 0, 0])
        # Convert Generator and Loads
        psspy.cong(0)
        # Order Network for matrix operation
        psspy.ordr(0)
        # Factorize Admittance matrix
        psspy.fact()
        # Solve switching study network solutions
        psspy.tysl()
Ejemplo n.º 5
0
def reduceModel(zonebuses):
    # Reduce the model
    psspy.bsys(sid=1, numbus=len(zonebuses), buses=zonebuses)
    psspy.gnet(sid=1, all=0)
    psspy.island()
    psspy.fdns(options=[1, 0, 1, 1, 1, 0, 0, 0])
    psspy.eeqv(sid=1, all=0, status=[0, 0, 0, 0, 1, 0], dval1=0)
    psspy.island()
    ierr = psspy.fdns(options=[1, 0, 1, 1, 1, 0, 0, 0])
    ival = psspy.solved()
    reducedModelName = "reduced"
    print "ival equal to "
    print ival
    if ival == 0:
        psspy.save(reducedModelName)
    else:
        return None
    return reducedModelName
Ejemplo n.º 6
0
_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")
ierr, busnames = psspy.abuschar(sid=-1, string="NAME")
ierr, busvoltages = psspy.abusreal(sid=-1, string="BASE")
#ierr, bus_shunts = psspy.abuscplx(sid=-1, string="SHUNTACT")

##############################################################################
Ejemplo n.º 7
0
                    max(S_BESS * S_BESS * derate * derate - P_BESS * P_BESS,
                        0)))

            psspy.machine_chng_2(100, r"""1""", [_i, _i, _i, _i, _i, _i], [
                P_Gen_1, Q_Gen_1, Q_Gen_1, Q_Gen_1, S_1, _f, _f, _f, _f, _f,
                _f, _f, _f, _f, _f, _f, _f
            ])
            psspy.machine_chng_2(200, r"""1""", [_i, _i, _i, _i, _i, _i], [
                P_BESS, Q_Gen_BESS, Q_Gen_BESS, Q_Gen_BESS, S_BESS, _f, _f, _f,
                _f, _f, _f, _f, _f, _f, _f, _f, _f
            ])
            # psspy.machine_chng_2(200, r"""1""", [_i, _i, _i, _i, _i, _i],  [P_BESS, _f,   _f,    _f,    S_BESS, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f])

            psspy.plant_data_3(SMIB_bus_no, 0, _i, [terminalv, _f])
            # fixed slope decoupled Newton-Raphson power flow calculation, 1_tap, 2_area_interchange, 3_phase_shift, 4_dc_tap, 5_switched shunt,6_flat_start, 7_Var_limit,8__non-divergent solution
            ierr = psspy.fdns([1, 0, 0, 1, 1, 0, 99, 0])

            #brnmsc: return real branch flow values
            ierr, pval = psspy.brnmsc(POC_bus_gen, POC_bus_grid, '1',
                                      'P')  # POC_P_value

            ierr, qval = psspy.brnmsc(POC_bus_gen, POC_bus_grid, '1',
                                      'Q')  # POC_Q_value

            ierr, vval = psspy.busdat(inverter_bus_1,
                                      'PU')  # inverter_terminal_voltage

            valid_pq = 0
            loop = 0
            while (1):
                if ((math.sqrt(P_Gen_1**2 + Q_Gen_1**2) <
Ejemplo n.º 8
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
Ejemplo n.º 9
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
Ejemplo n.º 10
0
    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

    ctrl = [0, 1, -1, 0, 0, 0, 0, 2, -1, 1, 0, 2, 0, 1, 0, 1]
    Qctrl = [0 for x in range(ncap)]
    for k in range(len(ctrl)):
        Qctrl[k] = Qload[tlbuses[0].index(capbus[k])] - ctrl[k] * capQ[k]
        ierr = psspy.load_data_3(i=capbus[k], REALAR2=Qctrl[k])
    psspy.fdns(OPTIONS1=0, OPTIONS5=0,
               OPTIONS6=1)  # do power flow on the disturbed system
    ierr, voltdc = 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)

    x2 = excelpy.workbook(
        r'C:\Documents and Settings\xw0419\Mes documents\Mon Projet\Simulation\IREQ\PythonProgs\final_result.xls',
        sheet="Feuil1",
        overwritesheet=True,
        mode='w')
    x2.show()
    x2.show_alerts(False)

    x2.set_range(2, 1, zip(*volt[0]))
    x2.set_range(2, 2, zip(*volt1[0]))
    x2.set_range(2, 3, zip(*[voltdc[0]]))
        gen_bus = gen_bus[0]

        #change the load and the generation
        percentage = 1 - (current_percentage - 5) / current_percentage
        pssepylib.change_load(load_bus, percentage)
        increment = pssepylib.LoadIncreaseMW(load_bus, percentage)
        pssepylib.change_gen(gen_bus, increment)

        # try:
        #   load_real_sum = sum(load_real)
        # except:
        #   pdb.set_trace()

        # run load flow
        #psspy.case(savecase)
        psspy.fdns()

        # check convergency
        N = psspy.solved()

    if N == 0:

        output = StringIO.StringIO()
        with silence(output):
            case_name = case_name_constant % (current_percentage - 5)
            psspy.save(case_name)

    else:

        print '### system collapses ###'
        #break
Ejemplo n.º 12
0
##ierr = psspy.branch_data(44202, 44207, "1", intgar1=0) #ctps-mtps line
##ierr = psspy.branch_data(44202, 44207, "2", intgar1=0)
##
##ierr = psspy.branch_data(44403, 45400, "1", intgar1=0) #RTPS - ranchi line
##ierr = psspy.branch_data(44403, 45400, "2", intgar1=0) 
##ierr = psspy.branch_data(44404, 45404, "1", intgar1=0) #DSTPS - paruliaPG line
##ierr = psspy.branch_data(44404, 45404, "2", intgar1=0) 
##ierr = psspy.branch_data(44404, 44403, "1", intgar1=1) #DSTPS - RTPS line
##ierr = psspy.branch_data(44404, 44403, "2", intgar1=1) 

#----------------------------

psspy.solution_parameters_2(intgar1=150)
psspy.fdns(option1=0, #tap adjustment disabled
           option2=0, #area interchange disables
           option3=0, #phase shift option disabled
           option4=0, #dc tap adjustment option disabled
           option5=0, #switched shunt adjustment option disabled
           )
psspy.fnsl()
psspy.inibus(0)
#ierr = psspy.pout(sid=1, all=0)
#n = psspy.totbus()

ierr = psspy.bsys(sid=1, numzone=1, zones=44)
businfo = subsystem_info('bus', ['NUMBER', 'BASE', 'NAME'], sid=-1)
#print businfo
mybuslst = subsystem_info('bus', ['NUMBER', 'BASE', 'NAME'], sid=1)
#print mybuslst
mygeninfo = subsystem_info('mach', ['NUMBER', 'PGEN', 'NAME'], sid=1)
#print mygeninfo
myloadinfo = subsystem_info('load', ['NUMBER', 'MVAACT', 'NAME'], sid=1)
Ejemplo n.º 13
0
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]

ierr, busidx = psspy.abusint(-1, string='NUMBER')  # find All buses
busidx0 = []
nbus = len(busidx0)  # No. of all buses
ierr, PVidx = psspy.agenbusint(-1, 1, 'NUMBER')  # find PV buses
Ejemplo n.º 14
0
##ierr = psspy.branch_data(44202, 44207, "2", intgar1=0)
##
##ierr = psspy.branch_data(44403, 45400, "1", intgar1=0) #RTPS - ranchi line
##ierr = psspy.branch_data(44403, 45400, "2", intgar1=0)
##ierr = psspy.branch_data(44404, 45404, "1", intgar1=0) #DSTPS - paruliaPG line
##ierr = psspy.branch_data(44404, 45404, "2", intgar1=0)
##ierr = psspy.branch_data(44404, 44403, "1", intgar1=1) #DSTPS - RTPS line
##ierr = psspy.branch_data(44404, 44403, "2", intgar1=1)

#----------------------------

psspy.solution_parameters_2(intgar1=150)
psspy.fdns(
    option1=0,  #tap adjustment disabled
    option2=0,  #area interchange disables
    option3=0,  #phase shift option disabled
    option4=0,  #dc tap adjustment option disabled
    option5=0,  #switched shunt adjustment option disabled
)
psspy.fnsl()
psspy.inibus(0)
#ierr = psspy.pout(sid=1, all=0)
#n = psspy.totbus()

ierr = psspy.bsys(sid=1, numzone=1, zones=44)
businfo = subsystem_info('bus', ['NUMBER', 'BASE', 'NAME'], sid=-1)
#print businfo
mybuslst = subsystem_info('bus', ['NUMBER', 'BASE', 'NAME'], sid=1)
#print mybuslst
mygeninfo = subsystem_info('mach', ['NUMBER', 'PGEN', 'NAME'], sid=1)
#print mygeninfo
    def runSimulation(self):
        """Runs the simulation by crating an instance of psspy, loading the raw and dyr data, applying the disturbance and controling PEV output power. Finally plots in native PSS/E or export to matlab."""
        sufix = str(self._disturbance)+"_"+str(self._control)
        conec_file = trash_dir+"\\CC1_"+sufix+".out"
        conet_file = trash_dir+"\\CT1_"+sufix+".out"
        compile_file = trash_dir+"\\compile_"+sufix+".out"
    
        psspy.psseinit(49)
        
        #suppress output if required, else redirect it to python
        if self._suppress_output:
            psspy.report_output(6,"",[0,0])
            psspy.progress_output(6,"",[0,0])
            #psspy.progress_output(2,r"""pot.txt""",[0,0])
        else:
            #redirect psse output to python
            import redirect
            redirect.psse2py()
    
        #----------------------
        #read in case data
        psspy.read(0,self._power_system_object._raw_filename)

        #solve the power flow
        psspy.fdns([0,0,0,1,1,1,99,0])

        #----------------------
        #convert all generators
        psspy.cong(0)

        #----------------------
        #conv_standard_loads
        #change the vector of numbers to get constant current, admittance or power conversion
        utils.convertLoads([0.0,100.0,0.0,100.0])

        #convert the PEVs to constant power loads
        utils.convertPEVs()
        
        #----------------------------------------
        #read in dynamics data

        psspy.dyre_new([1,1,1,1],self._power_system_object._dyr_filename,"","","")

        #solve power flow with dynamics tysl - and fact devices (was in tutorial) - not sure if we need it though
        psspy.fact()
        psspy.tysl(1)
    
        #set up pre designated channels
        self._channels.setUpChannels()
    
    
        #designate channel output_file
        psspy.strt(0,self._channels._channel_file)
        
        self._performDynamicSimulation()
        
        if self._plot:
            self._channels.plot(self._channels._channels_to_include)
            
        if self._export_to_matlab:
            description = sufix.replace(" ","_").replace(".","_").replace("=","__")
            self._channels.exportToMatlab(matlab_dir+"\\"+description+".m",description,True,True,self._export_figures)
            if self._export_figures:
                import win32com.client
                h = win32com.client.Dispatch('matlab.application')
                h.Execute ("cd('"+os.getcwd()+"\\"+matlab_dir+"');")
                h.Execute (description)
            
            
        #clean up
        try:
            os.remove(conec_file)
        except:
            pass
        try:
            os.remove(conet_file)
        except:
            pass
        try:
            os.remove(compile_file)
        except:
            pass
            
        return self._channels
        fromflow.append(brnflo(bus_num[1],bus_num[0],str(k)))

    ReactivePowerDifference = abs(fromflow[0].imag - fromflow[1].imag)
    RealPowerDifference = abs(fromflow[0].real - fromflow[1].real)

    # Scale up the load at certain percentage
    change_load(ScaleLoadAtBuses,percentage)
    load = aloadreal(0,1,'TOTALACT')
    load = load[0]

##    #switch off the capbank
##    for shunt_bus_num in shunt_bus:
##        switchOffCap(shunt_bus_num)

    # run load flow
    psspy.fdns()
    N = psspy.solved()
    
    if N == 0:

        # measure the voltage at each bus
        psspy.bsys(sid = 1,numbus = len(bus_num), buses = bus_num)
        ierr,bus_voltage = psspy.abusreal(1,1,['PU'])
        bus_voltage = bus_voltage[0]
        psspy.save(savecase)

    else:

        print '### system collapses ###'

                _f, _f, _f, _f
            ])
            psspy.machine_data_2(102, r"""1""", [_i, _i, _i, _i, _i, _i], [
                P_Gen, Q_Gen, Q_Gen, Q_Gen, S, 0, _f, _f, _f, _f, _f, _f, _f,
                _f, _f, _f, _f
            ])
            psspy.machine_data_2(103, r"""1""", [_i, _i, _i, _i, _i, _i], [
                P_Gen, Q_Gen, Q_Gen, Q_Gen, S, 0, _f, _f, _f, _f, _f, _f, _f,
                _f, _f, _f, _f
            ])
            psspy.machine_data_2(104, r"""1""", [_i, _i, _i, _i, _i, _i], [
                P_Gen, Q_Gen, Q_Gen, Q_Gen, S, 0, _f, _f, _f, _f, _f, _f, _f,
                _f, _f, _f, _f
            ])
            psspy.plant_data(600, _i, [terminalv, _f])
            psspy.fdns([1, 0, 1, 1, 1, 1, 99, 0])
            ierr, pval = psspy.brnmsc(
                400, 46660, '1', 'P')  # chang: make sure there is such branch.
            ierr, qval = psspy.brnmsc(400, 46660, '1', 'Q')
            ierr, vval = psspy.busdat(101, 'PU')

            valid_pq = 0
            loop = 0
            while (1):
                if ((math.sqrt(P_Gen**2 + Q_Gen**2) <
                     ((S * min(derate, vval)) + 0.02)) and vval <= 1.1):
                    valid_pq = 1
                    break

                if loop >= 50:
                    valid_pq = 0
    def runSimulation(self):
        """Runs the simulation by crating an instance of psspy, loading the raw and dyr data, applying the disturbance and controling PEV output power. Finally plots in native PSS/E or export to matlab."""
        sufix = str(self._disturbance) + "_" + str(self._control)
        conec_file = trash_dir + "\\CC1_" + sufix + ".out"
        conet_file = trash_dir + "\\CT1_" + sufix + ".out"
        compile_file = trash_dir + "\\compile_" + sufix + ".out"

        psspy.psseinit(49)

        #suppress output if required, else redirect it to python
        if self._suppress_output:
            psspy.report_output(6, "", [0, 0])
            psspy.progress_output(6, "", [0, 0])
            #psspy.progress_output(2,r"""pot.txt""",[0,0])
        else:
            #redirect psse output to python
            import redirect
            redirect.psse2py()

        #----------------------
        #read in case data
        psspy.read(0, self._power_system_object._raw_filename)

        #solve the power flow
        psspy.fdns([0, 0, 0, 1, 1, 1, 99, 0])

        #----------------------
        #convert all generators
        psspy.cong(0)

        #----------------------
        #conv_standard_loads
        #change the vector of numbers to get constant current, admittance or power conversion
        utils.convertLoads([0.0, 100.0, 0.0, 100.0])

        #convert the PEVs to constant power loads
        utils.convertPEVs()

        #----------------------------------------
        #read in dynamics data

        psspy.dyre_new([1, 1, 1, 1], self._power_system_object._dyr_filename,
                       "", "", "")

        #solve power flow with dynamics tysl - and fact devices (was in tutorial) - not sure if we need it though
        psspy.fact()
        psspy.tysl(1)

        #set up pre designated channels
        self._channels.setUpChannels()

        #designate channel output_file
        psspy.strt(0, self._channels._channel_file)

        self._performDynamicSimulation()

        if self._plot:
            self._channels.plot(self._channels._channels_to_include)

        if self._export_to_matlab:
            description = sufix.replace(" ",
                                        "_").replace(".",
                                                     "_").replace("=", "__")
            self._channels.exportToMatlab(
                matlab_dir + "\\" + description + ".m", description, True,
                True, self._export_figures)
            if self._export_figures:
                import win32com.client
                h = win32com.client.Dispatch('matlab.application')
                h.Execute("cd('" + os.getcwd() + "\\" + matlab_dir + "');")
                h.Execute(description)

        #clean up
        try:
            os.remove(conec_file)
        except:
            pass
        try:
            os.remove(conet_file)
        except:
            pass
        try:
            os.remove(compile_file)
        except:
            pass

        return self._channels