Exemple #1
0
def Out_Put_Channels():
	psspy.dyre_new([1,1,1,1],Dynamic_File,"","","") #Open our .dyr file that gives the information for dynamic responses of the machines
	psspy.chsb(0,1,[-1,-1,-1,1,4,0]) #Setup Dynamic Simulation channels, Machine voltages in this case
	#psspy.chsb(0,1,[-1,-1,-1,1,14,0]) #Bus voltage and angle
	psspy.chsb(0,1,[-1,-1,-1,1,12,0]) #Frequency
	psspy.chsb(0,1,[-1,-1,-1,1,2,0]) #Machine Real power
	psspy.chsb(0,1,[-1,-1,-1,1,3,0]) #Machine Reactive Power
	#psspy.chsb(0,1,[-1,-1,-1,1,1,0]) #Machine Angle
	psspy.chsb(0,1,[-1,-1,-1,1,7,0]) #Machine Speed
	psspy.chsb(0,1,[-1,-1,-1,1,14,0])
Exemple #2
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()
Exemple #3
0
    file_name = "SummerLo-20171226-043047-34-SystemNormal_all_bus_DDSF"
if LoadScenario == "SimplifiedSystem":
    file_name = "NEOEN Western Downs Solar Farm_C3WV_mod"

#########################################   Read Input List #######################################

# Active Power Setpoint
ActivePowerSetpoint = range(0, 101, 50)
ReactivePowerSetpoint = [-40, 40]
vref = numpy.arange(0.70, 1.3, 0.05)
S = 100
# Initialize
psspy.read(0, GridInfoPath + LoadScenario + "/" + file_name + ".raw")
psspy.resq(GridInfoPath + LoadScenario + "/" + file_name + ".seq")
psspy.dyre_new([1, 1, 1, 1],
               GridInfoPath + LoadScenario + "/" + file_name + ".dyr", "", "",
               "")
psspy.addmodellibrary(HuaweiModelPath + 'HWH9001_342.dll')
psspy.addmodellibrary(HuaweiModelPath +
                      'PPC_PSSE_ver_13_08_34_2_10082018_AUS.dll')
psspy.addmodellibrary(HuaweiModelPath + 'MOD_GPM_SB_V7.dll')
psspy.dynamics_solution_param_2([_i, _i, _i, _i, _i, _i, _i, _i],
                                [1.000, _f, 0.001, 0.004, _f, _f, _f, _f])

for i in range(0, len(ActivePowerSetpoint)):
    for j in range(0, len(ReactivePowerSetpoint)):
        for k in range(0, len(vref)):
            # re - initialize
            psspy.read(0,
                       GridInfoPath + LoadScenario + "/" + file_name + ".raw")
            psspy.resq(GridInfoPath + LoadScenario + "/" + file_name + ".seq")
Exemple #4
0
# ------------------------------------------------- #
# Dynamic Simulation
# Convert gen & load
# convert generators
ierr = psspy.cong(0)

# convert load
for i in [1, 2, 3]:
    ierr = psspy.conl(0, 1, i, [0, 0], [100, 0, 0, 100])[0]

# save converted case
psspy.save(r'{0}\savnw_C.sav'.format(example_path))

# Load dynamics
ierr = psspy.dyre_new([_i, _i, _i, _i], dyr_case, _s, _s, _s)

# Set output channels
psspy.chsb(sid=0, all=1, status=[-1, -1, -1, 1, 12, 0])
#

# Save snapshot
psspy.snap(sfile=r'{0}\PythonDynTest.snp'.format(example_path))

# Initialize and run the dynamic scenario
psspy.strt(option=0, outfile=out_file)
psspy.run(0, 1, 0, 0, 0)

# 3-phase fault on bus 151 (default bus fault is a 3phase and there is no bus 151)
psspy.dist_bus_fault(ibus=151)
Exemple #5
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
    _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])

    # convert load , do not change
    psspy.cong(0)
    psspy.conl(0, 1, 1, [0, 0], [100.0, 0.0, 0.0, 100.0])
    psspy.conl(0, 1, 2, [0, 0], [100.0, 0.0, 0.0, 100.0])
