Пример #1
0
    def plot_data_set(self, rs='all', meass='all', lim=20, window=1.0,
                      norm=False):
        #~ mpl.rcdefaults()
        os.chdir('/home/jaime/Documents/ResearchTopics/Publications/Current Reflections/Data Sets/')

        for rss in self.root.iter('return_stroke'):

            r_s = int(rss.find('number').text)

            if rs == -1:
                pass
            elif 'all' in rs.lower():
                pass
            elif r_s == int(rs):
                pass
            else:
                continue

            fileSave = "./DataFiles/%s_data_%s_rs%d.p" % (self.eventNamef,
                                                             self.eventDate,
                                                             r_s)

            data = pickle.load(open(fileSave, "rb"))

            data_only = {}

            if "all" in meass:
                ignore = []
                E = ['E_5', 'E_18', 'E_23', 'E_12F', 'E_12', 'E_NW60',
                     'E_NW100']
                dE = ['dE_1', 'dE_3', 'dE_4', 'dE_5', 'dE_7', 'dE_8', 'dE_9', 'dE_11', 'dE_17', 'dE_25', 'dE_OB']
                intt = ['intE_1', 'intE_3', 'intE_4', 'intE_5', 'intE_7', 'intE_8', 'intE_9', 'intE_11', 'intE_17', 'intE_25', 'intE_OB']

                ignore.extend(intt)
                ignore.extend(E)
                ignore.extend(['II_HI'])
                # ignore.extend(dE)

                for key in data:
                    if key in ignore:
                        pass
                    else:
                        data_only[key] = data[key]

                keys = data_only.keys()
                sort_data = {}

                for i, key in enumerate(keys):
                    value = data[key].ax.get_title().split()

                    if len(value) == 4:
                        s = value[3]
                        ind = s.find('km')

                        if ind > 0:
                            temp = float(value[3][:ind])
                            s = '%d' % (temp*1E3)

                        ind = s.find('m')

                        if ind > 0:
                            s = value[3][:ind]

                        sort_data[key] = float(s)

                    else:
                        s = value[4]
                        ind = s.find('km')

                        if ind > 0:
                            temp = float(value[4][:ind])
                            s = '%d' % (temp*1E3)

                        ind = s.find('m')

                        if ind > 0:
                            s = value[4][:ind]

                        sort_data[key] = float(s)

                sorted_data = sorted(sort_data.items(),
                                     key=operator.itemgetter(1))

                """
                Print all in individual figures
                """
                mpl.rcParams['savefig.directory'] = '/home/jaime/Documents/My Papers/Ongoing/Current Reflections/LaTex/Pictures/Temp/'

                for i in range(len(sorted_data)):

                    fig, ax = plt.subplots(1, 1)

                    #~ fig.suptitle('%s (%s/%s/%s)' % (event, eventDate[:2],eventDate[2:4], eventDate[4:]), fontsize=16)
                    #~ fig.suptitle(event)#, fontsize=16)

                    temp_data = data[sorted_data[i][0]].data

                    # print(sorted_data[i], len(data[sorted_data[i][0]]), len(temp_data), len(data['time']), np.max(temp_data))

                    zoom_lim = [-1, int(lim)]

                    # print(zoom_lim)

                    factor = 1E-3
                    l_width = 2.5

                    if 'dE_' in sorted_data[i][0]:
                        factor = 1E-9
                        l_width = 1.5

                    ax.plot(data[sorted_data[i][0]].dataTime, factor*temp_data,
                            linewidth=l_width)
                    ax.set_title(data[sorted_data[i][0]].ax.get_title())

                    if "ii_hi" in sorted_data[i][0].lower():
                        ylabel = '(kA)'

                    elif "int" in sorted_data[i][0].lower():
                        ylabel = '(kV/m)'

                    elif "de" in sorted_data[i][0].lower():
                        ylabel = '(kV/m/$\mu$s)'

                    elif "e_" in sorted_data[i][0].lower():
                        ylabel = '(kV/m)'

                    else:
                        ylabel = data[sorted_data[i][0]].ax.get_ylabel()

                    if '/us' in ylabel:
                        ylabel = ylabel[:-3] + ylabel[-1]

                    #~ ax.set_ylabel(ylabel)
                    ax.set_xlim(zoom_lim)
                    ax.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
                    ax.grid(True, which='both')
                    ax.xaxis.set_tick_params(width=1.5)
                    #~ ax.autoscale(True,'y')
                    #~ ax.set_xlabel('Time ($\mu$s)')

                    p = df.pickerPlot(fig, ax)
                    p.plot()

            else:
                mpl.rcParams['savefig.directory'] = '/home/jaime/Documents/My Papers/Ongoing/Current Reflections/LaTex/Pictures/Temp/'

                x = data[meass].dataTime
                y = data[meass].data

                y_filtered = filters.moving_average(y, window)

                #~ plt.plot(x, y, '-', x,y_filtered, '--')

                norm_factor = 1.0
                factor = 1E-3
                l_width = 2.5

                if 'dE_' in meass:
                    factor = 1E-9
                    l_width = 1.5

                ### Normalize waveform
                if norm:
                    p = df.RelativeTimePlot(x,y)
                    p.plot()

                    plt.show()

                    zero = y[p.zero_ind]

                    p = df.RelativeTimePlot(x, y)
                    p.plot()

                    plt.show()

                    peak = y[p.zero_ind]

                    norm_factor = float(peak - zero)*factor

                fig = plt.figure()
                ax = fig.add_subplot(111)

                zoom_lim = [-1, int(lim)]

                title = '%s (RS #%d)' % (self.eventName, r_s)
                # title = '%s (ICC)' % self.eventName
                # title = data[meass].ax.get_title()

                # if factor == 1E-3:
                #     ylabel = '(k%s' % (data[meass].ax.get_ylabel()[1:])
                # else:
                #     ylabel = data[meass].ax.get_ylabel()

                xlabel = 'Time ($\mu$s)'

                ax.plot(x*1e6, y_filtered*factor/norm_factor, linewidth=l_width)
                ax.set_title(title)
                #~ ax.set_ylabel(ylabel)
                #~ ax.set_xlabel(xlabel)
                ax.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
                ax.grid(True, which='both')
                ax.xaxis.set_tick_params(width=1.5)
                #~ ax.autoscale(True,'y')
                ax.set_xlim(zoom_lim)
                #~ ax.yaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())

                p = df.pickerPlot(fig, ax)
                p.plot()

            plt.show()
