示例#1
0
def main():
    signals = []  # will print all signals, else you can indicate them like so   signals = [1,2,4,5]
    for outfile in os.listdir(WorkingFolder):
        if outfile.endswith(".out"):
            excel_file = outfile.split(".out")[0] + "_excel" # This line was added to show that xlsfile can be used to change name or even directory
            dyntools.CHNF(outfile).xlsout(channels=signals, show=False, outfile=outfile, xlsfile=excel_file)
示例#2
0
# Simulation Procedure
##1.	System initialization and run simulation to t = 1 s.
psspy.run(0, 1, 0, 0, 0)
##2.	Apply 3-phase fault at line B6 – B7 at t = 1s.
psspy.dist_branch_fault(6, 7, '1', 3, 0.0, [75.625e-5, 0])
##3.	Continue simulation to t = 1.1s.
psspy.run(0, 1.1, 0, 0, 0)
##4.	Trip line B6 – B7 and clear fault at t = 1.1s.
psspy.dist_clear_fault()
psspy.dist_branch_trip(6, 7, '1')
##5.	Continue simulation to t = 6.1s.
psspy.run(0, 6.1, 0, 0, 0)
##6.	Reschedule generator with run-up M1 from 250 MW to 500 MW and run-down M2 from about 573 MW to 300 MW, and trip load at B7 at t = 6.1s at t = 6.1s
psspy.increment_gref(30, '1', 0.25)
psspy.increment_gref(31, '1', -0.273)
psspy.dist_branch_trip(7, 71, '1')
##7.	Continue simulation to t = 30s.
psspy.run(0, 30, 0, 0, 0)

### Reconnect Load
##psspy.busdata2(jbus,INTGAR1=1);
##psspy.DIST_BRANCH_CLOSE(ibus, jbus, id);

# Data Retrieval
achnf = dyntools.CHNF(out_file)

# Export Data to Excel
achnf.xlsout()

