Ejemplo n.º 1
0
def islandCaseNoDynamics(zone):
	Initialize_Case()

	toBus, fromBus, busInZone, busZones, fromTotalBus, toTotalBus = branchDataZone(zone)
	#print fromBus
	createIsland(toBus, fromBus)
	
	#print len(busInZone)
	
	ierr, buses = psspy.tree(1, 1)
	while buses != 0:
		ierr, buses = psspy.tree(2, 1)	
	
	psspy.save(r"""C:\Users\psse\aires\Carter_Case\RTS-96\NewOpCases\FirstCase\FirstIslanded.sav""")	
	
	one, two, localMin, localMax = Solve_Steady()
	zonesMWload, zonesMVARload, zonesMWgen, zonesMVARgen, zonesMWloss, zonesMVARloss = zoneTotalsPsseFunc()
	microGridRealPower, microGridReactivePower, microGridRealLoad, microGridReactiveLoad, microGridRealLoss, microGridReactiveLoss, mainGridRealPower, mainGridReactivePower, mainGridRealLoad, mainGridReactiveLoad, mainGridRealLoss, mainGridReactiveLoss = inOutMicroGridTotals(zone, zonesMWload, zonesMVARload, zonesMWgen, zonesMVARgen, zonesMWloss, zonesMVARloss)
Ejemplo n.º 2
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
####################################### main #############################################################

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

percentage_set = [
    100, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20
]
stepNumber = len(percentage_set)

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

PSSE_CASE = r"IEEE_118.sav"
psspy.case(PSSE_CASE)  #r"""2019SUM_2013Series_Updated.sav""")
case_name = "IEEE_118_100.sav"
psspy.save(case_name)
import pdb

### if you had already created voltageMeasurementAllBuses.csv, then please remove it.
#os.remove('voltageMeasurementAllBuses.csv')

#os.remove(savefile)

for index in range(0, stepNumber):

    # choose current percentage
    current_percentage = percentage_set[index]

    # choose the case
    case_name_constant = "IEEE_118_%s.sav"
    PSSE_CASE = case_name_constant % current_percentage
        sys.stdout = old_stdout


####################################### main #############################################################

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

percentage_set = [100, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20]
stepNumber = len(percentage_set)

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

PSSE_CASE = r"IEEE_118.sav"
psspy.case(PSSE_CASE)#r"""2019SUM_2013Series_Updated.sav""")
case_name="IEEE_118_100.sav"
psspy.save(case_name)
import pdb


### if you had already created voltageMeasurementAllBuses.csv, then please remove it.
#os.remove('voltageMeasurementAllBuses.csv')

#os.remove(savefile)

for index in range(0,stepNumber):

    # choose current percentage
    current_percentage = percentage_set[index]

    # choose the case
    case_name_constant = "IEEE_118_%s.sav"
def save_case(file_name, folder_name):
    psspy.save(folder_name + '/' + file_name + ".sav")

    return
Ejemplo n.º 6
0
        ################################################################################

        ##### 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])


        savFile = rawFileName + '.sav'
        snpFile = rawFileName + '.snp'
        ierr = psspy.save(savFile)
        ierr = psspy.snap([_i,_i,_i,_i,_i],snpFile)

    """
    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
    """





                          '1',
                          realar1=sheet.cell(row=i, column=5).value,
                          realar2=0.01 * sheet.cell(row=i, column=5).value)

        print('Changes completed...')
        psspy.rawd_2(
            0, 1, [0, 0, 1, 0, 0, 0, 0], 0,
            "Snap_before_PF.raw")  #save the raw file to convert to CIM
        b = 'h' + str(i - 2) + '_before_PF.raw'
        os.rename("Snap_before_PF.raw", b)
        psspy.fnsl([1, 0, 0, 0, 0, 0, 0, 0])  #solve the power flow
        ival = psspy.solved()  #flag to check power flow convergence
        if ival == 0:
            print('Convergence')
            sheet.cell(row=i, column=7).value = 'Convergence'
            psspy.save('temp.sav')  #save temporarily the solved case
            psspy.case('temp.sav')  #set the saved case as current case
            psspy.rawd_2(
                0, 1, [0, 0, 1, 0, 0, 0, 0], 0,
                "Snap_after_PF.raw")  #save the raw file to convert to CIM
            b = 'h' + str((i - 2)) + '_after_PF.raw'
            os.rename("Snap_after_PF.raw", b)
        else:
            print('No convergence')
            sheet.cell(row=i, column=7).value = 'Non-convergence'

    psspy.close_powerflow()
    #save the Excel file with all data
    ld.save('load_distribution.xlsx')

