Exemple #1
0
def circle_index(atr,circle_par):
    ## Return Index of Elements within a Circle
    ## Inputs:
    ##     atr        : (dictionary) attributes containging width, length info
    ##     circle_par : (string) center_x,center_y,radius

    width  = int(atr['WIDTH'])
    length = int(atr['FILE_LENGTH'])
    cir_par = circle_par.split(',')
    try:
        c_y    = int(cir_par[0])
        c_x    = int(cir_par[1])
        radius = int(float(cir_par[2]))
    except:
        try:
            c_lat  = float(cir_par[0])
            c_lon  = float(cir_par[1])
            radius = int(float(cir_par[2]))
            c_y = subset.coord_geo2radar(c_lat,atr,'lat')
            c_x = subset.coord_geo2radar(c_lon,atr,'lon')
        except:
            print '\nERROR: Unrecognized circle index format: '+circle_par
            print 'Supported format:'
            print '--circle 200,300,20            for radar coord input'
            print '--circle 31.0214,130.5699,20   for geo   coord input\n'
            return 0

    y,x = np.ogrid[-c_y:length-c_y, -c_x:width-c_x]
    idx = x**2 + y**2 <= radius**2

    return idx
Exemple #2
0
def circle_index(atr,circle_par):
    ## Return Index of Elements within a Circle
    ## Inputs:
    ##     atr        : (dictionary) attributes containging width, length info
    ##     circle_par : (string) center_x,center_y,radius

    width  = int(atr['WIDTH'])
    length = int(atr['FILE_LENGTH'])
    cir_par = circle_par.split(',')
    #import pdb; pdb.set_trace()
    try:
        c_y    = int(cir_par[0])
        c_x    = int(cir_par[1])
        radius = int(float(cir_par[2]))
    except:
        try:
            c_lat  = float(cir_par[0])
            c_lon  = float(cir_par[1])
            radius = int(float(cir_par[2]))
            c_y = subset.coord_geo2radar(c_lat,atr,'lat')
            c_x = subset.coord_geo2radar(c_lon,atr,'lon')
        except:
            print '\nERROR: Unrecognized circle index format: '+circle_par
            print 'Supported format:'
            print '--circle 200,300,20            for radar coord input'
            print '--circle 31.0214,130.5699,20   for geo   coord input\n'
            return 0

    y,x = np.ogrid[-c_y:length-c_y, -c_x:width-c_x]
    idx = x**2 + y**2 <= radius**2

    return idx
Exemple #3
0
def read_dis_lalo(lat, lon, dateList, timeseriesFile, radius=0, unit='cm'):
    atr = readfile.read_attribute(timeseriesFile)
    h5 = h5py.File(timeseriesFile, 'r')

    x = subset.coord_geo2radar(lon, atr, 'longitude')
    y = subset.coord_geo2radar(lat, atr, 'latitude')
    if radius == 0: radius = 3
    xsub = [x - radius, x + radius]
    ysub = [y - radius, y + radius]

    dis, dis_mean, dis_std = read_dis_xy(xsub, ysub, dateList, h5, unit)[0:3]
    h5.close()

    return dis, dis_mean, dis_std
Exemple #4
0
def main(argv):
    inps = cmdLineParse()
    inps.file = ut.get_file_list(inps.file)

    atr = readfile.read_attribute(inps.file[0])
    length = int(atr['FILE_LENGTH'])
    width = int(atr['WIDTH'])

    if inps.reset:
        print '----------------------------------------------------------------------------'
        for file in inps.file:
            remove_reference_pixel(file)
        return

    ##### Check Input Coordinates
    # Read ref_y/x/lat/lon from reference/template
    # priority: Direct Input > Reference File > Template File
    if inps.template_file:
        print 'reading reference info from template: ' + inps.template_file
        inps = read_seed_template2inps(inps.template_file, inps)
    if inps.reference_file:
        print 'reading reference info from reference: ' + inps.reference_file
        inps = read_seed_reference2inps(inps.reference_file, inps)

    ## Do not use ref_lat/lon input for file in radar-coord
    #if not 'X_FIRST' in atr.keys() and (inps.ref_lat or inps.ref_lon):
    #    print 'Lat/lon reference input is disabled for file in radar coord.'
    #    inps.ref_lat = None
    #    inps.ref_lon = None

    # Convert ref_lat/lon to ref_y/x
    if inps.ref_lat and inps.ref_lon:
        if 'X_FIRST' in atr.keys():
            inps.ref_y = subset.coord_geo2radar(inps.ref_lat, atr, 'lat')
            inps.ref_x = subset.coord_geo2radar(inps.ref_lon, atr, 'lon')
        else:
            # Convert lat/lon to az/rg for radar coord file using geomap*.trans file
            inps.ref_y, inps.ref_x = ut.glob2radar(np.array(inps.ref_lat), np.array(inps.ref_lon),\
                                                   inps.trans_file, atr)[0:2]
        print 'Input reference point in lat/lon: ' + str(
            [inps.ref_lat, inps.ref_lon])
    print 'Input reference point in   y/x  : ' + str([inps.ref_y, inps.ref_x])

    # Do not use ref_y/x outside of data coverage
    if (inps.ref_y and inps.ref_x
            and not (0 <= inps.ref_y <= length and 0 <= inps.ref_x <= width)):
        inps.ref_y = None
        inps.ref_x = None
        print 'WARNING: input reference point is OUT of data coverage!'
        print 'Continue with other method to select reference point.'

    # Do not use ref_y/x in masked out area
    if inps.ref_y and inps.ref_x and inps.mask_file:
        print 'mask: ' + inps.mask_file
        mask = readfile.read(inps.mask_file)[0]
        if mask[inps.ref_y, inps.ref_x] == 0:
            inps.ref_y = None
            inps.ref_x = None
            print 'WARNING: input reference point is in masked OUT area!'
            print 'Continue with other method to select reference point.'

    ##### Select method
    if inps.ref_y and inps.ref_x:
        inps.method = 'input-coord'
    elif inps.coherence_file:
        if os.path.isfile(inps.coherence_file):
            inps.method = 'max-coherence'
        else:
            inps.coherence_file = None

    if inps.method == 'manual':
        inps.parallel = False
        print 'Parallel processing is disabled for manual seeding method.'

    ##### Seeding file by file
    # check outfile and parallel option
    if inps.parallel:
        num_cores, inps.parallel, Parallel, delayed = ut.check_parallel(
            len(inps.file))

    if len(inps.file) == 1:
        seed_file_inps(inps.file[0], inps, inps.outfile)

    elif inps.parallel:
        #num_cores = min(multiprocessing.cpu_count(), len(inps.file))
        #print 'parallel processing using %d cores ...'%(num_cores)
        Parallel(n_jobs=num_cores)(delayed(seed_file_inps)(file, inps)
                                   for file in inps.file)
    else:
        for File in inps.file:
            seed_file_inps(File, inps)

    print 'Done.'
    return
