Beispiel #1
0
 def open(self):
     # Check input data type
     if isinstance(self.filebase, str):
         self.dataInput = utils.readcsv(self.filebase+'.str', unitrow=8,
                                        checkNaN=False, echo=self.echo)
     elif isinstance(self.filebase, meca.Stress):
         self.dataInput = self.filebase.dataOutput
     else:
         raise TypeError('[ERROR] Unknown type of input data {}, should be <str> or <meca.Stress> object'.format(self.filebase))
     # Check where to count
     if self.gages is None: # count cycles on every spot over each tower gage
         print("|- [ALERT] Every stress history will be used to count Rainflow",
               "cycles. If you don't mean it, try to choose serval tower gages in",
               "order to reduce calculation time")
         allSpots = self.dataInput.getkeys()
         try:
             allSpots.remove('Time') # remove "Time" column
         except:
             pass
         self.spots = allSpots
     elif isinstance(self.gages[0], int): # count cycles over given tower gages
         available = self.dataInput.getkeys()
         try:
             available.remove('Time') # remove "Time" column
         except:
             pass
         for name in available:
             if int(name[4]) in self.gages:
                 self.spots.append(name)
             else:
                 print("|- [ALERT] There is no tower gage TwHt{} in input file".format(name[4]))
     else:
         raise Exception('[ERROR] Wrong list of tower gages {}, shoud be a list of integer numbers or None'.format(self.gages))
Beispiel #2
0
 def getConditions(self):
     for v in self._speedRange:
         filename = self._outputPath.joinpath("CST_{}.out".format(v))
         data = utils.readcsv(filename)
         conditions = collections.OrderedDict().fromkeys(
             self._conditionKeys)
         for key in self._conditionKeys:
             conditions[key] = data.get(key)["Records"][-1]
         self._allConditions[v] = conditions
Beispiel #3
0
def compare_YawBrTDx(columns=['YawBrTDxt'], minor=[True, True, True, True], xlim=[60, 90, 10], ylim=[-0.9, 0.7, 0.1], file='', residu=False, withPV=False, toPDF=[]):
    # reference data
    X1 = DATA_REF.get('Time')['Records']
    Y1 = DATA_REF.get(columns[0])['Records']
    # data to be compared
    data = utils.readcsv(file)
    X2 = data.get('Time')['Records']
    Y2 = data.get(columns[0])['Records']

    fig, axeLeft = plt.subplots()
    # --- Left axis
    color = 'tab:blue'
    legendString1 = axeLeft.plot(X1, Y1, '--', label=DATA_REF.get(columns[0])['Title'])
    if not residu:
        legendString2 = axeLeft.plot(X2, Y2, label=data.get(columns[0])['Title']+file+" with TRD")
    axeLeft.set_ylabel("Deflection (m)", color=color)
    axeLeft.tick_params(axis='y', labelcolor=color)
    axeLeft.set_yticks(numpy.arange(ylim[0], ylim[1]+ylim[2], ylim[2]))
    plt.ylim(ylim[0], ylim[1])

    if withPV: # mark peak and valley
        filename = "reference_"+columns[0]+".ext"
        plot_peak_and_valley(filename, axeLeft)
        filename = file.rstrip(".out")+"_"+columns[0]+".ext"
        plot_peak_and_valley(filename, axeLeft)

    # --- Right axis
    if residu:
        color = 'tab:pink'
        axeRight = axeLeft.twinx() # instantiate a second axes that shares the same x-axis
        # calculate relative difference
        X_residu = X1
        Y_residu = [Y2[i]-Y1[i] for i in range(len(Y1))]
        legendString2 = axeRight.plot(X_residu, Y_residu, '-', linewidth=0.8, color=color, label="Residue = REF - "+file)
        axeRight.set_ylabel("Reletive difference in deflection (m)", color=color)
        axeRight.tick_params(axis='y', labelcolor=color)
        axeRight.set_yticks(numpy.arange(ylim[0], ylim[1]+ylim[2], ylim[2]))
        plt.ylim(ylim[0], ylim[1])
        
    # --- Common setting
    lns = legendString1 + legendString2
    labs = [l.get_label() for l in lns]
    axeLeft.legend(lns, labs, loc=0)
    
    plt.xlim(xlim[0], xlim[1])
    plt.xticks(numpy.arange(xlim[0], xlim[1]+xlim[2], step=xlim[2]))
    axeLeft.set_xlabel("Time (s)")
    axeLeft.grid(axis='x')
    axeLeft.grid(axis='y')

    chart.draw(fig, toPDF)