print('Execution done')
Ejemplo n.º 8
0
def createIsland(toBus, fromBus):
	for x in range(0, len(toBus)):
		print(toBus[x], fromBus	[x])
		psspy.branch_chng(fromBus[x], toBus[x],r"""1""",[0,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f])
	psspy.save(r"""C:\Users\psse\aires\Carter_Case\Poland_Case\Islanded.sav""")	
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 = []
    for i in range(0,len(bus_num)):
        k = i + 1
Ejemplo n.º 10
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
Ejemplo n.º 11
0
    def update_raw_files(self, to_excel=True, out_dir=None):
        """Function for updating the psse case file.
        Args:
            to_excel(default=True): If a summary should be written to excel
            out_dir: The directory where the results are stored
        """
        if not out_dir:
            out_dir = os.getcwd()

        redirect.psse2py()
        psspy.throwPsseExceptions = True
        nbuses = 50000  # max no of buses
        ierr = psspy.psseinit(nbuses)
        psspy.case(self.basecase)

        if to_excel:
            self.create_excel_sheet()
            self.to_excel = True
        else:
            self.sheet = None

        for i, col in zip(range(0, 24), range(2, 2 + 24 * 3, 3)):
            # Represent HVDC links as load and some other exchanges as well
            print('Changing additional loads...')

            row = 15
            for load in self.ex_as_load:
                self.load_change(load, i, to_excel, row, col)
                row = row + 1

            print('Changing interarea exchanges...')
            row = 3
            for area, info in self.area_info.items():
                country = area[0:2]
                # Changing interarea exchanges
                exchange = self.calculate_exchange(info, area, i)
                self.area_data(info.number, info.bus, exchange, area, row,
                               col + 2)
                # Changing areas production and consumption
                self.change_prod_con(info.number,
                                     self.data[country]["PS"][area][i],
                                     self.data[country]["FB"][area][i],
                                     info.pf,
                                     tol=4,
                                     row=row,
                                     column=col)
                row = row + 1

            print('Changes completed...')
            # Save the raw file to convert to CIM
            psspy.rawd_2(0, 1, [0, 0, 1, 0, 0, 0, 0], 0, "Snap_before_PF.raw")
            b = os.path.join(out_dir, 'h' + str(
                (col - 1) / 3) + '_before_PF.raw')
            os.rename("Snap_before_PF.raw", b)
            # Solve the power flow
            psspy.fnsl([1, 2, 0, 0, 1, 0, 0, 0])
            ival = psspy.solved()  # flag to check power flow convergence
            if ival == 0:
                print('Convergence')
                if self.to_excel:
                    self.sheet.cell(row=42, column=col).value = 'Convergence'

                temp_fname = os.path.join(out_dir, "temp.sav")
                print(temp_fname)

                psspy.save(temp_fname)  # save temporarily the solved case
                psspy.case(temp_fname)  # set the saved case as current case

                # save the raw file to convert to CIM
                raw_fname = os.path.join(out_dir, "Snap_after_PF.raw")
                psspy.rawd_2(0, 1, [0, 0, 1, 0, 0, 0, 0], 0, raw_fname)
                b = os.path.join(out_dir, 'h' + str(i) + '_after_PF.raw')
                os.rename(raw_fname, b)

                if self.to_excel:
                    # Merge cells
                    self.sheet.merge_cells(start_row=1,
                                           start_column=col,
                                           end_row=1,
                                           end_column=col + 2)

                    self.sheet.cell(
                        row=2,
                        column=col).alignment = (Alignment(wrapText=True))
                    self.sheet.cell(row=2, column=col +
                                    1).alignment = (Alignment(wrapText=True))
                    self.sheet.cell(row=2, column=col +
                                    2).alignment = (Alignment(wrapText=True))
                    self.sheet.cell(
                        row=14,
                        column=col).alignment = (Alignment(wrapText=True))
                    self.sheet.cell(row=14, column=col +
                                    1).alignment = (Alignment(wrapText=True))
                    self.sheet.cell(
                        row=30,
                        column=col).alignment = (Alignment(wrapText=True))
                    self.sheet.cell(row=30, column=col +
                                    1).alignment = (Alignment(wrapText=True))

                    # Headers for data from nordpool
                    self.sheet.cell(row=1,
                                    column=col).value = ('hour ' + str(i))
                    self.sheet.cell(
                        row=2,
                        column=col).value = ('Scheduled\nProduction\n[MWh]')
                    self.sheet.cell(
                        row=2, column=col +
                        1).value = ('Scheduled\nConsumption\n[MWh]')
                    self.sheet.cell(row=2, column=col +
                                    2).value = ('Scheduled\nExchange\n[MWh]')

                    # Headers for exchanges represented as loads
                    self.sheet.cell(row=14,
                                    column=col).value = ('Active Power\n[MW]')
                    self.sheet.cell(row=14, column=col +
                                    1).value = ('Reactive Power\n[MW]')

                    # Headers for results after PSS/E
                    self.sheet.cell(
                        row=30, column=col).value = ('PSSE\nProduction\n[MWh]')
                    self.sheet.cell(row=30, column=col +
                                    1).value = ('PSSE\nConsumption\n[MWh]')
                    self.sheet.cell(row=30, column=col +
                                    2).value = ('PSSE\nExchange\n[MWh]')

                    row = 31
                    for _, info in self.area_info.items():
                        # to get the area production complex power
                        ierr = psspy.ardat(info.number, 'GEN')
                        self.sheet.cell(row=row, column=col).value = (round(
                            ierr[1].real, 0))

                        # to get the area consumption complex power
                        ierr = psspy.ardat(info.number, 'LOAD')
                        self.sheet.cell(row=row,
                                        column=col + 1).value = (round(
                                            ierr[1].real, 0))
                        row += 1

                    # to get the value of the areas active power interchange
                    ierr, intch = psspy.aareareal(-1, 1, 'PINT')
                    for r in range(0, len(intch[0])):
                        self.sheet.cell(row=31 + r,
                                        column=col + 2).value = round(
                                            intch[0][r].real, 0)

                    # limits check
                    ierr, busvoltages = psspy.abusreal(sid=-1, string="PU")
                    if any(x < 0.95 or x > 1.05 for x in busvoltages[0]):
                        self.sheet.cell(
                            row=43, column=col).value = ('Bus voltage problem')
                    ierr, machPGen = psspy.amachreal(sid=-1, string="PGEN")
                    ierr, machPMax = psspy.amachreal(sid=-1, string="PMAX")
                    ierr, machPMin = psspy.amachreal(sid=-1, string="PMIN")
                    ierr, machQGen = psspy.amachreal(sid=-1, string="QGEN")
                    ierr, machQMax = psspy.amachreal(sid=-1, string="QMAX")
                    ierr, machQMin = psspy.amachreal(sid=-1, string="QMIN")
                    ierr, machS = psspy.amachreal(sid=-1, string="MVA")
                    ierr, machMbase = psspy.amachreal(sid=-1, string="MBASE")
                    for l in range(0, len(machPGen[0])):
                        if (machPGen[0][l] <= machPMin[0][l]
                                or machPGen[0][l] >= machPMax[0][l]):
                            self.sheet.cell(row=45, column=col).value = (
                                'Generator active power output problem')
                for m in range(0, len(machQGen[0])):
                    if (machQGen[0][m] <= machQMin[0][m]
                            or machQGen[0][m] >= machQMax[0][m]):
                        self.sheet.cell(row=46, column=col).value = (
                            'Generator reactive power output problem')
                        break
                for n in range(0, len(machS[0])):
                    if machS[0][n] >= machMbase[0][n]:
                        self.sheet.cell(row=47, column=col).value = (
                            'Generator overloading problem')
                        break
                ierr, brflowA = psspy.aflowreal(sid=-1, string="PCTCORPRATEA")
                if any(x >= 100 for x in brflowA[0]):
                    self.sheet.cell(row=48, column=col).value = (
                        'Branch overloading problem (Rate A)')
                ierr, brflowB = psspy.aflowreal(sid=-1, string="PCTCORPRATEB")
                if any(x >= 100 for x in brflowB[0]):
                    self.sheet.cell(row=48, column=col).value = (
                        'Branch overloading problem (Rate B)')
                ierr, brflowC = psspy.aflowreal(sid=-1, string="PCTCORPRATEC")
                if any(x >= 100 for x in brflowC[0]):
                    self.sheet.cell(row=48, column=col).value = (
                        'Branch overloading problem (Rate C)')
            else:
                print('No convergence')
                self.sheet.cell(row=43, column=col).value = 'No convergence'

        psspy.close_powerflow()

        # save the Excel file with all data
        self.wb.save(os.path.join(out_dir, 'PSSE_in_out.xlsx'))
        os.remove(temp_fname)
                Vsch = Vinf + dV_POC / V_factor
                psspy.plant_data(bus_inf, realar1=Vsch)  # set the infinite bus scheduled voltage to the estimated voltage for this condition
                psspy.fdns([0, 0, 1, 1, 0, 0, 99, 0])
                ierr, Vinf = psspy.busdat(bus_inf, 'PU')
                ierr, Vpoc = psspy.busdat(bus_poc, 'PU')
                dV_POC = POC_VCtrl_Tgt - Vpoc
            ierr, QpocNOW = psspy.brnmsc(bus_poc, bus_dummy, "1", 'Q')
            dQpoc = QpocNOW-qpoc
        ierr, PpocNOW = psspy.brnmsc(bus_poc, bus_dummy, "1", 'P')
        dPpoc = PpocNOW - ppoc
        print(dPpoc)
    psspy.machine_data_2(bus_gen, '1', realar1=PgenNOW, realar2=QgenNOW, realar3=QgenNOW, realar4=QgenNOW)
    ierr, PpocNOW = psspy.brnmsc(bus_poc, bus_dummy, "1", 'P')
    ierr, QpocNOW = psspy.brnmsc(bus_poc, bus_dummy, "1", 'Q')

    print "Line Flow_at_PoC (P) is %s" % PpocNOW
    print "Line Flow_at_PoC (Q) is %s" % QpocNOW
    psspy.fdns([0, 0, 1, 1, 0, 0, 99, 0])
    if caseIndex == 0:  # Qexport at POC is 0
        psspy.save(CasePath + 'Case' + ("%03d" % (caseNum+1)) + str(case_id) + '_' + 'Qzero' + '.sav')
    elif caseIndex == 1:
        psspy.save(CasePath + 'Case' + ("%03d" % (caseNum+1)) + str(case_id) + '_' + 'Qlag' + '.sav')
    elif caseIndex == 2:
        psspy.save(CasePath + 'Case' + ("%03d" % (caseNum+1)) + str(case_id) + '_' + 'Qlead' + '.sav')
    print(caseNum)
    VpocALL[caseNum] = Vpoc
    QpocALL[caseNum] = QpocNOW
    PpocALL[caseNum] = PpocNOW