Пример #2
0
    def plot_data(self):
        print("Plotting results...")
        mpl.rcdefaults()
        mpl.rcParams['keymap.back'] = 'b'
        mpl.rcParams['keymap.forward'] = 'b'
        
        time = self.time - self.D/c
        xlims = [-2, 80]

        ### All fields in one figure

        fig = plt.figure()
        fig.suptitle('Distance from channel: %d m' % self.D)

        ax_es = fig.add_subplot(411)
        ax_es.plot(time*1E6, self.E_es)
        ax_es.set_ylabel('E_es (V/m)')
        ax_es.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
        ax_es.grid(True,which='both')
        ax_es.set_xlim(xlims)
        ax_es.autoscale(enable=True, axis='y', tight=True)

        ax_ind = fig.add_subplot(412)
        ax_ind.plot(time*1E6, self.E_ind)
        ax_ind.set_ylabel('E_ind (V/m)')
        ax_ind.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
        ax_ind.grid(True,which='both')
        ax_ind.set_xlim(xlims)
        ax_ind.autoscale(enable=True, axis='y', tight=True)

        ax_rad = fig.add_subplot(413)
        ax_rad.plot(time*1E6, self.E_rad)
        ax_rad.set_ylabel('E_rad (V/m)')
        ax_rad.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
        ax_rad.grid(True,which='both')
        ax_rad.set_xlim(xlims)
        ax_rad.autoscale(enable=True, axis='y', tight=True)

        ax = fig.add_subplot(414)
        ax.plot(time*1E6, self.E_tot)
        ax.set_ylabel('E (V/m)')
        ax.set_xlabel('Time ($\mu$s)')
        ax.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
        ax.grid(True,which='both')
        ax.set_xlim(xlims)
        ax.autoscale(enable=True, axis='y', tight=True)

        ### Total E-field

        if self.D == 70.0:
            meas = 'E_NW60'
        elif self.D == 180.0:
            meas = 'E_12F'
        elif self.D == 315.0:
            meas = 'dE_8'
        elif self.D == 391.0:
            meas = 'dE_9'
        elif self.D == 3000.0:
            meas = 'E_GOLF'
        elif self.D == 42000.0:
            meas = 'E_LOG'
    
        fo = pickle.load(open(self.fileSave, "rb"))
        E_meas = fo[meas]
        t = fo['time']*1E-6
        E_meas = E_meas[::int(len(E_meas)/len(t))]

        fig = plt.figure()
        fig.suptitle('Distance from channel: %d m' % self.D)

        ax = fig.add_subplot(111)
        ax.plot(t[:int(len(self.E_tot))]*1E6, E_meas[:int(len(self.E_tot))], 'g', label=meas)
        ax.plot(time*1E6, self.E_tot, label='E-total')
        ax.set_title('$E_{total}$')
        ax.set_ylabel('E (V/m)')
        ax.set_xlabel('Time ($\mu$s)')
        ax.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
        ax.grid(True,which='both')
        ax.set_xlim(xlims)
        ax.autoscale(enable=True, axis='y', tight=True)
        plt.legend()

        picker = df.pickerPlot(fig,ax)
        picker.plot()

        #~ plt.figure()
        #~ plt.plot(z_array,result)
        plt.show()

        ### E_es

        #~ fig = plt.figure()
        #~ ax = fig.add_subplot(111)
        #~ ax.plot(time*1E6, self.E_es)
        #~ ax.set_title('$E_{es}$')
        #~ ax.set_ylabel('E (V/m)')
        #~ ax.set_xlabel('Time ($\mu$s)')

        ### E_ind

        #~ fig = plt.figure()
        #~ ax = fig.add_subplot(111)
        #~ ax.plot(time*1E6, self.E_ind)
        #~ ax.set_title('$E_{ind}$')
        #~ ax.set_ylabel('E (V/m)')
        #~ ax.set_xlabel('Time ($\mu$s)')

        ### E_rad

        #~ fig = plt.figure()
        #~ ax = fig.add_subplot(111)
        #~ ax.plot(time*1E6, self.E_rad)
        #~ ax.set_title('$E_{rad}$')
        #~ ax.set_ylabel('E (V/m)')
        #~ ax.set_xlabel('Time ($\mu$s)')

        print("  - Done.")
        plt.show()