Beispiel #4
0
def main():
    # get reference data
    filebase = 'reference'
    global DATA_REF
    DATA_REF = utils.readcsv(filebase+".out")
    
    graphNum = 1

    if graphNum == 0: # get peak/valley and its time
        amp.find_peak_valley(filebase, header=7, datarow=6009, startline=12,
                             channels=["YawBrTDxt",])

    if graphNum == 1:
        # plot_Wind1Vel(file='EOG_O_277.826.7-86.712-17.0222.out')
        compare_YawBrTDx(file='EOG_O_277.826.7-86.712-17.0222.out', withPV=True)
Beispiel #5
0
 def open(self,):
     ''' Read data from .out file
     '''
     temp = utils.readcsv(filename=self.filenameInput, datarow=self.datarow,
                          checkNaN=False, echo=self.echo)
     self.dataInput['Time'] = temp.get('Time')['Records']
     for i in self.gages: # force and moment on each node
         self.dataInput[i] = {'FLzt':[], 'MLxt':[], 'MLyt':[]}
         self.dataInput[i]['FLzt'] = temp.get('TwHt'+str(i)+'FLzt')['Records']
         self.dataInput[i]['MLxt'] = temp.get('TwHt'+str(i)+'MLxt')['Records']
         self.dataInput[i]['MLyt'] = temp.get('TwHt'+str(i)+'MLyt')['Records']
     self.dataLength = len(self.dataInput[i]['FLzt'])
     if self.echo:
         print("|- {} lines of data have been imported from {}".format(self.dataLength,
               self.filenameInput))
Beispiel #6
0
def plot_trd_AON_AOFF(TRD_AON, TRD_AOFF, columns=('NTRD_FC', 'NTRD_A', 'NTRD_VA'),
                      velocities=('I','R-2','R','R+2','O'), xlim=(60, 90, 10),
                      file='', toPDF=[]):
    for v in velocities:
        fig, axes = plt.subplots()
        # Create subplots
        axes = []
        gs = gridspec.GridSpec(3, 1, height_ratios=[2, 1, 2])
        axes.append( plt.subplot(gs[0]) )
        axes.append( plt.subplot(gs[1]) )
        axes.append( plt.subplot(gs[2]) )

        # slice data
        data = utils.readcsv(file)
        start = data.get('Time')['Records'].index(xlim[0])
        end = data.get('Time')['Records'].index(xlim[1])
        X = data.get('Time')['Records'][start:end]
        
        # Chart 1: NTRD_FC -----------------------------------------------------
        Y = data.get(columns[0])['Records'][start:end]
        axes[0].plot(X, Y, label=data.get(columns[0])['Title'])

        # Chart 2: NTRD_A ------------------------------------------------------
        Y = data.get(columns[1])['Records'][start:end]
        axes[1].plot(X, Y, '--', label=data.get(columns[1])['Title'])
        
        indices = [i for (i,y) in enumerate(Y) if y == 1] # TRD is activated: A = 1
        axes[1].plot([X[i] for i in indices], [Y[i] for i in indices], '.', markersize=1, color='tab:green', label="TRD ON")
        
        indices = [i for (i,y) in enumerate(Y) if y == 0] # TRD is inactivated: A = 0
        axes[1].plot([X[i] for i in indices], [Y[i] for i in indices],'.', markersize=1, color='tab:red', label="TRD OFF")

        # Chart 3: NTRD_VA -----------------------------------------------------
        Y = data.get(columns[2])['Records'][start:end]
        axes[2].plot(X, Y, ':', label=data.get(columns[2])['Title'])
        # TRD_AON
        indices = [i for (i,y) in enumerate(Y) if y >= TRD_AON]
        axes[2].plot([X[i] for i in indices], [Y[i] for i in indices], '.', markersize=1, color='tab:green', label="AON="+str(TRD_AON))
        # TRD_AOFF
        indices = [i for (i,y) in enumerate(Y) if y <= TRD_AOFF]
        axes[2].plot([X[i] for i in indices], [Y[i] for i in indices],'.', markersize=1, color='tab:red', label="AOFF="+str(TRD_AOFF))

        # Set axes properties
        chart.adjust(axes[0], xlim=xlim, ylim=[-30e3, 30e3], ylabel="Force (kN)", xVisible=False)
        chart.adjust(axes[1], xlim=xlim, ylim=[-0.2, 1.2], ylabel="TRD Status", xVisible=False, seperator=False)
        chart.adjust(axes[2], xlim=xlim, ylim=[-0.1, 2.0], ylabel="Amplitude of vibration (m/s)", seperator=False)

        chart.draw(fig, toPDF, left=0.08, bottom=0.06, right=0.92, top=0.94, wspace=0.14, hspace=0.14)
