Example #1
0
def create_ev_sta_kml(input_dics, events):
    """
    create event/station/ray in KML format readable by Google-Earth
    :param input_dics:
    :param events:
    :return:
    """
    try:
        from pykml.factory import KML_ElementMaker as KML
        from lxml import etree
    except:
        sys.exit('[ERROR] pykml should be installed first!')

    if not os.path.isdir('kml_dir'):
        os.mkdir('kml_dir')
    else:
        print('[INFO] kml_dir already exists!')

    # create a document element with multiple label style
    kmlobj = KML.kml(KML.Document())
    counter = 0
    for ei in range(len(events)):
        print(events[ei]['event_id'])
        counter += 1

        ev_date = '%04i/%02i/%02i-%02i:%02i:%02i' \
                  % (events[ei]['datetime'].year,
                     events[ei]['datetime'].month,
                     events[ei]['datetime'].day,
                     events[ei]['datetime'].hour,
                     events[ei]['datetime'].minute,
                     events[ei]['datetime'].second
                     )

        if input_dics['plot_focal']:
            try:
                focmecs = [float(events[ei]['focal_mechanism'][0]),
                           float(events[ei]['focal_mechanism'][1]),
                           float(events[ei]['focal_mechanism'][2]),
                           float(events[ei]['focal_mechanism'][3]),
                           float(events[ei]['focal_mechanism'][4]),
                           float(events[ei]['focal_mechanism'][5])]
            except:
                print("WARNING: 'focal_mechanism' does not exist!")
                focmecs = [1, 1, 1, 0, 0, 0]
        else:
            focmecs = [1, 1, 1, 0, 0, 0]

        if 0 <= events[ei]['depth'] < 70:
            event_color = 'red'
        elif 70 <= events[ei]['depth'] < 300:
            event_color = 'green'
        else:
            event_color = 'blue'

        try:
            Beachball(focmecs,
                      outfile=os.path.join(
                          'kml_dir', events[ei]['event_id'] + '.png'),
                      facecolor=event_color,
                      edgecolor=event_color)
        except Exception as error:
            print(error)
            print(focmecs)
            continue
        plt.close()
        plt.clf()

        if input_dics['plot_ev'] or input_dics['plot_ray']:
            kmlobj.Document.append(
                KML.Style(
                    KML.IconStyle(
                        KML.Icon(KML.href(os.path.join(
                            events[ei]['event_id'] + '.png')),
                        ),
                        KML.scale(events[ei]['magnitude']/2.),
                        KML.heading(0.0),
                    ),
                    id='beach_ball_%i' % counter
                ),
            )

            kmlobj.Document.append(
                KML.Placemark(
                    KML.name(events[ei]['event_id']),
                    KML.ExtendedData(
                        KML.Data(
                            KML.value('%s' % events[ei]['event_id']),
                            name='event_id'
                        ),
                        KML.Data(
                            KML.value('%s' % events[ei]['magnitude']),
                            name='magnitude'
                        ),
                        KML.Data(
                            KML.value('%s' % ev_date),
                            name='datetime'
                        ),
                        KML.Data(
                            KML.value('%s' % events[ei]['depth']),
                            name='depth'
                        ),
                        KML.Data(
                            KML.value('%s' % events[ei]['latitude']),
                            name='latitude'
                        ),
                        KML.Data(
                            KML.value('%s' % events[ei]['longitude']),
                            name='longitude'
                        ),
                    ),
                    KML.styleUrl('#beach_ball_%i' % counter),
                    # KML.Point(KML.coordinates(events[ei]['longitude'], ',',
                    #                           events[ei]['latitude'], ',',
                    #                           700000 -
                    #                           abs(events[ei]['depth']*1000)),
                    #           KML.altitudeMode('absolute')
                    #           ),
                    KML.Point(KML.coordinates(events[ei]['longitude'], ',',
                                              events[ei]['latitude'], ',',
                                              0.),
                              KML.altitudeMode('absolute')
                              ),
                ),
            )

        if input_dics['plot_sta'] or input_dics['plot_ray']:
            target_path = locate(input_dics['datapath'],
                                 events[ei]['event_id'])
            if len(target_path) < 1:
                continue
            if len(target_path) > 1:
                print("[LOCAL] more than one path was found for the event:")
                print(target_path)
                print("[INFO] use the first one:")
                target_path = target_path[0]
                print(target_path)
            else:
                print("[LOCAL] Path:")
                target_path = target_path[0]
                print(target_path)

            update_sta_ev_file(target_path, events[ei])
            sta_ev_arr = np.loadtxt(os.path.join(target_path,
                                                 'info', 'station_event'),
                                    delimiter=',', dtype=bytes, ndmin=2).astype(np.str)
            sta_ev_arr = sta_ev_arr.astype(np.object)
            del_index = []
            for sti in range(len(sta_ev_arr)):

                if not plot_filter_station(input_dics, sta_ev_arr[sti]):
                    del_index.append(sti)

                dist, azi, bazi = gps2DistAzimuth(events[ei]['latitude'],
                                                  events[ei]['longitude'],
                                                  float(sta_ev_arr[sti, 4]),
                                                  float(sta_ev_arr[sti, 5]))

                epi_dist = dist/111.194/1000.
                if input_dics['min_azi'] or input_dics['max_azi'] or \
                        input_dics['min_epi'] or input_dics['max_epi']:
                    if input_dics['min_epi']:
                        if epi_dist < input_dics['min_epi']:
                            del_index.append(sti)
                    if input_dics['max_epi']:
                        if epi_dist > input_dics['max_epi']:
                            del_index.append(sti)
                    if input_dics['min_azi']:
                        if azi < input_dics['min_azi']:
                            del_index.append(sti)
                    if input_dics['max_azi']:
                        if azi > input_dics['max_azi']:
                            del_index.append(sti)

            del_index = list(set(del_index))
            del_index.sort(reverse=True)
            for di in del_index:
                sta_ev_arr = np.delete(sta_ev_arr, (di), axis=0)

            kmlobj.Document.append(
                KML.Style(
                    KML.IconStyle(
                        KML.scale(2.5),
                        KML.heading(0.0),
                    ),
                    id='station'
                ),
            )
            kmlobj.Document.append(
                KML.Style(
                    KML.LineStyle(
                        KML.width(1.0),
                        # KML.color('ff33ccff'),
                        KML.color('2333ccff'),
                    ),
                    id='great_circle_distance'
                ),
            )
            for sti in sta_ev_arr:
                dist, azi, bazi = gps2DistAzimuth(events[ei]['latitude'],
                                                  events[ei]['longitude'],
                                                  float(sti[4]),
                                                  float(sti[5]))
                epi_dist = dist/111.194/1000.
                sta_id = '%s.%s.%s.%s' % (sti[0], sti[1], sti[2], sti[3])
                kmlobj.Document.append(
                    KML.Placemark(
                        KML.name(sta_id),
                        KML.ExtendedData(
                            KML.Data(
                                KML.value('%s' % sta_id),
                                name='StationID'
                            ),
                            KML.Data(
                                KML.value('%s' % epi_dist),
                                name='Distance'
                            ),
                            KML.Data(
                                KML.value('%s' % sti[6]),
                                name='Elevation'
                            ),
                            KML.Data(
                                KML.value('%s' % sti[7]),
                                name='Depth'
                            ),
                            KML.Data(
                                KML.value('%s' % bazi),
                                name='Back-Azimuth'
                            ),
                            KML.Data(
                                KML.value('%s' % azi),
                                name='Azimuth'
                            ),
                            KML.Data(
                                KML.value('%s' % events[ei]['event_id']),
                                name='EventID'
                            ),
                            KML.Data(
                                KML.value('%s' % sti[8]),
                                name='Source'
                            ),
                        ),
                        KML.styleUrl('station'),
                        KML.Point(KML.coordinates(
                            float(sti[5]), ',', float(sti[4]))
                        ),
                    ),
                )
                if input_dics['plot_ray']:
                    kmlobj.Document.append(
                        KML.Placemark(
                            KML.name(sta_id),
                            KML.ExtendedData(
                                KML.Data(
                                    KML.value('%s' % sta_id),
                                    name='StationID'
                                ),
                            ),
                            KML.styleUrl('great_circle_distance'),
                            KML.LineString(KML.coordinates(
                                '%s,%s,0\n'
                                '%s,%s,0' % (float(sti[5]),
                                             float(sti[4]),
                                             events[ei]['longitude'],
                                             events[ei]['latitude'])),
                                KML.tessellate(1)),
                        ),
                    )
    kml_outfile = file(os.path.join(
        'kml_dir',
        'kml_output.kml'), 'w')
    kml_outfile.write(etree.tostring(kmlobj, pretty_print=True))
    sys.exit('[INFO] KML file is stored in ./kml_dir!')