Пример #3
0
    elif run == 17:
        label = r'MTLE Model, $\lambda$ = 10km'
    ###
        
    ax.plot(run_data['%d'%run]['t_array']['sum']*xfactor, ave*yfactor, '-', label=label)#r'$E^{MTLE}_{tot}$')# -- Run %02d' % run)
    
ax.set_title(sup_title)
#~ ax.set_xlabel(xlabel)
#~ ax.set_ylabel(ylabel)
ax.set_xlim(xlim)
ax.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
ax.yaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
ax.grid(True,which='both')
ax.legend(loc=4)

p = df.pickerPlot(fig, ax)
p.plot()

### dE/dt
dE = np.gradient(run_data['%d'%runs[0]]['E_tot']['sum'], np.diff(run_data['%d'%run]['t_array']['rs'])[0])
boost = dE_mult
ylim = [-2, 16]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title(sup_title + ' -- dE/dt (D = %0.1f m)' % dist)
ax.plot(run_data['%d'%run]['t_array']['dE_measured'], moving_average(run_data['%d'%run]['E_tot']['dE_measured'],30)*1E-9, label=r'Measured')
ax.plot(run_data['%d'%run]['t_array']['sum']*xfactor,moving_average(dE,5)*boost*1E-9, label=r'MTLE $\times$ %0.2f' % boost)

ax.set_xlim(xlim)
ax.set_ylim(ylim)
    if root == parent:
        files = file

for file in files:
    print(file)
    data = pickle.load(open(parent+file, 'rb'))['II_HI']
    t = data.dataTime * 1E-6
    i = data.data

    __, di, __ = diff.differentiate(t, i)

    i = i / np.max(i)
    di = di / np.max(di)

    di_filtered = filters.moving_average(di)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(t, i, t, di_filtered)
    ax.set_title(file[0:6] + '_'+ file[-8:-5] + ' - Normalized and filtered dI/dt (5 pt MA)')
    p = df.pickerPlot(fig, ax)
    p.plot()

    fig1 = plt.figure()
    ax1 = fig1.add_subplot(111)
    ax1.plot(t, i, t, di)
    ax1.set_title(file[0:6] + '_'+ file[-8:-5] + '- Normalized raw data')
    p1 = df.pickerPlot(fig1, ax1)
    p1.plot()
    plt.show()