print(VpocALL)
print(QpocALL)
print(PpocALL)
Ejemplo n.º 13
0
psspy.conl(0, 1, 2, [1, 0], [0.0, 100.0, 0.0, 100.0])
psspy.conl(0, 1, 3, [1, 0], [0.0, 100.0, 0.0, 100.0])

# Order Network for matrix operation
psspy.ordr(0)

# Factorize Admittance maatrix
psspy.fact()

# Solve switching study network solutions
psspy.tysl()

# Save sav file after conversion

trans_file = raw_file[0:raw_file.find(".")] + "_trans.sav"
psspy.save(trans_file)

# Select Channels
psspy.delete_all_plot_channels()
psspy.chsb(0, 1, [-1, -1, -1, 1, 1, 0])
psspy.chsb(0, 1, [-1, -1, -1, 1, 2, 0])
psspy.voltage_and_angle_channel([-1, -1, -1, 6], ["", ""])
psspy.voltage_and_angle_channel([-1, -1, -1, 7], ["", ""])
psspy.voltage_and_angle_channel([-1, -1, -1, 9], ["", ""])
psspy.voltage_and_angle_channel([-1, -1, -1, 13], ["", ""])
psspy.voltage_and_angle_channel([-1, -1, -1, 14], ["", ""])
psspy.voltage_and_angle_channel([-1, -1, -1, 39], ["", ""])
psspy.branch_p_channel([-1, -1, -1, 6, 7], r"""1""", "")
psspy.branch_p_channel([-1, -1, -1, 13, 14], r"""1""", "")
psspy.branch_p_channel([-1, -1, -1, 39, 9], r"""1""", "")
psspy.branch_mva_channel([-1, -1, -1, 5, 8], r"""1""", "")
Ejemplo n.º 14
0
    def calculate_nr(self, model_path, logger):
        """
		PSS/E funkce vyuzivajici Newton-Raphson metodu pro vypocet chodu site. Kombinuje ruzne nastaveni metody,
		aby se pokusila najit reseni.
		@return: Vraci jednotku v pripade chyby. Pro detail chyby je potreba proverit API dokumentaci PSS/E
		"""
        # Automaticke aplikovani mezi jaloviny s non diverge solution
        psspy.save(model_path[:-4] + '.sav')
        psspy.case(model_path[:-4] + '.sav')
        with redirected_stdout() as fake_stdout:
            ierr = psspy.fnsl([0, 0, 0, 0, 0, 1, 99, 1])
        if ierr != 0:
            logger.error(
                "Chyba modelu pri vypoctu chodu site. PSS/E chyba: {}".format(
                    ierr))
            return 1
        ierr, ibus, cmpval = psspy.maxmsm()
        bestsol = [(cmpval.real**2 + cmpval.imag**2)**0.5, 1, 99]
        if (cmpval.real**2 + cmpval.imag**2)**0.5 < 0.1 and ierr == 0:
            logger.info(
                "Newton Raphson Load Flow reseni nalezeno. Flatstart: 1,"
                " meze jaloveho vykonu aplikovany automaticky, non-divergent solution 1."
            )
            return 0
        # Automaticke aplikovani mezi jaloviny bez non-divergent reseni.
        psspy.case(model_path[:-4] + '.sav')
        with redirected_stdout() as fake_stdout:
            ierr = psspy.fnsl([0, 0, 0, 0, 0, 1, 99, 0])
        if ierr != 0:
            logger.error(
                "Chyba modelu pri vypoctu chodu site. PSS/E chyba: {}".format(
                    ierr))
            return 1
        ierr, ibus, cmpval = psspy.maxmsm()
        if (cmpval.real**2 + cmpval.imag**2)**0.5 < bestsol[0]:
            bestsol = [(cmpval.real**2 + cmpval.imag**2)**0.5, 1, 99]
        if (cmpval.real**2 + cmpval.imag**2)**0.5 < 0.1 and ierr == 0:
            logger.info(
                "Newton Raphson Load Flow reseni nalezeno. Flatstart: 1,"
                " meze jaloveho vykonu aplikovany automaticky, non-divergent solution 0."
            )
            return 0
        with redirected_stdout() as fake_stdout:
            ierr = psspy.fnsl([0, 0, 0, 0, 0, 0, 99, 1])
        if ierr != 0:
            logger.error(
                "Chyba modelu pri vypoctu chodu site. PSS/E chyba: {}".format(
                    ierr))
            return 1
        ierr, ibus, cmpval = psspy.maxmsm()
        bestsol = [(cmpval.real**2 + cmpval.imag**2)**0.5, 1, 99]
        if (cmpval.real**2 + cmpval.imag**2)**0.5 < 0.1 and ierr == 0:
            logger.info(
                "Newton Raphson Load Flow reseni nalezeno. Flatstart: 0,"
                " meze jaloveho vykonu aplikovany automaticky, non-divergent solution 1."
            )
            return 0
        # Automaticke aplikovani mezi jaloviny bez non-divergent reseni.
        psspy.case(model_path[:-4] + '.sav')
        with redirected_stdout() as fake_stdout:
            ierr = psspy.fnsl([0, 0, 0, 0, 0, 0, 99, 0])
        if ierr != 0:
            logger.error(
                "Chyba modelu pri vypoctu chodu site. PSS/E chyba: {}".format(
                    ierr))
            return 1
        ierr, ibus, cmpval = psspy.maxmsm()
        if (cmpval.real**2 + cmpval.imag**2)**0.5 < bestsol[0]:
            bestsol = [(cmpval.real**2 + cmpval.imag**2)**0.5, 1, 99]
        if (cmpval.real**2 + cmpval.imag**2)**0.5 < 0.1 and ierr == 0:
            logger.info(
                "Newton Raphson Load Flow reseni nalezeno. Flatstart: 0,"
                " meze jaloveho vykonu aplikovany automaticky, non-divergent solution 0."
            )
            return 0
        # Aplikovani mezi jaloviny pri ruznych iteracich
        iteration = range(20)
        for flatstart in [0, 1]:
            for nondivergentsolution in [0, 1]:
                for varlimits in iteration:
                    psspy.case(model_path[:-4] + '.sav')
                    with redirected_stdout() as fake_stdout:
                        ierr = psspy.fnsl([
                            0, 0, 0, 0, 0, flatstart, varlimits,
                            nondivergentsolution
                        ])
                    if ierr != 0:
                        logger.error(
                            "Chyba modelu pri vypoctu chodu site. PSS/E chyba: {}"
                            .format(ierr))
                        return 1
                    ierr, ibus, cmpval = psspy.maxmsm()
                    if (cmpval.real**2 + cmpval.imag**2)**0.5 < bestsol[0]:
                        bestsol = [(cmpval.real**2 + cmpval.imag**2)**0.5,
                                   flatstart, varlimits]
                    if (cmpval.real**2 +
                            cmpval.imag**2)**0.5 < 0.1 and ierr == 0:
                        logger.info(
                            "Newton Raphson Load Flow reseni nalezeno. Flatstart: {},"
                            " Aplikace mezi Q pri iteraci: {}, , non-divergent solution {}."
                            .format(flatstart, varlimits,
                                    nondivergentsolution))
                        return 0
        psspy.case(model_path[:-4] + '.sav')
        with redirected_stdout() as fake_stdout:
            ierr = psspy.fnsl([0, 0, 0, 0, 0, 1, -1, 0])
        if ierr != 0:
            logger.error(
                "Chyba modelu pri vypoctu chodu site. PSS/E chyba: {}".format(
                    ierr))
            return 1
        ierr, ibus, cmpval = psspy.maxmsm()
        if (cmpval.real**2 + cmpval.imag**2)**0.5 < bestsol[0]:
            bestsol = [(cmpval.real**2 + cmpval.imag**2)**0.5, 1, -1]
        if (cmpval.real**2 + cmpval.imag**2)**0.5 < 0.1 and ierr == 0:
            logger.info(
                "Newton Raphson Load Flow reseni nalezeno. Flatstart: {},"
                " meze jaloveho vykonu ignorovany, non-divergent solution 0.".
                format(flatstart))
            return 0
        psspy.case(model_path[:-4] + '.sav')
        with redirected_stdout() as fake_stdout:
            ierr = psspy.fnsl([0, 0, 0, 0, 0, bestsol[1], bestsol[2], 0])
        if ierr != 0:
            logger.error(
                "Chyba modelu pri vypoctu chodu site. PSS/E chyba: {}".format(
                    ierr))
            return 1
        ierr, ibus, cmpval = psspy.maxmsm()
        logger.error("Newton Raphson Load Flow reseni modelu nebylo nalezeno. "
                     "Maximalni meziiteracni chyba: {}".format(
                         (cmpval.real**2 + cmpval.imag**2)**0.5))
        return 1