def main():
    try:
        ''' Drives a PSS/E Dynamic simulation and returns values '''

        ##### Get everything set up on the PSSE side
        redirect.psse2py()

        #output = StringIO.StringIO()
        with silence():
            psspy.psseinit(buses=80000)
            _i = psspy.getdefaultint()
            _f = psspy.getdefaultreal()
            _s = psspy.getdefaultchar()
        """
        # Redirect any psse outputs to psse_log
        psspy.report_output(2,psse_log,[0,0])
        psspy.progress_output(2,psse_log,[0,0]) #ignored
        psspy.alert_output(2,psse_log,[0,0]) #ignored
        psspy.prompt_output(2,psse_log,[0,0]) #ignored
        """

        k = 1
        for rawFile in RawFileList:

            # get the percentage loading from the raw file name
            if rawFile == 'savnw_conp.raw':
                PL = '100'
            else:
                rawFileName = rawFile.replace('.raw', '')
                PL = rawFileName[-3:]

            #Parameters. CONFIGURE THIS
            settings = {
                # use the same raw data in PSS/E and TS3ph #####################################
                'filename':
                rawFile,  #use the same raw data in PSS/E and TS3ph
                ################################################################################
                'dyr_file':
                dyrFile,
                'out_file':
                'output2.out',
                'pf_options': [
                    0,  #disable taps
                    0,  #disable area exchange
                    0,  #disable phase-shift
                    0,  #disable dc-tap
                    0,  #disable switched shunts
                    0,  #do not flat start
                    0,  #apply var limits immediately
                    0,  #disable non-div solution
                ]
            }

            ##### Load Raw Datafile and do power flow

            print "\n Reading raw file:", settings['filename']
            #    " Reading raw file: {0:s}".format('text')

            FaultRpu = 1e-06
            Sbase = 100.0

            #FaultBusNomVolt = float(BusDataDict[FaultBus].NominalVolt)

            #Zbase = FaultBusNomVolt**2/Sbase  # float since Sbase is a float
            #Rohm = FaultRpu*Zbase # fault impedance in ohms
            ##########################

            # run nested loops to see if there are any abnormal low voltages
            simCount = 0  # to keep track of how many simulations are already done
            croppedHVLineSet = list(HVLineSet)

            for line1 in croppedHVLineSet:
                for line2 in croppedHVLineSet:
                    # stability_indicator = 1
                    # Bus_issues = [] # list of buses where issues (low voltage or high dv_dt) are reported
                    # the lines cannot be the same
                    if line1 == line2:
                        continue
                    # part to ensure there is no duplication of events
                    currentSet = line1 + ';' + line2
                    currentSetReverse = line2 + ';' + line1
                    # if case causes topology inconsistencies, continue
                    if currentSet in topology_inconsistent_set or currentSetReverse in topology_inconsistent_set:
                        continue

                    line1Elements = line1.split(',')
                    line2Elements = line2.split(',')

                    # Line 1 params
                    L1Bus1 = int(line1Elements[0])
                    L1Bus2 = int(line1Elements[1])
                    L1cktID = line1Elements[2].strip("'").strip()

                    # Line 2 params
                    L2Bus1 = int(line2Elements[0])
                    L2Bus2 = int(line2Elements[1])
                    L2cktID = line2Elements[2].strip("'").strip()

                    FaultBusList = [L2Bus1,
                                    L2Bus2]  # apply faults at both buses

                    for FaultBus in FaultBusList:

                        output = StringIO.StringIO()
                        with silence():
                            ierr = psspy.read(0, settings['filename'])
                            #This is for the power flow. I'll use the solved case instead
                            ierr = psspy.fnsl(settings['pf_options'])

                            ##### Prepare case for dynamic simulation
                            # Load conversion (multiple-step)
                            psspy.conl(_i, _i, 1, [0, _i], [_f, _f, _f, _f])
                            # all constant power load to constant current, constant reactive power load to constant admittance
                            # standard practice for dynamic simulations, constant MVA load is not acceptable
                            psspy.conl(1, 1, 2, [_i, _i],
                                       [100.0, 0.0, 0.0, 100.0])
                            psspy.conl(_i, _i, 3, [_i, _i], [_f, _f, _f, _f])

                            ierr = psspy.cong(0)  #converting generators
                            ierr = psspy.ordr(
                                0
                            )  #order the network nodes to maintain sparsity
                            ierr = psspy.fact(
                            )  #factorise the network admittance matrix
                            ierr = psspy.tysl(0)  #solving the converted case
                            ierr = psspy.dynamicsmode(0)  #enter dynamics mode

                            print "\n Reading dyr file:", settings['dyr_file']

                            ierr = psspy.dyre_new([1, 1, 1, 1],
                                                  settings['dyr_file'])
                            ierr = psspy.docu(0, 1, [
                                0, 3, 1
                            ])  #print the starting point of state variables

                            # select time step ##############################################################
                            ierr = psspy.dynamics_solution_params(
                                [_i, _i, _i, _i, _i, _i, _i, _i], [
                                    _f, _f, 0.00833333333333333, _f, _f, _f,
                                    _f, _f
                                ],
                                'out_file')  # the number here is the time step
                            ################################################################################

                            ##### select channels
                            ierr = psspy.delete_all_plot_channels(
                            )  # clear channels

                            # get all the bus voltages, angles and frequencies
                            for bus in BusDataDict:
                                bus = int(bus)
                                ierr = psspy.voltage_and_angle_channel(
                                    [-1, -1, -1, bus])
                                ierr = psspy.bus_frequency_channel([-1, bus])

                        eventStr = PL + '/' + line1 + ';' + line2 + '/F' + str(
                            FaultBus)
                        print 'Event: {}'.format(eventStr)
                        # 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
                        ResultsDict = {}

                        #output = StringIO.StringIO()
                        with silence(output):
                            ierr = psspy.strt(0, settings['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 ' + eventStr + ':'
                            print 'Network did not converge between branch 1 trip and fault application, skipping...'
                            continue
                        #######

                        # check for convergence during fault
                        #output = StringIO.StringIO()
                        with silence(output):
                            ierr = psspy.dist_bus_fault(
                                FaultBus, 3, 0.0, [Rohm, 0.0])
                            ierr = psspy.run(0, 0.3, 1, 1, 1)  #fault off time
                            ierr = psspy.dist_clear_fault(1)

                        outputStr = output.getvalue()
                        if "Network not converged" in outputStr:
                            print 'For ' + eventStr + ':'
                            print 'Network did not converge during fault, skipping...'
                            continue

                        # check for convergence between fault clearance and second branch trip
                        #output = StringIO.StringIO()
                        with silence(output):
                            ierr = psspy.run(0, 0.31, 1, 1, 1)  #fault off time
                            ierr = psspy.dist_branch_trip(
                                L2Bus1, L2Bus2, L2cktID)
                            ierr = psspy.run(0, 0.35, 1, 1, 1)  #fault off time

                        # check for non-convergence
                        #output = StringIO.StringIO()
                        outputStr = output.getvalue()
                        if "Network not converged" in outputStr:
                            print 'For ' + eventStr + ':'
                            print 'Network did not converge between fault clearance and branch 2 trip, skipping...'
                            continue

                        # select run time ##############################################################
                        output = StringIO.StringIO()
                        with silence(output):
                            ierr = psspy.run(
                                0, 10.0, 1, 1, 1
                            )  #exit time (second argument is the end time)
                        ################################################################################
                        # check for non-convergence

                        outputStr = output.getvalue()
                        if "Network not converged" in outputStr:
                            print 'For ' + eventStr + ':'
                            print 'Network did not converge sometime after 2nd branch trip, skipping...'
                            continue

                        outputData = dyntools.CHNF(settings['out_file'])

                        data = outputData.get_data()

                        channelDict = data[
                            1]  # dictionary where the value is the channel description
                        valueDict = data[
                            2]  # dictionary where the values are the signal values, keys match that of channelDict

                        tme = valueDict['time']  # get time
                        ResultsDict['time'] = tme
                        for key in channelDict:
                            if key == 'time':
                                continue

                            signalDescr = channelDict[key]
                            words = signalDescr.split()
                            signalType = words[0].strip()
                            bus = words[1].strip()
                            #print Bus + ' ' + signalType
                            if bus not in ResultsDict:
                                ResultsDict[bus] = Results()

                            if signalType == 'VOLT':
                                ResultsDict[bus].volt = valueDict[key]

                            elif signalType == 'ANGL':
                                ResultsDict[bus].angle = valueDict[key]
                            elif signalType == 'FREQ':
                                ResultsDict[bus].freq = valueDict[key]

                        EventsDict[eventStr] = ResultsDict
                        simCount += 1
                        print 'Simulation ' + str(simCount) + ' out of ' + str(
                            totalSims)

                        # Uncomment next two lines if you want to see the output
                        #with open('output'+str(k) + '.txt','w') as f:
                        #    f.write(outputStr)
                        k += 1

        save_obj(EventsDict, 'EventData')
    except Exception:
        traceback.print_exc(file=logfile)
    sys.exit(0)
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
title2    = 'flatstart'
conl      = 'Conl.idv'
channels  = 'channels.idv'
mylog = '%s.log'%study
#
psspy.progress_output(2,mylog,[0,0])
psspy.report_output(2,mylog,[0,0])
psspy.progress(' \n')
psspy.progress('***************************************\n')
psspy.progress('*            MakeCnvSnp %s \n'%study)
psspy.progress('*\n')
psspy.progress('***************************************\n')

psspy.case(mysav)
#psspy.runrspnsfile(re_add)			#adds RE topology
psspy.runrspnsfile(conl)
psspy.fnsl((_i,0,_i,_i,_i,_i,_i,0))
psspy.cong(0)
psspy.ordr(0)
psspy.fact()
psspy.tysl(0)
psspy.tysl(0)
psspy.save('%s_cnv'%study)
psspy.dyre_new([1,1,1,1],
               mydyr,
               r"""conec.flx""",
               r"""conet.flx""",
               r"""compile.bat""")
psspy.snap([-1,-1,-1,-1,-1],'%s'%study)
psspy.progress_output(1)
FigurePath = "D:/NEOEN/"

file_name = "SummerHi-20171219-153047-34-SystemNormal_all_bus_DDSF"


# Initialize
ierr = psspy.addmodellibrary(GridInfoPath + 'dsusr.dll')
ierr = psspy.addmodellibrary(HuaweiModelPath + 'HWH9001_342.dll')
ierr = psspy.addmodellibrary(HuaweiModelPath + 'PPC_PSSE_ver_13_08_34_2_10082018_AUS.dll')
ierr = psspy.addmodellibrary(HuaweiModelPath + 'MOD_GPM_SB_V7.dll')
ierr = psspy.addmodellibrary(GridInfoPath + 'GEWTG34.dll')
ierr = psspy.addmodellibrary(GridInfoPath + 'SMAPPC_B111_34_IVF111.dll')
ierr = psspy.addmodellibrary(GridInfoPath + 'SMASC_C135_34_IVF111.dll')
ierr = psspy.read(0, GridInfoPath + file_name + ".raw")
ierr = psspy.resq(GridInfoPath + file_name + ".seq")
ierr = psspy.dyre_new([1, 1, 1, 1], GridInfoPath + file_name + ".dyr", "", "", "")

# psspy.machine_data_2(100,r"""1""",[_i,_i,_i,_i,_i,_i],[_f,_f, 80,_f, 132,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f])
# psspy.machine_data_2(100,r"""1""",[_i,_i,_i,_i,_i,_i],[_f,_f,_f, 80, 132,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f])
psspy.fdns([1, 0, 1, 1, 1, 1, 99, 0])
#psspy.change_plmod_icon(101, r"""1""", r"""GPMPPC""", 4, 3)
#psspy.change_plmod_con(101, r"""1""", r"""GPMPPC""", 10, 0.45)

psspy.dynamics_solution_param_2([_i, _i, _i, _i, _i, _i, _i, _i], [1.000, _f, 0.001, 0.004, _f, _f, _f, _f])

# discard disturbance
psspy.dscn(30531)
psspy.dscn(36530)
psspy.dscn(37530)
psspy.machine_data_2(30531, r"""12""", [0, _i, _i, _i, _i, _i],
                     [_f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f])
Exemple #11
0
def runPSSESimBatches(simList, dyrFile, objName):
    import sys, os
    # add psspy to the system path
    sys.path.append(r"C:\Program Files (x86)\PTI\PSSE33\PSSBIN")
    os.environ['PATH'] = (r"C:\Program Files (x86)\PTI\PSSE33\PSSBIN;" +
                          os.environ['PATH'])

    from contextlib import contextmanager
    import StringIO
    from getBusDataFn import getBusData

    @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
            yield
        finally:
            sys.stdout = old_stdout
            if file_object is None:
                file_object.close()

    # Local imports
    import redirect
    import psspy
    import dyntools

    # getting the raw file

    ##### Get everything set up on the PSSE side
    redirect.psse2py()

    #output = StringIO.StringIO()
    with silence():
        psspy.psseinit(buses=80000)
        _i = psspy.getdefaultint()
        _f = psspy.getdefaultreal()
        _s = psspy.getdefaultchar()

    # some important parameters
    FaultRpu = 1e-06
    Sbase = 100.0
    EventsDict = {}
    for event in simList:
        eventWords = event.split('/')
        RawFileIndicator = eventWords[0].strip()
        linesOutage = eventWords[1].strip()
        FaultBus = eventWords[2].strip()[
            1:]  # exclude the 'F' at the beginning

        # get the raw file
        if RawFileIndicator == '100':
            rawFile = 'savnw_conp.raw'
        else:
            rawFile = 'savnw_conp{}.raw'.format(RawFileIndicator)

        #Parameters. CONFIGURE THIS
        settings = {
            # use the same raw data in PSS/E and TS3ph #####################################
            'filename':
            rawFile,  #use the same raw data in PSS/E and TS3ph
            ################################################################################
            'dyr_file':
            dyrFile,
            'out_file':
            'output2.out',
            'pf_options': [
                0,  #disable taps
                0,  #disable area exchange
                0,  #disable phase-shift
                0,  #disable dc-tap
                0,  #disable switched shunts
                0,  #do not flat start
                0,  #apply var limits immediately
                0,  #disable non-div solution
            ]
        }

        output = StringIO.StringIO()
        with silence(output):
            ierr = psspy.read(0, settings['filename'])
            #This is for the power flow. I'll use the solved case instead
            ierr = psspy.fnsl(settings['pf_options'])

            ##### Prepare case for dynamic simulation
            # Load conversion (multiple-step)
            psspy.conl(_i, _i, 1, [0, _i], [_f, _f, _f, _f])
            # all constant power load to constant current, constant reactive power load to constant admittance
            # standard practice for dynamic simulations, constant MVA load is not acceptable
            psspy.conl(1, 1, 2, [_i, _i], [100.0, 0.0, 0.0, 100.0])
            psspy.conl(_i, _i, 3, [_i, _i], [_f, _f, _f, _f])

            ierr = psspy.cong(0)  #converting generators
            ierr = psspy.ordr(0)  #order the network nodes to maintain sparsity
            ierr = psspy.fact()  #factorise the network admittance matrix
            ierr = psspy.tysl(0)  #solving the converted case
            ierr = psspy.dynamicsmode(0)  #enter dynamics mode

            print "\n Reading dyr file:", settings['dyr_file']

            ierr = psspy.dyre_new([1, 1, 1, 1], settings['dyr_file'])
            ierr = psspy.docu(
                0, 1, [0, 3, 1])  #print the starting point of state variables

            # select time step ##############################################################
            ierr = psspy.dynamics_solution_params(
                [_i, _i, _i, _i, _i, _i, _i, _i],
                [_f, _f, 0.00833333333333333, _f, _f, _f, _f, _f],
                'out_file')  # the number here is the time step
            ################################################################################

            ##### select channels
            ierr = psspy.delete_all_plot_channels()  # clear channels

            BusDataDict = getBusData(rawFile)
            # get all the bus voltages, angles and frequencies
            for bus in BusDataDict:
                bus = int(bus)
                ierr = psspy.voltage_and_angle_channel([-1, -1, -1, bus])
                ierr = psspy.bus_frequency_channel([-1, bus])

        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
        ResultsDict = {}

        # get the line params
        line1Elements = linesOutage.split(';')[0].strip()
        line2Elements = linesOutage.split(';')[1].strip()

        # Line 1 params
        line1 = line1Elements.split(',')
        L1Bus1 = int(line1[0].strip())
        L1Bus2 = int(line1[1].strip())
        L1cktID = line1[2].strip("'").strip()
        #print L1Bus1
        #print L1Bus2
        #print L1cktID

        # Line 2 params
        line2 = line2Elements.split(',')
        L2Bus1 = int(line2[0].strip())
        L2Bus2 = int(line2[1].strip())
        L2cktID = line2[2].strip("'").strip()
        #print L2Bus1
        #print L2Bus2
        #print L2cktID

        #output = StringIO.StringIO()
        with silence(output):
            ierr = psspy.strt(0, settings['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...'
            continue
        #######

        # check for convergence during fault
        #output = StringIO.StringIO()
        with silence(output):
            ierr = psspy.dist_bus_fault(int(FaultBus), 3, 0.0, [Rohm, 0.0])
            ierr = psspy.run(0, 0.3, 1, 1, 1)  #fault off time
            ierr = psspy.dist_clear_fault(1)

        outputStr = output.getvalue()
        if "Network not converged" in outputStr:
            print 'For ' + event + ':'
            print 'Network did not converge during fault, skipping...'
            continue

        # check for convergence between fault clearance and second branch trip
        #output = StringIO.StringIO()
        with silence(output):
            ierr = psspy.run(0, 0.31, 1, 1, 1)  #fault off time
            ierr = psspy.dist_branch_trip(L2Bus1, L2Bus2, L2cktID)
            ierr = psspy.run(0, 0.35, 1, 1, 1)  #fault off time

        # check for non-convergence
        #output = StringIO.StringIO()
        outputStr = output.getvalue()
        if "Network not converged" in outputStr:
            print 'For ' + event + ':'
            print 'Network did not converge between fault clearance and branch 2 trip, skipping...'
            continue

        # select run time ##############################################################
        #output = StringIO.StringIO()
        with silence(output):
            ierr = psspy.run(0, 10.0, 1, 1,
                             1)  #exit time (second argument is the end time)
        ################################################################################
        # check for non-convergence

        outputStr = output.getvalue()
        if "Network not converged" in outputStr:
            print 'For ' + event + ':'
            print 'Network did not converge sometime after 2nd branch trip, skipping...'
            continue

        # write to output file
        #with open('outputTmp.txt','w') as f:
        #   f.write(outputStr)

        outputData = dyntools.CHNF(settings['out_file'])

        data = outputData.get_data()

        channelDict = data[
            1]  # dictionary where the value is the channel description
        valueDict = data[
            2]  # dictionary where the values are the signal values, keys match that of channelDict

        tme = valueDict['time']  # get time
        ResultsDict['time'] = tme
        for key in channelDict:
            if key == 'time':
                continue

            signalDescr = channelDict[key]
            words = signalDescr.split()
            signalType = words[0].strip()
            bus = words[1].strip()
            #print Bus + ' ' + signalType
            if bus not in ResultsDict:
                ResultsDict[bus] = Results()

            if signalType == 'VOLT':
                ResultsDict[bus].volt = valueDict[key]

            elif signalType == 'ANGL':
                ResultsDict[bus].angle = valueDict[key]
            elif signalType == 'FREQ':
                ResultsDict[bus].freq = valueDict[key]

        EventsDict[event] = ResultsDict

    return EventsDict
    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

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

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

# Start PSS/E
psspy.psseinit(10000) # 10 000 is requested bus size. Count of buses = 10 000?

# Initiation----------------------------------------------------------------------------------------------------------------------------------
psspy.case(casefile)  # Read in the power flow data
psspy.dyre_new([1, 1, 1, 1], dyrfile, "", "", "") # Read the dynamics data

# Establish which channels we wish to analyze in the output
#psspy.chsb(0,1,[-1,-1,-1,1,1,0]) # Channel 1 ANGLE, machine relative rotor angle (degrees)
#psspy.chsb(0,1,[-1,-1,-1,1,2,0]) # Channel 2 PELEC, machine electrical power (pu on SBASE).
#psspy.chsb(0,1,[-1,-1,-1,1,4,0]) # Channel 4 ETERM, machine terminal voltage (pu)
#psspy.chsb(0,1,[-1,-1,-1,1,12,0]) # Channel 12 BSFREQ, bus pu frequency deviations
#psspy.chsb(0,1,[-1,-1,-1,1,13,0]) # Channel 13 VOLT, bus pu voltages (complex)
#psspy.chsb(0,1,[-1,-1,-1,1,16,0]) # Channel 16 branch flow (P and Q)

# Convert the loads for dynamic simulation
psspy.cong(0)
psspy.conl(0, 1, 1, [0, 0], [50.0, 50.0, 0.0, 100.0]) # Convert loads, IZP-format 
psspy.conl(0, 1, 2, [0, 0], [50.0, 50.0, 0.0, 100.0])
psspy.conl(0, 1, 3, [0, 0], [50.0, 50.0, 0.0, 100.0])
def do_simulation():
    global num_sample_id

    # set Samples Path
    sample_path = r'./Sample_9bus_' + input('请输入样本集编号:')
    if os.path.exists(sample_path):
        print('该样本集已存在,请重新输入...\n')
        sample_path = r'./Sample_9bus_' + input('请重新输入样本集编号:')
    else:
        os.makedirs(sample_path)

    # # 1 母线故障——样本编号:1~12*num_bus -> [1,  108]
    # for i in range(num_bus):
    # # for i in range(1):
    # 	for j in range(len(clear_time)):
    # 		# init
    # 		psspy.psseinit(50)
    # 		psspy.case(r""".\Models\9Bus-test\ieee9bus_v32.sav""")
    # 		psspy.fnsl([0, 0, 0, 1, 1, 0, 99, 0])
    # 		psspy.cong(0)
    # 		psspy.conl(0, 1, 1, [0, 0], [100.0, 0.0, 0.0, 100.0])
    # 		psspy.conl(0, 1, 2, [0, 0], [100.0, 0.0, 0.0, 100.0])
    # 		psspy.conl(0, 1, 3, [0, 0], [100.0, 0.0, 0.0, 100.0])
    # 		psspy.fact()
    # 		psspy.tysl(0)
    # 		psspy.dyre_new([1, 1, 1, 1], r""".\Models\9Bus-test\ieee9bus.dyr""", "", "", "")
    #
    # 		# perform Dynamic Simulation
    # 		# 1) set "Channal Setup Wizard"
    # 		psspy.chsb(0, 1, [-1, -1, -1, 1, 1, 0])    # Angle
    # 		psspy.chsb(0, 1, [-1, -1, -1, 1, 7, 0])    #
    # 		psspy.chsb(0, 1, [-1, -1, -1, 1, 13, 0])  #
    #
    # 		# 2) name output file
    # 		psspy.set_chnfil_type(0)  # 1 for OUTX format, 0 for (old) OUT format
    # 		psspy.strt_2([0, 1], sample_path + '\\t9Bus-PY-00' + str(num_sample_id) + '.out')
    # 		num_sample_id += 1
    #
    # 		# 3) in normal stat, run network to 1 seconds
    # 		psspy.run(0, 1.0, 0, 1, 1)
    #
    # 		# 4) set Balanced_bus_fault with R,X -> [0, 0]
    # 		psspy.dist_bus_fault(bus_id[i], 1, bus_kv[i], [0.0, -2E+2])		# --------  ! important
    #
    # 		# 5) set fault run time
    # 		psspy.run(0, 1 + clear_time[j], 0, 1, 1)
    #
    # 		# 6) clear fault, and run net to 10 seconds
    # 		psspy.dist_clear_fault(1)
    # 		psspy.run(0, 10.0, 0, 1, 1)
    #
    # 		# 7) 关闭本次仿真相关的文件, importaant !!!!!!!!!!!!!!!!!!!!!!
    # 		psspy.pssehalt_2()

    # 2 非变压器支路故障——样本编号: [108+1,  108+360]
    for i in range(num_notrans_brch):
        # for i in range(1):
        for k in range(len(fault_position)):
            # for k in range(1):
            for j in range(len(clear_time)):
                print('\n\n\n\n----------------我是分割线--------------\n')
                print('已仿真第 ' + str(num_sample_id) + ' 条样本\n\n\n\n')

                # init
                psspy.psseinit(50)
                psspy.case(r""".\Models\9Bus-test\ieee9bus_v32.sav""")
                psspy.fnsl([0, 0, 0, 1, 1, 0, 99, 0])
                psspy.cong(0)
                psspy.conl(0, 1, 1, [0, 0], [100.0, 0.0, 0.0, 100.0])
                psspy.conl(0, 1, 2, [0, 0], [100.0, 0.0, 0.0, 100.0])
                psspy.conl(0, 1, 3, [0, 0], [100.0, 0.0, 0.0, 100.0])
                psspy.fact()
                psspy.tysl(0)
                psspy.dyre_new([1, 1, 1, 1],
                               r""".\Models\9Bus-test\ieee9bus.dyr""", "", "",
                               "")

                # perform Dynamic Simulation
                # 1) set "Channal Setup Wizard"
                psspy.chsb(0, 1, [-1, -1, -1, 1, 1, 0])  # Angle
                psspy.chsb(0, 1, [-1, -1, -1, 1, 7, 0])  #
                psspy.chsb(0, 1, [-1, -1, -1, 1, 13, 0])  #

                # 1.1) set Relative Machine Angle
                psspy.set_relang(1, 1, r"""1""")

                # 2) name output file
                psspy.set_chnfil_type(
                    0)  # 1 for OUTX format, 0 for (old) OUT format
                psspy.strt_2([0, 1], sample_path + '//t9Bus-PY-00' +
                             str(num_sample_id) + '.out')
                num_sample_id += 1

                # 3) in normal stat, run network to 1 seconds
                psspy.run(0, 1.0, 0, 1, 1)

                # 4) set unbalanced_Branch_fault -- 3 Phase -- with R,X -> [0, 0]
                psspy.dist_spcb_fault_2(
                    notrans_brch[i][0], notrans_brch[i][1], r"""1""",
                    [3, 0, 3, 1, 0, 0, 1],
                    [fault_position[k], 0.0, 0.0, 0.0, 0.0
                     ])  # --------  ! important

                # 5) set fault run time
                psspy.run(0, 1 + clear_time[j], 0, 1, 1)

                # 6) clear fault, and run net to 10 seconds
                psspy.dist_clear_fault(1)
                psspy.run(0, 10.0, 0, 1, 1)

                # 7) 关闭本次仿真相关的文件, importaant !!!!!!!!!!!!!!!!!!!!!!
                psspy.pssehalt_2()
def do_simulation(sav_path, dyr_path):
    global num_sample_id

    # set Samples Path
    sample_path = r'./Sample_14bus_' + input('请输入样本集编号:')
    if os.path.exists(sample_path):
        print('该样本集已存在,请重新输入...\n')
        sample_path = r'./Sample_14bus_' + input('请重新输入样本集编号:')
    else:
        os.makedirs(sample_path)

    # # 1 母线故障——样本编号:1~12*num_bus -> [1, 168]
    # for i in range(num_bus):
    # # for i in range(1):
    # 	for j in range(len(clear_time)):
    # 		# init
    # 		psspy.psseinit(50)
    # 		psspy.case(sav_path)
    # 		psspy.fnsl([0, 0, 0, 1, 1, 0, 99, 0])
    # 		psspy.cong(0)
    # 		psspy.conl(0, 1, 1, [0, 0], [100.0, 0.0, 0.0, 100.0])
    # 		psspy.conl(0, 1, 2, [0, 0], [100.0, 0.0, 0.0, 100.0])
    # 		psspy.conl(0, 1, 3, [0, 0], [100.0, 0.0, 0.0, 100.0])
    # 		psspy.fact()
    # 		psspy.tysl(0)
    # 		psspy.dyre_new([1, 1, 1, 1], dyr_path, "", "", "")
    #
    # 		# perform Dynamic Simulation
    # 		# 1) set "Channal Setup Wizard"
    # 		psspy.chsb(0, 1, [-1, -1, -1, 1, 1, 0])     # Angle -> 发电机功角
    # 		psspy.chsb(0, 1, [-1, -1, -1, 1, 14, 0])    # Volt & Angle -> 电压&相角
    # 		psspy.chsb(0, 1, [-1, -1, -1, 1, 16, 0])    # Flow (P & Q) -> 潮流
    #
    # 		# 2) name output file
    # 		psspy.set_chnfil_type(0)  # 1 for OUTX format, 0 for (old) OUT format
    # 		psspy.strt_2([0, 1], sample_path + '\\t14Bus-PY-00' + str(num_sample_id) + '.out')
    # 		num_sample_id += 1
    #
    # 		# 3) in normal stat, run network to 1 seconds
    # 		psspy.run(0, 1.0, 0, 1, 1)
    #
    # 		# 4) set Balanced_bus_fault; Default with R,X -> [0, -2e+009]
    # 		psspy.dist_bus_fault(bus_id[i], 1, bus_kv[i], [0.0, -2E9])		# --------  ! important
    #
    # 		# bus5 unbalanced fault with [R-LL, X-LL, R-LG, X-LG], 是单相故障 !!!!!!!
    # 		# 事实证明设置LL的RX对稳定毫无影响!!
    # 		# psspy.dist_scmu_fault_2([0, 0, 2, bus_id[i], ], [2E5, 3E5, 0, 0])
    #
    # 		# 5) set fault run time
    # 		psspy.run(0, 1 + clear_time[j], 0, 1, 1)
    #
    # 		# 5) clear fault, and run net to 10 seconds
    # 		psspy.dist_clear_fault(1)
    # 		psspy.run(0, 10.0, 0, 1, 1)

    # 2 非变压器支路故障——样本编号: [bus_id ,bus_id + 960]
    # 根据本循环写的嵌套次序,故障时间每12条仿真为一个循环
    # for i in range(num_notrans_brch):
    for i in range(1):
        # for k in range(len(fault_position)):
        for k in range(3):
            # for j in range(len(clear_time)):
            for j in range(12):
                print('\n\n\n\n----------------我是分割线--------------\n\n\n\n\n')
                print('已仿真第 ' + str(num_sample_id) + ' 条样本')

                # init
                psspy.psseinit(10)
                psspy.case(sav_path)
                psspy.fnsl([0, 0, 0, 1, 1, 0, 99, 0])
                psspy.cong(0)
                psspy.conl(0, 1, 1, [0, 0], [100.0, 0.0, 0.0, 100.0])
                psspy.conl(0, 1, 2, [0, 0], [100.0, 0.0, 0.0, 100.0])
                psspy.conl(0, 1, 3, [0, 0], [100.0, 0.0, 0.0, 100.0])
                psspy.fact()
                psspy.tysl(0)
                psspy.dyre_new([1, 1, 1, 1], dyr_path, "", "", "")

                # perform Dynamic Simulation
                # 1) set "Channal Setup Wizard"
                psspy.chsb(0, 1, [-1, -1, -1, 1, 1, 0])  # Angle -> 发电机功角
                psspy.chsb(0, 1,
                           [-1, -1, -1, 1, 14, 0])  # Volt & Angle -> 电压&相角
                psspy.chsb(0, 1, [-1, -1, -1, 1, 16, 0])  # Flow (P & Q) -> 潮流

                # 2) name output file
                psspy.set_chnfil_type(
                    0)  # 1 for OUTX format, 0 for (old) OUT format
                psspy.strt_2([0, 1], sample_path + '\\t14Bus-PY-00' +
                             str(num_sample_id) + '.out')
                num_sample_id += 1

                # 3) in normal stat, run network to 1 seconds
                psspy.run(0, 1.0, 0, 1, 1)

                # 4) set unbalanced_Branch_fault -- 3 Phase -- with R,X -> [0, 0]
                psspy.dist_spcb_fault_2(
                    notrans_brch[i][0], notrans_brch[i][1], r"""1""",
                    [3, 0, 3, 1, 0, 0, 1],
                    [fault_position[k], 0.0, 0.0, 0.0, 0.0
                     ])  # --------  ! important

                # 5) set fault run time
                psspy.run(0, 1 + clear_time[j], 0, 1, 1)

                # 6) clear fault, and run net to 10 seconds
                psspy.dist_clear_fault(1)
                psspy.run(0, 10.0, 0, 1, 1)

                # 7) 关闭本次仿真相关的文件, importaant !!!!!!!!!!!!!!!!!!!!!!
                psspy.pssehalt_2()
    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""")
    psspy.voltage_channel([2, -1, -1, 500], r"""Inverter Voltage Mag.""")
    psspy.voltage_channel([3, -1, -1, 800], r"""WISF POC Voltage Mag.""")
    psspy.branch_p_and_q_channel([4, -1, -1, 800, 900], r"""1""",
                                 [r"""P Injection""", r"""Q Injection"""])
        # Load conversion (multiple-step)
        psspy.conl(_i, _i, 1, [0, _i], [_f, _f, _f, _f])
        # all constant power load to constant current, constant reactive power load to constant admittance
        # standard practice for dynamic simulations, constant MVA load is not acceptable
        psspy.conl(1, 1, 2, [_i, _i], [100.0, 0.0, 0.0, 100.0])
        psspy.conl(_i, _i, 3, [_i, _i], [_f, _f, _f, _f])

        ierr = psspy.cong(0)  #converting generators
        ierr = psspy.ordr(0)  #order the network nodes to maintain sparsity
        ierr = psspy.fact()  #factorise the network admittance matrix
        ierr = psspy.tysl(0)  #solving the converted case
        ierr = psspy.dynamicsmode(0)  #enter dynamics mode

        print "\n Reading dyr file:", settings['dyr_file']

        ierr = psspy.dyre_new([1, 1, 1, 1], settings['dyr_file'])
        ierr = psspy.docu(
            0, 1, [0, 3, 1])  #print the starting point of state variables

        # select time step ##############################################################
        ierr = psspy.dynamics_solution_params(
            [_i, _i, _i, _i, _i, _i, _i, _i],
            [_f, _f, 0.00833333333333333, _f, _f, _f, _f, _f],
            'out_file')  # the number here is the time step
        ################################################################################

        ##### select channels
        ierr = psspy.delete_all_plot_channels()  # clear channels

        BusDataDict = getBusData(rawFile)
        # get all the bus voltages, angles and frequencies
    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