Exemple #5
0
def main(argv):
    inps = cmdLineParse()

    ##### 1. Extract the common area of two input files
    # Basic info
    atr1 = readfile.read_attribute(inps.file[0])
    atr2 = readfile.read_attribute(inps.file[1])
    if any('X_FIRST' not in i for i in [atr1, atr2]):
        sys.exit('ERROR: Not all input files are geocoded.')

    k1 = atr1['FILE_TYPE']
    print 'Input 1st file is ' + k1

    # Common AOI in lalo
    west, east, south, north = get_overlap_lalo(atr1, atr2)
    lon_step = float(atr1['X_STEP'])
    lat_step = float(atr1['Y_STEP'])
    width = int(round((east - west) / lon_step))
    length = int(round((south - north) / lat_step))

    # Read data in common AOI: LOS displacement, heading angle, incident angle
    u_los = np.zeros((2, width * length))
    heading = []
    incidence = []
    for i in range(len(inps.file)):
        fname = inps.file[i]
        print '---------------------'
        print 'reading ' + fname
        atr = readfile.read_attribute(fname)

        [x0, x1] = subset.coord_geo2radar([west, east], atr, 'lon')
        [y0, y1] = subset.coord_geo2radar([north, south], atr, 'lat')
        V = readfile.read(fname, (x0, y0, x1, y1))[0]
        u_los[i, :] = V.flatten(0)

        heading_angle = float(atr['HEADING'])
        if heading_angle < 0.:
            heading_angle += 360.
        print 'heading angle: ' + str(heading_angle)
        heading_angle *= np.pi / 180.
        heading.append(heading_angle)

        inc_angle = float(ut.incidence_angle(atr, dimension=0))
        #print 'incidence angle: '+str(inc_angle)
        inc_angle *= np.pi / 180.
        incidence.append(inc_angle)

    ##### 2. Project displacement from LOS to Horizontal and Vertical components
    # math for 3D: cos(theta)*Uz - cos(alpha)*sin(theta)*Ux + sin(alpha)*sin(theta)*Uy = Ulos
    # math for 2D: cos(theta)*Uv - sin(alpha-az)*sin(theta)*Uh = Ulos   #Uh_perp = 0.0
    # This could be easily modified to support multiple view geometry (e.g. two adjcent tracks from asc & desc) to resolve 3D

    # Design matrix
    A = np.zeros((2, 2))
    for i in range(len(inps.file)):
        A[i, 0] = np.cos(incidence[i])
        A[i, 1] = np.sin(incidence[i]) * np.sin(heading[i] - inps.azimuth)

    A_inv = np.linalg.pinv(A)
    u_vh = np.dot(A_inv, u_los)

    u_v = np.reshape(u_vh[0, :], (length, width))
    u_h = np.reshape(u_vh[1, :], (length, width))

    ##### 3. Output
    # Attributes
    atr = atr1.copy()
    atr['WIDTH'] = str(width)
    atr['FILE_LENGTH'] = str(length)
    atr['X_FIRST'] = str(west)
    atr['Y_FIRST'] = str(north)
    atr['X_STEP'] = str(lon_step)
    atr['Y_STEP'] = str(lat_step)

    print '---------------------'
    outname = inps.outfile[0]
    print 'writing   vertical component to file: ' + outname
    writefile.write(u_v, atr, outname)

    outname = inps.outfile[1]
    print 'writing horizontal component to file: ' + outname
    writefile.write(u_h, atr, outname)

    print 'Done.'
    return