Ejemplo n.º 15
0
def preprocesado(parametros, info_casos):

   # se inicia el PSS/E
   initpss.inicia_psse(print_alert_psse=True)

   for x in info_casos:
      try:
         #se encuentra caso en la carpeta y se carga
         path_caso_psse = os.path.join(Rutas().ruta_casos, str(x.N_Caso) + '.sav')
         caso_pss = redpsse.CasoPSSE(filepath=path_caso_psse)
         caso_pss.load(save_previous=False)
         #se comprueba si el caso es peninsular o insular consultando las areas
         areas = redpsse.get_areas()
         area_numbers = []
         for a in areas:
            area_numbers.append(a.number)
         if 9 in area_numbers:
            Umin = parametros.U_min_i
            Umax = parametros.U_max_i
         else:
            Umin = parametros.U_min_p
            Umax = parametros.U_max_p
      except Exception as e:
         raise StandardError('Error al cargar el caso de referencia: {}'.format(e.message))

      try:
         # Cambio a tipo 2 los buses tipo 1 e incluyo generador con Pgen=0.01 MW
         # se recupera lista con buses tipo 1
         list_bus = redpsse.get_bus_number_used_by_tension_tipo(Umin=Umin, Umax=Umax, tipo=1)
         for bus_num in list_bus:
            # se modifica el tipo del bus
            ierr = psspy.bus_chng_3(bus_num, [2, _i, _i, _i], [_f, _f, _f, _f, _f, _f, _f], _s)
            # se crea una planta en el bus para poder añadir después el generador
            ierr = psspy.plant_data(bus_num, _i, [_f, _f])
            # se crea el generador con Pgen=0.01 MW
            intgar = [_i, _i, _i, _i, _i]
            Pgen = 0.01  # MW
            Qmin = 0  # MVar
            Qmax = 0  # MVar
            realar = [Pgen, _f, Qmin, Qmax, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f, _f]
            idn = str(11)
            ierr = psspy.machine_data_2(bus_num, idn, intgar, realar)
      except Exception as e:
         raise StandardError('Error al modificar los nudos en el caso de referencia: {}'.format(e.message))

      try:
         # Modificacion del rateA y rateB segun ficheros de entrada
         #se recupera una lista con ramas
         list_branches = redpsse.get_branch_list()
         for branch in list_branches:
            ibus = branch.from_bus
            jbus = branch.to_bus
            ckt= branch.idn
            #se calculan los nuevos rates A y B de la rama segun parametros de entrada
            rateA=parametros.Rate_A/100 * branch.rate_a
            rateB=parametros.Rate_B/100 * branch.rate_a
            intgar=[_i,_i,_i,_i,_i,_i]
            realar=[_f,_f,_f,rateA,rateB,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]
            #se modifica la rama con los nuevos rates A y B
            ierr = psspy.branch_data(ibus, jbus, ckt, intgar, realar)
      except Exception as e:
         raise StandardError('Error al modificar los rates A y B de las ramas en el caso de referencia: {}'.format(e.message))

      #se guarda temporalmente el caso procesado
      ierr = psspy.save(os.path.join(Rutas().ruta_casos_procesados, str(x.N_Caso) + '_procesado.sav'))