Beispiel #7
0
def plot_Wind1Vel(columns=['Wind1VelX','Wind1VelY','Wind1VelZ'], xlim=[60, 90, 10], ylim=[-5, 35, 5], file='', toPDF=[]):
    data = utils.readcsv(file)

    fig, ax = plt.subplots()

    X = data.get('Time')['Records']
    Y = data.get(columns[0])['Records']
    ax.plot(X, Y, label=data.get(columns[0])['Title'])
    Y = data.get(columns[1])['Records']
    ax.plot(X, Y, 'o--', markevery=(0.1), label=data.get(columns[1])['Title'])
    Y = data.get(columns[2])['Records']
    ax.plot(X, Y, '^:', markevery=(0.05, 0.1), label=data.get(columns[2])['Title'])

    chart.adjust(ax, minor=[True, False, True, False], xlim=xlim, ylim=ylim, ylabel="Wind velocity (m/s)")

    chart.draw(fig, toPDF)
 def run(self):
     if self.echo: print("Extrema Finder v0.2 (October 17 2018)")
     if self.echo: print("|- Importing "+self.filebase+" ...")
     self.dataInput = utils.readcsv(filename=self.filebase+'.out', header=self.header,
                                    datarow=self.datarow, echo=self.echo)
     # searching peak/valley upon each channel
     for para in self.channels:
         if self.echo: print("|- Searching local maximum/minimum of {}..."
                             .format(para), end="")
         temp = self.find(para)
         if self.echo: print(" Done !")
         if self.saveToFile:
             self.save(para, temp)
         else:
             self.dataOutput.append(temp)
     print("|- The peak and valley of channel {} in {} are exported !".format(
           self.channels, self.filebase))
Beispiel #9
0
def get_peak_valley(filename):
    # Reference data
    # ref_time = (75.20, 77.33, 78.94, 80.48, 82.04, 83.56, 85.1, 86.64, 88.17,
    #              89.7) # time that occurs extremum deflection
    ref_index = (1520, 1733, 1894, 2048, 2204, 2356, 2510, 2664, 2817, 2970
                 )  # index of time in list of time
    ref_deflX = (0.5529, -0.8429, 0.495, -0.6029, 0.5595, -0.5398, 0.5607,
                 -0.5233, 0.5454, -0.5063)  # extremum deflection

    # get peak and valley
    data = utils.readcsv(filename='./Output/' + filename,
                         header=7,
                         datarow=6009)
    deflX = data.get("YawBrTDxt")["Records"]
    trd_deflX = [deflX[i] for i in ref_index]
    # calculate difference
    diff = sum([abs(x) - abs(y) for x, y in zip(trd_deflX, ref_deflX)])
    return diff