Example #2
0
    (575, 'http://maps.google.com/mapfiles/kml/shapes/schools.png', 1.2),
    # Lääni
    (580, 'http://maps.google.com/mapfiles/kml/shapes/schools.png', 1.2),
    # Erämaa-alue
    (630, 'http://maps.google.com/mapfiles/kml/shapes/parks.png'),
)

for styledef in STYLES:
    styleid = str(styledef[0])
    iconurl = styledef[1]
    if len(styledef) > 2:
        scale = str(styledef[2])
    else:
        scale = str(1.0)
    doc.append(
        KML.Style(KML.IconStyle(KML.Icon(KML.href(iconurl), KML.scale(scale))),
                  id=str(styleid)))

for binding in results.bindings:
    doc.append(
        KML.Placemark(
            KML.name(binding['label'].value),
            KML.description(binding['place'].value + "\n" +
                            binding['typelabel'].value),
            KML.styleUrl('#' + binding['placetype'].value[-3:]),
            KML.Point(
                KML.coordinates(
                    '%s,%s' % (binding['long'].value, binding['lat'].value)))))

print etree.tostring(etree.ElementTree(kml), pretty_print=True)
Example #3
0
    data.append({
        'datetime UTC': date,
        'azimuth_angle': sun.az.real,
        'altitude_angle': sun.alt.real,
    })

# create a KML file skeleton
stylename = "sn_shaded_dot"
doc = KML.kml(
    KML.Document(
        KML.Name("Sun Position"),
        KML.Style(
            KML.IconStyle(
                KML.scale(1.2),
                KML.Icon(
                    KML.href(
                        "http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png"
                    )),
            ),
            id=stylename,
        )))

# create placemark for the observer, and add it to the KML document
pm_observer = KML.Placemark(
    KML.name('Observer'),
    KML.styleUrl('#{0}'.format(stylename)),
    KML.Point(
        KML.extrude(True),
        KML.altitudeMode('relativeToGround'),
        KML.coordinates("{0},{1},{2}".format(longitude, latitude, height)),
    ),
)
Example #4
0
    def makeKmlDoc(self):
        """
        """
        self.cdatatext = {}
        args = self.config['arguments']

        trackfolder = imagefolder = None
        self.colourIndex = 0

        if ('update' in self.config['arguments']
                and self.config['arguments']['update']):

            with open(args['out'], 'r') as f:
                doc = KML.parse(f)
            # Find a folder that contains a Name with the text "tracks"
            trackfolder = doc.find('./Folder/[Name="tracks"]/..')
            # Find a folder that contains a Name with the text "tracks"
            imagefolder = doc.find('./Folder/[Name="images"]/..')

            if trackfolder:
                self.colourIndex = \
                    ((len(trackfolder.findall(KML.PlaceMark)) - 1) %
                      self.colourSetLen)
        else:
            # create a new KML structure from scratch
            doc = KML.Document(KML.description('Tracks and image placemarks'),
                               KML.visibility('1'), KML.open('1'),
                               KML.name("Tracks and Images"))

            # Append a style for pictures using the camera icon
            doc.append(
                KML.Style(
                    KML.IconStyle(
                        KML.scale(1.0),
                        KML.Icon(
                            KML.href(
                                'http://maps.google.com/mapfiles/kml/'\
                                'shapes/camera.png'),
                        ),
                        id="picture_style"
                    ),
                    id='picture'
                )
            )

            # Append styles for lines in different colours
            colourSet = [['7fff0000', 6, 'ffff0000', 8],
                         ['7f00ff00', 6, 'ff00ff00', 8],
                         ['7f0000ff', 6, 'ff0000ff', 8],
                         ['7fffff00', 6, 'ffffff00', 8],
                         ['7fff00ff', 6, 'ffff00ff', 8],
                         ['7f00ffff', 6, 'ff00ffff', 8]]
            self.colourSetLen = len(colourSet)

            for colourIndex in range(len(colourSet)):
                normal, narrow, highlight, wide = colourSet[colourIndex]
                colourID = 'colour' + str(colourIndex)
                self.colourStyle(doc, colourID, normal, narrow, highlight,
                                 wide)

            trackfolder = KML.Folder(KML.Name('tracks'))
            doc.append(trackfolder)

            imagefolder = KML.Folder(KML.Name('images'))
            doc.append(imagefolder)

        return (doc, trackfolder, imagefolder)
