Esempio n. 1
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 mintpy.utils import readfile, plot as pp
        from mintpy import save_kmz
        fname = 'geo_velocity_masked.h5'
        data, atr = readfile.read(fname)
        out_file = pp.auto_figure_title(fname, None)+'.kmz'
        save_kmz.write_kmz_file(data, atr, out_file)
    """
    if not inps:
        inps = cmd_line_parse()

    # disp min/max and colormap
    cmap_lut = 256
    if not inps.vlim:
        cmap_lut, inps.vlim = pp.auto_adjust_colormap_lut_and_disp_limit(data)
    inps.colormap = pp.auto_colormap_name(metadata, inps.colormap)
    inps.colormap = pp.ColormapExt(inps.colormap, cmap_lut).colormap

    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 = [2. * i * fig_scale 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()

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

    # Plot - reference pixel
    if inps.disp_ref_pixel:
        try:
            xref = int(metadata['REF_X'])
            yref = int(metadata['REF_Y'])
            ax.plot(xref,
                    yref,
                    inps.ref_marker,
                    color=inps.ref_marker_color,
                    ms=inps.ref_marker_size)
            print('show reference point')
        except:
            inps.disp_ref_pixel = 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.3 Generate KML file
    proj_name = metadata.get('PROJECT_NAME', 'InSAR_MintPy')
    doc = KML.kml(KML.Folder(KML.name(proj_name)))

    # Add data png file
    img_name = os.path.splitext(os.path.basename(data_png_file))[0]
    img = KML.GroundOverlay(
        KML.name(img_name),
        KML.Icon(KML.href(os.path.basename(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(img)

    # Add colorbar png file
    cbar_file = '{}_cbar.png'.format(out_name_base)
    cbar_overlay = generate_cbar_element(cbar_file,
                                         vmin=inps.vlim[0],
                                         vmax=inps.vlim[1],
                                         unit=inps.disp_unit,
                                         cmap=inps.colormap,
                                         loc=inps.cbar_loc,
                                         nbins=inps.cbar_bin_num,
                                         label=inps.cbar_label)
    doc.Folder.append(cbar_overlay)
    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, by
    # 1) go to the directory of kmz file
    run_dir = os.path.abspath(os.getcwd())
    os.chdir(os.path.abspath(os.path.dirname(out_file)))
    # 2) zip all data files
    kmz_file = '{}.kmz'.format(out_name_base)
    with ZipFile(kmz_file, 'w') as fz:
        for fname in [kml_file, data_png_file, cbar_file]:
            fz.write(os.path.relpath(fname))
            os.remove(fname)
    # 3) go back to the running directory
    os.chdir(run_dir)
    print('merged all files to {}'.format(kmz_file))
    return kmz_file
Esempio n. 2
0
def main(iargs=None):
    inps = cmd_line_parse(iargs)

    # 1. Read metadata and data
    k = readfile.read_attribute(inps.file)['FILE_TYPE']
    if k == 'timeseries' and inps.dset and '_' in inps.dset:
        inps.ref_date, inps.dset = inps.dset.split('_')
    else:
        inps.ref_date = None
    atr = readfile.read_attribute(inps.file, datasetName=inps.dset)

    # pix_box
    inps.pix_box = subset.subset_input_dict2box(vars(inps), atr)[0]
    inps.pix_box = ut.coordinate(atr).check_box_within_data_coverage(
        inps.pix_box)
    data_box = (0, 0, int(atr['WIDTH']), int(atr['LENGTH']))
    print('data   coverage in y/x: {}'.format(data_box))
    print('subset coverage in y/x: {}'.format(inps.pix_box))
    atr = attr.update_attribute4subset(atr, inps.pix_box)

    # read data
    data = readfile.read(inps.file, datasetName=inps.dset, box=inps.pix_box)[0]
    if k == 'timeseries' and inps.ref_date:
        data -= readfile.read(inps.file,
                              datasetName=inps.ref_date,
                              box=inps.pix_box)[0]

    # mask
    mask = pp.read_mask(inps.file,
                        mask_file=inps.mask_file,
                        datasetName=inps.dset,
                        box=inps.pix_box)[0]
    if mask is not None:
        print('masking out pixels with zero value in file: {}'.format(
            inps.mask_file))
        data[mask == 0] = np.nan
    if inps.zero_mask:
        print('masking out pixels with zero value')
        data[data == 0] = np.nan
    del mask

    # Data Operation - Display Unit & Rewrapping
    (data, inps.disp_unit, inps.disp_scale,
     inps.wrap) = pp.scale_data4disp_unit_and_rewrap(
         data,
         metadata=atr,
         disp_unit=inps.disp_unit,
         wrap=inps.wrap,
         wrap_range=inps.wrap_range)
    if inps.wrap:
        inps.vlim = inps.wrap_range

    # 2. Generate Google Earth KMZ
    # 2.1 Common settings
    # disp min/max and colormap
    cmap_lut = 256
    if not inps.vlim:
        cmap_lut, inps.vlim = pp.auto_adjust_colormap_lut_and_disp_limit(data)
    inps.colormap = pp.auto_colormap_name(atr, inps.colormap)
    inps.colormap = pp.ColormapExt(inps.colormap, cmap_lut).colormap
    inps.norm = colors.Normalize(vmin=inps.vlim[0], vmax=inps.vlim[1])

    # Output filename
    inps.fig_title = pp.auto_figure_title(inps.file,
                                          datasetNames=inps.dset,
                                          inps_dict=vars(inps))
    if not inps.outfile:
        inps.outfile = '{}.kmz'.format(inps.fig_title)
    inps.outfile = os.path.abspath(inps.outfile)

    # 2.2 Write KMZ file
    if 'Y_FIRST' in atr.keys():
        # create ground overlay KML for file in geo-coord
        write_kmz_overlay(
            data,
            meta=atr,
            out_file=inps.outfile,
            inps=inps,
        )

    else:
        # create placemark KML for file in radar-coord
        write_kmz_placemark(
            data,
            meta=atr,
            out_file=inps.outfile,
            geom_file=inps.geom_file,
            inps=inps,
        )

    return inps.outfile