Esempio n. 1
0
def get_overlap_lalo(atr1, atr2):
    """Find overlap area in lat/lon of two geocoded files
    Inputs:
        atr1/2 - dict, attribute dictionary of two input files in geo coord
    Outputs:
        W/E/S/N - float, West/East/South/North in deg 
    """
    W1, E1, S1, N1 = ut.four_corners(atr1)
    W2, E2, S2, N2 = ut.four_corners(atr2)

    west = max(W1, W2)
    east = min(E1, E2)
    north = min(N1, N2)
    south = max(S1, S2)

    return west, east, south, north
Esempio n. 2
0
def write_kmz_file(data, metadata, out_file, inps=None):
    """ Generate Google Earth KMZ file for input data matrix.
    Inputs:
        data - 2D np.array in int/float, data matrix to write
        out_file - string, output file name
        metadata  - dict, containing the following attributes:
               WIDTH/LENGTH      : required, file size
               X/Y_FIRST/STEP    : required, for lat/lon spatial converage
               ref_x/y           : optional, column/row number of reference pixel
               PROJECT_NAME      : optional, for KMZ folder name
        inps - Namespace, optional, input options for display
    Output:
        kmz_file - string, output KMZ filename
    Example:
        from pysar.utils import readfile, plot as pp
        from pysar import save_kml
        fname = 'geo_velocity_masked.h5'
        data, atr = readfile.read(fname)
        out_file = pp.auto_figure_title(fname, None)+'.kmz'
        save_kml.write_kmz_file(data, atr, out_file)
    """
    if not inps:
        inps = cmd_line_parse()

    if not inps.ylim:
        inps.ylim = [np.nanmin(data), np.nanmax(data)]

    west, east, south, north = ut.four_corners(metadata)

    # 2.1 Make PNG file - Data
    print('plotting data ...')

    # Figure size
    if not inps.fig_size:
        plot_shape = [east - west, north - south]
        fig_scale = min(pp.min_figsize_single / min(plot_shape),
                        pp.max_figsize_single / max(plot_shape),
                        pp.max_figsize_height / plot_shape[1])
        inps.fig_size = [np.floor(i * fig_scale * 2) / 2 for i in plot_shape]
    print('create figure in size: ' + str(inps.fig_size))
    fig = plt.figure(figsize=inps.fig_size, frameon=False)
    ax = fig.add_axes([0., 0., 1., 1.])
    ax.set_axis_off()

    print('colormap: ' + inps.colormap)
    inps.colormap = plt.get_cmap(inps.colormap)

    # Plot - data matrix
    ax.imshow(data,
              cmap=inps.colormap,
              vmin=inps.ylim[0],
              vmax=inps.ylim[1],
              aspect='auto',
              interpolation='nearest')

    # Plot - reference pixel
    if inps.disp_seed == 'yes':
        try:
            xref = int(metadata['REF_X'])
            yref = int(metadata['REF_Y'])
            ax.plot(xref, yref, 'ks', ms=inps.seed_size)
            print('show reference point')
        except:
            inps.disp_seed = False
            print('Cannot find reference point info!')

    width = int(metadata['WIDTH'])
    length = int(metadata['LENGTH'])
    ax.set_xlim([0, width])
    ax.set_ylim([length, 0])

    out_name_base = os.path.splitext(out_file)[0]
    data_png_file = out_name_base + '.png'
    print('writing {} with dpi={}'.format(data_png_file, inps.fig_dpi))
    plt.savefig(data_png_file,
                pad_inches=0.0,
                transparent=True,
                dpi=inps.fig_dpi)

    # 2.2 Making PNG file - colorbar
    pc = plt.figure(figsize=(1, 8))
    cax = pc.add_subplot(111)
    norm = mpl.colors.Normalize(vmin=inps.ylim[0], vmax=inps.ylim[1])
    cbar = mpl.colorbar.ColorbarBase(cax,
                                     cmap=inps.colormap,
                                     norm=norm,
                                     orientation='vertical')

    cbar.set_label('{} [{}]'.format(inps.cbar_label, inps.disp_unit))
    cbar.locator = mpl.ticker.MaxNLocator(nbins=inps.cbar_bin_num)
    cbar.update_ticks()

    pc.subplots_adjust(left=0.2, bottom=0.3, right=0.4, top=0.7)
    pc.patch.set_facecolor('white')
    pc.patch.set_alpha(0.7)

    cbar_png_file = '{}_cbar.png'.format(out_name_base)
    print('writing ' + cbar_png_file)
    pc.savefig(cbar_png_file,
               bbox_inches='tight',
               facecolor=pc.get_facecolor(),
               dpi=inps.fig_dpi)

    # 2.3 Generate KML file
    print('generating kml file ...')
    try:
        doc = KML.kml(KML.Folder(KML.name(metadata['PROJECT_NAME'])))
    except:
        doc = KML.kml(KML.Folder(KML.name('PySAR product')))

    # Add data png file
    slc = KML.GroundOverlay(
        KML.name(data_png_file), KML.Icon(KML.href(data_png_file)),
        KML.altitudeMode('clampToGround'),
        KML.LatLonBox(KML.north(str(north)), KML.east(str(east)),
                      KML.south(str(south)), KML.west(str(west))))
    doc.Folder.append(slc)

    # Add colorbar png file
    cb_rg = min(north - south, east - west)
    cb_N = (north + south) / 2.0 + 0.5 * 0.5 * cb_rg
    cb_W = east + 0.1 * cb_rg

    # Use mean height from existed DEM file
    if not inps.cbar_height:
        try:
            fileList = [
                'geo_geometry*.h5', 'INPUTS/geometry*.h5', 'dem*.h5', '*.dem',
                'radar*.hgt'
            ]
            dem_file = ut.get_file_list(fileList)[0]
            print('use mean height from file: {} + 1000 m as colorbar height.'.
                  format(dem_file))
            dem_data = readfile.read(dem_file, datasetName='height')[0]
            inps.cbar_height = np.rint(np.nanmean(dem_data)) + 1000.0
        except:
            pass
    elif str(inps.cbar_height).lower().endswith('ground'):
        inps.cbar_height = None

    if inps.cbar_height:
        print('set colorbar in height: %.2f m' % inps.cbar_height)
        slc1 = KML.GroundOverlay(
            KML.name('colorbar'), KML.Icon(KML.href(cbar_png_file)),
            KML.altitude(str(inps.cbar_height)), KML.altitudeMode('absolute'),
            KML.LatLonBox(KML.north(str(cb_N)),
                          KML.south(str(cb_N - 0.5 * cb_rg)),
                          KML.west(str(cb_W)),
                          KML.east(str(cb_W + 0.14 * cb_rg))))
    else:
        print('set colorbar clampToGround')
        slc1 = KML.GroundOverlay(
            KML.name('colorbar'), KML.Icon(KML.href(cbar_png_file)),
            KML.altitudeMode('clampToGround'),
            KML.LatLonBox(KML.north(str(cb_N)),
                          KML.south(str(cb_N - 0.5 * cb_rg)),
                          KML.west(str(cb_W)),
                          KML.east(str(cb_W + 0.14 * cb_rg))))
    doc.Folder.append(slc1)
    kmlstr = etree.tostring(doc, pretty_print=True).decode('utf8')

    # Write KML file
    kml_file = '{}.kml'.format(out_name_base)
    print('writing ' + kml_file)
    with open(kml_file, 'w') as f:
        f.write(kmlstr)

    # 2.4 Generate KMZ file
    kmz_file = '{}.kmz'.format(out_name_base)
    cmdKMZ = 'zip {} {} {} {}'.format(kmz_file, kml_file, data_png_file,
                                      cbar_png_file)
    print('writing {}\n{}'.format(kmz_file, cmdKMZ))
    os.system(cmdKMZ)

    cmdClean = 'rm {} {} {}'.format(kml_file, data_png_file, cbar_png_file)
    print(cmdClean)
    os.system(cmdClean)

    return kmz_file