Example #5
0
def section_to_kml(section, color, outfile_path="", write=True):
    """
        Converts a section into a kml file
        """
    line_style_id = "line-%s-5" % color
    red = "FF1212"
    green = "00B80C"
    start_icon_style_id = "icon-%s" % color
    end_icon_style_id = "icon-%s" % color
    make_coord = lambda p: (",".join(
        [str(x) for x in p["track_location"]["coordinates"]] + ["0.0"]))
    make_coord_point = lambda p: (",".join([str(x) for x in p["coordinates"]] +
                                           ["0.0"]))
    style_id = "style-%s" % section['section_start_time']
    pm = KML.Placemark(
        KML.styleUrl("#%s" % line_style_id), KML.name(section['_id']),
        KML.description(section["section_id"]),
        KML.LineString(
            KML.tessellate(1),
            KML.coordinates(" ".join([
                make_coord(track_point)
                for track_point in section['track_points']
            ]))))
    start_point = section['section_start_point']
    end_point = section['section_end_point']
    start_time = mongodate_to_datetime(section["section_start_time"])
    end_time = mongodate_to_datetime(section["section_end_time"])
    start_point = KML.Placemark(
        KML.styleUrl("#%s" % start_icon_style_id),
        KML.name("Start: %s" % start_time), KML.description("Starting point"),
        KML.Point(KML.coordinates(make_coord_point(start_point))))
    end_point = KML.Placemark(
        KML.styleUrl("#%s" % end_icon_style_id),
        KML.name("End: %s" % end_time), KML.description("Ending point"),
        KML.Point(KML.coordinates(make_coord_point(end_point))))
    line_style = KML.Style(
        KML.LineStyle(KML.color("ff%s" % color), KML.width("5")))
    line_style.set("id", line_style_id)
    start_icon_style = KML.Style(
        KML.IconStyle(
            KML.color("ff%s" % color), KML.scale("1.1"),
            KML.Icon(
                KML.href(
                    "http://www.gstatic.com/mapspro/images/stock/503-wht-blank_maps.png"
                ))))
    start_icon_style.set("id", start_icon_style_id)
    end_icon_style = KML.Style(
        KML.IconStyle(
            KML.color("ff%s" % color), KML.scale("1.1"),
            KML.Icon(
                KML.href(
                    "http://www.gstatic.com/mapspro/images/stock/503-wht-blank_maps.png"
                ))))
    end_icon_style.set("id", end_icon_style_id)
    fld = KML.Folder(
        KML.name(section['_id']),
        KML.description("From %s \nto %s" % (start_time, end_time)), pm,
        start_point, end_point)
    if write:
        kml = KML.kml(KML.Document(fld, section["user_id"]))
        path = os.path.join(outfile_path, str(section['user_id']) + '.kml')
        outfile = file(path, 'w')
        outfile.write(etree.tostring(kml, pretty_print=True))
    else:
        return fld, line_style, start_icon_style, end_icon_style
Example #6
0
        def write_kml(list_of_networks):
            has_data = False

            doc = KML.Document(
                KML.name("PH5 Events"),
                KML.Style(
                    KML.IconStyle(
                        KML.color('FF1400FF'),
                        KML.scale('1.25'),
                        KML.Icon(
                            KML.href(
                                'http://maps.google.com/mapfiles/' +
                                'kml/shapes/open-diamond.png')
                        )
                    ),
                    id='star'
                ),
            )

            for network in list_of_networks:
                network_folder = KML.Folder(KML.name(
                    "Network Code: " + str(network.code) +
                    " reportnum: " + network.reportnum))
                for shot_line in network.shot_lines:
                    folder = KML.Folder(
                        KML.name("ShotLine " + str(shot_line.name[-3:])))
                    for shot in shot_line.shots:
                        place_marker = (KML.Placemark(
                            KML.styleUrl("#star"),
                            KML.name(network.code + '.' + str(shot.shot_id)),
                            KML.description('Shot size: ' +
                                            str(shot.mag) +
                                            ' ' +
                                            shot.mag_units +
                                            '\n Shot Time: ' +
                                            shot.start_time +
                                            '\n\n' +
                                            shot.description),
                            KML.Point(
                                KML.coordinates(
                                    str(shot.lon) + ',' + str(shot.lat) + ',' +
                                    str(shot.elev))
                            )
                        ))
                        folder.append(place_marker)
                        has_data = True
                    network_folder.append(folder)
                doc.append(network_folder)

            if has_data:
                if outfile and hasattr(outfile, 'write'):
                    target = outfile
                elif outfile:
                    target = open(outfile, 'w')
                else:
                    target = sys.stdout

                target.write(
                    etree.tostring(
                        etree.ElementTree(doc),
                        pretty_print=True))
            else:
                raise NoDataError("Request resulted in no data being returned")
Example #7
0
def buildKML(patterns, latitude, longitude, days, frequence):
    patterns = [(i.replace("\'", '').replace('\"', '')) for i in patterns]
    origin = (latitude, longitude)
    count = 100
    global pm1
    pm1 = KML.Placemark(
        KML.TimeStamp(KML.when(count)), KML.name("f: " + str(frequence)),
        KML.Point(KML.coordinates(reproject3857to4326(origin))),
        KML.Style(KML.IconStyle(KML.Icon(KML.href("")))))
    folder.append(pm1)
    for pattern in patterns:
        coor = reproject3857to4326(origin)
        if (pattern == '1'):
            pm1 = KML.Placemark(
                KML.TimeStamp(KML.when(count)),
                KML.Point(KML.coordinates(coor)),
                KML.Style(KML.IconStyle(KML.Icon(KML.href("suns/so1.png")))))
            folder.append(pm1)
        elif (pattern == '2'):
            pm1 = KML.Placemark(
                KML.TimeStamp(KML.when(count)),
                KML.Point(KML.coordinates(coor)),
                KML.Style(KML.IconStyle(KML.Icon(KML.href("suns/so2.png")))))
            folder.append(pm1)
        elif (pattern == '3'):
            pm1 = KML.Placemark(
                KML.TimeStamp(KML.when(count)),
                KML.Point(KML.coordinates(coor)),
                KML.Style(KML.IconStyle(KML.Icon(KML.href("suns/so3.png")))))
            folder.append(pm1)
        elif (pattern == '4'):
            pm1 = KML.Placemark(
                KML.TimeStamp(KML.when(count)),
                KML.Point(KML.coordinates(coor)),
                KML.Style(KML.IconStyle(KML.Icon(KML.href("suns/so4.png")))))
            folder.append(pm1)
        elif (pattern == '5'):
            pm1 = KML.Placemark(
                KML.TimeStamp(KML.when(count)),
                KML.Point(KML.coordinates(coor)),
                KML.Style(KML.IconStyle(KML.Icon(KML.href("suns/so5.png")))))
            folder.append(pm1)
        elif (pattern == '6'):
            pm1 = KML.Placemark(
                KML.TimeStamp(KML.when(count)),
                KML.Point(KML.coordinates(coor)),
                KML.Style(KML.IconStyle(KML.Icon(KML.href("suns/so6.png")))))
            folder.append(pm1)
        elif (pattern == '7'):
            pm1 = KML.Placemark(
                KML.TimeStamp(KML.when(count)),
                KML.Point(KML.coordinates(coor)),
                KML.Style(KML.IconStyle(KML.Icon(KML.href("suns/so7.png")))))
            folder.append(pm1)
        elif (pattern == '8'):
            pm1 = KML.Placemark(
                KML.TimeStamp(KML.when(count)),
                KML.Point(KML.coordinates(coor)),
                KML.Style(KML.IconStyle(KML.Icon(KML.href("suns/so8.png")))))
            folder.append(pm1)
        count += 100
Example #8
0
    def KML_file_header(self, icon, tour_name):
        if tour_name == "Stadium Tour":
            icon_ok = icon[0]
        else:
            icon_ok = "../img/"+icon[0]

        kml_doc = KML.kml(
                     KML.Document(
                       KML.Style(
                         KML.IconStyle(
                           KML.scale('2.5'),
                           KML.Icon(
                             KML.href(icon_ok)
                           ),
                         ),
                         KML.LabelStyle(
                           KML.color("ff80ccff"),
                           KML.scale(2)
                         ),
                         KML.BalloonStyle(
                           KML.text("$[description]")
                         ),
                         KML.LineStyle(
                             KML.color('bf00aaff'),
                             KML.width(5)
                         ),
                         id=stylename
                       ),
                       KML.Style(
                         KML.IconStyle(
                           KML.scale('2.5'),
                           KML.Icon(
                             KML.href("../img/"+icon[1])
                           ),
                         ),
                         KML.LabelStyle(
                           KML.color("ff80ccff"),
                           KML.scale(4)
                         ),
                         KML.LineStyle(
                           KML.color('FFFF0000'),
                           GX.outerColor('FF4CBB17'),
                           GX.physicalWidth('25000'),
                           GX.outerWidth('0.40')
                        ),
                        id=stylename2
                       ),
                       GX.Tour(
                         KML.name(tour_name),
                         GX.Playlist(),
                       ),
                       KML.Folder(
                         KML.name('Features'),
                         KML.Style(
                           KML.ListStyle(
                             KML.listItemType("checkHideChildren")
                           )
                         ),
                         id='features',
                       ),
                     ),
                  )

        return kml_doc
