예제 #1
0
    def kml_overlay(self):
        url = urlparse.urljoin( options.baseurl, '/'.join( str(t) for t in (self.level, self.col, self.row) ) + "."+self.filetype )

        goverlay = KML.GroundOverlay()
        goverlay.Region = self.kml_region()
        goverlay.drawOrder = KML.drawOrder(self.level * DEFAULT_DRAW_ORDER_FACTOR)
        goverlay.Icon = KML.Icon(KML.href(url))
        goverlay.LatLonBox = self.latlonbox()


        assert_valid(goverlay)
        return goverlay
예제 #2
0
def overlay_for_tile(tile):
    goverlay = KML.GroundOverlay()
    goverlay.Region = TileRegion(tile.level, BBox(tile.col, tile.row, 1, 1)).kml_region()
    goverlay.LatLonBox = tile.latlonbox()
    goverlay.drawOrder = KML.drawOrder(tile.level * DEFAULT_DRAW_ORDER_FACTOR)

    url = urlparse.urljoin( options.baseurl, '/'.join( str(t) for t in (tile.level, tile.col, tile.row) ) + "."+tile.filetype )
    icon = factory.CreateIcon()
    icon.set_href( str(url) )
    goverlay.set_icon( icon )

    assert_valid(goverlay)
    return goverlay
예제 #3
0
def writeKML(file, img, colorbarImg,inps):
  South, North, West, East = get_lat_lon(file)  
  ############## Generate kml file
  print ('generating kml file')
  doc = KML.kml(KML.Folder(KML.name(os.path.basename(file))))
  slc = KML.GroundOverlay(KML.name(os.path.basename(img)),KML.Icon(KML.href(os.path.basename(img))),\
                          KML.TimeSpan(KML.begin(),KML.end()),\
                          KML.LatLonBox(KML.north(str(North)),KML.south(str(South)),\
                                        KML.east(str(East)),  KML.west(str(West))))
  doc.Folder.append(slc)

  #############################
  print ('adding colorscale')
  latdel = North-South
  londel = East-West
  
  slc1   = KML.ScreenOverlay(KML.name('colorbar'),KML.Icon(KML.href(os.path.basename(colorbarImg))),
        KML.overlayXY(x="0.0",y="1",xunits="fraction",yunits="fraction",),
        KML.screenXY(x="0.0",y="1",xunits="fraction",yunits="fraction",),
        KML.rotationXY(x="0.",y="1.",xunits="fraction",yunits="fraction",),
        KML.size(x="0",y="0.3",xunits="fraction",yunits="fraction",),
      )


  doc.Folder.append(slc1)

  

  #############################
  from lxml import etree
  kmlstr = etree.tostring(doc, pretty_print=True)
  print (kmlstr)
  kmlname = file + '.kml'
  print ('writing '+kmlname)
  kmlfile = open(kmlname,'wb')
  kmlfile.write(kmlstr)
  kmlfile.close()

  kmzName = file + '.kmz'
  print ('writing '+kmzName)
  cmdKMZ = 'zip ' + kmzName +' '+ os.path.basename(kmlname) +' ' + os.path.basename(img) + ' ' + os.path.basename(colorbarImg)
  os.system(cmdKMZ)
예제 #4
0
def save_kml(dirname, png_file, north, south, east, west, data_desc):

    llbox = KML.LatLonBox(KML.north(north), KML.south(south), KML.east(east),
                          KML.west(west))
    icon = KML.Icon(href=png_file)
    grnd = KML.GroundOverlay(KML.name(png_file), KML.description(data_desc),
                             icon, llbox)
    fld = KML.Folder(KML.name("GPM Validation Network"),
                     KML.description("Rain Rate"), grnd)

    #print(etree.tostring(fld, pretty_print=True).decode('UTF-8'))
    objectify.deannotate(fld, cleanup_namespaces=True)

    out_fn = dirname + '/' + png_file + '.kml'
    with open(out_fn, "w") as f:
        print('<?xml version="1.0" encoding="UTF-8"?>' + '\n' +
              etree.tostring(fld, pretty_print=True).decode('UTF-8'),
              file=f)

    return out_fn
