psspy.load_chng_4(3,
                          '1',
                          realar1=sheet.cell(row=i, column=3).value,
                          realar2=0.01 * sheet.cell(row=i, column=3).value)
        psspy.load_chng_4(4,
                          '1',
                          realar1=sheet.cell(row=i, column=4).value,
                          realar2=0.01 * sheet.cell(row=i, column=4).value)
        psspy.load_chng_4(5,
                          '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)
Beispiel #2
0
def main():
    # set output path
    outpath = r"""TpeOut\\"""

    # TPE reduction
    TPE_list = r"""TPE_list.xlsx"""
    rootbus1_list, bus_red_list, d1bus_list, rootbus2_list, retdbus_list, N_tpe = read_bus_TPE(TPE_list)

    for instance_i in range(N_tpe):
        bus_root1 = rootbus1_list[instance_i]
        bus_root2 = rootbus2_list[instance_i]
        bus_ret = retdbus_list[instance_i]
        bus_red = bus_red_list[instance_i]
        bus_d1 = d1bus_list[instance_i]

        # read power flow model before reduction step i
        psspy.psseinit(50000)
        if instance_i == 0:
            psspy.read(0, r"""FullModel\wecc179_v33.raw""")
        else:
            pass
        psspy.fnsl([1, 0, 0, 1, 1, 0, 0, 0])

        # get power flow data
        pfd = PFData()
        pfd.getdata(psspy)

        # count elements in full model
        if instance_i == 0:
            n_gen_bf, n_load_bf, n_bus_bf, n_line_bf, n_xfmr_bf, n_shunt_bf = CountEle(pfd)


        # prepare data for two-port equivalent
        P1, Q1, Vm1, Va1, PrateA1, PrateB1, P3, Q3, Vm3, Va3, PrateA3, PrateB3, PL, QL, PG, QG, MW_ll, MW_ul, Mvar_ll,\
        Mvar_ul, MVA_base, PS, QS, load_bus, gen_bus, shunt_bus = read_subsys_TPE(pfd, bus_root1, bus_red, bus_d1, bus_root2, bus_ret)



        # calculate TPE equivalent
        Vm2, Va2, r1, x1, r2, x2 = CalcTwoPortEqui(pfd, P1, Q1, Vm1, Va1, P3, Q3, Vm3, Va3, PL, QL, PG, QG, PS, QS)



        # Implement two-port equivalent in PSSE
        DoTpeInPsse(psspy, pfd, bus_root1, bus_root2, bus_ret, bus_red, bus_d1, PL, QL, PG, QG, PS, QS, PrateA1, PrateB1, PrateA3,
                PrateB3, MW_ll, MW_ul, Mvar_ll, Mvar_ul, MVA_base, Vm2, Va2, r1, x1, r2, x2)



        # save new power flow data
        psspy.rawd_2(0, 1, [0, 0, 1, 0, 0, 0, 0], 0, outpath + "tpe_step_" + str(instance_i + 1))



    # calc a summary for TPE reduction
    pfd.getdata(psspy)
    n_gen_af, n_load_af, n_bus_af, n_line_af, n_xfmr_af, n_shunt_af = CountEle(pfd)



    #
    print("\nTPE reduction summary:")
    print("(# of elements, Before, After, Reduction %)")
    print("-----------------------------------------------")
    print("       Buses: ", n_bus_bf, n_bus_af, str(float((n_bus_bf - n_bus_af))/n_bus_bf*100)[0:5] + "%")
    print(" Generations: ", n_gen_bf, n_gen_af, str(float((n_gen_bf - n_gen_af))/n_gen_bf*100)[0:5] + "%")
    print("       Loads: ", n_load_bf, n_load_af, str(float((n_load_bf - n_load_af))/n_load_bf*100)[0:5] + "%")
    print("       Lines: ", n_line_bf, n_line_af, str(float((n_line_bf - n_line_af))/n_line_bf*100)[0:5] + "%")
    print("Transformers: ", n_xfmr_bf + 1, n_xfmr_af + 1, str(float((n_xfmr_bf - n_xfmr_af))/(n_xfmr_bf+1)*100)[0:5] + "%")
    print("      Shunts: ", n_shunt_bf, n_shunt_af,
          str(float((n_shunt_bf - n_shunt_af)) / (n_shunt_bf + 1) * 100)[0:5] + "%")
            r"""ALL""", r"""ALL""", r"""ALL""", r"""ALL""", r"""ALL""",
            r"""ALL""", r"""ALL"""
        ], scopfdfx, fileINL, "")

        # write the flag whether the SCOPF is successful or not
        xscopf.write("A" + str(Row), caseX)
        xscopf.write("B" + str(Row), ierr)
        Row = Row + 1

        listtmp2 = [caseX, ierr]
        csv_scopf_writer.writerow(listtmp2)

        # save case
        savecase = scopfaddress + '\\' + caseX + '_scopf.sav'
        psspy.save(savecase)
        psspy.rawd_2(0, 1, [1, 1, 1, 0, 0, 0, 0], 0,
                     scopfaddress + '\\' + caseX + '_scopf.raw')

        print('------------------finish SCOPF for case:' + caseX +
              '  ------------------')

        #---------------------form the base case gen dictionary-------------------------------
        ierr, iarray = psspy.amachint(-1, 4, 'NUMBER')
        vbasecasegenbusno = iarray[
            0]  # this array has all the generator's bus number, including both in-service and out-service
        ierr, iarray = psspy.amachint(-1, 4, 'STATUS')
        vbasecasegenstatus = iarray[
            0]  # this array has all the generator's status: in-service (1) and out-service (0)
        ierr, carray = psspy.amachchar(-1, 4, 'ID')
        vbasecasegenid = carray[
            0]  # this array has all the generator's ID, string
        ierr, rarray = psspy.amachreal(-1, 4, 'PGEN')