Example #9
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
Example #10
0
dd = np.array(dd)
hr = np.array(hr)
mn = np.array(mn)
ss = np.array(ss)

##############################################################################################################################
#--- how to get it into Arcgis and google earth ---#

kmlobj = KML.kml(KML.Document())

for j in range(len(yyyy)):  #create the ref icons we will use
    kmlobj.Document.append(
        KML.Style(
            KML.IconStyle(
                KML.Icon(
                    KML.href('%s.png' % str(event_id[j])),
                    KML.scale(0.6),  #scale the beachball in googleEarth
                ),
                KML.heading(0.0),
            ),
            id='beach_ball_%s' %
            event_id[j]  #gives the icon a ref that will be used later
        ), )

# add images to the document element
for i in range(len(yyyy)):
    datum = str(date.date(int(yyyy[i]), int(mm[i]), int(dd[i])))
    ev_time = str(date.time(int(hr[i]), int(mn[i]), int(ss[i])))
    eventid = event_id[i]
    Mw = data['mw'][i]
    CD = data['CD'][i]
    Mo = data['mo'][i]
Example #11
0
    def KML_file_header_olympic_games(self):
        flags_list = []
        for country in self.data_set.medalTable:
            flags_list.append(country)

        kml_doc = KML.kml(
                    KML.Document(
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('3.5'),
                          KML.Icon(
                            KML.href("../img/"+str(self.data_set.year)+" Summer Olympics.png")
                          ),
                        ),
                        id=stylename_icon
                      ),
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('3.5'),
                          KML.Icon(
                            KML.href("../img/flags/"+flags_list[0].replace(" ","")+".png")
                          ),
                        ),
                        id=stylename_icon_flags1
                      ),
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('3.5'),
                          KML.Icon(
                            KML.href("../img/flags/"+flags_list[1].replace(" ","")+".png")
                          ),
                        ),
                        id=stylename_icon_flags2
                      ),
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('3.5'),
                          KML.Icon(
                            KML.href("../img/flags/"+flags_list[2].replace(" ","")+".png")
                          ),
                        ),
                        id=stylename_icon_flags3
                      ),
                      KML.Style(
                        KML.LabelStyle(
                          KML.color("FFFFFFFF"),
                          KML.scale(1.75)
                        ),
                        KML.IconStyle(
                          KML.scale('3.5'),
                          KML.Icon(
                            KML.hide(True)
                          ),
                        ),
                        id=stylename_icon_label
                      ),
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('4.0'),
                          KML.Icon(
                            KML.href("")
                          ),
                        ),
                        KML.LineStyle(
                          KML.color("ff793909"),
                          KML.colorMode("normal"),
                          KML.width(5000),
                        ),
                        KML.PolyStyle(
                          KML.color("ff793909"),
                          KML.colorMode("normal"),
                          KML.fill(1),
                          KML.outline(1),
                        ),
                        id=style_first
                      ),
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('4.0'),
                          KML.Icon(
                            KML.href("")
                          ),
                        ),
                        KML.LineStyle(
                          KML.color("ffee7920"),
                          KML.colorMode("normal"),
                          KML.width(5000),
                        ),
                        KML.PolyStyle(
                          KML.color("ffee7920"),
                          KML.colorMode("normal"),
                          KML.fill(1),
                          KML.outline(1),
                        ),
                        id=style_second
                      ),
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('4.0'),
                          KML.Icon(
                            KML.href("")
                          ),
                        ),
                        KML.LineStyle(
                          KML.color("fff3b17f"),
                          KML.colorMode("normal"),
                          KML.width(5000),
                        ),
                        KML.PolyStyle(
                          KML.color("fff3b17f"),
                          KML.colorMode("normal"),
                          KML.fill(1),
                          KML.outline(1),
                        ),
                        id=style_third
                      ),
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('4.0'),
                          KML.Icon(
                            KML.href("")
                          ),
                        ),
                        KML.LineStyle(
                          KML.color("ff00d7ff"),
                          KML.colorMode("normal"),
                          KML.width(5000),
                        ),
                        KML.PolyStyle(
                          KML.color("ff00d7ff"),
                          KML.colorMode("normal"),
                          KML.fill(1),
                          KML.outline(1),
                        ),
                        id=style_golden
                      ),
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('4.0'),
                          KML.Icon(
                            KML.href("")
                          ),
                        ),
                        KML.LineStyle(
                          KML.color("ffc0c0c0"),
                          KML.colorMode("normal"),
                          KML.width(5000),
                        ),
                        KML.PolyStyle(
                          KML.color("ffc0c0c0"),
                          KML.colorMode("normal"),
                          KML.fill(1),
                          KML.outline(1),
                        ),
                        id=style_silver
                      ),
                      KML.Style(
                        KML.IconStyle(
                          KML.scale('4.0'),
                          KML.Icon(
                            KML.href("")
                          ),
                        ),
                        KML.LineStyle(
                          KML.color("ff53788c"),
                          KML.colorMode("normal"),
                          KML.width(5000),
                        ),
                        KML.PolyStyle(
                          KML.color("ff53788c"),
                          KML.colorMode("normal"),
                          KML.fill(1),
                          KML.outline(1),
                        ),
                        id=style_bronze
                      ),
                      GX.Tour(
                        KML.name("Tour Name"),
                        GX.Playlist(),
                      ),
                      KML.Folder(
                        KML.name('Features'),
                        id='features',
                      ),
                    )
                  )

        return kml_doc
Example #12
0
print "Parsing CSV"
for row in data:
	item.append(dict(zip(fields, row)))

points = []
for x in range(len(item)):
        points.append((float(item[x]['LATITUDE'].strip('"')), float(item[x]['LONGITUDE'].strip('"')), float(item[x][valuetype].strip('"'))))
#        points.append((item[x]['LATITUDE'], item[x]['LONGITUDE'], float(item[x][valuetype].strip('"'))))

doc = KML.Document()
style1 = KML.Style(
		KML.IconStyle(
			KML.scale(0.5),
			KML.color("BF0000FF"),
			KML.Icon(
				KML.href("http://www.earthpoint.us/Dots/GoogleEarth/WhitePaddle/blu-blank.png")
			)
		),
                KML.LabelStyle(
                        KML.color("BF0000FF"),
                        KML.colorMode("normal"),
                        KML.scale(0.65)
                ),
		id="red"
	)
doc.append(style1)