Exemple #6
0
def main(argv):

    ## Default settings
    contour_step = 200.0
    contour_sigma = 3.0
    demShade = "yes"
    demContour = "yes"

    global markerSize, markderSize2, markerColor, markerColor2, rectColor
    global lineWidth, lineWidth2, edgeWidth, fontSize
    # global markerColor_ref, markerColor_ref2

    markerSize = 16
    markerSize2 = 16
    markerColor = "crimson"  # g
    markerColor2 = "lightgray"
    markerColor_ref = "white"
    markerColor_ref2 = "lightgray"
    rectColor = "black"
    lineWidth = 0
    lineWidth2 = 0
    edgeWidth = 1.5
    fontSize = 16

    global unit, radius, saveFig, dispFig, fig_dpi

    fig_dpi = 300
    radius = 0
    saveFig = "no"
    dispFig = "yes"
    unit = "cm"

    dispDisplacement = "no"
    dispOpposite = "no"
    dispContour = "only"
    smoothContour = "no"
    contour_step = 200
    showRef = "yes"
    vel_alpha = 1.0
    zero_start = "yes"

    global ref_xsub, ref_ysub, ref_date
    global h5timeseries_2, dates_2, dateList_2
    global lbound, hbound

    ############### Check Inputs ##################
    if len(sys.argv) < 2:
        Usage()
        sys.exit(1)
    elif len(sys.argv) == 2:
        if argv[0] == "-h":
            Usage()
            sys.exit(1)
        elif os.path.isfile(argv[0]):
            timeSeriesFile = argv[0]
            h5timeseries = h5py.File(timeSeriesFile)
            k = h5timeseries.keys()
            if not "timeseries" in k:
                print "ERROR: Input file is " + k[0] + ".\n\tOnly timeseries is supported.\n"
                sys.exit(1)
        else:
            Usage()
            sys.exit(1)

    elif len(sys.argv) > 2:
        try:
            opts, args = getopt.getopt(
                argv,
                "f:F:v:a:b:s:m:c:w:u:l:h:D:V:t:T:d:r:x:y:X:Y:o:E:",
                [
                    "save",
                    "nodisplay",
                    "unit=",
                    "exclude=",
                    "ref-date=",
                    "rect-color=",
                    "zero-start=",
                    "zoom-x=",
                    "zoom-y=",
                    "zoom-lon",
                    "zoom-lat",
                    "lalo=",
                    "opposite",
                    "dem-nocontour",
                    "dem-noshade",
                    "displacement",
                    "contour-step=",
                    "contour-smooth=",
                    "LALO=",
                ],
            )
        except getopt.GetoptError:
            Usage()
            sys.exit(1)

        for opt, arg in opts:
            if opt == "-f":
                timeSeriesFile = arg
            elif opt == "-F":
                timeSeriesFile_2 = arg
            elif opt == "-v":
                velocityFile = arg
            elif opt == "-a":
                vmin = float(arg)
            elif opt == "-b":
                vmax = float(arg)
            elif opt == "-s":
                fontSize = int(arg)
            elif opt == "-m":
                markerSize = int(arg)
                markerSize2 = int(arg)
            elif opt == "-c":
                markerColor = arg
            elif opt == "-w":
                lineWidth = int(arg)
            elif opt == "-u":
                unit = arg
            elif opt == "-l":
                lbound = float(arg)
            elif opt == "-h":
                hbound = float(arg)
            elif opt == "-D":
                demFile = arg
            elif opt == "-V":
                contour_step = float(arg)
            elif opt == "-t":
                minDate = arg
            elif opt == "-T":
                maxDate = arg
            elif opt == "-r":
                radius = abs(int(arg))
            elif opt == "-x":
                xsub = [int(i) for i in arg.split(":")]
                xsub.sort()
                # dispVelFig='no'
            elif opt == "-y":
                ysub = [int(i) for i in arg.split(":")]
                ysub.sort()
                # dispVelFig='no'
            elif opt == "-X":
                ref_xsub = [int(i) for i in arg.split(":")]
                ref_xsub.sort()
            elif opt == "-Y":
                ref_ysub = [int(i) for i in arg.split(":")]
                ref_ysub.sort()
                # dispVelFig='no'

            elif opt == "--contour-step":
                contour_step = float(arg)
            elif opt == "--contour-smooth":
                contour_sigma = float(arg)
            elif opt == "--dem-nocontour":
                demContour = "no"
            elif opt == "--dem-noshade":
                demShade = "no"
            elif opt == "--displacement":
                dispDisplacement = "yes"
            elif opt in ["-E", "--exclude"]:
                datesNot2show = arg.split(",")
            elif opt in "--lalo":
                lalosub = [float(i) for i in arg.split(",")]
            elif opt in "--LALO":
                ref_lalosub = [float(i) for i in arg.split(",")]
            elif opt in ["--rect-color"]:
                rectColor = arg
            elif opt in ["--ref-date"]:
                ref_date = ptime.yyyymmdd(arg)
            elif opt in ["-u", "--unit"]:
                unit = arg.lower()
            elif opt == "--save":
                saveFig = "yes"
            elif opt == "--nodisplay":
                dispFig = "no"
                saveFig = "yes"
            elif opt == "--opposite":
                dispOpposite = "yes"
            elif opt == "--zero-start":
                zero_start = arg.lower()
            elif opt == "--zoom-x":
                win_x = [int(i) for i in arg.split(":")]
                win_x.sort()
            elif opt == "--zoom-y":
                win_y = [int(i) for i in arg.split(":")]
                win_y.sort()
            elif opt == "--zoom-lon":
                win_lon = [float(i) for i in arg.split(":")]
                win_lon.sort()
            elif opt == "--zoom-lat":
                win_lat = [float(i) for i in arg.split(":")]
                win_lat.sort()

    ##############################################################
    ## Read time series file info
    if not os.path.isfile(timeSeriesFile):
        print "\nERROR: Input time series file does not exist: " + timeSeriesFile + "\n"
        sys.exit(1)
    h5timeseries = h5py.File(timeSeriesFile)
    k = h5timeseries.keys()
    # read h5 file and its group type
    if not "timeseries" in k:
        print "ERROR: Input file is " + k[0] + ".\n\tOnly timeseries is supported.\n"
        sys.exit(1)

    atr = readfile.read_attributes(timeSeriesFile)
    dateList1 = h5timeseries["timeseries"].keys()
    dateList1 = sorted(dateList1)
    dates1, datevector1 = ptime.date_list2vector(dateList1)
    print "\n************ Time Series Display - Point *************"

    ##### Select Check
    try:
        lalosub
        xsub = subset.coord_geo2radar([lalosub[1]], atr, "longitude")
        ysub = subset.coord_geo2radar([lalosub[0]], atr, "latitude")
        xsub = [xsub]
        ysub = [ysub]
        if radius == 0:
            radius = 3
    except:
        pass

    try:
        ref_lalosub
        ref_xsub = subset.coord_geo2radar([ref_lalosub[1]], atr, "longitude")
        ref_ysub = subset.coord_geo2radar([ref_lalosub[0]], atr, "latitude")
        ref_xsub = [ref_xsub]
        ref_ysub = [ref_ysub]
        if radius == 0:
            radius = 3
    except:
        pass

    ##############################################################
    global dates, dateList, datevector_all, dateListMinMax

    print "*******************"
    print "All dates existed:"
    print dateList1
    print "*******************"

    ## Check exclude date input
    try:
        datesNot2show
        if os.path.isfile(datesNot2show[0]):
            try:
                datesNot2show = ptime.read_date_list(datesNot2show[0])
            except:
                print "Can not read date list file: " + datesNot2show[0]
        print "dates not to show: " + str(datesNot2show)
    except:
        datesNot2show = []

    ## Check Min / Max Date
    dateListMinMax = []
    try:
        minDate
        minDate = ptime.yyyymmdd(minDate)
        dateListMinMax.append(minDate)
        minDateyy = ptime.yyyymmdd2years(minDate)
        print "minimum date: " + minDate
        for date in dateList1:
            yy = ptime.yyyymmdd2years(date)
            if yy < minDateyy:
                datesNot2show.append(date)
    except:
        pass
    try:
        maxDate
        maxDate = ptime.yyyymmdd(maxDate)
        dateListMinMax.append(maxDate)
        maxDateyy = ptime.yyyymmdd2years(maxDate)
        print "maximum date: " + maxDate
        for date in dateList1:
            yy = ptime.yyyymmdd2years(date)
            if yy > maxDateyy:
                datesNot2show.append(date)
    except:
        pass

    dateListMinMax = sorted(dateListMinMax)
    if not dateListMinMax:
        print "no min/max date input."
    else:
        datesMinMax, dateVecMinMax = ptime.date_list2vector(dateListMinMax)

    ## Finalize Date List
    try:
        dateList = []
        for date in dateList1:
            if date not in datesNot2show:
                dateList.append(date)
        print "--------------------------------------------"
        print "dates used to show time series displacements:"
        print dateList
        print "--------------------------------------------"
    except:
        dateList = dateList1
        print "using all dates to show time series displacement"

    ## Read Date Info (x axis for time series display)
    dates, datevector = ptime.date_list2vector(dateList)
    datevector_all = list(datevector)

    ## Check reference date input
    try:
        ref_date
        if not ref_date in dateList:
            print "Reference date - " + ref_date + " - is not included in date list to show."
            sys.exit(1)
        else:
            print "reference date: " + ref_date
    except:
        if zero_start == "yes":
            ref_date = dateList[0]
            print "set the 1st date as reference for displacement display."
        else:
            pass

    ##############################################################
    ##### Plot Fig 1 - Velocity / last epoch of time series / DEM
    fig = plt.figure(1)
    ax = fig.add_subplot(111)

    ##### Check subset range
    width = int(atr["WIDTH"])
    length = int(atr["FILE_LENGTH"])
    print "file size: " + str(length) + ", " + str(width)
    try:
        win_y = subset.coord_geo2radar(win_lat, atr, "latitude")
    except:
        try:
            win_y
        except:
            win_y = [0, length]
    try:
        win_x = subset.coord_geo2radar(win_lon, atr, "longitude")
    except:
        try:
            win_x
        except:
            win_x = [0, width]
    win_y, win_x = subset.check_subset_range(win_y, win_x, atr)

    try:
        velocityFile
        try:
            vel, vel_atr = readfile.read(velocityFile)
        except:
            vel, vel_atr = readfile.read(timeSeriesFile, velocityFile)
        ax.set_title(velocityFile)
        print "display: " + velocityFile
    except:
        vel, vel_atr = readfile.read(timeSeriesFile, dateList1[-1])
        ax.set_title("epoch: " + dateList1[-1])
        print "display last epoch"

    ##### show displacement instead of phase
    if vel_atr["FILE_TYPE"] in ["interferograms", ".unw"] and dispDisplacement == "yes":
        print "show displacement"
        phase2range = -float(vel_atr["WAVELENGTH"]) / (4 * np.pi)
        vel *= phase2range
    else:
        dispDisplacement = "no"

    ## Reference Point
    if showRef == "yes":
        try:
            ax.plot(int(atr["ref_x"]), int(atr["ref_y"]), "ks", ms=6)
        except:
            pass

    if dispOpposite == "yes":
        print "show opposite value in figure/map 1"
        vel *= -1

    ## Flip
    try:
        flip_lr
    except:
        try:
            flip_ud
        except:
            flip_lr, flip_ud = view.auto_flip_check(atr)

    ## Status bar
    ## Geo coordinate
    try:
        ullon = float(atr["X_FIRST"])
        ullat = float(atr["Y_FIRST"])
        lon_step = float(atr["X_STEP"])
        lat_step = float(atr["Y_STEP"])
        lon_unit = atr["Y_UNIT"]
        lat_unit = atr["X_UNIT"]
        geocoord = "yes"
        print "Input file is Geocoded"
    except:
        geocoord = "no"

    def format_coord(x, y):
        col = int(x + 0.5)
        row = int(y + 0.5)
        if col >= 0 and col <= width and row >= 0 and row <= length:
            z = vel[row, col]
            try:
                lon = ullon + x * lon_step
                lat = ullat + y * lat_step
                return "x=%.1f, y=%.1f, value=%.4f, lon=%.4f, lat=%.4f" % (x, y, z, lon, lat)
            except:
                return "x=%.1f, y=%.1f, value=%.4f" % (x, y, z)

    ax.format_coord = format_coord

    ## DEM
    try:
        demFile
        dem, demRsc = readfile.read(demFile)
        ax = view.plot_dem_yx(ax, dem, demShade, demContour, contour_step, contour_sigma)
        vel_alpha = 0.8
    except:
        print "No DEM file"

    try:
        img = ax.imshow(vel, vmin=vmin, vmax=vmax, alpha=vel_alpha)
    except:
        img = ax.imshow(vel, alpha=vel_alpha)
    plt.colorbar(img)

    ## Zoom In (subset)
    if flip_lr == "yes":
        ax.set_xlim(win_x[1], win_x[0])
    else:
        ax.set_xlim(win_x[0], win_x[1])
    if flip_ud == "yes":
        ax.set_ylim(win_y[0], win_y[1])
    else:
        ax.set_ylim(win_y[1], win_y[0])

    ## Flip
    # if flip_lr == 'yes':  fig.gca().invert_xaxis()
    # if flip_ud == 'yes':  fig.gca().invert_yaxis()

    ##########################################
    ##### Plot Fig 2 - Time series plot
    # fig2 = plt.figure(num=2,figsize=(12,6))
    fig2 = plt.figure(2, figsize=(12, 6))
    ax2 = fig2.add_subplot(111)

    try:
        timeSeriesFile_2
        h5timeseries_2 = h5py.File(timeSeriesFile_2)
        dateList_2 = h5timeseries_2["timeseries"].keys()
        dateList_2 = sorted(dateList_2)
        dates_2, datevector_2 = ptime.date_list2vector(dateList_2)
        datevector_all += list(set(datevector_2) - set(datevector_all))
        datevector_all = sorted(datevector_all)
    except:
        pass

    ################################  Plot Code Package <start> #################################
    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"

    ################################  Plot Code Package <end> #################################

    ########### 1. Plot Time Series with x/y ##########
    try:
        xsub
        ysub
        plot_ts(ax, ax2, fig2, xsub, ysub, h5timeseries)
    except:
        print "No x/y input"
        pass

    ########### 2. Plot Time Series with Click ##########
    ## similar to 1. Plot Time Series with x/y

    def onclick(event):
        ax2.cla()
        xsub = [int(event.xdata)]
        ysub = [int(event.ydata)]
        plot_ts(ax, ax2, fig2, xsub, ysub, h5timeseries)

        if dispFig == "yes":
            plt.show()

    try:
        cid = fig.canvas.mpl_connect("button_press_event", onclick)
    except:
        pass

    if dispFig == "yes":
        plt.show()