##id_xls_COMPARE.close();
        ierr = psspy.run(0,30.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 (for debugging)
    #with open('outputTmp.txt','w') as f:
    #   f.write(outputStr)


    outputData = dyntools.CHNF(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
    keySet = set()
    for key in channelDict:
        if key == 'time':
            continue

        signalDescr = channelDict[key]
        words = signalDescr.split()
示例#4
0
 def _compute_achnf(self):
     if self.achnf is None:
         self.achnf = dyntools.CHNF(self.out_file)
示例#5
0
                    dst_file = OUTDIR+pdfName
                    pdfNameNew = pdfName[:-4]+'_'+str((plotCount-1)/maxPlots)+'.pdf'
                    new_dst_file = OUTDIR+pdfNameNew
                    os.rename(dst_file, new_dst_file)

                    pdfNameNew = pdfName[:-4]+'_'+str(((plotCount-1)/maxPlots)+1)+'.pdf'
                    pp = PdfPages(OUTDIR+pdfNameNew) #pp is the PDF where all plots will go

                elif (plotCount) > maxPlots and ((plotCount-1)%maxPlots == 0):
                    pp.close() #close the PDF
                    #plt.close()
                    pdfNameNew = pdfName[:-4]+'_'+str(((plotCount-1)/maxPlots)+1)+'.pdf'
                    pp = PdfPages(OUTDIR+pdfNameNew) #pp is the PDF where all plots will go
                #*********************************************************************************************
                outlst = [outfile]
                chnf = dyntools.CHNF(outlst)
                outfilename = outlst[0].split('\\')[-1] #title for plots created with this .out file will be the filename
                # test_data_extraction(chnf)
                figNo,subplotNo = test_plots2pdf(chnf,figNo,subplotNo,outfilename,pp,primaryAxisChs,secondaryAxisChs,layout,Primary2Ylabel) #returns next figure and subplot number
        if subplotNo != 1:#== int(layout[0])*int(layout[1]):
            #plt.tight_layout(pad=5.0,w_pad=5.0, h_pad=7.0)
            plt.savefig(pp, format='pdf') #bbox_inches='tight' #TM: added 29/07/2016
            if SAVE_IMAGES:
                plt.savefig(IMAGEDIR+outfilename+'_'+str(figNo)+'.png')
                print IMAGEDIR+outfilename+'_'+str(figNo)+'.png saved'
        pp.close() #close the PDF
        print OUTDIR+pdfName,"saved"
        figNo = 1

# =============================================================================================
示例#6
0
load = load_models.Load(6500)  # Create a load consisting of Trondheim

ierr = psspy.strt(outfile=outputfile)  # Tell PSS/E to write to the output file

# Simulation----------------------------------------------------------------------------------------------------------------------------------

if ierr == 0:
    # nprt: number of time steps between writing to screen
    # nplt: number of time steps between writing to output file
    psspy.run(tpause=0, nprt=0, nplt=0)  # run the simulation
    load.step(100)  # Do a 100MW load step in Trondheim
    psspy.run(tpause=120)  # Pause the simulation after 120 seconds


else:
        print(ierr)

# Read the putput file
chnf = dyntools.CHNF(outputfile)
# assign the data to variables
sh_ttl, ch_id, ch_data = chnf.get_data()

# Do the plotting
plt.figure(1)
plt.plot(ch_data['time'], ch_data[1])  # Kvilldal Power

plt.figure(2)
plt.plot(ch_data['time'], ch_data[2])  # Kvilldal frequency

plt.show()
import sys

sys_path_PSSE = r'D:\Program Files (x86)\PTI\PSSEXplore34\PSSPY34'  # or where else you find the psspy.pyc
sys.path.append(sys_path_PSSE)
os_path_PSSE = r'D:\Program Files (x86)\PTI\PSSEXplore34\PSSBIN'  # or where else you find the psse.exe
os.environ['PATH'] += ';' + os_path_PSSE
os.environ['PATH'] += ';' + sys_path_PSSE

import dyntools
import matplotlib.pyplot as plt

sample_id = 1

for i in range(0, 5):
    for j in range(12):
        outfile_noRel = dyntools.CHNF('./t14Bus-PY-00' + str(sample_id) +
                                      '.out')
        sample_id += 1
        short_title_noRel, chanid_dict_noRel, chandata_dict_noRel = outfile_noRel.get_data(
        )
        time_noRel = chandata_dict_noRel['time']

        fig = plt.figure(i + 1)
        fig.patch.set_facecolor(
            '0.8'
        )  # set background color, could use float number and color name
        # plt.subplots_adjust(top=0.95, bottom=0.06, left=0.05, right=0.98, wspace=0.15, hspace=0.45)  # 调整 subplot在 fig中的边界距离

        plt.subplot(4, 3, j + 1)
        plt.plot(time_noRel,
                 chandata_dict_noRel[1],
                 linestyle='-',
示例#8
0
        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]
示例#9
0
import os
import sys
import matplotlib.pyplot as plt

sys_path_PSSE = r'D:\Program Files (x86)\PTI\PSSEXplore34\PSSPY34'  # or where else you find the psspy.pyc
sys.path.append(sys_path_PSSE)

os_path_PSSE = r'D:\Program Files (x86)\PTI\PSSEXplore34\PSSBIN'  # or where else you find the psse.exe
os.environ['PATH'] += ';' + os_path_PSSE
os.environ['PATH'] += ';' + sys_path_PSSE

import dyntools

# file PATH
outfile = dyntools.CHNF('./Sample_14bus_1/t14Bus-PY-001.out')

short_title, chanid_dict, chandata_dict = outfile.get_data()
print('\n标题“short_title”是:', short_title)
print('类型是:', type(short_title), '--字符串')
print('字符串长度为: ', len(short_title))
# print(input('按回车继续...'))

print('\n通道 id“chanid_dict”,以及通道 data“chandata_dict“')
print('类型是:', type(chanid_dict), '--字典')
print('字典的 keys 均为:', chanid_dict.keys())
print('其长度为: ', len(chanid_dict))
# print(input('按回车继续...'))

print('\n通道 id“chanid_dict”的 values 为:\n ', chanid_dict.values())
# print(input('按回车继续...'))
#

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

# Run to 3 cycles
time = 3.0 / 60.0
psspy.run(0, 1 + time, 0, 0, 0)

# Clear fault (assuming only part of bus faults)
psspy.dist_clear_fault()
psspy.dist_branch_trip(ibus=151, jbus=201, id='1')

# Run to 10 seconds
time = 10
psspy.run(0, time, 0, 0, 0)

# Export channel data to Excel
dyntools.CHNF.xlsout(dyntools.CHNF(out_file),
                     channels='',
                     show='True',
                     xlsfile='out.xls',
                     sheet='',
                     overwritesheet=True)
示例#11
0
def plot(out_folder,
         out_file,
         out_chans,
         plot_title=["NA"] * 12,
         plot_x_label=["Time (s)"] * 12,
         plot_y_label=[""] * 12,
         top_title="",
         xlims="",
         ylims="",
         angle=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]):
    '''if isinstance(out_file, basestring):
        out_file = [out_file]
    elif "_PSSE" in out_file[1].lower():
        out_file[0], out_file[1] = out_file[1], out_file[0]'''

    if out_chans is None:
        out_chans = []

    if not (ylims == "" or isinstance(ylims[0], list)):
        ylims = [ylims] * 12

    if not (xlims == "" or isinstance(xlims[0], list)):
        xlims = [xlims] * 12

    # for x in xrange(len(out_chans)):
    #     if not isinstance(out_chans, list):
    #         out_chans[x] = [out_chans[x]]

    _ch_id, _ch_data, _sh_tt, time = [], [], [], []
    try:
        chnfobj = dyntools.CHNF(out_file[0])
        sh_tt_0, ch_id_0, ch_data_0 = chnfobj.get_data()
        _ch_data.append(ch_data_0)
        _ch_id.append(ch_id_0)
        _sh_tt.append(sh_tt_0)
        #print(len(ch_data_0))
        time.append(ch_data_0['time'])
    except OverflowError:
        error_plot(
            out_folder, out_file[0],
            "The OUT file seems to have infinite data in it and cannot be read.\nThis case is considered a failed case."
        )
        return

    #read EXCEL
    filename = out_file[1]
    import os
    from os.path import join, dirname, abspath, isfile
    from collections import Counter
    import xlrd
    from xlrd.sheet import ctype_text
    cwd = os.getcwd()
    import psse34
    import dyntools

    def read_excel_tools(filename, sheet_index):
        xl_workbook = xlrd.open_workbook(filename)
        xl_sheet = xl_workbook.sheet_by_index(sheet_index)
        return xl_sheet

    def get_data(xl_sheet):
        import re
        chanid = {}
        chandata = {}
        title_row = 1
        title_col = 0
        chan_number_row = 0
        title_row = 0
        short_title = os.path.splitext(filename)[0]
        row_chan = xl_sheet.row(chan_number_row)
        row_title = xl_sheet.row(title_row)
        for chan_idx in range(len(row_chan)):
            chan_idx_data = []
            for row_idx in range(1, xl_sheet.nrows):
                cell_obj = (xl_sheet.cell(row_idx, chan_idx)).value
                if (isinstance(cell_obj, unicode)):
                    if len(re.findall(("\d+\.\d+"), cell_obj)) > 0:
                        cell_obj = float(re.findall("\d+\.\d+", cell_obj)[0])
                    elif len(re.findall(("\d+"), cell_obj)) > 0:
                        cell_obj = float(re.findall("\d+", cell_obj)[0])
                    else:
                        print 'This is not float type'
                #print(cell_obj)
                # if type(cell_obj) != float:
                #     cell_obj = float(re.findall("\d+\.\d+", cell_obj)[0])
                chan_idx_data.append(cell_obj)
            if chan_idx == 0:
                chan_idx_data = []
                simtime = 0
                T_step = 0.02
                for row_idx in range(1, xl_sheet.nrows):
                    chan_idx_data.append(simtime)
                    simtime += T_step
                chanid['time'] = str(row_title[chan_idx].value)
                chandata['time'] = chan_idx_data
            else:
                chanid[int(chan_idx)] = str(row_title[chan_idx].value)
                chandata[int(chan_idx)] = chan_idx_data
        return short_title, chanid, chandata

    xl_sheet = read_excel_tools(filename, sheet_index=1)
    short_title, chanid, chandata = get_data(xl_sheet)

    _ch_data.append(chandata)
    _ch_id.append(chanid)
    _sh_tt.append(short_title)
    #print(len(ch_data_0))
    time.append(chandata['time'])

    # loop through each of the channels required and extract the data
    data = []
    angle_data = []
    for y in xrange(
            len(out_file)):  #len(outfile) = 2, psse and pscad inf file name
        j = 0
        data.append([])
        for chan in out_chans[y]:
            if isinstance(chan, list):
                data[y].append([])
                for i in xrange(len(chan)):
                    data[y][j].append(_ch_data[y][chan[i]])

            else:
                data[y].append([])
                data[y][j].append(_ch_data[y][chan])

            j += 1
        for angle_chan in angle:
            angle_data.append([])
            try:
                angle_data[y].append(_ch_data[y][angle_chan])
            except Exception:
                angle_data[y].append([None])

    if not isinstance(plot_title, list):
        plot_title = [plot_title]
    if not isinstance(plot_x_label, list):
        plot_x_label = [plot_x_label]
    if not isinstance(plot_y_label, list):
        plot_y_label = [plot_y_label]

    # set up inital values for the plot
    nRows, nCols = find_row_col(len(out_chans[y]))
    fig = plt.figure(figsize=[(2 + 10 * nCols), (2 + 4 * nRows)])
    fig.suptitle(top_title, fontsize=20)

    # pre-initialize
    ax = []
    time_diff = 0
    num = len(data[0])
    for sub in xrange(num):

        # If no label given, default to blank labels to prevent error being thrown
        if sub > len(plot_title) - 1:
            plot_title.append("")
        if sub > len(plot_x_label) - 1:
            plot_x_label.append("Time (s)")
        if sub > len(plot_y_label) - 1:
            plot_y_label.append("")

        # The following code is plotting and plot options

        # Set it up so that all plots share the same x axis, this means that you can zoom and navigate the plot...
        #       and all the subplots will move together
        if xlims == "" or isinstance(xlims[0], int) or isinstance(
                xlims[0], float):
            if sub == 0:
                ax.append(plt.subplot(nRows, nCols, sub + 1))
            else:
                ax.append(plt.subplot(nRows, nCols, sub + 1, sharex=ax[0]))
        else:
            ax.append(plt.subplot(nRows, nCols, sub + 1))

        # Titles and labels
        if not isinstance(out_chans[0][sub], list):
            if plot_title[sub] == "NA":
                plt.title(_ch_id[0][out_chans[0][sub]], fontsize=13)
            else:
                plt.title(plot_title[sub], fontsize=13)
        elif plot_title[sub] == "NA":
            plt.title("", fontsize=13)
        else:
            plt.title(plot_title[sub], fontsize=13)
        plt.xlabel(plot_x_label[sub])
        plt.ylabel(plot_y_label[sub], labelpad=20)

        data_lims = []
        # If out data to plot, plot it
        for y in xrange(len(out_file)):
            if "_PSSE" in out_file[y]:
                psse_pscad = " Psse"
            else:
                psse_pscad = " Pscad"
            if isinstance(out_chans[0][sub], list):
                for x in xrange(len(out_chans[0][sub])):
                    if data[y][sub][x] != -1:
                        '''Ts = 0.02 #from the start to the finish of the slope, 20 milliseconds                        
                        simt = 0
                        tDataArrayIndex_start = 0
                        tDataArrayIndex_stop = 0
                        data_110 = []
                        data_90 = []
                        time_bounce = []
                        while tDataArrayIndex_stop < len(time[y]):
                            simt = time[y][tDataArrayIndex_stop]-time[y][tDataArrayIndex_start]
                            while simt < Ts:
                                simt = time[y][tDataArrayIndex_stop]-time[y][tDataArrayIndex_start]
                                tDataArrayIndex_stop += 1
                                
                            #time[y][tDataArrayIndex_start]
                            #time[y][tDataArrayIndex_stop]
                            #tDataArrayIndex_start
                            #tDataArrayIndex_stop
                            #data[y][sub][x][tDataArrayIndex_start]
                            #data[y][sub][x][tDataArrayIndex_stop]
                            data_110.append(data[y][sub][x][tDataArrayIndex_start] + 0.1*(data[y][sub][x][tDataArrayIndex_stop]-data[y][sub][x][tDataArrayIndex_start]))
                            data_90.append(data[y][sub][x][tDataArrayIndex_start] - 0.1*(data[y][sub][x][tDataArrayIndex_stop]-data[y][sub][x][tDataArrayIndex_start]))
                            time_bounce.append(time[y][tDataArrayIndex_start])
                            tDataArrayIndex_start += 1
                            tDataArrayIndex_stop += 1'''
                        tDataArrayIndex_start = 0
                        tDataArrayIndex_stop = 0
                        data_110 = []
                        data_90 = []
                        time_bounce = []
                        y_dev = 0.1 * (max(data[y][sub][x]) -
                                       min(data[y][sub][x]))
                        for index in range(len(time[y])):
                            data_110.append(data[y][sub][x][index] + y_dev)
                            data_90.append(data[y][sub][x][index] - y_dev)
                            time_bounce.append(time[y][index])

                        # CUSTOM
                        if angle[sub] != 0:
                            try:
                                for d in xrange(len(data[y][sub][x])):
                                    data[y][sub][x][d] -= angle_data[y][sub][d]
                            except Exception:
                                print(
                                    "ERROR -=-=-=-==-=-=-=-=-=-=------------=-=-==-=-=--==-=-=-=-=-=-=-=-=-"
                                )
                                # /CUSTOM
                        if psse_pscad == " Psse":
                            plt.plot(time[y],
                                     data[y][sub][x],
                                     label=_ch_id[y][out_chans[0][sub][x]] +
                                     psse_pscad)
                            #plt.plot(time_bounce,data_90,':',label="90% Boundary",color='gray')
                            #plt.plot(time_bounce,data_110,':',label="110% Boundary",color='gray')
                        else:
                            plt.plot(time[y],
                                     data[y][sub][x],
                                     linestyle='dashed',
                                     dashes=(4, 3),
                                     label=_ch_id[y][out_chans[1][sub][x]] +
                                     psse_pscad)
                            plt.plot(time_bounce,
                                     data_90,
                                     ':',
                                     label="90% Boundary",
                                     color='gray')
                            plt.plot(time_bounce,
                                     data_110,
                                     ':',
                                     label="110% Boundary",
                                     color='gray')
                        data_lims += data[y][sub][x]
            else:
                if data[y][sub][0] != -1:
                    if angle[sub] != 0:
                        try:
                            for d in xrange(len(data[y][sub][0])):
                                data[y][sub][0][d] -= angle_data[y][sub][d]
                        except Exception:
                            print(
                                "ERROR -=-=-=-==-=-=-=-=-=-=------------=-=-==-=-=--==-=-=-=-=-=-=-=-=-"
                            )
                    # plt.plot(time, data[y][sub][0], label=_ch_id[y][out_chans[sub]] + psse_pscad)
                    if psse_pscad == " Psse":
                        plt.plot(time,
                                 data[y][sub][x],
                                 label=_ch_id[y][out_chans[0][sub][x]] +
                                 psse_pscad)
                        plt.plot(time[y],
                                 np.multiply(data[y][sub][x], 0.9),
                                 ':',
                                 label="90% Boundary")
                        plt.plot(time[y],
                                 np.multiply(data[y][sub][x], 1.1),
                                 ':',
                                 label="110% Boundary")
                    else:
                        plt.plot(time,
                                 data[y][sub][x],
                                 linestyle="dashed",
                                 dashes=(4, 3),
                                 label=_ch_id[y][out_chans[1][sub][x]] +
                                 psse_pscad)
                    data_lims += data[y][sub][0]

        plt.grid(True)  # turn on grid

        # Axis settings
        ax[sub].xaxis.set_minor_locator(ticker.AutoMinorLocator(
            2))  # automatically put a gridline in between tickers
        ax[sub].grid(b=True, which='minor',
                     linestyle=':')  # gridline style is dots
        ax[sub].tick_params(
            axis='x', which='minor',
            bottom='on')  # display small ticks at bottom midway
        ax[sub].get_xaxis().get_major_formatter().set_useOffset(
            False)  # turn off the annoying offset values
        ax[sub].get_yaxis().get_major_formatter().set_useOffset(False)
        plt.tight_layout()

        # Make sure that there is 15% padding on top and bottom
        max_data = max(data_lims)
        min_data = min(data_lims)
        data_range = max_data - min_data
        if ylims == "" or len(ylims) < sub + 1 or ylims[sub] == "":
            ylimit = ax[sub].get_ylim()
            new_y = restrict_y_axis(ylimit, data_range, max_data, min_data)
            ax[sub].set_ylim(new_y)
        else:
            ax[sub].set_ylim(ylims[sub])

        if xlims == "" or len(xlims) < sub + 1 or xlims[sub] == "":
            xlimit = [min(time), max(time)]
            ax[sub].set_xlim(xlimit)
        else:
            ax[sub].set_xlim(xlims[sub])

        # If there is a top title, make sure there is room for it
        top = 0.9
        if top_title == "":
            top = 0.95
        plt.subplots_adjust(right=0.9,
                            hspace=0.3,
                            wspace=0.3,
                            top=top,
                            left=0.1,
                            bottom=0.12)
        legend = plt.legend(bbox_to_anchor=(0., -0.28, 1., .105),
                            loc=3,
                            ncol=2,
                            mode="expand",
                            prop={'size': 6},
                            borderaxespad=0.)
        legend.get_title().set_fontsize('6')  # legend 'Title' fontsize
        plt.setp(plt.gca().get_legend().get_texts(),
                 fontsize='10')  # legend 'list' fontsize
        plt.subplots_adjust(hspace=0.5)
        # plt.legend(bbox_to_anchor=(0., -0.55, 1., .105), loc=3,
        #        ncol=4, mode="expand", borderaxespad=0.)

    # Plot the legend on the bottom, underneath everything
    # plt.legend(bbox_to_anchor=(0., -0.55, 1., .105), loc=3,
    #            ncol=4, mode="expand", borderaxespad=0.)

    # Save file

    file_str = os.path.join(out_folder,
                            out_file[0]).replace('_PSSE.out', '.pdf')
    #file_str = file_str.split(".png", 1)
    #file_str = file_str[0] + ".png"
    plot_name = os.path.basename(file_str[0:-4])
    plt.suptitle(plot_name, fontsize=14, fontweight='bold')
    plt.savefig(file_str, dpi=100)
    print str(plot_name + "Saved")
    plt.close()
示例#12
0
import os,sys
# import excelpy, csv
# import psspy, pssarrays
import dyntools

FILEPATH = os.path.abspath('U:\\Projects\\PS101926_2208519A\\05_WrkPapers\\WP\\GPS Report Technical Record\\Results_7June18')
print('WD=' + FILEPATH)

#redirect.psse2py()
#psspy.psseinit(10000)

Excel ='Template.xlsx'

for outfile in os.listdir(FILEPATH):
    if outfile.endswith(".out"):
		dyn = dyntools.CHNF(outfile)
                # xl = excelpy.workbook(xlsfile=Excel,mode='w')
		extract = dyn.xlsout(show=False,channels='', outfile='', sheet='Raw')
		# xl.close()

print 'You Are Done'


		### Use this to write in excel template
		#dyntools.CHNF.xlsout(dyn, channels=[], show=False, xlsfile=Excel, outfile=outfile,sheet=outfile,overwritesheet=True)

		#xl = excelpy.workbook(xlsfile=Excel,mode='w')
		#dyn.xlsout(channels='',xlsfile=Excel,outfile=outfile,sheet=outfile,overwritesheet=True)
		#dyn.xlsout(channels='',xlsfile=Excel, outfile=outfile, sheet=outfile,overwritesheet=True)
		#dyn.xlsout(channels='',xlsfile=Excel,outfile=outfile, sheet=outfile,overwritesheet=True)
		#xl.close()
import excelpy
import dyntools
"""
Comienza a extraer la información para cada uno de los *.out
"""
OutNames = "NETS-NYPS 68 Bus System_1"  #[Out1, Out2]
Ruta = "C:\\Program Files (x86)\\PTI\\PSSE34\\EXAMPLE\\New England 68-Bus Test System\\PSSE"

rootDir = Ruta + "\\"
logFile = file(rootDir + "Reporte_" + OutNames + "_Din.txt", "w")
logFile1 = file(rootDir + "Errores_" + OutNames + "_Din.txt", "w")
sys.stdout = logFile  # Las salidas
sys.stderr = logFile1  # Los errores
logFile.close()
logFile1.close()

outFile = dyntools.CHNF(
    "C:\\Program Files (x86)\\PTI\\PSSE34\\EXAMPLE\\New England 68-Bus Test System\\PSSE\\NETS-NYPS 68 Bus System_1.out"
)
#Extrae información del archivo *.out
#short_title, chanid_dict, chandata_dict = outFile.get_data()
outFile.xlsout(channels='', show=True, overwritesheet=True)
#report=Ruta+"\\"+"ex1.xlsx"
#xl=excelpy.workbook(xlsfile=report, sheet="", overwritesheet=True, mode='w')
#xl.show()
#xl.set_range(1, 'a', zip([short_title]))
#xl.set_range(1, 'b', zip([chanid_dict]))
#xl.set_range(1, 'c', [chandata_dict])
#xl.save()
示例#14
0
    def read_data(self, filename):
        # Read PSSE data

        if (filename[-4:].lower() in '.out') and ('pscad'
                                                  not in filename.lower()):
            print('Plotting file: ' + str(filename))
            self.filenames.append(filename)
            # PSSE output fileslen(time)
            import os, psse34
            import dyntools

            outfile_data = dyntools.CHNF(os.path.basename(filename))
            short_title, chanid, chandata = outfile_data.get_data()

            time = np.array(chandata['time'])
            data = np.zeros((len(chandata) - 1, len(time)))

            chan_ids = []
            for key in chandata.keys()[:-1]:
                print(key, chanid[key])
                data[key - 1] = chandata[key]
                chan_ids.append(chanid[key])
            self.timearrays.append(time)
            self.dataarrays.append(data)
            self.scales.append(np.ones(len(data) + 1))
            self.offsets.append(np.zeros(len(data) + 1))
            self.channel_names = chan_ids
        #Read PSCAD file
        if filename[-4:].lower() in ('*.inf'):
            print('Plotting file: ' + str(filename))
            # PSCAD output files
            import os, glob, re
            cwd = os.getcwd()
            outfiles = []
            for pscadfile in glob.glob(cwd + "/" + filename[0:-4] + "_*.out"):
                outfiles.append(pscadfile)
            #
            chan_ids = []
            f = open(filename, 'r')
            lines = f.readlines()
            f.close()
            for idx, rawline in enumerate(lines):
                line = re.split(r'\s{1,}', rawline)
                chan_ids.append(line[2][6:-1])
            #
            # Setup time array using last outfile
            time = []
            f = open(outfiles[0], 'r')
            lines = f.readlines()
            f.close()
            for l_idx, rawline in enumerate(lines[1:]):
                line = re.split(r'\s{1,}', rawline)
                time.append(float(line[1]))
            time = np.array(time)
            #
            # Setup empty data array using known number of channels and time steps
            data = np.zeros((len(chan_ids), len(time)))
            #
            # Populate data array using all outfiles
            for f_idx, outfile in enumerate(outfiles):
                f = open(outfile, 'r')
                lines = f.readlines()
                f.close()
                for n, rawline in enumerate(lines[1:]):
                    line = re.split(r'\s{1,}', rawline)
                    for m, value in enumerate(line[2:-1]):
                        data[(f_idx * 10) + m][n] = value
            for n, chan_id in enumerate(chan_ids):
                print(n + 1, chan_id)

            # Add data to arrays in class
            self.timearrays.append(time)
            self.dataarrays.append(data)
            self.scales.append(np.ones(len(data) + 1))
            self.offsets.append(np.zeros(len(data) + 1))
            self.channel_names = chan_ids

            # Read PSCAD INFX file
        if filename[-5:].lower() in ('*.infx'):
            print('Plotting file: ' + str(filename))
            # PSCAD output files
            import os, glob, re
            cwd = os.getcwd()
            outfiles = []
            for pscadfile in glob.glob(cwd + "/" + filename[0:-5] + "_*.out"):
                outfiles.append(pscadfile)
            #
            chan_ids = []
            f = open(filename, 'r')
            lines = f.readlines()
            f.close()
            lines = lines[5:(len(lines) - 3)]
            for idx, rawline in enumerate(lines):
                name_start = rawline.find("Analog name=") + 13
                name_stop = rawline.find("index") - 2
                rawline_short = rawline[name_start:name_stop]
                name_start = rawline_short.find(":") + 1
                chan_id = rawline_short[name_start:]

                name_start = rawline.find("dim=") + 5
                name_stop = rawline.find("unit") - 2
                dim = rawline[name_start:name_stop]
                dim = int(dim)
                if dim == 1:
                    chan_ids.append(chan_id)
                else:
                    for i in range(dim):
                        chan_ids.append(chan_id + '_%d' % (i + 1))
            print('chan_ids:')
            print(len(chan_ids))
            #
            # Setup time array using last outfile
            time = []
            f = open(outfiles[0], 'r')
            lines = f.readlines()
            f.close()
            for l_idx, rawline in enumerate(lines[1:]):
                line = re.split(r'\s{1,}', rawline)
                time.append(float(line[1]))
            time = np.array(time)
            #
            # Setup empty data array using known number of channels and time steps
            data = np.zeros((len(chan_ids), len(time)))
            #
            # Populate data array using all outfiles
            for f_idx, outfile in enumerate(outfiles):
                f = open(outfile, 'r')
                lines = f.readlines()
                f.close()
                for n, rawline in enumerate(lines[1:]):
                    line = re.split(r'\s{1,}', rawline)
                    for m, value in enumerate(line[2:-1]):
                        data[(f_idx * 10) + m][n] = value
            for n, chan_id in enumerate(chan_ids):
                print(n + 1, chan_id)

            # Add data to arrays in class
            self.timearrays.append(time)
            self.dataarrays.append(data)
            self.scales.append(np.ones(len(data) + 1))
            self.offsets.append(np.zeros(len(data) + 1))
            self.channel_names = chan_ids

        #Read Excel PSSE standard file
        if filename[-5:].lower() in ('*.xlsx'):
            print('Plotting file: ' + str(filename))
            import os
            from os.path import join, dirname, abspath, isfile
            from collections import Counter
            import xlrd
            from xlrd.sheet import ctype_text
            cwd = os.getcwd()
            import psse34
            import dyntools

            def read_excel_tools(filename, sheet_index):
                xl_workbook = xlrd.open_workbook(filename)
                xl_sheet = xl_workbook.sheet_by_index(sheet_index)
                return xl_sheet

            def get_data(xl_sheet):
                chanid = {}
                chandata = {}
                row = xl_sheet.row(2)
                short_title = str(xl_sheet.row(1)[0].value) + '\n' + str(
                    xl_sheet.row(2)[0].value)

                row_chan = xl_sheet.row(3)
                row_title = xl_sheet.row(4)
                for chan_idx in range(len(row_chan)):
                    chan_idx_data = []
                    for row_idx in range(5, xl_sheet.nrows):
                        cell_obj = xl_sheet.cell(row_idx, chan_idx)
                        chan_idx_data.append(cell_obj.value)
                    if chan_idx == 0:
                        chanid['time'] = str(row_title[chan_idx].value)
                        chandata['time'] = chan_idx_data
                    else:
                        chanid[int(row_chan[chan_idx].value)] = str(
                            row_title[chan_idx].value)
                        chandata[int(row_chan[chan_idx].value)] = chan_idx_data
                return short_title, chanid, chandata

            xl_sheet = read_excel_tools(filename, sheet_index=0)
            short_title, chanid, chandata = get_data(xl_sheet)
            time = np.array(chandata['time'])
            data = np.zeros((len(chandata) - 1, len(time)))
            chan_ids = []
            for key in chandata.keys()[:-1]:
                print(key, chanid[key])
                data[key - 1] = chandata[key]
                chan_ids.append(chanid[key])
            print('\n')
            self.timearrays.append(time)
            self.dataarrays.append(data)
            self.scales.append(np.ones(len(data) + 1))
            self.offsets.append(np.zeros(len(data) + 1))
            self.channel_names = chan_ids
def test2_subplots_one_trace(outpath=None, show=True):

    import dyntools

    outfile1, outfile2, outfile3, prgfile = get_demotest_file_names(outpath)

    chnfobj = dyntools.CHNF(outfile1, outfile2)

    chnfobj.set_plot_page_options(size='letter', orientation='portrait')
    chnfobj.set_plot_markers('square', 'triangle_up', 'thin_diamond', 'plus',
                             'x', 'circle', 'star', 'hexagon1')
    chnfobj.set_plot_line_styles('solid', 'dashed', 'dashdot', 'dotted')
    chnfobj.set_plot_line_colors('blue', 'red', 'black', 'green', 'cyan',
                                 'magenta', 'pink', 'purple')

    optnfmt = {
        'rows': 3,
        'columns': 2,
        'dpi': 300,
        'showttl': True,
        'showoutfnam': True,
        'showlogo': True,
        'legendtype': 1,
        'addmarker': True
    }

    optnchn1 = {
        1: {
            'chns': 1,
            'title': 'Ch#1,bus154_fault'
        },
        2: {
            'chns': 6,
            'title': 'Ch#6,bus154_fault'
        },
        3: {
            'chns': 11,
            'title': 'Ch#11,bus154_fault'
        },
        4: {
            'chns': 16,
            'title': 'Ch#16,bus154_fault'
        },
        5: {
            'chns': 26,
            'title': 'Ch#26,bus154_fault'
        },
        6: {
            'chns': 40,
            'title': 'Ch#40,bus154_fault'
        },
    }
    pn, x = os.path.splitext(outfile1)
    pltfile1 = pn + '.png'

    optnchn2 = {
        1: {
            'chns': {
                outfile2: 1
            },
            'title': 'Channel 1 from bus3018_gentrip'
        },
        2: {
            'chns': {
                outfile2: 6
            },
            'title': 'Channel 6 from bus3018_gentrip'
        },
        3: {
            'chns': {
                outfile2: 11
            }
        },
        4: {
            'chns': {
                outfile2: 16
            }
        },
        5: {
            'chns': {
                outfile2: 26
            }
        },
        6: {
            'chns': {
                outfile2: 40
            }
        },
    }
    pn, x = os.path.splitext(outfile2)
    pltfile2 = pn + '.png'

    figfiles1 = chnfobj.xyplots(optnchn1, optnfmt, pltfile1)

    chnfobj.set_plot_legend_options(loc='lower center',
                                    borderpad=0.2,
                                    labelspacing=0.5,
                                    handlelength=1.5,
                                    handletextpad=0.5,
                                    fontsize=8,
                                    frame=False)

    optnfmt = {
        'rows': 3,
        'columns': 1,
        'dpi': 300,
        'showttl': False,
        'showoutfnam': True,
        'showlogo': False,
        'legendtype': 2,
        'addmarker': False
    }

    figfiles2 = chnfobj.xyplots(optnchn2, optnfmt, pltfile2)

    if figfiles1 or figfiles2:
        print 'Plot fils saved:'
        if figfiles1: print '   ', figfiles1[0]
        if figfiles2: print '   ', figfiles2[0]

    if show:
        chnfobj.plots_show()
    else:
        chnfobj.plots_close()
# # psspy.run(0, 15, 10000,  20, 0)
# # # psspy.load_data_3(1000,r"""1""",[_i,_i,_i,_i,_i],[ 950,_f,_f,_f,_f,_f])
# psspy.run(0, 25, 500,  1, 1)
# psspy.load_data_3(1000,r"""1""",[_i,_i,_i,_i,_i],[ 800,_f,_f,_f,_f,_f])
# psspy.run(0, 60, 10000,  20, 0)

# start draw curves
# new folder if necessary
GraphPath = FigurePath + ClauseName + TestName + '/'
if not os.path.exists(GraphPath):
    os.makedirs(GraphPath)

# read data curves
# chnfobj = dyntools.CHNF('F:/PosDoc Projects/11_Industrial Projects/HuaWei/WISF/D_SimplifiedSystem/test_5.outx')
chnfobj = dyntools.CHNF(
    'F:/PosDoc Projects/11_Industrial Projects/HuaWei/WISF/D_SimplifiedSystem/FC_PPC_3.outx'
)
short_title, chanid, chandata = chnfobj.get_data()
freq_data = numpy.array(chandata[8])

# set figure preference
mpl.rcParams['grid.color'] = 'k'
mpl.rcParams['grid.linestyle'] = ':'
mpl.rcParams['grid.linewidth'] = 0.5
mpl.rcParams['axes.grid'] = 'on'

mpl.rcParams['font.size'] = 24

mpl.rcParams['lines.linewidth'] = 3.0

mpl.rcParams['legend.fancybox'] = True
def test3_subplots_mult_trace(outpath=None, show=True):

    import dyntools

    outfile1, outfile2, outfile3, prgfile = get_demotest_file_names(outpath)

    chnfobj = dyntools.CHNF(outfile1, outfile2, outfile3)

    chnfobj.set_plot_page_options(size='letter', orientation='portrait')
    chnfobj.set_plot_markers('square', 'triangle_up', 'thin_diamond', 'plus',
                             'x', 'circle', 'star', 'hexagon1')
    chnfobj.set_plot_line_styles('solid', 'dashed', 'dashdot', 'dotted')
    chnfobj.set_plot_line_colors('blue', 'red', 'black', 'green', 'cyan',
                                 'magenta', 'pink', 'purple')

    optnfmt = {
        'rows': 2,
        'columns': 2,
        'dpi': 300,
        'showttl': False,
        'showoutfnam': True,
        'showlogo': False,
        'legendtype': 2,
        'addmarker': True
    }

    optnchn1 = {
        1: {
            'chns': [1]
        },
        2: {
            'chns': [2]
        },
        3: {
            'chns': [3]
        },
        4: {
            'chns': [4]
        },
        5: {
            'chns': [5]
        }
    }
    pn, x = os.path.splitext(outfile1)
    pltfile1 = pn + '.png'

    optnchn2 = {
        1: {
            'chns': {
                outfile2: 1
            }
        },
        2: {
            'chns': {
                'v82_test1_bus_fault.out': 3
            }
        },
        3: {
            'chns': 4
        },
        4: {
            'chns': [5]
        }
    }
    pn, x = os.path.splitext(outfile2)
    pltfile2 = pn + '.pdf'

    optnchn3 = {
        1: {
            'chns': {
                'v80_test1_bus_fault.out': 1
            }
        },
        2: {
            'chns': {
                'v80_test2_complex_wind.out': [1, 5]
            }
        },
        3: {
            'chns': {
                'v82_test1_bus_fault.out': 3
            }
        },
        5: {
            'chns': [4, 5]
        },
    }
    pn, x = os.path.splitext(outfile3)
    pltfile3 = pn + '.eps'

    figfiles1 = chnfobj.xyplots(optnchn1, optnfmt, pltfile1)
    figfiles2 = chnfobj.xyplots(optnchn2, optnfmt, pltfile2)
    figfiles3 = chnfobj.xyplots(optnchn3, optnfmt, pltfile3)

    figfiles = figfiles1[:]
    figfiles.extend(figfiles2)
    figfiles.extend(figfiles3)
    if figfiles:
        print 'Plot fils saved:'
        for f in figfiles:
            print '    ', f

    if show:
        chnfobj.plots_show()
    else:
        chnfobj.plots_close()
示例#18
0
 def __init__(self, params):
     '''
     Constructor
     '''
     self._chnfobj = dyntools.CHNF([params[0]])
def test5_plots2word(outpath=None, show=True):

    import dyntools

    outfile1, outfile2, outfile3, prgfile = get_demotest_file_names(outpath)

    chnfobj = dyntools.CHNF(outfile1, outfile2, outfile3)

    p, nx = os.path.split(outfile1)
    docfile = os.path.join(p, 'savnw_response')
    overwrite = True
    caption = True
    align = 'center'
    captionpos = 'below'
    height = 0.0
    width = 0.0
    rotate = 0.0

    optnfmt = {'rows': 3, 'columns': 1, 'dpi': 300, 'showttl': True}

    optnchn = {
        1: {
            'chns': {
                outfile1: 1,
                outfile2: 1,
                outfile3: 1
            }
        },
        2: {
            'chns': {
                outfile1: 7,
                outfile2: 7,
                outfile3: 7
            }
        },
        3: {
            'chns': {
                outfile1: 17,
                outfile2: 17,
                outfile3: 17
            }
        },
        4: {
            'chns': [1, 2, 3, 4, 5]
        },
        5: {
            'chns': {
                outfile2: [1, 2, 3, 4, 5]
            }
        },
        6: {
            'chns': {
                outfile3: [1, 2, 3, 4, 5]
            }
        },
    }
    ierr, docfile = chnfobj.xyplots2doc(optnchn, optnfmt, docfile, show,
                                        overwrite, caption, align, captionpos,
                                        height, width, rotate)

    if not ierr:
        print 'Plots saved to file:'
        print '    ', docfile
示例#20
0
def plot(out_folder,
         out_file,
         out_chans,
         filename,
         plot_title=["NA"] * 12,
         plot_x_label=["Time (s)"] * 12,
         plot_y_label=[""] * 12,
         top_title="",
         xlims="",
         ylims="",
         angle=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]):
    '''if isinstance(out_file, basestring):
        out_file = [out_file]
    elif "_pre" in out_file[1].lower():
        out_file[0], out_file[1] = out_file[1], out_file[0]'''

    if out_chans is None:
        out_chans = []

    if not (ylims == "" or isinstance(ylims[0], list)):
        ylims = [ylims] * 12

    if not (xlims == "" or isinstance(xlims[0], list)):
        xlims = [xlims] * 12

    # for x in xrange(len(out_chans)):
    #     if not isinstance(out_chans, list):
    #         out_chans[x] = [out_chans[x]]

    _ch_id, _ch_data, _sh_ttl, time = [], [], [], []
    for file in xrange(len(out_file)):
        try:
            chnfobj = dyntools.CHNF(os.path.join(out_folder, out_file[file]))
            sh_ttl, ch_id, ch_data = chnfobj.get_data()
            _ch_data.append(ch_data)
            _ch_id.append(ch_id)
            _sh_ttl.append(sh_ttl)

            time.append(ch_data['time'])
        except OverflowError:
            error_plot(
                out_folder, out_file[file],
                "The OUT file seems to have infinite data in it and cannot be read.\nThis case is considered a failed case."
            )
            return

    # loop through each of the channels required and extract the data
    data = []
    angle_data = []
    for y in xrange(len(out_file)):
        j = 0
        data.append([])
        for chan in out_chans[y]:
            if isinstance(chan, list):
                data[y].append([])
                for i in xrange(len(chan)):
                    if type(chan[i]) is str:
                        for key in _ch_id[y]:
                            if chan[i] == _ch_id[y][key]:
                                chan[i] = key
                                break
                    data[y][j].append(_ch_data[y][chan[i]])
            else:
                print chan
                data[y].append([])
                if type(chan) is str:
                    for key in _ch_id[y]:
                        if chan == _ch_id[y][key]:
                            chan = key
                            break
                print chan
                data[y][j].append(_ch_data[y][chan])

            j += 1
        for angle_chan in angle:
            angle_data.append([])
            try:
                angle_data[y].append(_ch_data[y][angle_chan])
            except Exception:
                angle_data[y].append([None])
        print 'Outfile channels %d: %s' % (y, _ch_id[y])

    if not isinstance(plot_title, list):
        plot_title = [plot_title]
    if not isinstance(plot_x_label, list):
        plot_x_label = [plot_x_label]
    if not isinstance(plot_y_label, list):
        plot_y_label = [plot_y_label]

    # set up inital values for the plot
    nRows, nCols = find_row_col(len(out_chans[y]))
    fig = plt.figure(figsize=[(2 + 6 * nCols), (2 + 4 * nRows)])
    fig.suptitle(top_title, fontsize=20)

    # pre-initialize
    ax = []
    time_diff = 0
    num = len(data[0])

    for sub in xrange(num):

        # If no label given, default to blank labels to prevent error being thrown
        if sub > len(plot_title) - 1:
            plot_title.append("")
        if sub > len(plot_x_label) - 1:
            plot_x_label.append("Time (s)")
        if sub > len(plot_y_label) - 1:
            plot_y_label.append("")

        # The following code is plotting and plot options

        # Set it up so that all plots share the same x axis, this means that you can zoom and navigate the plot...
        #       and all the subplots will move together
        # if xlims == "" or isinstance(xlims[0], int) or isinstance(xlims[0], float):
        #     if sub == 0:
        #         ax.append(plt.subplot(nRows, nCols, sub + 1))
        #     else:
        #         ax.append(plt.subplot(nRows, nCols, sub + 1, sharex=ax[0]))
        # else:

        ax.append(plt.subplot(nRows, nCols, sub + 1))

        # Titles and labels
        if not isinstance(out_chans[0][sub], list):
            if plot_title[sub] == "NA":
                plt.title(_ch_id[0][out_chans[0][sub]], fontsize=13)
            else:
                plt.title(plot_title[sub], fontsize=13)
        elif plot_title[sub] == "NA":
            plt.title("", fontsize=13)
        else:
            plt.title(plot_title[sub], fontsize=13)
        plt.xlabel(plot_x_label[sub])
        plt.ylabel(plot_y_label[sub], labelpad=20)
        data_lims = []
        # If out data to plot, plot it
        for y in xrange(len(out_file)):
            if filename[0] in out_file[y]:
                prepost = filename[0]
            else:
                prepost = filename[1]
            if isinstance(out_chans[0][sub], list):
                for x in xrange(len(out_chans[0][sub])):
                    if type(out_chans[0][sub][x]) is str:
                        for key in _ch_id[y]:
                            if out_chans[0][sub][x] == _ch_id[y][key]:
                                out_chans[0][sub][x] = key
                                break
                    if data[y][sub][x] != -1:
                        t_start = 10
                        t_stop = 15
                        tDataArrayIndex = 0
                        simt = time[y][tDataArrayIndex]
                        while simt < t_start:
                            simt = time[y][tDataArrayIndex]
                            tDataArrayIndex += 1
                        tDataArrayIndex_start = tDataArrayIndex
                        while simt < t_stop:
                            simt = time[y][tDataArrayIndex]
                            tDataArrayIndex += 1
                        tDataArrayIndex_stop = tDataArrayIndex
                        data_110 = []
                        data_90 = []
                        time_bounce = []
                        y_dev = 0.1 * (max(data[y][sub][x]) -
                                       min(data[y][sub][x]))
                        y_dev = 0.1 * (
                            (data[y][sub][x][tDataArrayIndex_stop]) -
                            (data[y][sub][x][tDataArrayIndex_start]))
                        for index in range(len(time[y])):
                            data_110.append(data[y][sub][x][index] + y_dev)
                            data_90.append(data[y][sub][x][index] - y_dev)
                            time_bounce.append(time[y][index])

                        # CUSTOM
                        if angle[sub] != 0:
                            try:
                                for d in xrange(len(data[y][sub][x])):
                                    data[y][sub][x][d] -= angle_data[y][sub][d]
                            except Exception:
                                print(
                                    "ERROR -=-=-=-==-=-=-=-=-=-=------------=-=-==-=-=--==-=-=-=-=-=-=-=-=-"
                                )
                                # /CUSTOM
                        if prepost == filename[0]:
                            plt.plot(time[y],
                                     data[y][sub][x],
                                     label=_ch_id[y][out_chans[0][sub][x]] +
                                     prepost)
                            # plt.plot(time_bounce,data_90,':',label="90% Boundary",color='gray')
                            # plt.plot(time_bounce,data_110,':',label="110% Boundary",color='gray')
                        else:
                            plt.plot(time[y],
                                     data[y][sub][x],
                                     linestyle='dashed',
                                     dashes=(4, 3),
                                     label=_ch_id[y][out_chans[1][sub][x]] +
                                     prepost)
                        # plt.plot(time_bounce,data_90,':',label="90% Boundary",color='gray')
                        # plt.plot(time_bounce,data_110,':',label="110% Boundary",color='gray')
                        data_lims += data[y][sub][x]

            else:
                if type(out_chans[0][sub]) is str:
                    for key in _ch_id[y]:
                        if out_chans[0][sub] == _ch_id[y][key]:
                            out_chans[0][sub] = key
                            break
                if data[y][sub][0] != -1:
                    t_start = 5
                    t_stop = 30

                    tDataArrayIndex = 0
                    simt = time[y][tDataArrayIndex]
                    while simt < t_start:
                        simt = time[y][tDataArrayIndex]
                        tDataArrayIndex += 1
                    tDataArrayIndex_start = tDataArrayIndex
                    while simt < t_stop:
                        simt = time[y][tDataArrayIndex]
                        tDataArrayIndex += 1
                    tDataArrayIndex_stop = tDataArrayIndex
                    data_110 = []
                    data_90 = []
                    time_bounce = []
                    y_dev = 0.1 * (max(data[y][sub][x]) - min(data[y][sub][x]))
                    y_dev = 0.1 * ((data[y][sub][x][tDataArrayIndex_stop]) -
                                   (data[y][sub][x][tDataArrayIndex_start]))
                    for index in range(len(time[y])):
                        data_110.append(data[y][sub][x][index] + y_dev)
                        data_90.append(data[y][sub][x][index] - y_dev)
                        time_bounce.append(time[y][index])

                    if angle[sub] != 0:
                        try:
                            for d in xrange(len(data[y][sub][0])):
                                data[y][sub][0][d] -= angle_data[y][sub][d]
                        except Exception:
                            print(
                                "ERROR -=-=-=-==-=-=-=-=-=-=------------=-=-==-=-=--==-=-=-=-=-=-=-=-=-"
                            )
                    # plt.plot(time, data[y][sub][0], label=_ch_id[y][out_chans[sub]] + prepost)
                    if prepost == filename[0]:
                        plt.plot(time[y],
                                 data[y][sub][x],
                                 label=_ch_id[y][out_chans[0][sub][x]] +
                                 prepost)
                        # plt.plot(time_bounce,data_90,':',label="90% Boundary",color='gray')
                        # plt.plot(time_bounce,data_110,':',label="110% Boundary",color='gray')
                    else:
                        plt.plot(time[y],
                                 data[y][sub][x],
                                 linestyle='dashed',
                                 dashes=(4, 3),
                                 label=_ch_id[y][out_chans[1][sub][x]] +
                                 prepost)
                        # plt.plot(time_bounce,data_90,':',label="90% Boundary",color='gray')
                        # plt.plot(time_bounce,data_110,':',label="110% Boundary",color='gray')
                    data_lims += data[y][sub][x]

        plt.grid(True)  # turn on grid

        # Axis settings
        ax[sub].xaxis.set_minor_locator(ticker.AutoMinorLocator(
            2))  # automatically put a gridline in between tickers
        ax[sub].grid(b=True, which='minor',
                     linestyle=':')  # gridline style is dots
        ax[sub].tick_params(
            axis='x', which='minor',
            bottom='on')  # display small ticks at bottom midway
        ax[sub].get_xaxis().get_major_formatter().set_useOffset(
            False)  # turn off the annoying offset values
        ax[sub].get_yaxis().get_major_formatter().set_useOffset(False)
        plt.tight_layout()

        # Make sure that there is 15% padding on top and bottom
        max_data = max(data_lims)
        min_data = min(data_lims)
        data_range = max_data - min_data
        if ylims == "" or len(ylims) < sub + 1 or ylims[sub] == "":
            ylimit = ax[sub].get_ylim()
            new_y = restrict_y_axis(ylimit, data_range, max_data, min_data)
            ax[sub].set_ylim(new_y)
        else:
            ax[sub].set_ylim(ylims[sub])

        if xlims == "" or len(xlims) < sub + 1 or xlims[sub] == "":
            xlimit = [0, (max(time[0]))]  #time = [[time]]
            #xlimit = ax[sub].get_xlim()
            ax[sub].set_xlim(xlimit)
        else:
            ax[sub].set_xlim(xlims[sub])

        # If there is a top title, make sure there is room for it
        top = 0.9
        if top_title == "":
            top = 0.95
        plt.subplots_adjust(right=0.9,
                            hspace=0.3,
                            wspace=0.3,
                            top=top,
                            left=0.1,
                            bottom=0.12)
        legend = plt.legend(bbox_to_anchor=(0., -0.28, 1., .105),
                            loc=3,
                            ncol=2,
                            mode="expand",
                            prop={'size': 6},
                            borderaxespad=0.)
        legend.get_title().set_fontsize('6')  # legend 'Title' fontsize
        plt.setp(plt.gca().get_legend().get_texts(),
                 fontsize='10')  # legend 'list' fontsize
        plt.subplots_adjust(hspace=0.5)
        # plt.legend(bbox_to_anchor=(0., -0.55, 1., .105), loc=3,
        #        ncol=4, mode="expand", borderaxespad=0.)

    # Plot the legend on the bottom, underneath everything
    # plt.legend(bbox_to_anchor=(0., -0.55, 1., .105), loc=3,
    #            ncol=4, mode="expand", borderaxespad=0.)

    # Save file

    #file_str = os.path.join(out_folder, out_file[0]).replace('%s.out'%(filename[0]), '.pdf')
    file_str = os.path.join(out_folder,
                            out_file[0]).replace('.out',
                                                 '_VS' + filename[1] + '.pdf')
    #file_str = file_str.split(".png", 1)
    #file_str = file_str[0] + ".png"
    plot_name = os.path.basename(file_str[0:-4])
    plt.suptitle(plot_name, fontsize=12, fontweight='bold')
    plt.savefig(file_str, dpi=100)
    print str(file_str + "Saved")
    plt.close()
