示例#1
0
    def plot_rec_dwt_random_pairs(self):
        reclist = self.qt.getQTrecnamelist()
        sel1213 = conf['sel1213']
        sel1213set = set(sel1213)

        out_reclist = set(reclist)  # - sel1213set

        # dwt coef
        dwtECG = WTfeature()
        # records selected
        selected_record_list = []
        for ind, recname in enumerate(out_reclist):
            # inspect
            print 'processing record : {}'.format(recname)
            print '{} records left.'.format(len(out_reclist) - ind - 1)
            # debug selection
            if not recname.startswith(ur'sele0704'):
                continue
            sig = self.qt.load(recname)
            # wavelet
            waveletobj = dwtECG.gswt_wavelet()
            self.plot_dwt_rswt(sig['sig'],
                               waveletobj=waveletobj,
                               ECGrecordname=recname,
                               auto_plot=True)
示例#2
0
    def PlotDWTCoef(self, sig=None, figID=1, waveletobj=pywt.Wavelet('sym2')):
        if sig is None:
            sig = self.sig['sig']

        rawsig = sig
        wtf = WTfeature()
        # DWT
        Level = 7
        #waveletobj = wtf.gswt_wavelet()
        #waveletobj = pywt.Wavelet('sym2')
        res = pywt.wavedec(rawsig, waveletobj, level=Level)

        plt.figure(figID)
        N_subplot = Level + 2
        plt.subplot(N_subplot, 1, 1)
        plt.plot(rawsig)
        plt.title('Original Signal')
        detail_i = 1
        for i in xrange(Level, 0, -1):
            plt.subplot(N_subplot, 1, detail_i + 1)
            plt.plot(res[i])
            plt.xlim(0, len(res[i]) - 1)
            plt.title('Detail Level {}'.format(detail_i))
            detail_i += 1
        plt.subplot(N_subplot, 1, N_subplot)
        plt.plot(res[0])
        plt.xlim(0, len(res[0]) - 1)
        plt.title('Approximation Level')

        plt.show()