예제 #5
0
bg_hex = [a + b for a, b in zip(b_hex, g_hex)]
print bg_hex
bgr_hex = [a + b for a, b in zip(bg_hex, r_hex)]
hex_points = bgr_hex

# create a document element with a single label style
kmlobj = KML.kml(KML.Document(KML.Style(KML.LabelStyle(KML.scale(6)), )))

kmlobj.Document.append(
    KML.GroundOverlay(
        KML.name("Large-scale overlay on terrain"),
        KML.visibility("1"),
        KML.Icon(
            KML.href(
                "http://gdata1.sci.gsfc.nasa.gov/daac-bin/G3/giovanni-wmx.cgi?SERVICE=WMS&WMTVER=1.0.0&REQUEST=GetMap&SRS=EPSG:4326&EXCEPTIONS=INIMAGE&LAYERS=MAMO_CHLO_4km.CR::l3m_data:max=30.0:min=0.05&STYLES=latlonplot:top=surface:bottom=surface:ctype=predefined:palette=Rainbow&BBOX=107.400,-24.000,177.600,17.400&TIME=2012-01-01T00:00:00Z/2012-02-01T00:00:00Z&FORMAT=GIF&transparent=true&WIDTH=800&HEIGHT=400"
            ), ),
        KML.LatLonBox(
            KML.north("17.400"),
            KML.south("-24.000"),
            KML.east("177.600"),
            KML.west("107.400"),
        ),
    ), )

kmlobj.Document.append(
    KML.ScreenOverlay(
        KML.name("Background colour bar"),
        KML.visibility("1"),
        KML.Icon(
            KML.href("l3m_data_MAMO_CHLO_4km_CR_AreaMap_2012-01_cb.png"), ),
        KML.overlayXY(
            x="0",
예제 #6
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()

    if not inps.vlim:
        inps.vlim = [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 = [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()

    inps.colormap = pp.check_colormap_input(metadata, inps.colormap)
    # 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
    print('generating 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)
    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
    # 2) zip all data files
    # 3) go back to the working directory
    kmz_file = '{}.kmz'.format(out_name_base)
    cmd = 'cd {d1}; zip {fz} {fl} {fd} {fc}; cd {d2}'.format(
        d1=os.path.abspath(os.path.dirname(kmz_file)),
        fz=os.path.basename(kmz_file),
        fl=os.path.basename(kml_file),
        fd=os.path.basename(data_png_file),
        fc=os.path.basename(cbar_file),
        d2=os.getcwd())
    print(cmd)
    os.system(cmd)
    print('finished wirting to {}'.format(kmz_file))

    cmd = 'rm {} {} {}'.format(kml_file, data_png_file, cbar_file)
    print(cmd)
    os.system(cmd)

    return kmz_file
예제 #7
0
                          loss,
                          fig,
                          ax,
                          plot_legend=False,
                          plot_points=False)

            plt.show()
            fig.savefig('coverage.png', dpi=300)

            kml = KML.Folder(
                KML.name("RF Coverage"),
                KML.GroundOverlay(
                    KML.name("{},{} - {} km".format(
                        latitude, longitude, max_distance_meters / 1000.0)),
                    KML.Icon(KML.href('coverage.png')),
                    KML.color('b0ffffff'),  #first value is alpha, ff=opaque 
                    KML.LatLonBox(KML.north(area.bounds[1]),
                                  KML.south(area.bounds[3]),
                                  KML.east(area.bounds[2]),
                                  KML.west(area.bounds[0]))),
                KML.Placemark(
                    KML.name('Basestation'),
                    KML.Point(
                        KML.extrude(1), KML.altitudeMode('relativeToGround'),
                        KML.coordinates("{}, {}".format(longitude,
                                                        latitude)))))
            s = etree.tostring(kml, pretty_print=True)
            with open('coverage.kml', 'wb') as f:
                f.write(s)

        else:
예제 #8
0
def write_kmz_overlay(data, meta, out_file, inps):
    """Generate Google Earth Overlay KMZ file for data in GEO coordinates.
    Parameters: data     - 2D np.array in int/float, data matrix to write
                meta     - 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
                out_file - string, output file name
                inps     - Namespace, optional, input options for display
    Returns:    kmz_file - string, output KMZ filename
    """

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

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

    # Figure size
    if not inps.fig_size:
        inps.fig_size = pp.auto_figure_size(
            ds_shape=[north - south, east - west], scale=2.0)
    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,
              vmin=inps.vlim[0],
              vmax=inps.vlim[1],
              cmap=inps.colormap,
              aspect='auto',
              interpolation='nearest')

    # Plot - reference pixel
    rx = meta.get('REF_X', None)
    ry = meta.get('REF_Y', None)
    if inps.disp_ref_pixel and rx is not None and ry is not None:
        ax.plot(int(rx),
                int(ry),
                inps.ref_marker,
                color=inps.ref_marker_color,
                ms=inps.ref_marker_size)
        print('show reference point')
    else:
        print('no plot for reference point.')

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

    out_file_base = os.path.splitext(out_file)[0]
    data_png_file = out_file_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. Generate KML file
    kml_doc = KML.Document()

    # Add data png file
    img_name = os.path.splitext(os.path.basename(data_png_file))[0]
    img_overlay = 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)),
        ),
    )
    kml_doc.append(img_overlay)

    # Add colorbar png file
    cbar_file = '{}_cbar.png'.format(out_file_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,
    )
    kml_doc.append(cbar_overlay)

    # Write KML file
    kmz_file = write_kmz_file(
        out_file_base,
        kml_doc,
        data_files=[data_png_file, cbar_file],
        keep_kml_file=inps.keep_kml_file,
    )

    return kmz_file