示例#21
0
def plot(out_folder,
         out_file,
         out_chans,
         outchans_adj,
         plot_title=["NA"] * 12,
         plot_x_label=["Time (s)"] * 12,
         plot_y_label=[""] * 12,
         top_title="",
         xlims="",
         ylims="",
         angle=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         xoffset="",
         step_boundary=""):
    '''if isinstance(out_file, basestring):
        out_file = [out_file]
    elif "_PSSE" in out_file[1].lower():
        out_file[0], out_file[1] = out_file[1], out_file[0]'''

    if out_chans is None:
        out_chans = []
    if outchans_adj is None:
        outchans_adj = []

    if not (ylims == "" or isinstance(ylims[0], list)):
        ylims = [ylims] * 12

    if not (xlims == "" or isinstance(xlims[0], list)):
        xlims = [xlims] * 12

    # for x in xrange(len(out_chans)):
    #     if not isinstance(out_chans, list):
    #         out_chans[x] = [out_chans[x]]

    _ch_id, _ch_data, _sh_tt, time = [], [], [], []
    try:
        chnfobj = dyntools.CHNF(out_file[0])
        sh_tt_0, ch_id_0, ch_data_0 = chnfobj.get_data()
        _ch_data.append(ch_data_0)
        _ch_id.append(ch_id_0)
        _sh_tt.append(sh_tt_0)
        #print(len(ch_data_0))
        for i in range(len(ch_data_0['time'])):
            ch_data_0['time'][i] += xoffset
        time.append(ch_data_0['time'])
    except OverflowError:
        error_plot(
            out_folder, out_file[0],
            "The OUT file seems to have infinite data in it and cannot be read.\nThis case is considered a failed case."
        )
        return
    print('PSSE channels: ' + str(ch_id_0))
    #read PSCAD
    filename = out_file[1]
    # PSCAD output files
    import glob, re
    import os
    import numpy as np
    #
    outfiles = []
    for pscadfile in glob.glob(filename[0:-4] + "_*.OUT"):
        outfiles.append(pscadfile)
    #Find the channel ids name
    chan_ids = []
    f = open(filename, 'r')
    lines = f.readlines()
    f.close()
    for idx, rawline in enumerate(lines):
        line = re.split(r'\s{1,}', rawline)
        chan_ids.append(line[2][6:-1])

    # change format to similar to PSSE
    ch_id_1 = {}
    for i in range(len(chan_ids)):
        ch_id_1[i + 1] = chan_ids[i]
        ch_id_1['time'] = 'Time(s)'

    time1 = []
    f = open(outfiles[-1], 'r')
    lines = f.readlines()
    f.close()
    for l_idx, rawline in enumerate(lines[1:]):
        line = re.split(r'\s{1,}', rawline)
        time1.append(float(line[1]))

    #
    # Setup empty data array using known number of channels and time steps
    data1 = np.zeros((len(ch_id_1), len(time1)))
    #
    # Populate data array using all outfiles
    for f_idx, pscadout in enumerate(outfiles):
        f = open(pscadout, 'r')
        lines = f.readlines()
        f.close()
        for n, rawline in enumerate(lines[1:]):
            line = re.split(r'\s{1,}', rawline)
            for m, value in enumerate(line[2:-1]):
                data1[(f_idx * 10) + 1 + m][n] = value
            data1[0][n] = line[1]
    ch_data_1 = {}
    for i in range(len(data1) - 1):
        ch_data_1[i + 1] = data1[i + 1].tolist()
    ch_data_1['time'] = data1[0].tolist()
    sh_ttl = sh_tt_0
    # Setup time array using data
    print('PSCAD channels: ' + str(ch_id_1))
    _ch_data.append(ch_data_1)
    _ch_id.append(ch_id_1)
    # _sh_tt.append(sh_tt_0)
    time.append(data1[0].tolist())

    # loop through each of the channels required and extract the data
    data = []
    angle_data = []
    for y in xrange(
            len(out_file)):  #len(outfile) = 2, psse and pscad inf file name
        j = 0
        data.append([])
        for k, chan in enumerate(out_chans[y]):
            if isinstance(chan, list):
                data[y].append([])
                for i in xrange(len(chan)):
                    scale = outchans_adj[y][k][i][0]
                    offset = outchans_adj[y][k][i][1]
                    if type(chan[i]) is str:
                        for key in _ch_id[y]:
                            if chan[i] == _ch_id[y][key]:
                                chan[i] = key
                                break
                    add = (np.array(_ch_data[y][chan[i]]) * scale +
                           offset).tolist()
                    # data[y][j].append(_ch_data[y][chan[i]])
                    data[y][j].append(add)
            else:
                data[y].append([])
                data[y][j].append(_ch_data[y][chan])

            j += 1
        for angle_chan in angle:
            angle_data.append([])
            try:
                angle_data[y].append(_ch_data[y][angle_chan])
            except Exception:
                angle_data[y].append([None])

    if not isinstance(plot_title, list):
        plot_title = [plot_title]
    if not isinstance(plot_x_label, list):
        plot_x_label = [plot_x_label]
    if not isinstance(plot_y_label, list):
        plot_y_label = [plot_y_label]

    # # set up inital values for the plot
    # nRows, nCols = find_row_col(len(out_chans[y]))
    # fig = plt.figure(figsize=[(2 + 10 * nCols), (2 + 4 * nRows)])

    subplots = len(out_chans[y])
    if subplots == 1:
        subplot_index = [111]
        nRows = 1
        nCols = 1
        # plt.figure(figsize = (29.7/ 2.54, 21.0/ 2.54))
        plt.figure(figsize=[(2 + 18 * nCols), (2 + 10 * nRows)])
        # plt.subplots_adjust(bottom = 0.05, top = 0.91, right = 0.98, left = 0.1, hspace = 0.25)
    if subplots == 2:
        subplot_index = [211, 212]
        nRows = 2
        nCols = 1
        # plt.figure(figsize = (29.7/ 2.54, 21.0/ 2.54))
        plt.figure(figsize=[(2 + 18 * nCols), (2 + 5 * nRows)])
        # plt.subplots_adjust(bottom = 0.05, top = 0.91, right = 0.98, left = 0.1, hspace = 0.28)
    if subplots == 3:
        subplot_index = [311, 312, 313]
        nRows = 3
        nCols = 1
        # plt.figure(figsize = (29.7/ 2.54, 21.0/ 2.54))
        plt.figure(figsize=[(2 + 24 * nCols), (2 + 5 * nRows)])
        # plt.subplots_adjust(bottom = 0.05, top = 0.91, right = 0.98,  left = 0.1, hspace = 0.32, wspace = 0.2)
    if subplots == 4:
        nRows = 2
        nCols = 2
        subplot_index = [221, 222, 223, 224]
        # plt.figure(figsize = (29.7/ 2.54, 21.0/ 2.54))
        plt.figure(figsize=[(2 + 12 * nCols), (2 + 6.5 * nRows)])
        # plt.subplots_adjust(bottom = 0.05, top = 0.91, right = 0.98, left = 0.1, hspace = 0.32, wspace = 0.2)
    if subplots == 5:
        subplot_index = [311, 323, 324, 325, 326]
        nRows = 3
        nCols = 2
        # plt.figure(figsize = (29.7/ 2.54, 21.0/ 2.54))
        plt.figure(figsize=[(2 + 12 * nCols), (2 + 5 * nRows)])
        # plt.subplots_adjust(bottom = 0.05, top = 0.91, right = 0.98, left = 0.1, hspace = 0.35, wspace = 0.2)
    if subplots == 6:
        nRows = 3
        nCols = 2
        subplot_index = [321, 322, 323, 324, 325, 326]
        # plt.figure(figsize = (29.7/ 2.54, 21.0/ 2.54))
        plt.figure(figsize=[(2 + 12 * nCols), (2 + 5 * nRows)])

    plt.suptitle(plot_title, fontsize=22, fontweight='bold')
    plt.rc('xtick', labelsize=18)
    plt.rc('ytick', labelsize=18)

    # pre-initialize
    ax = []
    time_diff = 0
    num = len(data[0])
    for sub in xrange(num):
        # If no label given, default to blank labels to prevent error being thrown
        if sub > len(plot_title) - 1:
            plot_title.append("")
        if sub > len(plot_x_label) - 1:
            plot_x_label.append("Time (s)")
        if sub > len(plot_y_label) - 1:
            plot_y_label.append("")

        # The following code is plotting and plot options

        # Set it up so that all plots share the same x axis, this means that you can zoom and navigate the plot...
        #       and all the subplots will move together
        if xlims == "" or isinstance(xlims[0], int) or isinstance(
                xlims[0], float):
            if sub == 0:
                ax.append(plt.subplot(nRows, nCols, sub + 1))
            else:
                ax.append(plt.subplot(nRows, nCols, sub + 1, sharex=ax[0]))
        else:
            ax.append(plt.subplot(nRows, nCols, sub + 1))

        # Titles and labels
        if not isinstance(out_chans[0][sub], list):
            if plot_title[sub] == "NA":
                plt.title(_ch_id[0][out_chans[0][sub]], fontsize=18)
            else:
                plt.title(plot_title[sub], fontsize=18)
        elif plot_title[sub] == "NA":
            plt.title("", fontsize=18)
        else:
            plt.title(plot_title[sub], fontsize=18)
        plt.xlabel(plot_x_label[sub], fontsize=18)
        plt.ylabel(plot_y_label[sub], fontsize=18, labelpad=20)

        plt.suptitle(plot_title, fontsize=22, fontweight='bold')
        plt.rc('xtick', labelsize=18)
        plt.rc('ytick', labelsize=18)
        plt.grid(1)

        data_lims = []
        # If out data to plot, plot it
        ymin = data[0][sub][0][0]
        ymax = data[0][sub][0][0]
        for y in xrange(len(out_file)):
            if "_PSSE" in out_file[y]:
                psse_pscad = " Psse"
            else:
                psse_pscad = " Pscad"
            if isinstance(out_chans[0][sub], list):
                for x in xrange(len(out_chans[0][sub])):
                    if type(out_chans[0][sub][x]) is str:
                        for key in _ch_id[y]:
                            if out_chans[0][sub][x] == _ch_id[y][key]:
                                out_chans[0][sub][x] = key
                                break
                    if data[y][sub][x] != -1:
                        '''Ts = 0.02 #from the start to the finish of the slope, 20 milliseconds                        
                        simt = 0
                        tDataArrayIndex_start = 0
                        tDataArrayIndex_stop = 0
                        data_110 = []
                        data_90 = []
                        time_bounce = []
                        while tDataArrayIndex_stop < len(time[y]):
                            simt = time[y][tDataArrayIndex_stop]-time[y][tDataArrayIndex_start]
                            while simt < Ts:
                                simt = time[y][tDataArrayIndex_stop]-time[y][tDataArrayIndex_start]
                                tDataArrayIndex_stop += 1
                                
                            #time[y][tDataArrayIndex_start]
                            #time[y][tDataArrayIndex_stop]
                            #tDataArrayIndex_start
                            #tDataArrayIndex_stop
                            #data[y][sub][x][tDataArrayIndex_start]
                            #data[y][sub][x][tDataArrayIndex_stop]
                            data_110.append(data[y][sub][x][tDataArrayIndex_start] + 0.1*(data[y][sub][x][tDataArrayIndex_stop]-data[y][sub][x][tDataArrayIndex_start]))
                            data_90.append(data[y][sub][x][tDataArrayIndex_start] - 0.1*(data[y][sub][x][tDataArrayIndex_stop]-data[y][sub][x][tDataArrayIndex_start]))
                            time_bounce.append(time[y][tDataArrayIndex_start])
                            tDataArrayIndex_start += 1
                            tDataArrayIndex_stop += 1'''

                        if xlims == "" or len(
                                xlims) < sub + 1 or xlims[sub] == "":
                            xlimit = [
                                min(min(time[0]), min(time[1])),
                                max(max(time[0]), max(time[1]))
                            ]
                        else:
                            xlimit = xlims[sub]

                        t_start = step_boundary[0]
                        t_stop = step_boundary[1]

                        t_start = xlimit[0]
                        t_stop = xlimit[1]

                        tDataArrayIndex = 0
                        simt = time[y][tDataArrayIndex]
                        while simt < t_start:
                            simt = time[y][tDataArrayIndex]
                            tDataArrayIndex += 1
                        tDataArrayIndex_start = tDataArrayIndex
                        while simt < t_stop:
                            simt = time[y][tDataArrayIndex]
                            if data[y][sub][x][tDataArrayIndex] < ymin:
                                ymin = data[y][sub][x][tDataArrayIndex]
                            elif data[y][sub][x][tDataArrayIndex] > ymax:
                                ymax = data[y][sub][x][tDataArrayIndex]
                            tDataArrayIndex += 1
                        tDataArrayIndex_stop = tDataArrayIndex

                        data_110 = []
                        data_90 = []
                        time_bounce = []
                        # y_dev = 0.1* (max(data[y][sub][x])-min(data[y][sub][x]))
                        # y_dev = 0.1* ((data[y][sub][x][tDataArrayIndex_stop])-(data[y][sub][x][tDataArrayIndex_start]))
                        y_dev = 0.1 * (ymax - ymin)
                        for index in range(len(time[y])):
                            data_110.append(data[y][sub][x][index] + y_dev)
                            data_90.append(data[y][sub][x][index] - y_dev)
                            time_bounce.append(time[y][index])

                        # CUSTOM
                        if angle[sub] != 0:
                            try:
                                for d in xrange(len(data[y][sub][x])):
                                    data[y][sub][x][d] -= angle_data[y][sub][d]
                            except Exception:
                                print(
                                    "ERROR -=-=-=-==-=-=-=-=-=-=------------=-=-==-=-=--==-=-=-=-=-=-=-=-=-"
                                )
                                # /CUSTOM
                        if psse_pscad == " Psse":
                            plt.plot(time[y],
                                     data[y][sub][x],
                                     label=_ch_id[y][out_chans[0][sub][x]] +
                                     psse_pscad,
                                     linewidth=3.5)
                            plt.plot(time_bounce,
                                     data_90,
                                     '--',
                                     label="90% Boundary",
                                     color='black',
                                     linewidth=1.5)
                            plt.plot(time_bounce,
                                     data_110,
                                     '--',
                                     label="110% Boundary",
                                     color='black',
                                     linewidth=1.5)
                        else:
                            plt.plot(time[y],
                                     data[y][sub][x],
                                     linestyle='dashed',
                                     dashes=(4, 3),
                                     label=_ch_id[y][out_chans[1][sub][x]] +
                                     psse_pscad,
                                     linewidth=3.5)
                            # plt.plot(time[y], data[y][sub][x],label=_ch_id[y][out_chans[1][sub][x]] + psse_pscad,linewidth = 3.5)
                            # plt.plot(time_bounce,data_90,':',label="90% Boundary",color='gray')
                            # plt.plot(time_bounce,data_110,':',label="110% Boundary",color='gray')
                        data_lims += data[y][sub][x]
            else:
                if type(out_chans[0][sub]) is str:
                    for key in _ch_id[y]:
                        if out_chans[0][sub] == _ch_id[y][key]:
                            out_chans[0][sub] = key
                            break
                if data[y][sub][0] != -1:
                    if angle[sub] != 0:
                        try:
                            for d in xrange(len(data[y][sub][0])):
                                data[y][sub][0][d] -= angle_data[y][sub][d]
                        except Exception:
                            print(
                                "ERROR -=-=-=-==-=-=-=-=-=-=------------=-=-==-=-=--==-=-=-=-=-=-=-=-=-"
                            )
                    # plt.plot(time, data[y][sub][0], label=_ch_id[y][out_chans[sub]] + psse_pscad)
                    if psse_pscad == " Psse":
                        plt.plot(time,
                                 data[y][sub][x],
                                 label=_ch_id[y][out_chans[0][sub][x]] +
                                 psse_pscad,
                                 linewidth=3.5)
                        plt.plot(time[y],
                                 np.multiply(data[y][sub][x], 0.9),
                                 '--',
                                 label="90% Boundary",
                                 linewidth=1.5)
                        plt.plot(time[y],
                                 np.multiply(data[y][sub][x], 1.1),
                                 '--',
                                 label="110% Boundary",
                                 linewidth=1.5)
                    else:
                        plt.plot(time,
                                 data[y][sub][x],
                                 linestyle="dashed",
                                 dashes=(4, 3),
                                 label=_ch_id[y][out_chans[1][sub][x]] +
                                 psse_pscad,
                                 linewidth=3.5)
                    data_lims += data[y][sub][0]

        plt.grid(True)  # turn on grid

        # Axis settings
        ax[sub].xaxis.set_minor_locator(ticker.AutoMinorLocator(
            2))  # automatically put a gridline in between tickers
        ax[sub].grid(b=True, which='minor',
                     linestyle=':')  # gridline style is dots
        ax[sub].tick_params(
            axis='x', which='minor',
            bottom='on')  # display small ticks at bottom midway
        ax[sub].get_xaxis().get_major_formatter().set_useOffset(
            False)  # turn off the annoying offset values
        ax[sub].get_yaxis().get_major_formatter().set_useOffset(False)
        plt.tight_layout()
        if xlims == "" or len(xlims) < sub + 1 or xlims[sub] == "":
            xlimit = [
                min(min(time[0]), min(time[1])),
                max(max(time[0]), max(time[1]))
            ]
            ax[sub].set_xlim(xlimit)
        else:
            xlimit = xlims[sub]
            ax[sub].set_xlim(xlimit)

        # Make sure that there is 15% padding on top and bottom
        max_data = max(data_lims)
        min_data = min(data_lims)
        max_data = ymax
        min_data = ymin

        data_range = max_data - min_data
        if ylims == "" or len(ylims) < sub + 1 or ylims[sub] == "":
            ylimit = ax[sub].get_ylim()
            ylimit = [ymin, ymax]
            new_y = restrict_y_axis(ylimit, data_range, max_data, min_data)
            ax[sub].set_ylim(new_y)
        else:
            # ylimit = ylims[sub]
            # new_y = restrict_y_axis(ylimit, data_range, max_data, min_data)
            # ax[sub].set_ylim(new_y)
            ax[sub].set_ylim(ylims[sub])

        # If there is a top title, make sure there is room for it
        top = 0.9
        if top_title == "":
            top = 0.95
        plt.subplots_adjust(right=0.9,
                            hspace=0.3,
                            wspace=0.3,
                            top=top,
                            left=0.1,
                            bottom=0.12)
        # legend = plt.legend(bbox_to_anchor=(0., -0.28, 1., .105), loc=3,
        #                     ncol=2, mode="expand", prop={'size': 16}, borderaxespad=0.)
        legend = plt.legend(bbox_to_anchor=(0., -0.25, 1., .105),
                            loc=2,
                            ncol=2,
                            mode="expand",
                            prop={'size': 16},
                            borderaxespad=0.1,
                            frameon=False)

        legend.get_title().set_fontsize('16')  # legend 'Title' fontsize
        plt.setp(plt.gca().get_legend().get_texts(),
                 fontsize='16')  # legend 'list' fontsize
        plt.subplots_adjust(hspace=0.5)
        # plt.legend(bbox_to_anchor=(0., -0.55, 1., .105), loc=3,
        #        ncol=4, mode="expand", borderaxespad=0.)

    # Plot the legend on the bottom, underneath everything
    # plt.legend(bbox_to_anchor=(0., -0.55, 1., .105), loc=3,
    #            ncol=4, mode="expand", borderaxespad=0.)

    # Save file

    file_str = os.path.join(out_folder,
                            out_file[0]).replace('_PSSE.out', '.pdf')
    #file_str = file_str.split(".png", 1)
    #file_str = file_str[0] + ".png"
    plot_name = os.path.basename(file_str[0:-4])
    plt.suptitle(plot_name, fontsize=20, fontweight='bold')
    plt.savefig(file_str, dpi=100)
    print(str(plot_name + "Saved"))
    plt.close()