Ejemplo n.º 16
0
    print "The iteration limit exceeded"
elif iVal > 1:
    print "Blown up or others"

# ------------------------------------------------- #
# 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)
Ejemplo n.º 17
0
        print("  Min %s" % min(fits))
        print("  Max %s" % max(fits))
        print("  Avg %s" % mean)
        print("  Std %s" % std)

    print("-- End of (successful) evolution --")

    best_ind = tools.selBest(pop, 1)[0]
    print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values))


if __name__ == "__main__":
    main()

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

ierr, vpu2 = psspy.abusreal(-1, string="PU")
vpu02 = vpu2[0]

ierr = psspy.save(r'network_compensated.sav')

print("Ploss before %s" % PLOSS1)
print("Ploss after %s" % PLOSS2)
print("Voltage before %s" % vpu01)
print("Voltage after %s" % vpu02)
Ejemplo n.º 18
0
                                                   load_change_region1)
            loadIncrement_region2 = LoadIncreaseMW(load_bus_region[0],
                                                   load_change_region2)
            loadIncrement_region3 = LoadIncreaseMW(load_bus_region[0],
                                                   load_change_region3)

            change_load(load_bus_region[0], load_change_region1)
            change_load(load_bus_region[1], load_change_region2)
            change_load(load_bus_region[2], load_change_region3)

            change_gen(gen_bus_region[0], loadIncrement_region1)
            change_gen(gen_bus_region[1], loadIncrement_region2)
            change_gen(gen_bus_region[2], loadIncrement_region3)

            savecase = 'ieee118bus_divided_temp.sav'
            psspy.save(savecase)

            # secure or not
            psspy.case(savecase)
            psspy.fnsl()

            # check convergency
            N = psspy.solved()

            [bus_voltage, bus_angle] = powerlib.getMeasurements(response_buses)

            # check voltage violation
            if N == 0:
                # get bus measurements number
                [bus_voltage,
                 bus_angle] = powerlib.getMeasurements(response_buses)
Ejemplo n.º 19
0
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)