예제 #9
0
파일: save_kml.py 프로젝트: zyh900908/PySAR
def write_kmz_file(data, atr, out_name_base, inps=None):
    ''' Generate Google Earth KMZ file for input data matrix.
    Inputs:
        data - 2D np.array in int/float, data matrix to write
        out_name_base - string, output file name base
        atr  - dict, containing the following attributes:
               WIDTH/FILE_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:
        import pysar._readfile as readfile
        import pysar.view as pview
        import pysar.save_kml as save_kml
        fname = 'geo_velocity_masked.h5'
        data, atr = readfile.read(fname)
        out_name_base = pview.auto_figure_title(fname, None)
        save_kml.write_kmz_file(data, atr, out_name_base)
    '''
    if not inps:
        inps = cmdLineParse()

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

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

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

    # Figure size
    if not inps.fig_size:
        fig_scale = min(pysar.figsize_single_min/min(data.shape),\
                        pysar.figsize_single_max/max(data.shape))
        inps.fig_size = [np.rint(i * fig_scale * 2) / 2 for i in data.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,
              aspect='auto',
              cmap=inps.colormap,
              vmin=inps.ylim[0],
              vmax=inps.ylim[1])

    # Plot - reference pixel
    if inps.disp_seed == 'yes':
        try:
            xref = int(atr['ref_x'])
            yref = int(atr['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(atr['WIDTH'])
    length = int(atr['FILE_LENGTH'])
    ax.set_xlim([0, width])
    ax.set_ylim([length, 0])

    data_png_file = out_name_base + '.png'
    print 'writing ' + data_png_file
    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(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 = out_name_base + '_cbar.png'
    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(atr['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

    if 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:
        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)

    # Write KML file
    kmlstr = etree.tostring(doc, pretty_print=True)
    kml_file = out_name_base + '.kml'
    print 'writing ' + kml_file
    f = open(kml_file, 'w')
    f.write(kmlstr)
    f.close()

    ## 2.4 Generate KMZ file
    kmz_file = out_name_base + '.kmz'
    print 'writing ' + kmz_file
    cmdKMZ = 'zip ' + kmz_file + ' ' + kml_file + ' ' + data_png_file + ' ' + cbar_png_file
    os.system(cmdKMZ)

    cmdClean = 'rm ' + kml_file
    print cmdClean
    os.system(cmdClean)
    cmdClean = 'rm ' + data_png_file
    print cmdClean
    os.system(cmdClean)
    cmdClean = 'rm ' + cbar_png_file
    print cmdClean
    os.system(cmdClean)

    return kmz_file
예제 #10
0
     KML.name("Ground Overlays"),
     KML.visibility("0"),
     KML.description("Examples of ground overlays"),
     KML.GroundOverlay(
         KML.name("Large-scale overlay on terrain"),
         KML.visibility("0"),
         KML.description(
             "Overlay shows Mount Etna erupting on July 13th, 2001."),
         KML.LookAt(
             KML.longitude("15.02468937557116"),
             KML.latitude("37.67395167941667"),
             KML.altitude("0"),
             KML.heading("-16.5581842842829"),
             KML.tilt("58.31228652890705"),
             KML.range("30350.36838438907"),
         ),
         KML.Icon(
             KML.href(
                 "http://code.google.com/apis/kml/documentation/etna.jpg"
             ), ),
         KML.LatLonBox(
             KML.north("37.91904192681665"),
             KML.south("37.46543388598137"),
             KML.east("15.35832653742206"),
             KML.west("14.60128369746704"),
             KML.rotation("-0.1556640799496235"),
         ),
     ),
 ),
 KML.Folder(
     KML.name("Screen Overlays"),
예제 #11
0
파일: save_kml.py 프로젝트: wuweh/PySAR
def main(argv):

    color_map = 'jet'
    disp_opposite = 'no'
    disp_colorbar = 'yes'
    rewrapping = 'no'
    dpi = 500

    if len(sys.argv) > 2:
        try:
            opts, args = getopt.getopt(argv, "f:m:M:d:c:w:i:r:")
        except getopt.GetoptError:
            Usage()
            sys.exit(1)

        for opt, arg in opts:
            if opt == '-f': File = arg
            elif opt == '-m': Vmin = float(arg)
            elif opt == '-M': Vmax = float(arg)
            elif opt == '-d': epoch_date = arg
            elif opt == '-c': color_map = arg
            elif opt == '-i': disp_opposite = arg
            elif opt == '-w': rewrapping = arg
            elif opt == '-r': dpi = int(arg)

    elif len(sys.argv) == 2:
        if argv[0] == '-h':
            Usage()
            sys.exit(1)
        elif os.path.isfile(argv[0]):
            File = argv[0]
        else:
            Usage()
            sys.exit(1)
    else:
        Usage()
        sys.exit(1)

    #######################################################
    ###################  Prepare Data  ####################
    ## prepare: data, North, East, South, West

    import matplotlib.pyplot as plt
    ext = os.path.splitext(File)[1]
    map = plt.get_cmap(color_map)

    if ext == '.h5':
        import h5py
        try:
            h5file = h5py.File(File, 'r')
        except:
            Usage()
            sys.exit(1)
        outName = File.split('.')[0]

        k = h5file.keys()
        if 'interferograms' in k: k[0] = 'interferograms'
        elif 'coherence' in k: k[0] = 'coherence'
        elif 'timeseries' in k: k[0] = 'timeseries'
        if k[0] in ('interferograms', 'coherence', 'wrapped'):
            atr = h5file[k[0]][h5file[k[0]].keys()[0]].attrs
        elif k[0] in ('dem', 'velocity', 'mask', 'temporal_coherence', 'rmse',
                      'timeseries'):
            atr = h5file[k[0]].attrs
        print 'Input file is ' + k[0]

        if k[0] in ('interferograms', 'wrapped', 'coherence'):
            ifgramList = h5file[k[0]].keys()
            for i in range(len(ifgramList)):
                if epoch_date in ifgramList[i]:
                    epoch_number = i
            print ifgramList[epoch_number]
            outName = ifgramList[epoch_number]
            #outName=epoch_date

            dset = h5file[k[0]][ifgramList[epoch_number]].get(
                ifgramList[epoch_number])
            data = dset[0:dset.shape[0], 0:dset.shape[1]]

            if k[0] == 'wrapped':
                print 'No wrapping for wrapped interferograms. Set rewrapping=no'
                rewrapping = 'no'
                Vmin = -np.pi
                Vmax = np.pi

        elif 'timeseries' in k:
            epochList = h5file['timeseries'].keys()
            for i in range(len(epochList)):
                if epoch_date in epochList[i]:
                    epoch_number = i

            #### Out name
            ref_date = h5file['timeseries'].attrs['ref_date']
            if len(epoch_date) == 8:
                outName = ref_date[2:] + '-' + epoch_date[2:]
            else:
                outName = ref_date[2:] + '-' + epoch_date

            dset = h5file['timeseries'].get(epochList[epoch_number])
            data = dset[0:dset.shape[0], 0:dset.shape[1]]

        ### one dataset format: velocity, mask, temporal_coherence, rmse, std, etc.
        else:
            dset = h5file[k[0]].get(k[0])
            data = dset[0:dset.shape[0], 0:dset.shape[1]]
            if disp_opposite in ('yes', 'Yes', 'Y', 'y', 'YES'):
                data = -1 * data

            try:
                xref = h5file[k[0]].attrs['ref_x']
                yref = h5file[k[0]].attrs['ref_y']
            except:
                pass

    elif ext in ['.unw', '.cor', '.hgt', '.trans', '.dem']:
        import pysar._readfile as readfile
        if ext in ['.unw', '.cor', '.hgt', '.trans']:
            a, data, atr = readfile.read_float32(File)
            outName = File
        elif ext == '.dem':
            data, atr = readfile.read_dem(File)
            outName = File
    else:
        sys.exit('Do not support ' + ext + ' file!')

    ########################################################

    if rewrapping == 'yes':
        data = rewrap(data)
        Vmin = -np.pi  #[-pi,pi] for wrapped interferograms
        Vmax = np.pi
    else:
        try:
            Vmin
        except:
            Vmin = np.nanmin(data)
        try:
            Vmax
        except:
            Vmax = np.nanmax(data)

    try:
        lon_step = float(atr['X_STEP'])
        lat_step = float(atr['Y_STEP'])
        lon_unit = atr['Y_UNIT']
        lat_unit = atr['X_UNIT']
        West = float(atr['X_FIRST'])
        North = float(atr['Y_FIRST'])
        South = North + lat_step * (data.shape[0] - 1)
        East = West + lon_step * (data.shape[1] - 1)
        geocoord = 'yes'
        print 'Input file is Geocoded.'
    except:
        print '%%%%%%%%%%'
        print 'Error:\nThe input file is not geocoded\n'
        print '%%%%%%%%%%'
        Usage()
        sys.exit(1)

#######################################################
###################  Output KMZ  ######################

############### Make PNG file
    print 'Making png file ...'
    length = data.shape[0]
    width = data.shape[1]
    fig = plt.figure()
    fig = plt.figure(frameon=False)
    # fig.set_size_inches(width/1000,length/1000)
    ax = plt.Axes(
        fig,
        [0., 0., 1., 1.],
    )
    ax.set_axis_off()
    fig.add_axes(ax)

    aspect = width / (length * 1.0)
    # ax.imshow(data,aspect='normal')

    try:
        ax.imshow(data, aspect='normal', vmax=Vmax, vmin=Vmin)
    except:
        ax.imshow(data, aspect='normal')

    ax.set_xlim([0, width])
    ax.set_ylim([length, 0])

    # figName = k[0]+'.png'
    figName = outName + '.png'
    plt.savefig(figName, pad_inches=0.0, dpi=dpi)
    # plt.show()

    ############### Making colorbar
    pc = plt.figure(figsize=(1, 4))
    axc = pc.add_subplot(111)
    cmap = mpl.cm.jet
    norm = mpl.colors.Normalize(vmin=Vmin * 1000, vmax=Vmax * 1000)
    clb = mpl.colorbar.ColorbarBase(axc,
                                    cmap=cmap,
                                    norm=norm,
                                    orientation='vertical')
    clb.set_label('mm/yr')
    pc.subplots_adjust(left=0.25, bottom=0.1, right=0.4, top=0.9)
    pc.savefig('colorbar.png', transparent=True, dpi=300)

    ############## Generate KMZ file
    print 'generating kml file'
    doc = KML.kml(KML.Folder(KML.name('PySAR product')))
    slc = KML.GroundOverlay(KML.name(figName),KML.Icon(KML.href(figName)),\
                            KML.TimeSpan(KML.begin('2003'),KML.end('2010')),\
                            KML.LatLonBox(KML.north(str(North)),KML.south(str(South)),\
                                          KML.east(str(East)),  KML.west(str(West))))
    doc.Folder.append(slc)

    #############################
    print 'adding colorscale'
    latdel = North - South
    londel = East - West
    slc1   = KML.GroundOverlay(KML.name('colorbar'),KML.Icon(KML.href('colorbar.png')),\
                               KML.altitude('9000'),KML.altitudeMode('absolute'),\
                               KML.LatLonBox(KML.north(str(North-latdel/2.+0.5)),KML.south(str(South+latdel/2.0-0.5)),\
                                             KML.east(str(West-0.2*londel)),     KML.west(str(West-0.4*londel))))
    doc.Folder.append(slc1)

    #############################
    from lxml import etree
    kmlstr = etree.tostring(doc, pretty_print=True)
    # kmlname=k[0]+'.kml'
    kmlname = outName + '.kml'
    print 'writing ' + kmlname
    kmlfile = open(kmlname, 'w')
    kmlfile.write(kmlstr)
    kmlfile.close()

    # kmzName = k[0]+'.kmz'
    kmzName = outName + '.kmz'
    print 'writing ' + kmzName
    # cmdKMZ = 'zip ' + kmzName +' '+ kmlname +' ' + figName
    cmdKMZ = 'zip ' + kmzName + ' ' + kmlname + ' ' + figName + ' colorbar.png'
    os.system(cmdKMZ)

    cmdClean = 'rm ' + kmlname
    os.system(cmdClean)
    cmdClean = 'rm ' + figName
    os.system(cmdClean)
    cmdClean = 'rm colorbar.png'
    os.system(cmdClean)
예제 #12
0
파일: save_kml.py 프로젝트: whigg/PySAR
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
예제 #13
0
def main(argv):
    plt.switch_backend('Agg')

    cbar_bin_num  = 9
    cbar_label    = 'Mean LOS velocity'
    color_map     = 'jet'
    data_alpha    = 0.7
    disp_opposite = 'no'
    disp_colorbar = 'yes'
    rewrapping    = 'no'
    fig_dpi       = 500
    #fig_size      = [6.0,9.0]
    fig_unit      = 'mm/yr'
    disp_ref      = 'yes'
    ref_size      = 5
    dispDisplacement = 'no'

    if len(sys.argv)>2:
        try:   opts, args = getopt.getopt(argv,"f:m:M:d:c:w:i:r:",['noreference','fig-size',\
                                               'ref-size=','cbar-label=','displacement','cbar-bin-num='])
        except getopt.GetoptError:  usage() ; sys.exit(1)

        for opt,arg in opts:
            if   opt == '-f':        File = arg
            elif opt == '-m':        Vmin = float(arg)
            elif opt == '-M':        Vmax = float(arg)
            elif opt == '-d':        epoch_date    = arg
            elif opt == '-c':        color_map     = arg
            elif opt == '-i':        disp_opposite = arg
            elif opt == '-w':        rewrapping    = arg
            elif opt == '-r':        fig_dpi = int(arg)
            elif opt == '--cbar-bin-num' :   cbar_bin_num     = int(arg)
            elif opt == '--cbar-label'   :   cbar_label       = arg
            elif opt == '--displacement' :   dispDisplacement = 'yes'
            elif opt == '--fig-size'     :   fig_size = [float(i) for i in arg.split(',')][0:2]
            elif opt == '--ref-size'     :   ref_size = int(arg)
            elif opt == '--noreference'  :   disp_ref = 'no'

    elif len(sys.argv)==2:
        if argv[0]=='-h':               usage(); sys.exit(1)
        elif os.path.isfile(argv[0]):   File = argv[0]
        else:                           usage(); sys.exit(1)
    else:                             usage(); sys.exit(1)

    #######################################################
    ###################  Prepare Data  ####################
    ## prepare: data, North, East, South, West

    ext = os.path.splitext(File)[1].lower()
    atr = readfile.read_attribute(File)
    k = atr['FILE_TYPE']
    #print '\n*************** Output to KMZ file ****************'
    print 'Input file is '+k

    if ext == '.h5':
        try:      h5file=h5py.File(File,'r')
        except:   usage() ; sys.exit(1)
        outName=File.split('.')[0]

        if k in ('interferograms','wrapped','coherence'):
            ifgramList=h5file[k].keys()
            for i in range(len(ifgramList)):
                if epoch_date in ifgramList[i]:
                    epoch_number = i
            print ifgramList[epoch_number]
            outName = ifgramList[epoch_number]
            #outName=epoch_date

            dset = h5file[k][ifgramList[epoch_number]].get(ifgramList[epoch_number])
            data = dset[0:dset.shape[0],0:dset.shape[1]]

            if k == 'wrapped':
                print 'No wrapping for wrapped interferograms. Set rewrapping=no'
                rewrapping = 'no'
                Vmin = -np.pi    
                Vmax = np.pi

        elif 'timeseries' in k:
            epochList=h5file['timeseries'].keys()
            for i in range(len(epochList)):
                if epoch_date in epochList[i]:
                    epoch_number = i

            #### Out name
            try:    ref_date = atr['ref_date']
            except: ref_date = ut.yyyymmdd(atr['DATE'])[0]
            #ref_date=h5file['timeseries'].attrs['ref_date']
            if len(epoch_date)==8:  outName=ref_date[2:]+'-'+epoch_date[2:]
            else:                   outName=ref_date[2:]+'-'+epoch_date

            dset = h5file['timeseries'].get(epochList[epoch_number])
            data = dset[0:dset.shape[0],0:dset.shape[1]]

        ### one dataset format: velocity, mask, temporal_coherence, rmse, std, etc.
        else:
            dset = h5file[k].get(k)
            data=dset[0:dset.shape[0],0:dset.shape[1]]
            if disp_opposite in('yes','Yes','Y','y','YES'):
                data=-1*data

            try:
                xref=h5file[k].attrs['ref_x']
                yref=h5file[k].attrs['ref_y']
            except: pass

    elif ext in ['.unw','.cor','.hgt','.trans','.dem']:
        if   ext in ['.unw','.cor','.hgt','.trans']:
            a,data,atr = readfile.read_float32(File)
            outName = File
            if ext in ['.unw']:
                if dispDisplacement == 'yes':
                    print 'show displacement'
                    phase2range = -float(atr['WAVELENGTH']) / (4*np.pi)
                    data *= phase2range
                    atr['UNIT'] = 'm'
                    rewrapping == 'no'
                    fig_unit = 'mm'
                if rewrapping == 'yes':
                    data = rewrap(data,atr)
                    fig_unit = 'radian'
        elif ext == '.dem':
            data,atr = readfile.read_real_int16(File)
            outName = File
        if   ext in ['.hgt','.dem']:     fig_unit = 'm'
        elif ext in ['.cor','.trans']:   fig_unit = ' '
    else: sys.exit('Do not support '+ext+' file!')


    ########################################################
    if rewrapping=='yes':
        data=rewrap(data)
        Vmin = -np.pi    #[-pi,pi] for wrapped interferograms
        Vmax =  np.pi
    else:
        try:     Vmin
        except:  Vmin = np.nanmin(data)
        try:     Vmax
        except:  Vmax = np.nanmax(data)

    try:
        lon_step = float(atr['X_STEP'])
        lat_step = float(atr['Y_STEP'])
        lon_unit = atr['Y_UNIT']
        lat_unit = atr['X_UNIT']
        West     = float(atr['X_FIRST'])
        North    = float(atr['Y_FIRST'])
        South    = North+lat_step*(data.shape[0]-1)
        East     = West +lon_step*(data.shape[1]-1)
        geocoord = 'yes'
        print 'Geocoded'
    except:
        print '%%%%%%%%%%'
        print 'Error:\nThe input file is not geocoded\n'
        print '%%%%%%%%%%'
        usage();sys.exit(1)


    #######################################################
    ###################  Output KMZ  ######################

    ############### Make PNG file
    print 'Making png file ...'   
    length = data.shape[0]
    width  = data.shape[1]
    try:fig_size
    except:
        fig_size_0 = 6.0           ## min figure dimension: 6.0
        ratio = float(length)/float(width)
        fig_size = [fig_size_0,fig_size_0*ratio]
    print 'figure size:  %.1f, %.1f'%(fig_size[0],fig_size[1])
    ccmap = plt.get_cmap(color_map)
    fig = plt.figure(figsize=fig_size,frameon=False)
    ax = fig.add_axes([0., 0., 1., 1.])
    ax.set_axis_off()

    aspect = width/(length*1.0)
    try:     ax.imshow(data,aspect='auto',cmap=ccmap,vmax=Vmax,vmin=Vmin)
    except:  ax.imshow(data,aspect='auto',cmap=ccmap)

    if disp_ref == 'yes':
        try:
            xref = int(atr['ref_x'])
            yref = int(atr['ref_y'])
            ax.plot(xref,yref,'ks',ms=ref_size)
            print 'show reference point'
        except: print 'Cannot find reference point info!'

    ax.set_xlim([0,width])
    ax.set_ylim([length,0])

    figName = outName + '.png'
    print 'writing '+figName
    plt.savefig(figName, pad_inches=0.0, transparent=True, dpi=fig_dpi)

    ############### Making colorbar
    pc = plt.figure(figsize=(1,8))
    axc = pc.add_subplot(111)
    if   fig_unit in ['mm','mm/yr']: v_scale = 1000
    elif fig_unit in ['cm','cm/yr']: v_scale = 100
    elif fig_unit in ['m',  'm/yr']: v_scale = 1
    norm = mpl.colors.Normalize(vmin=Vmin*v_scale, vmax=Vmax*v_scale)
    clb  = mpl.colorbar.ColorbarBase(axc,cmap=ccmap,norm=norm, orientation='vertical')

    #clb.set_label(fig_unit)
    clb.set_label(cbar_label+' ['+fig_unit+']')
    clb.locator = mpl.ticker.MaxNLocator(nbins=cbar_bin_num)
    clb.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)
    pc.savefig('colorbar.png',bbox_inches='tight',facecolor=pc.get_facecolor(),dpi=300)

    ############## Generate KMZ file
    print 'generating kml file ...'
    try:     doc = KML.kml(KML.Folder(KML.name(atr['PROJECT_NAME'])))
    except:  doc = KML.kml(KML.Folder(KML.name('PySAR product')))
    slc = KML.GroundOverlay(KML.name(figName),KML.Icon(KML.href(figName)),\
                            KML.altitudeMode('clampToGround'),\
                            KML.LatLonBox(KML.north(str(North)),KML.south(str(South)),\
                                          KML.east( str(East)), KML.west( str(West))))
    doc.Folder.append(slc)

    #############################
    print 'adding colorscale ...'
    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
    slc1 = KML.GroundOverlay(KML.name('colorbar'),KML.Icon(KML.href('colorbar.png')),\
                             KML.altitude('2000'),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))))
    doc.Folder.append(slc1)

    #############################
    kmlstr = etree.tostring(doc, pretty_print=True) 
    kmlname = outName + '.kml'
    print 'writing '+kmlname
    kmlfile = open(kmlname,'w')
    kmlfile.write(kmlstr)
    kmlfile.close()

    kmzName = outName + '.kmz'
    print 'writing '+kmzName
    cmdKMZ = 'zip ' + kmzName +' '+ kmlname +' ' + figName + ' colorbar.png'
    os.system(cmdKMZ)

    cmdClean = 'rm '+kmlname;      print cmdClean;    os.system(cmdClean)
    cmdClean = 'rm '+figName;      print cmdClean;    os.system(cmdClean)
    cmdClean = 'rm colorbar.png';  print cmdClean;    os.system(cmdClean)