示例#22
0
import channel_utils
# @Software: PyCharm

import os
import sys

sys_path_PSSE = r'D:\Program Files (x86)\PTI\PSSEXplore34\PSSPY34'  # or where else you find the psspy.pyc
sys.path.append(sys_path_PSSE)

os_path_PSSE = r'D:\Program Files (x86)\PTI\PSSEXplore34\PSSBIN'  # or where else you find the psse.exe
os.environ['PATH'] += ';' + os_path_PSSE
os.environ['PATH'] += ';' + sys_path_PSSE

import dyntools
import matplotlib.pyplot as plt

outfile_noRel = dyntools.CHNF('./t9bus-v34-001-noneRel.out')
short_title_noRel, chanid_dict_noRel, chandata_dict_noRel = outfile_noRel.get_data(
)

outfile_Average = dyntools.CHNF('./t9bus-v34-001-Average.out')
short_title_Average, chanid_dict_Average, chandata_dict_Average = outfile_Average.get_data(
)

time_noRel = chandata_dict_noRel['time']
angle_noRel = chandata_dict_noRel[
    1]  # based on the channel identifier set in the dynamic simulation

time_Average = chandata_dict_Average['time']
angle_Average = chandata_dict_Average[1]

# fig = plt.figure(figsize=(10, 3))   # 用这句,或者下面的 fig.set_figwidth()/_figheight() 效果一致
psspy.change_plmod_var(101, r"""1""", r"""GPMPPC""", 69, 1.03)
psspy.run(0, 10, 1000, 1, 0)
# psspy.change_var(var_ppc_setp + 68, 1.07)
# psspy.run(0, 65, 1000, 1, 0)
# psspy.change_var(var_ppc_setp + 68, 1.06)
# psspy.run(0, 100, 1000, 1, 0)

