示例#1
0
文件: tsviewer.py 项目: yunjunz/PySAR
    def plot_ts(ax, ax2, fig2, xsub, ysub, h5timeseries):
        ax2.cla()
        print "\n-------------------------------------------------------------------------------"
        disp_min = 0
        disp_max = 0

        ############################# Plot Time Series ##############################
        global ref_xsub, ref_ysub
        ##### 1.1 Plot Reference time series
        try:
            ref_xsub
            ref_ysub
            ref_xsub, ref_ysub = check_yx(ref_xsub, ref_ysub, radius, ax, rectColor)
            print "----------------------------------------------------"
            print "Reference Point:"
            print "ref_x=" + str(ref_xsub[0]) + ":" + str(ref_xsub[1])
            print "ref_y=" + str(ref_ysub[0]) + ":" + str(ref_ysub[1])

            print "-----------------------------"
            print "Time series with all dates:"
            dis1, dis1_mean, dis1_std, dis1_vel = read_dis(ref_xsub, ref_ysub, dateList1, h5timeseries, unit)
            (_, caps, _) = ax2.errorbar(
                dates1,
                dis1_mean,
                yerr=dis1_std,
                fmt="-ks",
                ms=markerSize2,
                lw=0,
                alpha=1,
                mfc=markerColor_ref,
                mew=edgeWidth,
                elinewidth=edgeWidth,
                ecolor="black",
                capsize=markerSize * 0.5,
            )
            for cap in caps:
                cap.set_markeredgewidth(edgeWidth)
            disp_min, disp_max = update_lim(disp_min, disp_max, dis1_mean, dis1_std)

            if not len(dateList) == len(dateList1):
                print "-----------------------------"
                print "Time series with dates of interest:"
                dis12, dis12_mean, dis12_std, dis12_vel = read_dis(ref_xsub, ref_ysub, dateList, h5timeseries, unit)
                (_, caps, _) = ax2.errorbar(
                    dates,
                    dis12_mean,
                    yerr=dis12_std,
                    fmt="-ks",
                    ms=markerSize2,
                    lw=0,
                    alpha=1,
                    mfc=markerColor_ref2,
                    mew=edgeWidth,
                    elinewidth=edgeWidth,
                    ecolor="black",
                    capsize=markerSize * 0.5,
                )
                for cap in caps:
                    cap.set_markeredgewidth(edgeWidth)
                disp_min, disp_max = update_lim(disp_min, disp_max, dis12_mean, dis12_std)

        except:
            pass

        ##### 1.2.0 Read y/x
        print "\n----------------------------------------------------"
        print "Point of Interest:"
        xsub, ysub = check_yx(xsub, ysub, radius, ax, rectColor)
        print "x=" + str(xsub[0]) + ":" + str(xsub[1])
        print "y=" + str(ysub[0]) + ":" + str(ysub[1])

        ##### 1.2.1 Plot 2nd time series
        try:
            timeSeriesFile_2
            print "-----------------------------"
            print "2nd Time Series:"
            dis2, dis2_mean, dis2_std, dis2_vel = read_dis(xsub, ysub, dateList_2, h5timeseries_2, unit)
            (_, caps, _) = ax2.errorbar(
                dates_2,
                dis2_mean,
                yerr=dis2_std,
                fmt="-ko",
                ms=markerSize2,
                lw=0,
                alpha=1,
                mfc=markerColor2,
                elinewidth=0,
                ecolor="black",
                capsize=0,
            )
            for cap in caps:
                cap.set_markeredgewidth(edgeWidth)
            disp_min, disp_max = update_lim(disp_min, disp_max, dis2_mean, dis2_std)
        except:
            pass

        ##### 1.2.2 Plot 1st time series
        print "-----------------------------"
        print "Time Series:"
        dis, dis_mean, dis_std, dis_vel = read_dis(xsub, ysub, dateList, h5timeseries, unit)
        (_, caps, _) = ax2.errorbar(
            dates,
            dis_mean,
            yerr=dis_std,
            fmt="-ko",
            ms=markerSize,
            lw=lineWidth,
            alpha=1,
            mfc=markerColor,
            elinewidth=edgeWidth,
            ecolor="black",
            capsize=markerSize * 0.5,
        )
        for cap in caps:
            cap.set_markeredgewidth(edgeWidth)
        disp_min, disp_max = update_lim(disp_min, disp_max, dis_mean, dis_std)

        ####################### Figure Format #######################
        ## x axis format
        try:
            ax2 = ptime.adjust_xaxis_date(ax2, dateVecMinMax, fontSize)
        except:
            ax2 = ptime.adjust_xaxis_date(ax2, datevector_all, fontSize)

        ## y axis format
        ax2.set_ylabel("Displacement [" + unit + "]", fontsize=fontSize)
        try:
            lbound
            hbound
            ax2.set_ylim(lbound, hbound)
        except:
            disp_buf = 0.2 * (disp_max - disp_min)
            ax2.set_ylim(disp_min - disp_buf, disp_max + disp_buf)
        for tick in ax2.yaxis.get_major_ticks():
            tick.label.set_fontsize(fontSize)

        ## title
        figTitle = "x=" + str(xsub[0]) + ":" + str(xsub[1]) + ", y=" + str(ysub[0]) + ":" + str(ysub[1])
        try:
            lonc = ullon + (xsub[0] + xsub[1]) / 2.0 * lon_step
            latc = ullat + (ysub[0] + ysub[1]) / 2.0 * lat_step
            figTitle += ", lalo=" + "%.4f,%.4f" % (latc, lonc)
        except:
            pass
        ax2.set_title(figTitle)

        ################## Save and Output #####################
        if saveFig == "yes":
            print "-----------------------------"
            Delay = {}
            Delay["displacement"] = dis
            Delay["unit"] = unit
            Delay["time"] = datevector
            Delay["velocity"] = dis_vel[0]
            Delay["velocity_unit"] = unit + "/yr"
            Delay["velocity_std"] = dis_vel[4]
            figBase = "x" + str(xsub[0]) + "_" + str(xsub[1] - 1) + "y" + str(ysub[0]) + "_" + str(ysub[1] - 1)
            sio.savemat(figBase + "_ts.mat", {"displacement": Delay})
            print "saved " + figBase + "_ts.mat"
            fig2.savefig(figBase + "_ts.pdf", bbox_inches="tight", transparent=True, dpi=fig_dpi)
            print "saved " + figBase + "_ts.pdf"
            if dispFig == "no":
                fig.savefig(figBase + "_vel.png", bbox_inches="tight", transparent=True, dpi=fig_dpi)
                print "saved " + figBase + "_vel.png"