Beispiel #4
0
def changeLoad(raw, start, end, step, newdir):
    """ 
        New raw files are created for each percentage step in [start,end]. 
        The current step defines the percentage scaling up (or down) factor for load and generation
    """

    # convert the raw file to another one where all the load is constant power
    raw_conp = raw.replace('.raw', '') + '_conp.raw'
    redirect.psse2py()
    psspy.psseinit(buses=80000)

    # ignore the output
    psspy.report_output(6, '', [0, 0])
    psspy.progress_output(6, '', [0, 0])
    psspy.alert_output(6, '', [0, 0])
    psspy.prompt_output(6, '', [0, 0])

    # read the raw file and convert all the loads to constant power
    ierr = psspy.read(0, raw)

    # multi-line command to convert the loads to 100% constant power
    psspy.conl(0, 1, 1, [1, 0], [0.0, 0.0, 0.0, 0.0])
    psspy.conl(0, 1, 2, [1, 0], [0.0, 0.0, 0.0, 0.0])
    psspy.conl(0, 1, 3, [1, 0], [0.0, 0.0, 0.0, 0.0])
    ierr = psspy.rawd_2(0, 1, [1, 1, 1, 0, 0, 0, 0], 0, raw_conp)
    # run change Load on the constant power load raw file

    rawBusDataDict = getBusData(raw_conp)
    # create a new directory to put the files in
    currentdir = os.getcwd()

    if not os.path.exists(newdir):
        os.mkdir(newdir)
    output_dir = currentdir + '/' + newdir
    #genDiscount = 0.90 # ratio of the actual increase in generation
    genDiscount = 1.0
    lossRatio = 0.0  # gen scale-up factor: (scalePercent + (scalePercent-100)*lossRatio)/100
    ############################################

    # create new raw files with scaled up loads and generation
    for scalePercent in range(start, end + step, step):
        scalePercent = float(
            scalePercent)  # float is needed, otherwise 101/100 returns 1

        scalePercentInt = int(
            scalePercent)  # integer value needed to append to filename
        scalePercentStr = str(scalePercentInt)

        # variables to store load data
        loadBusList = []  # list of load buses (string)
        loadPList = []  # list of Pload values (string)
        loadQList = []  # list of Qload values (string)
        loadPListInt = []  # list of Pload values (float)
        loadQListInt = []  # list of Qload values (float)
        #loadBusListInt = [] # list of load buses (int)

        # variables to store gen data
        genBusList = []
        #genBusListInt = []
        genPList = []
        genMVAList = []
        genMVAListInt = []
        genPListInt = []

        raw_name = raw_conp.replace('.raw', '')
        out_file = raw_name + scalePercentStr + '.raw'  # output file
        out_path = output_dir + '/' + out_file
        impLoadBuses = [
        ]  # enter specified load buses to scale, if empty all loads are scaled
        incLoss = (
            scalePercent - 100
        ) * lossRatio  # Additional percentage increase in Pgen (to account for losses)
        #############################################

        #Read raw file
        with open(raw_conp, 'r') as f:
            filecontent = f.read()
            filelines = filecontent.split('\n')

            ## Get start and end indices of load and gen info
            #########################################
            loadStartIndex = filelines.index(
                '0 / END OF BUS DATA, BEGIN LOAD DATA') + 1
            loadEndIndex = filelines.index(
                '0 / END OF LOAD DATA, BEGIN FIXED SHUNT DATA')

            genStartIndex = filelines.index(
                '0 / END OF FIXED SHUNT DATA, BEGIN GENERATOR DATA') + 1
            genEndIndex = filelines.index(
                '0 / END OF GENERATOR DATA, BEGIN BRANCH DATA')
            ##############################################################################

            totalPincr = 0.0
            totalQincr = 0.0
            percentIncr = (scalePercent -
                           100.0) / 100  # increment in percentage

            newPConList = []
            newQConList = []
            newIPList = []
            newIQList = []
            newZPList = []
            newZQList = []
            # Extract load info
            for i in range(loadStartIndex, loadEndIndex):
                words = filelines[i].split(',')
                loadBus = words[0].strip()
                #loadBusList.append(words[0].strip())
                loadPCon = float(words[5].strip())
                loadQCon = float(words[6].strip())
                loadIP = float(words[7].strip())
                loadIQ = float(words[8].strip())
                loadZP = float(words[9].strip())
                loadZQ = float(words[10].strip())

                # calculate the total MW (MVAr) increase in load
                loadBusVolt = float(rawBusDataDict[loadBus].voltpu)

                Pincr = percentIncr * (
                    loadPCon + loadIP * loadBusVolt + loadZP * loadBusVolt**2
                )  # this equation is provided in PAGV1 page 293
                Qincr = percentIncr * (loadQCon + loadIQ * loadBusVolt +
                                       loadZQ * loadBusVolt**2)
                totalPincr += Pincr
                totalQincr += Qincr
                ###

                # new load values
                newPConList.append(loadPCon * scalePercent / 100)
                newQConList.append(loadQCon * scalePercent / 100)
                newIPList.append(loadIP * scalePercent / 100)
                newIQList.append(loadIQ * scalePercent / 100)
                newZPList.append(loadZP * scalePercent / 100)
                newZQList.append(loadZQ * scalePercent / 100)
                """
                loadPList.append(words[5].strip()) # adding P value (constant power)
                loadQList.append(words[6].strip()) # adding Q value (constant power)
                loadIPList.append(words[7].strip()) # constant current P
                loadIQList.append(words[7].strip()) # constant current Q
                loadZPList.append(words[9].strip()) # adding P value (constant admittance)
                loadZQList.append(words[10].strip()) # adding Q value (constant admittance)
                """

            # get total MW gen
            totalGenMW = 0.0  # total generation excluding the swing bus
            for i in range(genStartIndex, genEndIndex):
                words = filelines[i].split(',')
                GenBus = words[0].strip()
                if rawBusDataDict[GenBus].type == '3':
                    continue
                PGen = float(words[2].strip())
                totalGenMW += PGen

            # get new MW Gen
            GenMWDict = {}  # dictionary to hold new PGen values
            for i in range(genStartIndex, genEndIndex):
                words = filelines[i].split(',')
                Bus = words[0].strip()
                if rawBusDataDict[Bus].type == '3':
                    continue
                macID = words[1].strip()
                key = Bus + macID
                PGen = float(words[2].strip())
                genIncr = PGen / totalGenMW * totalPincr
                newPGen = (PGen + genIncr) * genDiscount
                GenMVA = float(words[8].strip())
                if newPGen < GenMVA:
                    GenMWDict[key] = newPGen
                else:
                    GenMWDict[key] = GenMVA

        #  generate the new raw file
        with open(out_path, 'w') as f:
            # copy everything before load data
            for i in range(loadStartIndex):
                f.write(filelines[i])
                f.write('\n')

            # modify the load data
            j = 0
            for i in range(loadStartIndex, loadEndIndex):
                words = filelines[i].split(',')

                # change the constant MVA values
                words[5] = '%.3f' % newPConList[j]
                words[6] = '%.3f' % newQConList[j]
                words[5] = words[5].rjust(10)
                words[6] = words[6].rjust(10)

                # change the constant current values
                words[7] = '%.3f' % newIPList[j]
                words[8] = '%.3f' % newIQList[j]
                words[7] = words[7].rjust(10)
                words[8] = words[8].rjust(10)

                # change the constant impedance values
                words[9] = '%.3f' % newZPList[j]
                words[10] = '%.3f' % newZQList[j]
                words[9] = words[9].rjust(10)
                words[10] = words[10].rjust(10)

                # construct a whole string by inserting commas between the words list
                filelines[i] = reconstructLine2(words)
                f.write(filelines[i])
                f.write('\n')
                # increment the load list index
                j += 1

            # copy the shunt data, which is in between the load and gen data
            for i in range(loadEndIndex, genStartIndex):
                f.write(filelines[i])
                f.write('\n')

            # update and write the gen data
            for i in range(genStartIndex, genEndIndex):
                words = filelines[i].split(',')
                Bus = words[0].strip()

                if rawBusDataDict[Bus].type == '3':
                    f.write(filelines[i])
                    f.write('\n')
                    continue
                macID = words[1].strip()
                key = Bus + macID
                newPGen = GenMWDict[key]

                words[2] = '%.3f' % newPGen
                words[2] = words[2].rjust(10)

                # construct a whole string by inserting commas between the words list
                filelines[i] = reconstructLine2(words)
                f.write(filelines[i])
                f.write('\n')

                # copy the rest of the raw data
            for i in range(genEndIndex, len(filelines)):
                f.write(filelines[i])
                f.write('\n')

    # solves each of the newly generated raw files and saves them
    output_dir = currentdir + '/' + newdir
    NewRawFiles = os.listdir(output_dir)
    PathList = [(output_dir + '/' + f) for f in NewRawFiles]

    redirect.psse2py()
    psspy.psseinit(buses=80000)

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

    for i in range(len(PathList)):
        #Settings. CONFIGURE THIS
        settings = {
            # use the same raw data in PSS/E and TS3ph #####################################
            'filename':
            PathList[i],  #use the same raw data in PSS/E and TS3ph
            ################################################################################
            'dyr_file':
            '',
            '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
            ]
        }

        psse_log = output_dir + '/' + 'log' + NewRawFiles[i].replace(
            '.raw', '.txt')
        psspy.report_output(2, psse_log, [0, 0])
        psspy.progress_output(2, psse_log, [0, 0])
        psspy.alert_output(2, psse_log, [0, 0])
        psspy.prompt_output(2, psse_log, [0, 0])

        print "\n Reading raw file:", settings['filename']
        ierr = psspy.read(0, settings['filename'])
        ierr = psspy.fnsl(settings['pf_options'])
        converge = psspy.solved()
        if converge == 0:
            ierr = psspy.rawd_2(0, 1, [1, 1, 1, 0, 0, 0, 0], 0, PathList[i])
        else:  # file does not converge, remove raw file, keep log file
            os.remove(PathList[i])
        """
Beispiel #5
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)
def main():
    # set output path
    outpath = r"""SpeOut\\"""

    # SPE reduction
    SPE_list = r"""SPE_list.xlsx"""
    rootbus_list, redbus_list, d1bus_list, N_spe = read_bus(SPE_list)

    for instance_i in range(N_spe):
        bus_root = rootbus_list[instance_i]
        bus_red = redbus_list[instance_i]
        bus_d1 = d1bus_list[instance_i]

        # read power flow model before reduction step i
        psspy.psseinit(50000)
        if instance_i == 0:
            # psspy.readrawversion(0, r"""30""", r"""FullModel\wecc179.raw""")  # reading .raw file
            # psspy.case(r"""FullModel\Maui2022dm_v4_wHydro_step0""")  # reading .sav file
            psspy.read(0, r"""FullModel\wecc179_v33.raw""")
        else:
            pass
        psspy.fnsl([1, 0, 0, 1, 1, 0, 0, 0])

        # get power flow data
        pfd = PFData()
        pfd.getdata(psspy)

        # count elements in full model
        if instance_i == 0:
            n_gen_bf, n_load_bf, n_bus_bf, n_line_bf, n_xfmr_bf, n_shunt_bf = CountEle(pfd)


        # prepare data for single-port equivalent
        Pin, Qin, PL, QL, PG, QG, PS, QS, Vm, Va, Ve, PrateA, PrateB, MW_ll, MW_ul, Mvar_ll, Mvar_ul, MVA_base, \
        red_load_bus, red_gen_bus, red_shunt_bus = read_subsys(pfd, bus_root, bus_red, bus_d1)



        # calculate SPE equivalent
        k, Vae, r, x = CalcSinglePortEqui(pfd, Pin, Qin, PL, QL, PG, QG, PS, QS, Vm, Va, Ve)



        # Implement single-port equivalent in PSSE
        DoSpeInPsse(psspy, bus_root, bus_red, bus_d1, pfd, PL, QL, PG, QG, PS, QS, Ve, PrateA, PrateB, MW_ll, MW_ul,
                       Mvar_ll, Mvar_ul, MVA_base, k, r, x)



        # save new power flow data
        psspy.rawd_2(0, 1, [0, 0, 1, 0, 0, 0, 0], 0, outpath + "spe_step_" + str(instance_i + 1))



    # calc a summary for SPE reduction
    pfd.getdata(psspy)
    n_gen_af, n_load_af, n_bus_af, n_line_af, n_xfmr_af, n_shunt_af = CountEle(pfd)



    #
    print("\nSPE reduction summary:")
    print("(# of elements, Before, After, Reduction %)")
    print("-----------------------------------------------")
    print("       Buses: ", n_bus_bf, n_bus_af, str(float((n_bus_bf - n_bus_af))/n_bus_bf*100)[0:5] + "%")
    print(" Generations: ", n_gen_bf, n_gen_af, str(float((n_gen_bf - n_gen_af))/n_gen_bf*100)[0:5] + "%")
    print("       Loads: ", n_load_bf, n_load_af, str(float((n_load_bf - n_load_af))/n_load_bf*100)[0:5] + "%")
    print("       Lines: ", n_line_bf, n_line_af, str(float((n_line_bf - n_line_af))/n_line_bf*100)[0:5] + "%")
    print("Transformers: ", n_xfmr_bf + 1, n_xfmr_af + 1, str(float((n_xfmr_bf - n_xfmr_af))/(n_xfmr_bf+1)*100)[0:5] + "%")
    print("      Shunts: ", n_shunt_bf, n_shunt_af,
          str(float((n_shunt_bf - n_shunt_af)) / (n_shunt_bf + 1) * 100)[0:5] + "%")
redirect.psse2py()
psspy.psseinit(buses=80000)
_i = psspy.getdefaultint()
_f = psspy.getdefaultreal()
_s = psspy.getdefaultchar()

psse_log = 'log.log'
# 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

for currentRawFile in RawFileList:
    ierr = psspy.read(0, currentRawFile)
    rawFileName = currentRawFile.replace('.raw', '')
    if rawFileName == 'savnw_conp':
        PL = ''
    else:
        PL = rawFileName[
            -3:]  # last 3 character contain the percentage loading

    # Load conversion (multiple-step)
    # all constant power load converted to constant admittance load
    psspy.conl(0, 1, 1, [0, 0], [0.0, 100.0, 0.0, 100.0])
    psspy.conl(0, 1, 2, [0, 0], [0.0, 100.0, 0.0, 100.0])
    psspy.conl(0, 1, 3, [0, 0], [0.0, 100.0, 0.0, 100.0])

    newRawFileName = 'conZRaw/savnw_conz{}.raw'.format(PL)
    ierr = psspy.rawd_2(0, 1, [1, 1, 1, 0, 0, 0, 0], 0, newRawFileName)
Beispiel #8
0
import redirect
import psspy
import dyntools
import csv

# Inputs and outputs
filename = 'tmpv2.raw'  # old raw file
raw_new = 'tmpv2_island.raw'  # new raw file created after disconnecting all the islands
psse_log = 'psse_log.txt'
######
redirect.psse2py()
psspy.psseinit(buses=80000)
# Redirect any psse outputs to psse_log
psspy.report_output(2, psse_log, [0, 0])
psspy.progress_output(6, psse_log, [0, 0])  #ignored
psspy.alert_output(6, psse_log, [0, 0])  #ignored
psspy.prompt_output(6, psse_log, [0, 0])  #ignored
##############################

ierr = psspy.read(0, filename)
bus_count = 0  # keep count of number of buses in island getting disconnected
# the tree command is responsible for detecting and disconnecting islands (see API book page 651)
ierr, buses = psspy.tree(1, 1)
bus_count += buses
while buses > 0:
    ierr, buses = psspy.tree(2, 1)
    bus_count += buses

ierr = psspy.rawd_2(0, 1, [1, 1, 1, 0, 0, 0, 0], 0, raw_new)
print 'Number of buses disconnected: ', bus_count
Beispiel #9
0
    	psse_log = output_dir + '/' + 'log' + NewRawFiles[i].replace('.raw','.txt')


    	redirect.psse2py()
    	psspy.psseinit(buses=80000)
    	psspy.report_output(2,psse_log,[0,0])
    	psspy.progress_output(2,psse_log,[0,0])
    	psspy.alert_output(2,psse_log,[0,0])
    	psspy.prompt_output(2,psse_log,[0,0])
    	_i=psspy.getdefaultint()
    	_f=psspy.getdefaultreal()
    	_s=psspy.getdefaultchar()
    	print "\n Reading raw file:",settings['filename']
    	ierr = psspy.read(0, settings['filename'])
    	ierr = psspy.fnsl(settings['pf_options'])
    	ierr = psspy.rawd_2(0,1,[1,1,1,0,0,0,0],0,PathList[i])
    	"""
        # Uncomment if you want to save .sav files as well
    	# Load conversion (multiple-step)
        ierr = psspy.cong(0) #converting generators
    	psspy.conl(_i,_i,1,[0,_i],[_f,_f,_f,_f])
    	psspy.conl(1,1,2,[_i,_i],[0.0, 0.0,100.0, 100.0])
    	psspy.conl(_i,_i,3,[_i,_i],[_f,_f,_f,_f])

    	ierr = psspy.save(PathList[i].replace('.raw','.sav'))
        """



Beispiel #10
0
    0,  #do not flat start
    0,  #apply var limits immediately
    0,  #disable non-div solution
]

# Inputs and outputs
filename = 'savnw.raw'  # raw file
#raw_new = 'tmpv2_island.raw' # new raw file created after disconnecting all the islands
psse_log = 'output' + filename.replace('.raw', '.txt')
######
redirect.psse2py()
psspy.psseinit(buses=80000)
# 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
##############################
_i = psspy.getdefaultint()
_f = psspy.getdefaultreal()
_s = psspy.getdefaultchar()

ierr = psspy.read(0, filename)

# Load conversion (multiple-step)
psspy.conl(_i, _i, 1, [0, _i], [_f, _f, _f, _f])
psspy.conl(1, 1, 2, [_i, _i], [0.0, 0.0, 100.0, 100.0])
psspy.conl(_i, _i, 3, [_i, _i], [_f, _f, _f, _f])

ierr = psspy.rawd_2(0, 1, [1, 1, 1, 0, 0, 0, 0], 0, 'savnw_exp.raw')
#ierr = psspy.fnsl(pf_options) # solve power flow