示例#3
0
def PlotDWT():
    dat = scipy.io.loadmat('test.mat')
    dat = dat['sig']
    dat = [float(x) for x in dat]
    #plt.plot(dat)
    #plt.show()

    wtf = WTfeature()
    # DWT
    Level = 5
    res = pywt.wavedec(dat, wtf.gswt_wavelet(), level=Level)

    plt.figure(2)
    plt.plot(dat)

    plt.figure(1)
    for i in xrange(0, Level + 1):
        plt.subplot(Level + 1, 1, i + 1)
        plt.plot(res[i])
        plt.title('Level {}'.format(i + 1))

    plt.show()
    def plot_dwt_pairs_no_arrow(self, rawsig, relation_importance):
        ## =========================================V
        # 展示RSWT示意图
        # No Arrow, only points
        ## =========================================V
        N = 5
        figureID = 1
        fs = conf['fs']
        FixedWindowLen = conf['winlen_ratio_to_fs'] * fs
        print 'Fixed Window Length:{}'.format(FixedWindowLen)
        xL = 1000
        xR = xL + FixedWindowLen
        tarpos = 1500
        # -----------------
        # get median
        # -----------------
        importance_arr = []
        for rel_layer in relation_importance:
            for rel, imp in rel_layer:
                importance_arr.append(imp)
        N_imp = len(importance_arr)
        # ascending order:0->1
        importance_arr.sort()
        IMP_Thres = importance_arr[int(N_imp / 2)]
        # get wavelet obj
        # dwt coef
        dwtECG = WTfeature()
        waveletobj = dwtECG.gswt_wavelet()
        # props of ARROW
        #arrowprops = dict(width = 1,headwidth = 4,facecolor='black', shrink=0)
        pltxLim = range(xL, xR)
        sigAmp = [rawsig[x] for x in pltxLim]
        cA = rawsig
        # ====================
        # plot raw signal input
        # ====================
        plt.figure(figureID)
        # plot raw ECG
        plt.subplot(N + 1, 1, 1)
        # get handle for annote arrow
        # hide axis
        #frame = plt.gca()
        #frame.axes.get_xaxis().set_visible(False)
        #frame.axes.get_yaxis().set_visible(False)
        plt.plot(pltxLim, sigAmp)
        # plot reference point
        #plt.plot(tarpos,rawsig[tarpos],'ro')
        plt.title('ECG sample')
        #plt.xlim(pltxLim)

        for i in range(2, N + 2):
            # relation&importance
            rel_layer = relation_importance[i - 2]
            cA, cD = pywt.dwt(cA, waveletobj)
            xL /= 2
            xR /= 2
            tarpos /= 2
            # crop x range out
            xi = range(xL, xR)
            cDamp = [cD[x] for x in xi]
            # get relation points
            rel_x = []
            rel_y = []
            cur_N = len(cDamp)
            for rel_pair, imp in rel_layer:
                rel_x.append(rel_pair[0])
                if rel_x[-1] >= cur_N:
                    rel_y.append(0)
                else:
                    rel_y.append(cDamp[rel_pair[0]])
                rel_x.append(rel_pair[1])
                if rel_x[-1] >= cur_N:
                    rel_y.append(0)
                else:
                    rel_y.append(cDamp[rel_x[-1]])
            # plot
            fig = plt.subplot(N + 1, 1, i)

            #plt.grid(True)
            plt.plot(rel_x, rel_y, '.b')
            plt.plot(cDamp)
            # reference point
            # plt.plot(tarpos,cDamp[tarpos-xL],'ro')
            plt.xlim(0, len(cDamp) - 1)
            plt.title('DWT Level ({}):'.format(i - 1))
        # plot result
        plt.show()
    def plot_dwt_pairs_arrow(self,
                             rawsig,
                             relation_importance,
                             Window_Left=1200,
                             savefigname=None,
                             figsize=(10, 8),
                             figtitle='ECG Sample',
                             showFigure=True):
        ## =========================================V
        # 展示RSWT示意图
        # Plot Arrow
        ## =========================================V
        #
        #================
        # constants
        #================
        N = 5
        N_subplot = N + 2
        # importance pairs lower than this threshold is not shown in the figure
        Thres_min_importance = self.get_min_Importance_threshold(
            relation_importance)
        figureID = 1
        fs = conf['fs']
        FixedWindowLen = conf['winlen_ratio_to_fs'] * fs
        print 'Fixed Window Length:{}'.format(FixedWindowLen)
        xL = Window_Left
        xR = xL + FixedWindowLen
        tarpos = 1500
        # props of ARROW
        arrowprops = dict(width=1, headwidth=4, facecolor='black', shrink=0)
        # -----------------
        # get median
        # -----------------
        importance_arr = []
        for rel_layer in relation_importance:
            for rel, imp in rel_layer:
                importance_arr.append(imp)
        N_imp = len(importance_arr)
        # ascending order:0->1
        importance_arr.sort()
        IMP_Thres = importance_arr[int(N_imp / 2)]
        IMP_MAX = importance_arr[-1]
        # get wavelet obj
        # dwt coef
        dwtECG = WTfeature()
        waveletobj = dwtECG.gswt_wavelet()
        # props of ARROW
        #arrowprops = dict(width = 1,headwidth = 4,facecolor='black', shrink=0)
        pltxLim = range(xL, xR)
        sigAmp = [rawsig[x] for x in pltxLim]
        cA = rawsig
        # ====================
        # plot raw signal input
        # ====================
        Fig_main = plt.figure(figureID, figsize=figsize)
        # plot raw ECG
        plt.subplot((N_subplot + 1) / 2, 2, 1)
        # get handle for annote arrow
        # hide axis
        #frame = plt.gca()
        #frame.axes.get_xaxis().set_visible(False)
        #frame.axes.get_yaxis().set_visible(False)
        plt.plot(pltxLim, sigAmp)
        # plot reference point
        #plt.plot(tarpos,rawsig[tarpos],'ro')
        #plt.title(figtitle+'[Window Left = {}]'.format(Window_Left))
        plt.title(figtitle)
        plt.xlim(pltxLim[0], pltxLim[-1])

        for i in range(2, N_subplot):
            # relation&importance
            rel_layer = relation_importance[i - 2]
            cA, cD = pywt.dwt(cA, waveletobj)
            xL /= 2
            xR /= 2
            tarpos /= 2
            # crop x range out
            xi = range(xL, xR)
            cDamp = [cD[x] for x in xi]
            # get relation points
            rel_x = []
            rel_y = []
            cur_N = len(cDamp)
            # ------------
            # sub plot
            # ------------
            #fig = plt.subplot(N+1,1,i)
            fig = plt.subplot((N_subplot + 1) / 2, 2, i)
            plt.title('DWT Detail Coefficient {}'.format(i - 1))
            #------------
            # find pair&its amplitude
            # -----------
            # sort rel_layer with imp
            rel_layer.sort(key=lambda x: x[1])
            for rel_pair, imp in rel_layer:
                # do not show imp lower than threshold
                if imp < Thres_min_importance:
                    continue
                # importance thres
                alpha = (imp - Thres_min_importance) / (IMP_MAX -
                                                        Thres_min_importance)
                arrow_color = self.get_RGB_from_Alpha((1, 0, 0), alpha,
                                                      (1, 1, 1))
                arrowprops = dict(width=0.15,
                                  linewidth=0.15,
                                  headwidth=1.5,
                                  headlength=1.5,
                                  facecolor=arrow_color,
                                  edgecolor=arrow_color,
                                  shrink=0)

                rel_x.append(rel_pair[0])
                if rel_x[-1] >= cur_N:
                    rel_y.append(0)
                else:
                    rel_y.append(cDamp[rel_pair[0]])
                rel_x.append(rel_pair[1])
                if rel_x[-1] >= cur_N:
                    rel_y.append(0)
                else:
                    rel_y.append(cDamp[rel_x[-1]])
                fig.annotate('',
                             xy=(rel_x[-2], rel_y[-2]),
                             xytext=(rel_x[-1], rel_y[-1]),
                             arrowprops=arrowprops)

            #plt.grid(True)
            plt.plot(rel_x, rel_y, '.b')
            plt.plot(cDamp)
            # reference point
            # plt.plot(tarpos,cDamp[tarpos-xL],'ro')
            plt.xlim(0, len(cDamp) - 1)
        # plot Approximation Level
        rel_x = []
        rel_y = []
        rel_layer = relation_importance[-1]
        #fig = plt.subplot((N_subplot + 1)/2,2,N_subplot)
        fig = plt.subplot(4, 1, 4)
        plt.title('Approximation Coefficient')
        cAamp = [cA[x] for x in xi]
        # sort rel_layer with imp
        rel_layer.sort(key=lambda x: x[1])
        for rel_pair, imp in rel_layer:
            # do not show imp lower than threshold
            if imp < Thres_min_importance:
                continue
            # importance thres
            alpha = (imp - Thres_min_importance) / (IMP_MAX -
                                                    Thres_min_importance)
            arrow_color = self.get_RGB_from_Alpha((1, 0, 0), alpha, (1, 1, 1))
            #arrowprops = dict(width = 1,headwidth = 4,facecolor=arrow_color,edgecolor = arrow_color,shrink=0)
            arrowprops = dict(width=0.15,
                              linewidth=0.15,
                              headwidth=1.5,
                              headlength=1.5,
                              facecolor=arrow_color,
                              edgecolor=arrow_color,
                              shrink=0)

            rel_x.append(rel_pair[0])
            if rel_x[-1] >= cur_N:
                rel_y.append(0)
            else:
                rel_y.append(cAamp[rel_pair[0]])
            rel_x.append(rel_pair[1])
            if rel_x[-1] >= cur_N:
                rel_y.append(0)
            else:
                rel_y.append(cAamp[rel_x[-1]])
            fig.annotate('',
                         xy=(rel_x[-2], rel_y[-2]),
                         xytext=(rel_x[-1], rel_y[-1]),
                         arrowprops=arrowprops)

        # reference point
        plt.plot(rel_x, rel_y, '.b')
        plt.plot(cAamp)
        plt.xlim(0, len(cAamp) - 1)

        # plot result
        if showFigure == True:
            plt.show()
        # save fig
        if savefigname is not None:
            Fig_main.savefig(savefigname, dpi=Fig_main.dpi)
            Fig_main.clf()
    def plot_dwt_pairs_arrow_partial_window_compare(self,
                                                    rawsig,
                                                    relation_importance,
                                                    Window_Left=1200,
                                                    savefigname=None,
                                                    figsize=(10, 8),
                                                    figtitle='ECG Sample',
                                                    showFigure=True):
        ## =========================================V
        # 展示RSWT示意图
        ## =========================================V
        #
        #================
        # constants
        #================
        N = 5
        figureID = 1
        fs = conf['fs']
        FixedWindowLen = conf['winlen_ratio_to_fs'] * fs
        print 'Fixed Window Length:{}'.format(FixedWindowLen)
        xL = Window_Left
        xR = xL + FixedWindowLen
        tarpos = 1500
        # props of ARROW
        arrowprops = dict(width=1, headwidth=4, facecolor='black', shrink=0)
        # -----------------
        # get median
        # -----------------
        importance_arr = []
        for rel_layer in relation_importance:
            for rel, imp in rel_layer:
                importance_arr.append(imp)
        N_imp = len(importance_arr)
        # ascending order:0->1
        importance_arr.sort()
        IMP_Thres = importance_arr[int(N_imp / 2)]
        IMP_MAX = importance_arr[-1]
        # get wavelet obj
        # dwt coef
        dwtECG = WTfeature()
        waveletobj = dwtECG.gswt_wavelet()
        # props of ARROW
        #arrowprops = dict(width = 1,headwidth = 4,facecolor='black', shrink=0)
        pltxLim = range(xL, xR)
        sigAmp = [rawsig[x] for x in pltxLim]
        cA = rawsig
        # ====================
        # plot raw signal input
        # ====================
        Fig_main = plt.figure(figureID, figsize=figsize)
        # plot raw ECG
        plt.subplot(N + 1, 2, 1)
        # get handle for annote arrow
        # hide axis
        #frame = plt.gca()
        #frame.axes.get_xaxis().set_visible(False)
        #frame.axes.get_yaxis().set_visible(False)
        plt.plot(pltxLim, sigAmp)
        # plot reference point
        #plt.plot(tarpos,rawsig[tarpos],'ro')
        plt.title('Window the signal before DWT')
        #plt.xlim(pltxLim)
        # ===========Col2=================
        plt.subplot(N + 1, 2, 2)
        plt.plot(pltxLim, sigAmp)
        cA_col2 = cA[xL:xR]
        plt.title('Window the signal after DWT')

        for i in range(2, N + 2):
            # ====================
            # subplot col2
            # ====================
            cA_col2, cD_col2 = pywt.dwt(cA_col2, waveletobj)
            plt.subplot(N + 1, 2, i * 2 - 1)
            plt.plot(cA_col2)
            # relation&importance
            rel_layer = relation_importance[i - 2]
            cA, cD = pywt.dwt(cA, waveletobj)
            xL /= 2
            xR /= 2
            tarpos /= 2
            # crop x range out
            xi = range(xL, xR)
            cDamp = [cD[x] for x in xi]
            # get relation points
            rel_x = []
            rel_y = []
            cur_N = len(cDamp)
            # ------------
            # sub plot
            # ------------
            # plot
            fig = plt.subplot(N + 1, 2, 2 * i)
            #------------
            # find pair&its amplitude
            # -----------
            for rel_pair, imp in rel_layer:
                # importance thres
                arrowprops = dict(width=1,
                                  headwidth=4,
                                  facecolor='r',
                                  edgecolor='r',
                                  alpha=imp / IMP_MAX,
                                  shrink=0)

                rel_x.append(rel_pair[0])
                if rel_x[-1] >= cur_N:
                    rel_y.append(0)
                else:
                    rel_y.append(cDamp[rel_pair[0]])
                rel_x.append(rel_pair[1])
                if rel_x[-1] >= cur_N:
                    rel_y.append(0)
                else:
                    rel_y.append(cDamp[rel_x[-1]])
                fig.annotate('',
                             xy=(rel_x[-2], rel_y[-2]),
                             xytext=(rel_x[-1], rel_y[-1]),
                             arrowprops=arrowprops)

            #plt.grid(True)
            plt.plot(rel_x, rel_y, '.b')
            plt.plot(cDamp)
            # reference point
            # plt.plot(tarpos,cDamp[tarpos-xL],'ro')
            plt.xlim(0, len(cDamp) - 1)
            plt.title('DWT Level ({}):'.format(i - 1))
        # plot result
        if showFigure == True:
            plt.show()
        # save fig
        if savefigname is not None:
            Fig_main.savefig(savefigname, dpi=Fig_main.dpi)
            Fig_main.clf()
示例#7
0
        plt.title('Original Signal')
        detail_i = 1
        for i in xrange(Level, 0, -1):
            plt.subplot(N_subplot, 1, detail_i + 1)
            plt.plot(res[i])
            plt.xlim(0, len(res[i]) - 1)
            plt.title('Detail Level {}'.format(detail_i))
            detail_i += 1
        plt.subplot(N_subplot, 1, N_subplot)
        plt.plot(res[0])
        plt.xlim(0, len(res[0]) - 1)
        plt.title('Approximation Level')

        plt.show()


if __name__ == '__main__':
    wt = WT_choose()
    wtf = WTfeature()
    reclist = wt.reclist
    for ind in xrange(0, 105):
        if reclist[ind] != 'sel46':
            continue
        wt.loadsig(ind)
        rawsig = wt.sig['sig']
        rawsig = rawsig[1000:2000]
        wt.PlotDWTCoef(sig=rawsig, waveletobj=pywt.Wavelet('db2'))
        # gswt
        waveletobj = wtf.gswt_wavelet()
        wt.PlotDWTCoef(sig=rawsig, figID=2, waveletobj=waveletobj)