示例#2
0
def main(argv):

    ##### Default
    fontSize    = 12
    lineWidth   = 2
    markerColor = 'crimson'
    markerSize  = 16

    disp_fig  = 'no'
    save_fig  = 'yes'
    save_list = 'yes'

    ref_file  = 'reference_date.txt'
    drop_file = 'drop_date.txt'

    ##### Check Inputs
    if len(sys.argv)>3:
        try:
            opts, args = getopt.getopt(argv,'h:f:m:o:x:y:',['help','circle='])
        except getopt.GetoptError:
            print 'Error in reading input options!';  Usage() ; sys.exit(1)

        for opt,arg in opts:
            if opt in ("-h","--help"):    Usage() ; sys.exit()
            elif opt == '-f':  File      = arg
            elif opt == '-m':  maskFile  = arg
            elif opt == '-x':  xsub = [int(i) for i in arg.split(':')];  xsub.sort()
            elif opt == '-y':  ysub = [int(i) for i in arg.split(':')];  ysub.sort()
            elif opt == '--circle'   :  cir_par   = [i for i in arg.split(';')]
            #elif opt == '-o':  outName   = arg
            
    else:
        try:  File = argv[0]
        except: Usage(); sys.exit(1)
        try:  maskFile = argv[1]
        except: pass

    try:  atr  = readfile.read_attributes(File)
    except: Usage(); sys.exit(1)
    ext      = os.path.splitext(File)[1].lower()
    FileBase = os.path.basename(File).split(ext)[0]
    outNameBase = 'spatialMean_'+FileBase
    print '\n*************** Spatial Average ******************'

    ##### Input File Info
    k = atr['FILE_TYPE']
    print 'Input file is '+k
    width  = int(atr['WIDTH'])
    length = int(atr['FILE_LENGTH'])

    h5file = h5py.File(File)
    epochList = h5file[k].keys();
    epochList = sorted(epochList)
    epochNum  = len(epochList)
    print 'number of epoch: '+str(epochNum)
    dates,datevector = ptime.date_list2vector(epochList)

    ##### Mask Info
    try:
        Mask_orig,Matr = readfile.read(maskFile)
        print 'mask file: '+maskFile
        Masking = 'yes'
    except:
        print 'No mask. Use the whole area for ramp estimation.'
        Masking = 'no'
        Mask_orig=np.ones((length,width))
    Mask = np.zeros((length,width))
    Mask[:] = Mask_orig[:]

    ## Bounding Subset
    try:
        xsub
        ysub
        ysub,xsub = subset.check_subset_range(ysub,xsub,atr)
        Mask[ysub[0]:ysub[1],xsub[0]:xsub[1]] = Mask_orig[ysub[0]:ysub[1],xsub[0]:xsub[1]]*2
        #Mask[0:ysub[0],:]      = 0
        #Mask[ysub[1]:length,:] = 0
        #Mask[:,0:xsub[0]]      = 0
        #Mask[:,xsub[1]:width]  = 0
    except:
        Mask = Mask_orig*2
        print 'No subset input.'

    ## Circle Inputs
    try:
        cir_par
        for i in range(len(cir_par)):
            cir_idx = circle_index(atr,cir_par[i])
            Mask[cir_idx] = Mask_orig[cir_idx]
            print 'Circle '+str(i)+': '+cir_par[i]
    except: print 'No circle of interest input.'
    
    ## Mask output
    idx = Mask == 2
    idxNum = float(sum(sum(idx)))
    
    fig = plt.figure()
    plt.imshow(Mask,cmap='gray')
    plt.savefig(outNameBase+'_mask.png',bbox_inches='tight')
    print 'save mask to '+outNameBase+'_mask.png'
    #fig.clf()

    ##### Calculation
    meanList   = np.zeros(epochNum)
    pixPercent = np.zeros(epochNum)
    pixT = 0.7
    print 'calculating ...'
    print '  Date       Mean   Percentage'
    for i in range(epochNum):
        epoch = epochList[i]
        d      = h5file[k].get(epoch)[:]
        #d[Mask==0]  = np.nan
        
        meanList[i]   = np.nanmean(d[idx])
        pixPercent[i] = np.sum(d[idx] >= pixT)/idxNum
        
        print epoch+' :   %.2f    %.1f%%'%(meanList[i],pixPercent[i]*100)
    del d
    h5file.close()

    ##### Reference date - Max Value
    top3 = sorted(zip(meanList,epochList), reverse=True)[:3]
    print '------------ Top 3 Mean ------------------'
    print top3
    ## Write to txt file
    fref = open(ref_file,'w')
    fref.write(str(top3[0][1])+'\n')
    fref.close()
    print 'write optimal reference date to '+ref_file
    idxMean = meanList == np.nanmax(meanList)

    ##### Drop dates - mean threshold
    #meanT = 0.7
    #idxMean  = meanList < meanT
    #print '------------ Mean Value < '+str(meanT)+' --------'
    #print np.array(epochList)[idxMean]
    #print meanList[idxMean]

    ##### Drop dates - good pixel percentage
    pixNumT = 0.7
    print '------------ Good Pixel Percentage < %.0f%% -------'%(pixNumT*100)
    idxPix = pixPercent < pixNumT
    dropEpochList = np.array(epochList)[idxPix]
    print dropEpochList
    print pixPercent[idxPix]
    ## Write to txt file
    fdrop = open(drop_file,'w')
    for i in range(len(dropEpochList)):
        fdrop.write(str(dropEpochList[i])+'\n')
    fdrop.close()
    print 'write drop dates to '+drop_file
    print '-------------------------------------------'

    ##### Display
    fig = plt.figure(figsize=(12,12))
    ax  = fig.add_subplot(211)
    ax.plot(dates, meanList, '-ko', ms=markerSize, lw=lineWidth, alpha=0.7, mfc=markerColor)
    #ax.plot([dates[0],dates[-1]],[meanT,meanT], '--b', lw=lineWidth)
    #sc = ax.scatter(dates, np.tile(0.5,epochNum), c=meanList, s=22**2, alpha=0.3, vmin=0.0, vmax=1.0)
    #ax.scatter(np.array(dates)[idxMean], 0.5, c=meanList[idxMean], s=22**2, alpha=1.0, vmin=0.0, vmax=1.0)
    ax = ptime.adjust_xaxis_date(ax,datevector)
    ax.set_ylim(0,1)
    ax.set_title('Spatial Average Value', fontsize=fontSize)
    ax.set_xlabel('Time [years]',         fontsize=fontSize)
    #cbar = plt.colorbar(sc)
    #cbar.set_label('Spatial Mean of Normalized Sum Epochs')

    ax  = fig.add_subplot(212)
    ax.plot(dates, pixPercent, '-ko', ms=markerSize, lw=lineWidth, alpha=0.7, mfc=markerColor)
    ax.plot([dates[0],dates[-1]],[pixNumT,pixNumT], '--b', lw=lineWidth)
    ax = ptime.adjust_xaxis_date(ax,datevector)
    ax.set_ylim(0,1)
    ax.set_title('Percenrage of Pixels with Value > '+str(pixNumT), fontsize=fontSize)
    ax.set_xlabel('Time [years]',         fontsize=fontSize)
    vals = ax.get_yticks()
    ax.set_yticklabels(['{:3.0f}%'.format(i*100) for i in vals])

    if save_fig == 'yes':
        plt.savefig(outNameBase+'.png',bbox_inches='tight')
        print 'save figure to '+outNameBase+'.png'

    if disp_fig == 'yes':
        plt.show()

    ##### Output
    if save_list == 'yes':
        epochList6 = ptime.yymmdd(epochList)
        fl = open(outNameBase+'.txt','w')
        for i in range(epochNum):
            str_line = epochList6[i]+'    %.2f    %.2f\n'%(meanList[i],pixPercent[i])
            fl.write(str_line)
        fl.close()
        print 'write data to '+outNameBase+'.txt\n'