# start draw curves
# new folder if necessary

GraphPath = FigurePath + ClauseName
if not os.path.exists(GraphPath):
    os.makedirs(GraphPath)

# read data curves
chnfobj = dyntools.CHNF(OutputFilePath)
short_title, chanid, chandata = chnfobj.get_data()
freq_data = numpy.array(chandata[1])

# set figure preference
mpl.rcParams['grid.color'] = 'k'
mpl.rcParams['grid.linestyle'] = ':'
mpl.rcParams['grid.linewidth'] = 0.5
mpl.rcParams['axes.grid'] = 'on'

mpl.rcParams['font.size'] = 24

mpl.rcParams['lines.linewidth'] = 3.0

mpl.rcParams['legend.fancybox'] = True
mpl.rcParams['legend.loc'] = 'lower center'
示例#25
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)
        #Line outage or line fault
        a = int(x[0])
        b = int(x[1])
        c = int(x[2])
        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
        #ierr[17] = psspy.dist_branch_fault(a,b,r"""1""",1, c,[0.0,-0.2E+10]) #Line Fault, NaN (network no good)
        #generator outage
        #x = int(x)
        #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
        #Bus Fault
        #ierr[17] = psspy.dist_bus_fault(211,1, 230.0,[0.0,-0.2E+10]) #bus Fault, NaN (network no good)
        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