Exemple #7
0
def main(argv):

    ## Default settings
    contour_step = 200.0
    contour_sigma = 3.0
    demShade = 'yes'
    demContour = 'yes'

    global markerSize, markderSize2, markerColor, markerColor2, rectColor
    global lineWidth, lineWidth2, edgeWidth, fontSize
    #global markerColor_ref, markerColor_ref2

    markerSize = 16
    markerSize2 = 16
    markerColor = 'crimson'  # g
    markerColor2 = 'lightgray'
    markerColor_ref = 'white'
    markerColor_ref2 = 'lightgray'
    rectColor = 'black'
    lineWidth = 0
    lineWidth2 = 0
    edgeWidth = 1.5
    fontSize = 16

    global unit, radius, saveFig, dispFig, fig_dpi

    fig_dpi = 300
    radius = 0
    saveFig = 'no'
    dispFig = 'yes'
    unit = 'cm'

    dispDisplacement = 'no'
    dispOpposite = 'no'
    dispContour = 'only'
    smoothContour = 'no'
    contour_step = 200
    showRef = 'yes'
    vel_alpha = 1.0
    zero_start = 'yes'

    global ref_xsub, ref_ysub, ref_date
    global h5timeseries_2, dates_2, dateList_2
    global lbound, hbound

    ############### Check Inputs ##################
    if len(sys.argv) < 2:
        usage()
        sys.exit(1)
    elif len(sys.argv) == 2:
        if argv[0] == '-h':
            usage()
            sys.exit(1)
        elif os.path.isfile(argv[0]):
            timeSeriesFile = argv[0]
            h5timeseries = h5py.File(timeSeriesFile)
            k = h5timeseries.keys()
            if not 'timeseries' in k:
                print 'ERROR: Input file is ' + k[
                    0] + '.\n\tOnly timeseries is supported.\n'
                sys.exit(1)
        else:
            usage()
            sys.exit(1)

    elif len(sys.argv) > 2:
        try:            opts, args = getopt.getopt(argv,"f:F:v:a:b:s:m:c:w:u:l:h:D:V:t:T:d:r:x:y:X:Y:o:E:",
                                           ['save','nodisplay','unit=','exclude=','ref-date=','rect-color=',\
                                            'zero-start=','zoom-x=','zoom-y=','zoom-lon','zoom-lat','lalo=',\
                                            'opposite','dem-nocontour','dem-noshade','displacement','contour-step=',\
                                            'contour-smooth=','LALO='])
        except getopt.GetoptError:
            usage()
            sys.exit(1)

        for opt, arg in opts:
            if opt == '-f': timeSeriesFile = arg
            elif opt == '-F': timeSeriesFile_2 = arg
            elif opt == '-v': velocityFile = arg
            elif opt == '-a': vmin = float(arg)
            elif opt == '-b': vmax = float(arg)
            elif opt == '-s': fontSize = int(arg)
            elif opt == '-m':
                markerSize = int(arg)
                markerSize2 = int(arg)
            elif opt == '-c':
                markerColor = arg
            elif opt == '-w':
                lineWidth = int(arg)
            elif opt == '-u':
                unit = arg
            elif opt == '-l':
                lbound = float(arg)
            elif opt == '-h':
                hbound = float(arg)
            elif opt == '-D':
                demFile = arg
            elif opt == '-V':
                contour_step = float(arg)
            elif opt == '-t':
                minDate = arg
            elif opt == '-T':
                maxDate = arg
            elif opt == '-r':
                radius = abs(int(arg))
            elif opt == '-x':
                xsub = sorted([int(i) for i in arg.split(':')])
            elif opt == '-y':
                ysub = sorted([int(i) for i in arg.split(':')])
            elif opt == '-X':
                ref_xsub = sorted([int(i) for i in arg.split(':')])
            elif opt == '-Y':
                ref_ysub = sorted([int(i) for i in arg.split(':')])

            elif opt == '--contour-step':
                contour_step = float(arg)
            elif opt == '--contour-smooth':
                contour_sigma = float(arg)
            elif opt == '--dem-nocontour':
                demContour = 'no'
            elif opt == '--dem-noshade':
                demShade = 'no'
            elif opt == '--displacement':
                dispDisplacement = 'yes'
            elif opt in ['-E', '--exclude']:
                datesNot2show = arg.split(',')
            elif opt in '--lalo':
                lalosub = [float(i) for i in arg.split(',')]
            elif opt in '--LALO':
                ref_lalosub = [float(i) for i in arg.split(',')]
            elif opt in ['--rect-color']:
                rectColor = arg
            elif opt in ['--ref-date']:
                ref_date = ptime.yyyymmdd(arg)
            elif opt in ['-u', '--unit']:
                unit = arg.lower()
            elif opt == '--save':
                saveFig = 'yes'
            elif opt == '--nodisplay':
                dispFig = 'no'
                saveFig = 'yes'
            elif opt == '--opposite':
                dispOpposite = 'yes'
            elif opt == '--zero-start':
                zero_start = arg.lower()
            elif opt == '--zoom-x':
                win_x = sorted([int(i) for i in arg.split(':')])
            elif opt == '--zoom-y':
                win_y = sorted([int(i) for i in arg.split(':')])
            elif opt == '--zoom-lon':
                win_lon = sorted([float(i) for i in arg.split(':')])
            elif opt == '--zoom-lat':
                win_lat = sorted([float(i) for i in arg.split(':')])

    ##############################################################
    ## Read time series file info
    if not os.path.isfile(timeSeriesFile):
        print '\nERROR: Input time series file does not exist: ' + timeSeriesFile + '\n'
        sys.exit(1)
    h5timeseries = h5py.File(timeSeriesFile, 'r')
    k = h5timeseries.keys()
    # read h5 file and its group type
    if not 'timeseries' in k:
        print 'ERROR: Input file is ' + k[
            0] + '.\n\tOnly timeseries is supported.\n'
        sys.exit(1)

    atr = readfile.read_attribute(timeSeriesFile)
    dateList1 = sorted(h5timeseries['timeseries'].keys())
    dates1, datevector1 = ptime.date_list2vector(dateList1)
    print '\n************ Time Series Display - Point *************'

    ##### Select Check
    try:
        lalosub
        xsub = subset.coord_geo2radar([lalosub[1]], atr, 'longitude')
        ysub = subset.coord_geo2radar([lalosub[0]], atr, 'latitude')
        xsub = [xsub]
        ysub = [ysub]
        if radius == 0: radius = 3
    except:
        pass

    try:
        ref_lalosub
        ref_xsub = subset.coord_geo2radar([ref_lalosub[1]], atr, 'longitude')
        ref_ysub = subset.coord_geo2radar([ref_lalosub[0]], atr, 'latitude')
        ref_xsub = [ref_xsub]
        ref_ysub = [ref_ysub]
        if radius == 0: radius = 3
    except:
        pass

    ##############################################################
    global dates, dateList, datevector_all, dateListMinMax

    print '*******************'
    print 'All dates existed:'
    print dateList1
    print '*******************'

    ## Check exclude date input
    try:
        datesNot2show
        if os.path.isfile(datesNot2show[0]):
            try:
                datesNot2show = ptime.read_date_list(datesNot2show[0])
            except:
                print 'Can not read date list file: ' + datesNot2show[0]
        print 'dates not to show: ' + str(datesNot2show)
    except:
        datesNot2show = []

    ## Check Min / Max Date
    dateListMinMax = []
    try:
        minDate
        minDate = ptime.yyyymmdd(minDate)
        dateListMinMax.append(minDate)
        minDateyy = ptime.yyyymmdd2years(minDate)
        print 'minimum date: ' + minDate
        for date in dateList1:
            yy = ptime.yyyymmdd2years(date)
            if yy < minDateyy:
                datesNot2show.append(date)
    except:
        pass
    try:
        maxDate
        maxDate = ptime.yyyymmdd(maxDate)
        dateListMinMax.append(maxDate)
        maxDateyy = ptime.yyyymmdd2years(maxDate)
        print 'maximum date: ' + maxDate
        for date in dateList1:
            yy = ptime.yyyymmdd2years(date)
            if yy > maxDateyy:
                datesNot2show.append(date)
    except:
        pass

    dateListMinMax = sorted(dateListMinMax)
    if not dateListMinMax: print 'no min/max date input.'
    else: datesMinMax, dateVecMinMax = ptime.date_list2vector(dateListMinMax)

    ## Finalize Date List
    try:
        dateList = []
        for date in dateList1:
            if date not in datesNot2show:
                dateList.append(date)
        print '--------------------------------------------'
        print 'dates used to show time series displacements:'
        print dateList
        print '--------------------------------------------'
    except:
        dateList = dateList1
        print 'using all dates to show time series displacement'

    ## Read Date Info (x axis for time series display)
    dates, datevector = ptime.date_list2vector(dateList)
    datevector_all = list(datevector)

    ## Check reference date input
    try:
        ref_date
        if not ref_date in dateList:
            print 'Reference date - ' + ref_date + ' - is not included in date list to show.'
            sys.exit(1)
        else:
            print 'reference date: ' + ref_date
    except:
        if zero_start == 'yes':
            ref_date = dateList[0]
            print 'set the 1st date as reference for displacement display.'
        else:
            pass

    ##############################################################
    ##### Plot Fig 1 - Velocity / last epoch of time series / DEM
    fig = plt.figure(1)
    ax = fig.add_subplot(111)

    ##### Check subset range
    width = int(atr['WIDTH'])
    length = int(atr['FILE_LENGTH'])
    print 'file size: ' + str(length) + ', ' + str(width)
    try:
        win_y = subset.coord_geo2radar(win_lat, atr, 'latitude')
    except:
        try:
            win_y
        except:
            win_y = [0, length]
    try:
        win_x = subset.coord_geo2radar(win_lon, atr, 'longitude')
    except:
        try:
            win_x
        except:
            win_x = [0, width]
    win_box = (win_x[0], win_y[0], win_x[1], win_y[1])
    win_box = subset.check_box_within_data_coverage(win_box, atr)

    try:
        velocityFile
        try:
            vel, vel_atr = readfile.read(velocityFile)
        except:
            vel, vel_atr = readfile.read(timeSeriesFile, velocityFile)
        ax.set_title(velocityFile)
        print 'display: ' + velocityFile
    except:
        vel, vel_atr = readfile.read(timeSeriesFile, dateList1[-1])
        ax.set_title('epoch: ' + dateList1[-1])
        print 'display last epoch'

    ##### show displacement instead of phase
    if vel_atr['FILE_TYPE'] in ['interferograms', '.unw'
                                ] and dispDisplacement == 'yes':
        print 'show displacement'
        phase2range = -float(vel_atr['WAVELENGTH']) / (4 * np.pi)
        vel *= phase2range
    else:
        dispDisplacement = 'no'

    ## Reference Point
    if showRef == 'yes':
        try:
            ax.plot(int(atr['ref_x']), int(atr['ref_y']), 'ks', ms=6)
        except:
            pass

    if dispOpposite == 'yes':
        print 'show opposite value in figure/map 1'
        vel *= -1

    ## Flip
    try:
        flip_lr
    except:
        try:
            flip_ud
        except:
            flip_lr, flip_ud = view.auto_flip_direction(atr)

    ## Status bar
    ## Geo coordinate
    try:
        ullon = float(atr['X_FIRST'])
        ullat = float(atr['Y_FIRST'])
        lon_step = float(atr['X_STEP'])
        lat_step = float(atr['Y_STEP'])
        lon_unit = atr['Y_UNIT']
        lat_unit = atr['X_UNIT']
        geocoord = 'yes'
        print 'Input file is Geocoded'
    except:
        geocoord = 'no'

    def format_coord(x, y):
        col = int(x + 0.5)
        row = int(y + 0.5)
        if col >= 0 and col <= width and row >= 0 and row <= length:
            z = vel[row, col]
            try:
                lon = ullon + x * lon_step
                lat = ullat + y * lat_step
                return 'x=%.1f, y=%.1f, value=%.4f, lon=%.4f, lat=%.4f' % (
                    x, y, z, lon, lat)
            except:
                return 'x=%.1f, y=%.1f, value=%.4f' % (x, y, z)

    ax.format_coord = format_coord

    ## DEM
    try:
        demFile
        dem, demRsc = readfile.read(demFile)
        ax = view.plot_dem_yx(ax, dem, demShade, demContour, contour_step,
                              contour_sigma)
        vel_alpha = 0.8
    except:
        print 'No DEM file'

    try:
        img = ax.imshow(vel, vmin=vmin, vmax=vmax, alpha=vel_alpha)
    except:
        img = ax.imshow(vel, alpha=vel_alpha)
    plt.colorbar(img)

    ## Zoom In (subset)
    if flip_lr == 'yes': ax.set_xlim(win_box[2], win_box[0])
    else: ax.set_xlim(win_box[0], win_box[2])
    if flip_ud == 'yes': ax.set_ylim(win_box[1], win_box[3])
    else: ax.set_ylim(win_box[3], win_box[1])

    ## Flip
    #if flip_lr == 'yes':  fig.gca().invert_xaxis()
    #if flip_ud == 'yes':  fig.gca().invert_yaxis()

    ##########################################
    ##### Plot Fig 2 - Time series plot
    #fig2 = plt.figure(num=2,figsize=(12,6))
    fig2 = plt.figure(2, figsize=(12, 6))
    ax2 = fig2.add_subplot(111)

    try:
        timeSeriesFile_2
        h5timeseries_2 = h5py.File(timeSeriesFile_2)
        dateList_2 = sorted(h5timeseries_2['timeseries'].keys())
        dates_2, datevector_2 = ptime.date_list2vector(dateList_2)
        datevector_all += list(set(datevector_2) - set(datevector_all))
        datevector_all = sorted(datevector_all)
    except:
        pass

    ################################  Plot Code Package <start> #################################
    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_xy(
                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_xy(
                    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_xy(
                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_xy(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.auto_adjust_xaxis_date(ax2, dateVecMinMax, fontSize)
        except:
            ax2 = ptime.auto_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'

    ################################  Plot Code Package <end> #################################

    ########### 1. Plot Time Series with x/y ##########
    try:
        xsub
        ysub
        plot_ts(ax, ax2, fig2, xsub, ysub, h5timeseries)
    except:
        print 'No x/y input'
        pass

    ########### 2. Plot Time Series with Click ##########
    ## similar to 1. Plot Time Series with x/y

    def onclick(event):
        ax2.cla()
        xsub = [int(event.xdata)]
        ysub = [int(event.ydata)]
        plot_ts(ax, ax2, fig2, xsub, ysub, h5timeseries)

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

    try:
        cid = fig.canvas.mpl_connect('button_press_event', onclick)
    except:
        pass

    if dispFig == 'yes': plt.show()
Exemple #8
0
def main(argv):

    global method_default
    ##### Referencing methods
    method_default = 'max_coherence'
    #method = 'manual'
    #method = 'max_coherence'        ## Use phase on point with max coherence [default]
    #method = 'global_average'       ## Use Nan Mean of phase on all pixels
    #method = 'random'
    #maskFile = 'Mask.h5'

    global SeedingDone
    
    ############################## Check Inputs ##############################
    if len(sys.argv) > 2:
        try:  opts, args = getopt.getopt(argv,"h:c:f:m:y:x:l:L:t:o:r:",\
                                         ['manual','max-coherence','global-average','random'])
        except getopt.GetoptError:  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 == '-c':        corFile  = arg
            elif opt == '-o':        outFile  = arg

            elif opt == '-y':        ry       = int(arg)
            elif opt == '-x':        rx       = int(arg)
            elif opt == '-l':        rlat     = float(arg)
            elif opt == '-L':        rlon     = float(arg)
            elif opt == '-r':        refFile  = arg
            elif opt == '-t':        templateFile = arg

            elif opt == '--global-average' :  method = 'global_average'
            elif opt == '--manual'         :  method = 'manual'
            elif opt == '--max-coherence'  :  method = 'max_coherence'
            elif opt == '--random'         :  method = 'random'

    elif len(sys.argv)==2:
        if   argv[0]=='-h':            Usage(); sys.exit(1)
        elif os.path.isfile(argv[0]):  File = argv[0]
        else:  print 'Input file does not existed: '+argv[0];  sys.exit(1)
    elif len(sys.argv)<2:             Usage(); sys.exit(1)

    ##### Input File Info
    try:
        File
        atr = readfile.read_attributes(File)
        k = atr['FILE_TYPE']
        length = int(atr['FILE_LENGTH'])
        width  = int(atr['WIDTH'])
    except:  Usage() ; sys.exit(1)
    ext = os.path.splitext(File)[1].lower()

    try:    outFile
    except: outFile = 'Seeded_'+File
  
    ############################## Reference Point Input ####################
    try:
        refFile
        atr_ref = readfile.read_attributes(refFile)
    except: pass
  
    try:
        templateFile
        templateContents = readfile.read_template(templateFile)
    except: pass

    ### Priority
    ## lat/lon > y/x
    ## Direct Input > Reference File > Template File
    try:
        rlat
        rlon
    except:
        try:
            rlat = float(atr_ref['ref_lat'])
            rlon = float(atr_ref['ref_lon'])
        except:
            try: rlat,rlon = [float(i) for i in templateContents['pysar.seed.lalo'].split(',')]
            except: pass

    try:
        ry
        rx
    except:
        try:
            ry = int(atr_ref['ref_y'])
            rx = int(atr_ref['ref_x'])
        except:
            try: ry,rx       = [int(i)   for i in templateContents['pysar.seed.yx'].split(',')]
            except: pass

    ##### Check lalo / YX
    print '\n************** Reference Point ******************'
    try:
        rlat
        rlon
        y = sub.coord_geo2radar(rlat,atr,'lat')
        x = sub.coord_geo2radar(rlon,atr,'lon')
        0<= x <= width
        0<= y <= length
        rx = x
        ry = y
        print 'Reference point: lat = %.4f,   lon = %.4f'%(rlat,rlon)
        print '                 y   = %d,     x   = %d'%(ry,rx)
    except:
        print 'Skip input lat/lon reference point.'
        print 'Continue with the y/x reference point.'


    ######################### a. Read Mask File #########################
    ## Priority: Input mask file > pysar.mask.file 
    try:     maskFile
    except:
        try: maskFile = templateContents['pysar.mask.file']
        except:  print 'No mask found!';
    try:
        M,Matr = readfile.read(maskFile);
        print 'mask: '+maskFile
    except:
        print '---------------------------------------------------------'
        print 'WARNING: No mask, use the whole area as mask'
        print '---------------------------------------------------------'
        M = np.ones((length,width))

    ## Message
    try:
        rx
        ry
        0<= rx <= width
        0<= ry <= length
        if M[ry,rx] == 0:
            print 'Input point has 0 value in mask.'
    except: pass

    ######################### b. Stack ##################################
    stackFile = os.path.basename(File).split(ext)[0] + '_stack.h5'
    stack_file_exist = 'no'
    try:
        os.path.isfile(stackFile)
        stack,atrStack = readfile.read(stackFile)
        if width == int(atrStack['WIDTH']) and length == int(atrStack['FILE_LENGTH']):
            stack_file_exist = 'yes'
            print 'read stack from file: '+stackFile
    except: pass

    if stack_file_exist == 'no':
        print 'calculating stack of input file ...'
        stack = ut.stacking(File)
        atrStack = atr.copy()
        atrStack['FILE_TYPE'] = 'mask'
        writefile.write(stack,atrStack,stackFile)

    ## Message
    try:
        rx
        ry
        if stack[ry,rx] == 0:
            print 'Input point has nan value in data.'
    except: pass

    stack[M==0] = 0
    if np.nansum(M) == 0.0:
        print '\n*****************************************************'
        print   'ERROR:'
        print   'There is no pixel that has valid phase value in all datasets.' 
        print   'Check the file!'
        print   'Seeding failed'
        sys.exit(1)

    ######################### Check Method ##############################
    try:
        not stack[ry,rx] == 0
        method = 'input_coord'
    except:
        try:    method
        except: method = method_default
        print 'Skip input y/x reference point.'
        print 'Continue with '+method

    #h5file = h5py.File(File)

    ######################### Seeding ###################################
    ##### Sub-function
    def seed_method(method,File,stack,outFile,corFile=''):
        SeedingDone = 'no'
        next_method = method_default
        M = stack != 0

        if   method == 'manual':
            SeedingDone = seed_manual(File,stack,outFile)
            if SeedingDone == 'no':
                next_method = method_default
                print_warning(next_method)

        elif method == 'max_coherence':
            try:    SeedingDone = seed_max_coherence(File,M,outFile,corFile)
            except: SeedingDone = seed_max_coherence(File,M,outFile)
            if SeedingDone == 'no':
                next_method = 'random'
                print_warning(next_method)

        elif method == 'random':
            y,x = random_selection(stack)
            seed_xy(File,x,y,outFile)
            SeedingDone = 'yes'

        elif method == 'global_average':
            print '\n---------------------------------------------------------'
            print 'Automatically Seeding using Global Spatial Average Value '
            print '---------------------------------------------------------'
            print 'Calculating the global spatial average value for each epoch'+\
                  ' of all valid pixels ...'
            box = (0,0,width,length)
            meanList = ut.spatial_mean(File,M,box)
            seed_file(File,outFile,meanList,'','')
            SeedingDone = 'yes'

        return SeedingDone, next_method

    ##### Seeding
    SeedingDone = 'no'

    if method == 'input_coord':
        seed_xy(File,rx,ry,outFile)
        SeedingDone = 'yes'

    else:
        i = 0
        while SeedingDone == 'no' and i < 5:
            try:    SeedingDone,method = seed_method(method,File,stack,outFile,corFile)
            except: SeedingDone,method = seed_method(method,File,stack,outFile)
            i += 1
        if i >= 5:
            print 'ERROR: Seeding failed after more than '+str(i)+' times try ...'
            sys.exit(1)
Exemple #9
0
def main(argv):
    inps = cmdLineParse()
    print '\n**************** Transect *********************'
    print 'number of file: ' + str(len(inps.file))
    print inps.file

    ##### Start / End Point Input
    # 1. lonlat file
    if inps.lola_file:
        inps.start_lalo, inps.end_lalo = read_lonlat_file(inps.lola_file)
    # 2. Manually select in window display
    if (not inps.start_yx or not inps.end_yx) and (not inps.start_lalo
                                                   or not inps.end_lalo):
        print 'No input yx/lalo found.'
        print 'Continue with manually select start and end point.'
        inps.start_yx, inps.end_yx = manual_select_start_end_point(
            inps.file[0])
    # Message
    if inps.start_lalo and inps.end_lalo:
        print 'Start point:  lat = ' + str(
            inps.start_lalo[0]) + ', lon = ' + str(inps.start_lalo[1])
        print 'End   point:  lat = ' + str(
            inps.end_lalo[0]) + ', lon = ' + str(inps.end_lalo[1])
    else:
        print 'Start point:  y = ' + str(inps.start_yx[0]) + ', x = ' + str(
            inps.start_yx[1])
        print 'End   point:  y = ' + str(inps.end_yx[0]) + ', x = ' + str(
            inps.end_yx[1])

    ##### Get Transection/Profiles Data
    print 'extract transect from input files ...'
    transectList, atrList = transect_list(inps.file, inps)
    if inps.dem:
        demTransectList, demAtrList = transect_list([inps.dem], inps)
    print 'profile length: ' + str(transectList[0][-1, 0] / 1000.0) + ' km'

    ##### Plot
    # Figure 1 - Profile line in the 1st input file
    print 'plot profile line in the 1st input file'
    fig0 = plt.figure()
    ax0 = fig0.add_axes([0.1, 0.1, 0.8, 0.8])
    data0, atr0 = readfile.read(inps.file[0])
    ax0.imshow(data0)
    if inps.start_lalo and inps.end_lalo:
        [y0, y1] = sub.coord_geo2radar([inps.start_lalo[0], inps.end_lalo[0]],
                                       atr0, 'lat')
        [x0, x1] = sub.coord_geo2radar([inps.start_lalo[1], inps.end_lalo[1]],
                                       atr0, 'lon')
    else:
        [y0, y1] = [inps.start_yx[0], inps.end_yx[0]]
        [x0, x1] = [inps.start_yx[1], inps.end_yx[1]]
    ax0.plot([x0, x1], [y0, y1], 'ro-')
    ax0.set_xlim(0, np.shape(data0)[1])
    ax0.set_ylim(np.shape(data0)[0], 0)
    ax0.set_title('Transect Line in ' + inps.file[0])

    # Status bar
    def format_coord(x, y):
        col = int(x)
        row = int(y)
        if 0 <= col < data0.shape[1] and 0 <= row < data0.shape[0]:
            z = data0[row, col]
            if 'X_FIRST' in atr0.keys():
                lat = sub.coord_radar2geo(row, atr0, 'row')
                lon = sub.coord_radar2geo(col, atr0, 'col')
                return 'lon=%.4f, lat=%.4f, x=%.0f,  y=%.0f,  value=%.4f' % (
                    lon, lat, x, y, z)
            else:
                return 'x=%.0f,  y=%.0f,  value=%.4f' % (x, y, z)
        else:
            return 'x=%.0f,  y=%.0f' % (x, y)

    ax0.format_coord = format_coord

    # Figure 2 - Transections/Profiles
    print 'plot profiles'
    fig, ax = plt.subplots(figsize=inps.fig_size)
    # Plot 2.1 - Input Files
    if not inps.disp_unit:
        inps.disp_unit = atrList[0]['UNIT']
    inps.disp_scale, inps.disp_unit = get_scale_from_disp_unit(
        inps.disp_unit, atrList[0]['UNIT'])

    value_min = 0
    value_max = 0
    for i in range(len(inps.file)):
        # Profile Color based on Asc/Desc direction
        if atrList[i]['ORBIT_DIRECTION'][0].upper() == 'A':
            p_color = 'crimson'
        else:
            p_color = 'royalblue'
        # Plot
        distance = transectList[i][:, 0] / 1000.0  # km
        value = transectList[i][:, 1] * inps.disp_scale - inps.disp_offset * i
        ax.plot(distance,
                value,
                '.',
                color=p_color,
                markersize=inps.marker_size)
        # Y Stat
        value_min = np.nanmin([value_min, np.nanmin(value)])
        value_max = np.nanmax([value_max, np.nanmax(value)])

    # Y axis
    if not inps.disp_min:
        inps.disp_min = np.floor(value_min - (value_max - value_min) * 1.2 /
                                 len(inps.file))
    if not inps.disp_max:
        inps.disp_max = np.ceil(value_max)
    ax.set_ylim(inps.disp_min, inps.disp_max)
    ax.set_ylabel('Mean LOS Velocity (' + inps.disp_unit + ')',
                  fontsize=inps.font_size)
    # X axis
    ax.set_xlabel('Distance (km)', fontsize=inps.font_size)
    ax.tick_params(which='both', direction='out', labelsize=inps.font_size)

    # Plot 2.2 - DEM
    if inps.dem:
        ax2 = ax.twinx()
        distance = demTransectList[0][:, 0] / 1000.0  # km
        value = demTransectList[0][:, 1] / 1000.0  # km
        ax2.fill_between(distance, 0, value, facecolor='gray')

        # Y axis - display DEM in the bottom
        value_min = np.nanmin(value)
        value_max = np.nanmax(value)
        if not inps.dem_disp_min:
            inps.dem_disp_min = np.floor(value_min * 2.0) / 2.0
        if not inps.dem_disp_max:
            inps.dem_disp_max = np.ceil((value_max + (value_max - value_min) *
                                         (len(inps.file) + 0.0)) * 2.0) / 2.0
        ax2.set_ylim(inps.dem_disp_min, inps.dem_disp_max)
        ## Show lower part of yaxis
        #dem_tick = ax2.yaxis.get_majorticklocs()
        #dem_tick = dem_tick[:len(dem_tick)/2]
        #ax2.set_yticks(dem_tick)
        ax2.set_ylabel('Elevation (km)', fontsize=inps.font_size)
        ax2.tick_params(which='both',
                        direction='out',
                        labelsize=inps.font_size)

    ## X axis - Shared
    distanceMax = np.nanmax(transectList[0][:, 0] / 1000.0)  # in km
    plt.xlim(0, distanceMax)
    plt.tight_layout()

    ##### Output
    if not inps.outfile:
        figBase = 'transect_x' + str(x0) + 'y' + str(y0) + '_x' + str(
            x1) + 'y' + str(y1)
    else:
        figBase, inps.outfile_ext = os.path.splitext(inps.outfile)
        if not inps.outfile_ext:
            inps.outfile_ext = '.png'
    if inps.save_fig:
        print 'writing >>> ' + figBase + inps.outfile_ext
        fig0.savefig(inps.file[-1] + inps.outfile_ext,
                     bbox_inches='tight',
                     transparent=True,
                     dpi=inps.fig_dpi)
        fig.savefig(figBase + inps.outfile_ext,
                    bbox_inches='tight',
                    transparent=True,
                    dpi=inps.fig_dpi)

        print 'writing >>> ' + figBase + '.mat'
        transect_mat = {}
        for i in range(len(inps.file)):
            project = atrList[i]['PROJECT_NAME']
            transect_mat[project] = transectList[i]
        if inps.dem:
            transect_mat['elevation'] = demTransectList[0]
        sio.savemat(figBase + '.mat', {'transection': transect_mat})

    # Display
    if inps.disp_fig:
        print 'showing ...'
        plt.show()
    return
Exemple #10
0
def transect_lalo(z, atr, start_lalo, end_lalo, interpolation='nearest'):
    '''Extract 2D matrix (z) value along the line [start_lalo, end_lalo]'''
    [y0, y1] = sub.coord_geo2radar([start_lalo[0], end_lalo[0]], atr, 'lat')
    [x0, x1] = sub.coord_geo2radar([start_lalo[1], end_lalo[1]], atr, 'lon')
    transect = transect_yx(z, atr, [y0, x0], [y1, x1], interpolation)
    return transect