Пример #5
0
def get_currents(fileSave):
    ### Generate desired return-stroke waveform.

    # Triangular wave used in Uman et al. (1975)
    # (t_array_i, i) = cw.triangular(peak=1.0E4, peak_time=1.0E-6, t_end=25E-6, \
    #                                samples=500.0)
    #
    # t_end_i = t_array_i[-1]
    # delta_t = np.diff(t_array_i)[0]
    #
    # ### Generate the time derivative of the RS current waveform
    # di = np.gradient(i, delta_t)
    # i_r = i
    # ii_real = i
    #
    # return (t_array_i, delta_t, i, i_r, ii_real, di, t_end_i)

    # Current waveshape from Nucci et al. (1990)
    #~ I01 = 9.9E3
    #~ I02 = 7.5E3
    #~ 
    #~ tau_1 = 0.072E-6
    #~ tau_2 = 5E-6
    #~ tau_3 = 100E-6
    #~ tau_4 = 6E-6
    #~ 
    #~ eta = 0.845
    #~ 
    #~ (t_array_i, i, err) = cw.nucci_1990(I=[I01, I02], tau = [tau_1, tau_2, \
                                        #~ tau_3, tau_4], eta=eta, t_end=t_end_i,\
                                        #~ samples=samples_i)
                
    #~ fileSave = './UF1333_I_RS1.p'
    try:
        fo = pickle.load(open(currents, "rb"))
        i = fo['i']
        t_array_i = fo['t_array_i']
        i_r = fo['i_r']
        ii_real = fo['ii_real']
        
        #~ p = df.RelativeTimePlot(t_array_i, i_r)
        #~ p.plot()
        #~ plt.show()
        
        delta_t = np.diff(t_array_i)[0]
        #~ print(delta_t)
        
        #~ from scipy.signal import savgol_filter
        #~ i_r = savgol_filter(i_r, 9, 5)
        #~ i_r = i_r[p.zero_ind:-1]
        
        #### FOR UP/DOWN and REF ONLY (i_r must already be negative)
        if name != 'rs':
            i = i_r
        
        #~ plt.plot(i)
        #~ plt.plot(ii_real)
        #~ plt.plot(i_r)
        #~ plt.show()
        #~ sys.exit(1)
            
    except FileNotFoundError: 
        print('File not found: \' %s \'' % currents)
        
        try:
            fo = pickle.load(open(fileSave, "rb"))
            i = fo['i_model']
            t_array_i = fo['time']
            i_r = -0.5*fo['i_r']
            ii_real = fo['ii_hi']
            ind = fo['ind']
            
            delta_t = np.diff(t_array_i)[0]
            #~ print(delta_t)
            
            #~ p = df.RelativeTimePlot(t_array_i, i)
            #~ p.plot()
            #~ plt.show()
            #~ i = i[p.zero_ind:-1]# - i[p.zero_ind]
            
            #~ i = i[ind-int(fileSaveCurrentsDelay/delta_t):-1]
            
            p = df.RelativeTimePlot(t_array_i, i_r)
            p.plot()
            plt.show()
                        
            
            from scipy.signal import savgol_filter
            i_r = savgol_filter(i_r, 9, 5)
            i_r = i_r[p.zero_ind:-1]# - i_r[p.zero_ind]
            
            plt.plot(i)
            plt.plot(ii_real)
            
            p = df.pickerPlot(plt.gcf(), plt.gca())
            p.plot()
            plt.show()
            
            data = {}
            data['i'] = i
            data['t_array_i'] = t_array_i
            data['i_r'] = i_r
            data['ii_real'] = ii_real        
            
            pickle.dump(data, open(currents, 'wb'))
            
            #~ plt.plot(i)
            #~ plt.plot(ii_real)
            #~ plt.plot(i_r)
            #~ plt.show()
            #~ sys.exit(1)
                
        except FileNotFoundError: 
            print('File not found: \' %s \'' % fileSave)
            raise
        
    t_end_i = t_array_i[-1]
    delta_t = np.diff(t_array_i)[0]

    ### Generate the time derivative of the RS current waveform
    di = np.gradient(i, delta_t)
    
    return (t_array_i, delta_t, i, i_r, ii_real, di, t_end_i)