Beispiel #10
0
def main():
    testCase = 3
    if testCase == 1:  # simple case
        with utils.cd(
                "~/Eolien/Parameters/NREL_5MW_Onshore/Output/DLC2.3/withoutTRD/EOGO"
        ):
            # bande of grid loss
            filelist = [str(t) for t in utils.frange(74.0, 76.1, 0.1)]

            channels = [
                'YawBrTDxt', 'YawBrTDyt', 'YawBrFxp', 'YawBrFyp', 'TwHt4FLxt',
                'TwHt4FLyt', 'TwrBsFxt', 'TwrBsFyt', 'TwrBsMxt', 'TwrBsMyt'
            ]

            # # ----- Running on single processor
            # for file in filelist:
            #     amplitude.find_peak_valley(file, header=7, datarow=6009,
            #                                startline=12, channels=channels)

            # ----- Running on multi processor
            amp.find_peak_valley_multiprocess(filelist, 7, 6009, 12, channels)

    wind = 'EOG'
    speedRange = utils.frange(3.0, 25.1, 0.1)  # wind speed [m/s]
    timeRange = utils.frange(70.0, 80.1, 0.1)  # grid loss time [s]
    channels = [
        'YawBrTDxt',
    ]
    if testCase == 2:  # complex case
        with utils.cd("~/Eolien/Parameters/NREL_5MW_Onshore/Output/DLC2.3"):
            # find peak and valley
            filelist = [
                "{}_{}_{}".format(wind, v, t) for v in speedRange
                for t in timeRange
            ]
            amp.find_peak_valley_multiprocess(list_filebase=filelist,
                                              header=7,
                                              datarow=6009,
                                              startline=12,
                                              channels=channels)
            # find maximum amplitude
            all_files = []
            for v in speedRange:
                temp = ["{}_{}_{}".format(wind, v, t) for t in timeRange]
                all_files.append(temp)

            all_results = []
            for f in all_files:
                resu = amp.Amplitude.max_p2p_amplitude(f, channels, '.ext',
                                                       True)
                all_results.extend(resu)
            # save to file/print to screen
            output = amp.Amplitude.print(all_results, channels,
                                         'max_amplitude.amp')
            # compress files
            output_files = [
                elem["File"] + ".out" for elem in output[channels[0]]
            ]
            pool = multiprocessing.Pool()
            [
                pool.apply_async(utils.compress,
                                 args=(filename, True),
                                 error_callback=utils.handle_error)
                for filename in output_files
            ]
            pool.close()
            pool.join()

    # get maxi amplitude for all time range and all speed
    if testCase == 3:
        with utils.cd("."):
            all_files = [
                "{}_{}_{}".format(wind, v, t) for v in speedRange
                for t in timeRange
            ]
            all_results = []
            for f in all_files:
                resu = amp.Amplitude.max_p2p_amplitude(f, channels, '.ext',
                                                       True)
                all_results.extend(resu)
            output = amp.Amplitude.print(all_results, channels,
                                         'max_amplitude_ALL.amp')

    # For testing ...
    if testCase == 4:
        with utils.cd("~/Eolien/Parameters/Python/DLC2.3/Output/DLC2.3"):
            # find peak and valley
            filelist = ["{}_O_{}".format(wind, t) for t in timeRange]
            amp.find_peak_valley_multiprocess(list_filebase=filelist,
                                              header=7,
                                              datarow=6009,
                                              startline=12,
                                              channels=channels)
            # find maximum amplitude
            all_files = []
            all_files.append(filelist)

            all_results = []
            for f in all_files:
                resu = amp.Amplitude.max_p2p_amplitude(f, channels, '.ext',
                                                       False)
                all_results.extend(resu)
            # save to file/print to screen
            output = amp.Amplitude.print(all_results, channels,
                                         'max_amplitudeO.amp')

    # To verifiy if .out file contains NaN
    if testCase == 5:
        with utils.cd("."):
            list_filebase = utils.find(".", "*.out")
            option = 1
            # Option 1: through multiprocessing
            if option == 1:
                amp.find_peak_valley_multiprocess(list_filebase=list_filebase,
                                                  header=7,
                                                  datarow=6009,
                                                  startline=12,
                                                  channels=channels,
                                                  peak=False,
                                                  valley=False,
                                                  saveToFile=False)
            # Option 2: one by one
            if option == 2:
                for f in list_filebase:
                    try:
                        utils.readcsv("./" + f + ".out")
                    except:
                        print("[ERROR] {} has an error during reading, please "
                              "check this file".format(f))
                        raise