style2 = KML.Style(
                KML.IconStyle(
                        KML.scale(0.5),
                        KML.color("BF00FFFF"),
Example #13
0
def create_KML(dir_name, run_number):
    lat = 0
    lon = 0
    first = True
    steer = ''
    lines = []
    kml_name = dir_name + '/KML_' + str(run_number)

    doc = KML.kml(
        KML.Document(
            KML.name(kml_name),
            KML.Style(
                KML.IconStyle(
                    KML.scale(1.0),
                    KML.Icon(
                        KML.href("http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png"),
                    ),
                    id="mystyle"
                ),
                id="pushpin"
            ),
            KML.Style(
                KML.IconStyle(
                    KML.scale(1.5),
                    KML.Icon(
                        KML.href("http://maps.google.com/mapfiles/kml/paddle/red-circle.png"),
                    ),
                    id="mystyle"
                ),
                id="waypoint"
            ),
            KML.Style(
                KML.IconStyle(
                    KML.scale(1.5),
                    KML.Icon(
                        KML.href("http://maps.google.com/mapfiles/kml/paddle/S.png"),
                    ),
                    id="mystyle"
                ),
                id="start"
            ),
            KML.Style(
                KML.IconStyle(
                    KML.scale(1.5),
                    KML.Icon(
                        KML.href("http://maps.google.com/mapfiles/kml/paddle/E.png"),
                    ),
                    id="mystyle"
                ),
                id="end"
            )
        )
    )

    for line in open(dir_name + "/LOG_" + str(run_number) + '.TXT', 'r'):
        if re.search('RUN-STEER', line):
            if lat:
                if first:
                    pm = create_placemark(lat, lon, lines, '#start')
                    doc.Document.append(pm)
                    first = False
                else:
                    pm = create_placemark(lat, lon, lines, '#pushpin')
                    doc.Document.append(pm)

                del lines[:]
                lines.append(line)
        else:
            if re.search('RUN-THROTTLE', line):
                m = re.search('.*LAT:([^\s,]+).*LONG:([^\s,]+).*', line)
                lat = m.group(1)
                lon = m.group(2)
            lines.append(line)

        # reached waypoint
        if re.search('Reached Waypoint', line):
            m = re.search('.*Reached Waypoint[^:]+:([0-9]+).*', line)
            wpnum = m.group(1)
            pm = create_placemark(lat, lon, lines, '#waypoint')
            doc.Document.append(pm)

    pm = create_placemark(lat, lon, lines, '#end')
    doc.Document.append(pm)

    print etree.tostring(doc, pretty_print=True)

    # output a KML file (named based on the Python script)
    outfile = file(kml_name + '.KML', 'w')
    outfile.write(etree.tostring(doc, pretty_print=True))

    return
    def gen_klm(self):
        """
        Generate a KML file with keypoints on the locations of the pictures, including height
        :return:
        """
        style_dot = "sn_shaded_dot"
        style_path = "red_path"

        doc = KML.kml(
            KML.Document(
                KML.Name("GPS of the images"),
                KML.Style(
                    KML.IconStyle(
                        KML.scale(0.4),
                        KML.Icon(
                            KML.href(
                                "http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png"
                            )),
                    ),
                    id=style_dot,
                ),
                KML.Style(KML.LineStyle(
                    KML.color('7f0000ff'),
                    KML.width(6),
                    GX.labelVisibility('1'),
                ),
                          id=style_path)))

        # create points
        for i, gps in enumerate(self.tagged_gps):
            ii = i + 1
            doc.Document.append(
                KML.Placemark(
                    KML.styleUrl('#{0}'.format(style_dot)),
                    KML.Point(
                        KML.extrude(True),
                        KML.altitudeMode('relativeToGround'),
                        KML.coordinates("{},{},{}".format(
                            gps.lon, gps.lat, gps.alt))),
                    KML.name(str(ii))
                    if ii % 5 == 0 or ii == 1 else KML.name()))

        # create the path
        doc.Document.append(
            KML.Placemark(
                KML.styleUrl('#{0}'.format(style_path)),
                KML.LineString(
                    KML.altitudeMode('relativeToGround'),
                    KML.coordinates(' '.join([
                        "{},{},{}".format(gps.lon, gps.lat, gps.alt)
                        for gps in self.tagged_gps
                    ])))))

        s = etree.tostring(doc)

        file_path = self.output + 'GoogleEarth_points.kml'
        f = open(file_path, 'w')
        f.write(s)
        f.close()

        print '[INFO] KML file generated on:', file_path
Example #15
0
def validate():
    table = {}
    reader = open('{}/gtfs/files/shapes.txt'.format(REPORT_PATH))
    for line in reader:
        shape, lat, lng, seq = re.split(',', line.rstrip())
        if shape == 'shape_id':
            continue
        if shape not in table:
            table[shape] = {}
        table[shape][seq] = (lat, lng)

    # For each shape
    for shape in table:

        doc = KML.Document(KML.name('Shape {}'.format(shape)))

        # For each sequence in order
        for seq in sorted(table[shape].keys()):
            # Add a placemark in the KML file
            doc.append(
                KML.Placemark(
                    KML.name('{}'.format(seq)),
                    KML.styleUrl('#icon-503-777777'),
                    KML.Point(
                        KML.coordinates('{},{},0'.format(
                            table[shape][seq][1], table[shape][seq][0])))))

        # Add the normal style for the KML
        doc.append(
            KML.Style(KML.IconStyle(
                KML.color('ff777777'),
                KML.scale(1.1),
                KML.Icon(
                    KML.href(
                        'http://www.gstatic.com/mapspro/images/stock/503-wht-blank_maps.png'
                    )),
                KML.hotspot('',
                            x='16',
                            y='31',
                            xunits='pixels',
                            yunits='insetPixels'),
            ),
                      KML.LabelStyle(KML.scale(1.1)),
                      id='icon-503-777777-normal'))

        # Add the highlight style for the KML
        doc.append(
            KML.Style(KML.IconStyle(
                KML.color('ff555555'),
                KML.scale(1.1),
                KML.Icon(
                    KML.href(
                        'http://www.gstatic.com/mapspro/images/stock/503-wht-blank_maps.png'
                    )),
                KML.hotSpot('',
                            x='16',
                            y='31',
                            xunits='pixels',
                            yunits='insetPixels'),
            ),
                      KML.LabelStyle(KML.scale(1.1)),
                      id='icon-503-555555-highlight'))

        # Set the style map
        doc.append(
            KML.StyleMap(KML.Pair(KML.key('normal'),
                                  KML.styleUrl('#icon-503-777777-normal')),
                         KML.Pair(KML.key('highlight'),
                                  KML.styleUrl('#icon-503-777777-highlight')),
                         id='icon-503-777777'))

        # Send KML file to string and replace spurious \
        kml = KML.kml(doc)
        kml = etree.tostring(kml, pretty_print=True).decode(
            'utf-8', errors='strict').replace('\\', '')

        # Add encoding line
        final = ["<?xml version='1.0' encoding='UTF-8'?>"]

        # Unescape the CDATA description HTML
        for line in re.split('\n', kml):
            if re.search('\<description\>', line):
                final.append(unescape(line))
            else:
                final.append(line)

        # Write the file
        set_directory('{}/gtfs/test'.format(REPORT_PATH))
        writer = open('{}/gtfs/test/shape_{}.kml'.format(REPORT_PATH, shape),
                      'w')
        writer.write('\n'.join(final))
Example #16
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)
Example #17
0
#writing kml
print('Gerando arquivo KML... \n')
doc = KML.Document()

icons = {
    'verde': 'http://maps.google.com/mapfiles/kml/pushpin/grn-pushpin.png',
    'amarelo': 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png',
    'vermelho': 'http://maps.google.com/mapfiles/kml/pushpin/red-pushpin.png'
}

for color in icons:

    s = KML.Style(
        KML.IconStyle(
            KML.scale(1.2),
            KML.Icon(KML.href(icons[color])),
        ),
        id=color,
    )

    doc.append(s)

fld_ag_doc = KML.Folder(KML.name('Aguardando formalização de documentos'))
fld_ag_an = KML.Folder(KML.name('Aguardando análise'))
fld_ag_alt = KML.Folder(
    KML.name('Aguardando alterações de dados inconsistentes'))
fld_an = KML.Folder(KML.name('Em análise'))
fld_conc = KML.Folder(KML.name('Concedida'))
fld_ind = KML.Folder(KML.name('Indeferida'))

for index, row in df_filtrado.iterrows():
Example #18
0
    def tab_kml(self):

        df1 = self.run_files['file_input']['table_file']
        bb = self.run_files['file_input']['file_name']

        stylename = "earthquake-balloon-style"
        balloonstyle = KML.BalloonStyle(
            KML.text("""
        <table Border=1>
        <tr><th>Earthquake ID</th><td>$[Eqid_]</td></tr>
        <tr><th>Magnitude</th><td>$[Magnitude_]</td></tr>
        <tr><th>Depth</th><td>$[Depth_]</td></tr>
        <tr><th>Datetime</th><td>$[Datetime_]</td></tr>
        <tr><th>Coordinates</th><td>($[Lat_],$[Lat_])</td></tr>
        <tr><th>Region</th><td>$[Region_]</td></tr>
        </table>"""), )

        doc = KML.Document()

        iconstyles = [
            [1, 'ff000000'],
            [2, 'ffff0000'],
            [3, 'ff00ff55'],
            [4, 'ffff00aa'],
            [5, 'ff00ffff'],
            [6, 'ff0000ff'],
        ]

        for threshold, color in iconstyles:
            doc.append(
                KML.Style(KML.IconStyle(
                    KML.color(color),
                    KML.scale(1.1),
                    KML.Icon(
                        KML.href(
                            'http://www.gstatic.com/mapspro/images/stock/503-wht-blank_maps.png'
                        )),
                    KML.hotspot('',
                                x='16',
                                y='31',
                                xunits='pixels',
                                yunits='insetPixels'),
                ),
                          KML.LabelStyle(KML.scale(1.1)),
                          id='icon-503-{}-normal'.format(color)))

        def element(g, i):
            for k, row in g.iterrows():
                if len(iconstyles) > int(i):
                    jj = int(i) + 1
                elif len(iconstyles) <= int(i):
                    jj = int(i) - (len(iconstyles) - 1)
                pm = KML.Placemark(
                    KML.name("specimen={0}".format(row['specimen_voucher'])),
                    KML.styleUrl('#icon-503-{}-normal'.format(
                        iconstyles[jj][-1])),
                    KML.Point(
                        KML.coordinates("{0},{1}".format(
                            row['longitude'], row['latitude']))))

                fld.append(pm)
            return fld

        for i, g in df1.groupby('species_number'):

            fld = KML.Folder(
                KML.name(f'species number: {"unassigned" if i=="0" else i}'))

            gg = element(g, i)
            doc.append(gg)

        self.result_files['kml_file'] = doc
        self.result_files['file_name'] = bb
Example #19
0
 KML.name(gmlname + '.kml'),
 KML.Style(KML.LineStyle(KML.color('ff0000ff'), KML.width('2')),
           KML.PolyStyle(KML.fill('0')),
           id=('inline')),
 KML.StyleMap(KML.Pair(KML.key('normal'), KML.styleUrl("#inline")),
              KML.Pair(KML.key('highlight'),
                       KML.styleUrl("#inline")),
              id=('inline1')),
 KML.StyleMap(KML.Pair(KML.key('normal'), KML.styleUrl("#pushpin")),
              KML.Pair(KML.key('highlight'),
                       KML.styleUrl("#pushpin1")),
              id=('pushpinm')),
 KML.Style(KML.IconStyle(
     KML.scale('1.1'),
     KML.Icon(
         KML.href(
             'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png'
         )),
     KML.hotSpot(x=('20'),
                 y=('2'),
                 xunits=('pixels'),
                 yunits=('pixels')),
 ),
           id=('pushpin')),
 KML.Style(KML.IconStyle(
     KML.scale('1.3'),
     KML.Icon(
         KML.href(
             'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png'
         )),
     KML.hotSpot(x=('20'),
                 y=('2'),
Example #20
0
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)
Example #21
0
* The <scale> element should not be a subelement of <Icon>.
* The <gx:duration> element should be the first subelement of <gx:FlyTo>
'''

from lxml import etree
from pykml.parser import Schema
from pykml.factory import KML_ElementMaker as KML
from pykml.factory import GX_ElementMaker as GX

doc = KML.kml(
    KML.Document(
        KML.name("gx:AnimatedUpdate example"),
        KML.Style(KML.IconStyle(
            KML.scale(1.0),
            KML.Icon(
                KML.href(
                    "http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png"
                ), ),
            id="mystyle"),
                  id="pushpin"),
        KML.Placemark(KML.name("Pin on a mountaintop"),
                      KML.styleUrl("#pushpin"),
                      KML.Point(
                          KML.coordinates(170.1435558771009,
                                          -43.60505741890396, 0)),
                      id="mountainpin1"),
        GX.Tour(
            KML.name("Play me!"),
            GX.Playlist(
                GX.FlyTo(
                    GX.duration(3), GX.flyToMode("bounce"),
                    KML.Camera(
Example #22
0
from pykml.factory import KML_ElementMaker as KML
from pykml.factory import ATOM_ElementMaker as ATOM
from pykml.factory import GX_ElementMaker as GX

doc = KML.kml(
    KML.Document(
        KML.name("KML Samples"),
        KML.open("1"),
        KML.description(
            "Unleash your creativity with the help of these examples!"),
        KML.Style(
            KML.IconStyle(
                KML.Icon(
                    KML.href(
                        "http://maps.google.com/mapfiles/kml/pal4/icon28.png"),
                ), ),
            id="downArrowIcon",
        ),
        KML.Style(
            KML.IconStyle(
                KML.Icon(
                    KML.href(
                        "http://maps.google.com/mapfiles/kml/pal3/icon19.png"),
                ), ),
            KML.LineStyle(KML.width("2"), ),
            id="globeIcon",
        ),
        KML.Style(
            KML.LineStyle(
                KML.color("7fff00ff"),
                KML.width("4"),
Example #23
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
Example #24
0
def create_kml_document(inps, box_list, ts_obj, step):

    dot_file = "shaded_dot.png"
    dygraph_file = "dygraph-combined.js"

    ## 1. read data file into timeseries object

    kml_region_documents = []

    for i in range(len(box_list)):
        print(i)
        box = box_list[i]

        if box is None:
            box = (0, 0, width, length)

        length = box[3] - box[1]
        width = box[2] - box[0]

        # 1.1 Parse Date
        dates = np.array(
            ts_obj.times
        )  # 1D np.array of dates in datetime.datetime object in size of [num_date,]
        dates = list(map(lambda d: d.strftime("%Y-%m-%d"), dates))
        num_date = len(dates)

        # 1.2 Parse Spatial coordinates
        lats, lons = get_lat_lon(ts_obj.metadata, box=box)
        rows, cols = np.mgrid[box[1]:box[3] - 1:length * 1j,
                              box[0]:box[2] - 1:width * 1j]

        # 1.3 Read Velocity / time-series / temporal coherence data
        print('read velocity data')
        vel = readfile.read(inps.vel_file, datasetName='velocity',
                            box=box)[0] * 100.
        vel_std = readfile.read(
            inps.vel_file, datasetName='velocityStd', box=box)[0] * 100.
        print('read time-series data')
        ts_data = readfile.read(inps.ts_file, box=box)[0] * 100.
        ts_data -= np.tile(
            ts_data[0, :, :],
            (ts_data.shape[0], 1, 1))  # enforce displacement starts from zero
        print('read temporal coherence data')
        temp_coh = readfile.read(inps.tcoh_file, box=box)[0]
        mask = ~np.isnan(vel)

        ## 2. Create KML Document
        print('create KML file.')
        kml_document = KML.Document()

        # 2.1 Set and normalize colormap to defined vlim
        colormap = mpl.cm.get_cmap(inps.colormap)
        norm = mpl.colors.Normalize(vmin=inps.vlim[0], vmax=inps.vlim[1])

        # 2.2 Set number of pixels to use
        num_pixel = int(length / step) * int(width / step)
        msg = "add point time-series data "
        msg += "(select 1 out of every {} by {} pixels; select {} pixels in total) ...".format(
            step, step, num_pixel)
        print(msg)

        # 2.3 Create data folder for all points
        data_folder = KML.Folder(KML.name("Data"))
        for i in range(0, length, step):
            for j in range(0, width, step):
                if mask[i, j]:  # add point if it's not marked as masked out
                    lat = lats[i, j]
                    lon = lons[i, j]
                    row = rows[i, j]
                    col = cols[i, j]
                    ts = ts_data[:, i, j]
                    v = vel[i, j]
                    vstd = vel_std[i, j]
                    tcoh = temp_coh[i, j]

                    # 2.3.1 Create KML icon style element
                    style = KML.Style(
                        KML.IconStyle(
                            KML.color(get_color_for_velocity(
                                v, colormap, norm)), KML.scale(0.5),
                            KML.Icon(KML.href("../../{}".format(dot_file)))))

                    # 2.3.2 Create KML point element
                    point = KML.Point(KML.coordinates("{},{}".format(lon,
                                                                     lat)))

                    js_data_string = generate_js_datastring(
                        dates, dygraph_file, num_date, ts)

                    # 2.3.3 Create KML description element
                    stats_info = generate_description_string((lat, lon),
                                                             (row, col),
                                                             v,
                                                             vstd,
                                                             ts[-1],
                                                             tcoh=tcoh)
                    description = KML.description(stats_info, js_data_string)

                    # 2.3.4 Crate KML Placemark element to hold style, description, and point elements
                    placemark = KML.Placemark(style, description, point)

                    # 2.3.5 Append each placemark element to the KML document object
                    data_folder.append(placemark)

        # 2.4 Append data folder to KML document
        kml_document.append(data_folder)

        # 2.5 Append KML document to list of regionalized documents
        kml_region_documents.append(kml_document)

    return kml_region_documents, dot_file, dygraph_file
Example #25
0
            plot_contours(area,
                          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)
Example #26
0
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
Example #27
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,
                                         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
    # 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
Example #28
0
def create_kml_region_document(inps, box_list, ts_obj, step):
    """Create list of KML.Document() objects 
    for one level of details defined by box_list and step
    """
    dot_file = '../../{}'.format(os.path.basename(inps.dot_file))

    ## 1. read data file into timeseries object
    region_docs = []
    num_box = len(box_list)
    for i in range(num_box):
        box = box_list[i]

        if box is None:
            box = (0, 0, ts_obj.width, ts_obj.length)

        length = box[3] - box[1]
        width = box[2] - box[0]

        # 1.1 Parse Date
        dates = np.array(
            ts_obj.times
        )  # 1D np.array of dates in datetime.datetime object in size of [num_date,]
        dates = list(map(lambda d: d.strftime("%Y-%m-%d"), dates))
        num_date = len(dates)

        # 1.2 Parse Spatial coordinates
        lats, lons = ut.get_lat_lon(ts_obj.metadata, box=box)
        rows, cols = np.mgrid[box[1]:box[3] - 1:length * 1j,
                              box[0]:box[2] - 1:width * 1j]

        # 1.3 Read Velocity / time-series / temporal coherence data
        vel = readfile.read(inps.vel_file, datasetName='velocity',
                            box=box)[0] * 100.
        vel_std = readfile.read(
            inps.vel_file, datasetName='velocityStd', box=box)[0] * 100.
        ts_data = readfile.read(inps.ts_file, box=box)[0] * 100.
        ts_data -= np.tile(
            ts_data[0, :, :],
            (ts_data.shape[0], 1, 1))  # enforce displacement starts from zero
        temp_coh = readfile.read(inps.tcoh_file, box=box)[0]
        mask = readfile.read(inps.mask_file, box=box)[0]

        vel_c = np.array(vel, dtype=np.float32)
        if inps.wrap:
            vel_c = inps.vlim[0] + np.mod(vel_c - inps.vlim[0],
                                          inps.vlim[1] - inps.vlim[0])

        ## 2. Create KML Document
        kml_document = KML.Document()

        # 2.1 Set and normalize colormap to defined vlim
        colormap = mpl.cm.get_cmap(inps.colormap)
        norm = mpl.colors.Normalize(vmin=inps.vlim[0], vmax=inps.vlim[1])

        # 2.2 Set number of pixels to use
        num_pixel = int(length / step) * int(width / step)
        msg = "create KML doc for box {}/{}: {}".format(i + 1, num_box, box)
        msg += ", step: {} pixels, {} pixels in total ...".format(
            step, num_pixel)
        print(msg)

        # 2.3 Create data folder for all points
        data_folder = KML.Folder(KML.name("Data"))
        for i in range(0, length, step):
            for j in range(0, width, step):
                if mask[i, j]:  # add point if it's not marked as masked out
                    lat = lats[i, j]
                    lon = lons[i, j]
                    row = rows[i, j]
                    col = cols[i, j]
                    ts = ts_data[:, i, j]
                    v = vel[i, j]
                    vc = vel_c[i, j]
                    vstd = vel_std[i, j]
                    tcoh = temp_coh[i, j]

                    # 2.3.1 Create KML icon style element
                    style = KML.Style(
                        KML.IconStyle(
                            KML.color(get_hex_color(vc, colormap, norm)),
                            KML.scale(0.5),
                            KML.Icon(KML.href("{}".format(dot_file)))))

                    # 2.3.2 Create KML point element
                    point = KML.Point(KML.coordinates("{},{}".format(lon,
                                                                     lat)))

                    js_data_string = generate_js_datastring(
                        dates, inps.dygraph_file, num_date, ts)

                    # 2.3.3 Create KML description element
                    stats_info = get_description_string((lat, lon), (row, col),
                                                        v,
                                                        vstd,
                                                        ts[-1],
                                                        tcoh=tcoh)
                    description = KML.description(stats_info, js_data_string)

                    # 2.3.4 Crate KML Placemark element to hold style, description, and point elements
                    placemark = KML.Placemark(style, description, point)

                    # 2.3.5 Append each placemark element to the KML document object
                    data_folder.append(placemark)

        # 2.4 Append data folder to KML document
        kml_document.append(data_folder)

        # 2.5 Append KML document to list of regionalized documents
        region_docs.append(kml_document)

    return region_docs
Example #29
0
    [3, 'ffff0000'],
    [4, 'ff00ff55'],
    [5, 'ffff00aa'],
    [6, 'ff00ffff'],
    [7, 'ff0000ff'],
]

# create a series of Icon Styles
for threshold, color in iconstyles:
    doc.append(
        KML.Style(
            KML.IconStyle(
                KML.color(color),
                KML.scale(threshold / 2),
                KML.Icon(
                    KML.href(
                        "http://maps.google.com/mapfiles/kml/shapes/earthquake.png"
                    ), ),
                KML.hotSpot(x="0.5",
                            y="0",
                            xunits="fraction",
                            yunits="fraction"),
            ),
            balloonstyle,
            id="earthquake-style-{threshold}".format(threshold=threshold),
        ))

doc.append(KML.Folder())

# read in a csv file, and create a placemark for each record
url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M2.5.txt"
fileobject = urllib.request.urlopen(url)
Example #30
0
def main():
# ###############################################################################

    usage = "usage: %prog [options] <gpxfile>\n\n"
    usage += "where:\n"
    usage += "  <gpxfile>\tgpx formatted file"

    parser = optparse.OptionParser(usage=usage)
    parser.add_option("-p", "--points", dest="points", action="store_true", help="specify if points output is desired", default=False)
    parser.add_option("-f", "--flyover", dest="flyover", action="store_true", help="specify if flyover output is desired", default=False)
    parser.add_option("-c", "--color", dest="color", help="track color if not flyover", default='641400FF')
    parser.add_option("-o", "--output", dest="output", help="output file", default=None)
    (options, args) = parser.parse_args()

    # see http://www.zonums.com/gmaps/kml_color/
    colors = {'pink':'64781EF0', 'blue':'64F01E14'}
    
    gpxfile = args.pop(0)
    if options.output == None:
        outfile = os.path.basename(gpxfile) + '.kml'
    else:
        outfile = options.output

    # get input
    _GPX = open(gpxfile,'r')
    gpx = gpxpy.parse(_GPX)

    # create a KML file skeleton
    stylename = "sn_shaded_dot"
    color = colors[options.color]
    sty = KML.Style(
        KML.IconStyle(
            KML.scale(1.2),
            KML.Icon(
                KML.href("http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png")
                ),
            KML.color(colors[options.color]),
            ),
        id=stylename,
        )
    iconstylename = '#sn_shaded_dot'

    doc = KML.Document(
        KML.Name('generated from {0}'.format(gpxfile)),
        KML.open(1),
        )
    doc.append(sty)

    '''
    <TimeStamp>
      <when>1997-07-16T07:30:15Z</when>
    </TimeStamp>
    '''
    # loop through gpx tracks, creating kml placemarks
    times = []
    coords = []
    dists = []
    points = []
    lastpoint = None
    for track in gpx.tracks:
        for segment in track.segments:
            for point in segment.points:
                if not lastpoint:
                    lastpoint = point
                plon = point.longitude
                plat = point.latitude
                pelev = point.elevation
                points.append(point)
                thisdist = gpxpy.geo.distance(lastpoint.latitude, lastpoint.longitude, lastpoint.elevation, plat, plon, pelev)
                lastpoint = point
                dists.append(thisdist)
                ptime = t.dt2asc(point.time)
                times.append(ptime)
                coords.append('{lon},{lat},{alt}'.format(lon = plon,lat = plat,alt = 0))
    
    if options.flyover:
        plm = KML.Placemark()
        doc.append(plm)
        track = GX.track()
        plm.append(track)
        
        for when in times:
            track.append(KML.when(when))
        for coord in coords:
            track.append(KML.coordinates(coord))
            
        '''
        doc.append(KML.Placemark(
            KML.LookAt(
                KML.longitude(plon),
                KML.latitude(plat),
                KML.tilt(45),
                KML.heading(0),  # make this behind the guy
                KML.altitudeMode("relativeToGround"),
                KML.range(50),
                ),
            KML.Point(
                KML.altitudeMode("relativeToGround"),
                ,
                ,
                )
            ))
        '''
        
    elif options.points:
        #for coord in coords:
        #    ls.append(KML.coordinates(coord))
        lasttime = t.asc2epoch(times[0])
        totdist = 0
        for i in range(len(times)):
            thistime = t.asc2epoch(times[i])
            dur = thistime - lasttime
            lasttime = thistime
            totdist += dists[i]
            ex = KML.ExtendedData(
                KML.Data(KML.displayName('time'),KML.value(times[i])),
                KML.Data(KML.displayName('duration'),KML.value(dur)),
                KML.Data(KML.displayName('totdistance'),KML.value(int(round(totdist)))),
                )
            plm = KML.Placemark(
                #KML.name(times[i]),
                KML.name(''),
                KML.styleUrl(iconstylename),
                )
            plm.append(ex)
            plm.append(KML.Point(
                KML.altitudeMode('clampToGround'),
                KML.coordinates(coords[i])))
            doc.append(plm)
    
    else:
        if options.color:
            doc.append(
                KML.Style(
                    KML.LineStyle(
                    KML.color(colors[options.color]),
                    KML.width(5),
                    ),
                id=options.color))
            stylename = '#{0}'.format(options.color)
        
        '''
        <LineString id="ID">
          <!-- specific to LineString -->
          <gx:altitudeOffset>0</gx:altitudeOffset>  <!-- double -->
          <extrude>0</extrude>                      <!-- boolean -->
          <tessellate>0</tessellate>                <!-- boolean -->
          <altitudeMode>clampToGround</altitudeMode> 
              <!-- kml:altitudeModeEnum: clampToGround, relativeToGround, or absolute -->
              <!-- or, substitute gx:altitudeMode: clampToSeaFloor, relativeToSeaFloor -->
          <gx:drawOrder>0</gx:drawOrder>            <!-- integer --> 
          <coordinates>...</coordinates>            <!-- lon,lat[,alt] -->
        </LineString>
        '''
        plm = KML.Placemark(
            KML.name('runtrack'),
            )
        if options.color:
            plm.append(KML.styleUrl(stylename))
        doc.append(plm)
        ls = KML.LineString(
            KML.altitudeMode('clampToGround'),
#            KML.extrude(1),
#            KML.tessellate(1),
            )
        plm.append(ls)
        #for coord in coords:
        #    ls.append(KML.coordinates(coord))
        kcoords = ''
        for coord in coords:
            kcoords += coord + ' \n'
        ls.append(KML.coordinates(kcoords))
        
    _GPX.close()

    kml = KML.kml(doc)
    
    docstr = etree.tostring(kml, pretty_print=True)
    OUT = open(outfile,'w')
    OUT.write(docstr)
    OUT.close()