Example #1
0
def show_google_map(paths, API_key, region):

    lines = []
    for f in pbar()(paths.fragments):
        flines = []
        for l in f:
            line_coords = np.r_[list(l.coords.xy)].T
            for i in range(len(line_coords) - 1):
                flines.append(
                    gmaps.Line(start=tuple(line_coords[i][::-1]),
                               end=tuple(line_coords[i + 1][::-1])))
        lines.append(flines)
    lines = flatten(lines)
    print "found", len(lines), "line segments"

    markers = []

    for o, f in pbar()(zip(flatten(paths.resampled_orientations),
                           flatten(paths.resampled_fragments))):
        coords = np.r_[list(f.xy)].T
        markers.append([
            gmaps.Marker((coords[i][1], coords[i][0]),
                         info_box_content=str(o[i]))
            for i in range(len(coords))
        ])
    markers = flatten(markers)
    print "found", len(markers), "sampling locations"

    gmaps.configure(api_key=API_key)
    gmap_b = gmaps.Polygon([(i[1], i[0]) for i in region])
    fig = gmaps.figure(center=tuple(region.mean(axis=0)[::-1]), zoom_level=16)
    fig.add_layer(gmaps.drawing_layer(features=[gmap_b] + lines + markers))
    return fig
Example #2
0
 def predictSingle(self, imgFile, dataDir, ployGrid=None):
     '''
     Predicts softmax ouput by trained model for single image and plots it 
     imgFile has to look like: 
     # eg: <gridNo>+<lat,long>+<imageNo_date>.jpg 
     # eg: 60+48.4271513,-110.5611851+0_2009-06.jpg
     '''
     xx,yy = self.readData([imgFile], dataDir)
     yp = self.model.predict(xx)[0]
     yn = list(map(lambda x:x/max(yp), yp))
     dist, start, end = self.gridDist(ployGrid[np.argmax(yy[0])],ployGrid[np.argmax(yp)])
     if ployGrid:
         mx = max(yn)
         mn = min(yn)
         plt.plot([start[1],end[1]], [start[0],end[0]], color='black', 
                  label="Distance: {} miles".format(round(dist,3)))
         for k,i in ployGrid.items():
             if k==np.argmax(yy[0]):
                 plt.plot(i[:,1],i[:,0],color='blue',label="Actual Grid", alpha=1)
             else:
                 plt.plot(i[:,1],i[:,0],color='black', alpha=0.7)
             plt.fill(i[:,1],i[:,0],color='red', alpha=yn[k])
         plt.legend(loc="lower left")
         plt.show()
         
         gPoly = []
         gLine = gmaps.Line(
             start=start,
             end=end,
             stroke_color = 'blue'
         )
         for grid, polygon in ployGrid.items():
             gPoly.append(gmaps.Polygon(
                                     list(polygon),
                                     stroke_color='black',
                                     fill_color='red',
                                     fill_opacity=float(yn[grid])
                                     ))
         fig = gmaps.figure(center=(39.50,-98.35), zoom_level=4)
         fig.add_layer(gmaps.drawing_layer(features=gPoly))
         fig.add_layer(gmaps.drawing_layer(features=[gLine]))
         fig.add_layer(gmaps.symbol_layer([start], scale=3, 
                              fill_color='green',stroke_color='green', info_box_content='Expected'))
         fig.add_layer(gmaps.symbol_layer([end], scale=3, 
                                          fill_color='yellow', stroke_color='yellow', 
                                          info_box_content='Predicted: {}'.format(dist)))
         embed_minimal_html('gmap.html', views=fig)
         webbrowser.open('gmap.html',new=1)
     return dist
Example #3
0
def london():
    import gmaps
    import gmaps.datasets

    london_congestion_zone_path = gmaps.datasets.load_dataset(
        'london_congestion_zone')
    london_congestion_zone_path[:2]

    fig = gmaps.figure(center=(51.5, -0.1), zoom_level=12)
    london_congestion_zone_polygon = gmaps.Polygon(london_congestion_zone_path,
                                                   stroke_color='blue',
                                                   fill_color='blue')
    drawing = gmaps.drawing_layer(features=[london_congestion_zone_polygon],
                                  show_controls=False)
    fig.add_layer(drawing)
    fig
Example #4
0
    def predictSingle(self, imgFile, dataDir, ployGrid):
        '''
        Predicts softmax ouput by trained model for single image and plots it 
        mgFiles: String that contains test location image triplet folder name. String has to look like:
        # <gridNo>+<lat,long>
        # 60+48.4271513,-110.5611851
        dataDir: Directory that stores combined image files eg: "/dataCombinedSamples/"
        polyGrid: List of polygons that contain make up the USA split into grids.
                  It can be loaded from eg: "infoExtraction/usaPolyGrid.pkl"
        '''
        # read image triplets from single file
        xx, yy = self.readData([imgFile], dataDir)
        # predict single image triplet
        yp = self.model.predict(xx)[0]
        # normalize prediction for better visualization
        yn = list(map(lambda x: x / max(yp), yp))
        # evaluate distance for single point
        dist, start, end = self.gridDist(ployGrid[np.argmax(yy[0])],
                                         ployGrid[np.argmax(yp)])
        mx = max(yn)
        mn = min(yn)
        # plot result using matplotlib
        plt.plot([start[1], end[1]], [start[0], end[0]],
                 color='black',
                 label="Distance: {} miles".format(round(dist, 3)))
        for k, i in ployGrid.items():
            if k == np.argmax(yy[0]):
                plt.plot(i[:, 1],
                         i[:, 0],
                         color='blue',
                         label="Actual Grid",
                         alpha=1)
            else:
                plt.plot(i[:, 1], i[:, 0], color='black', alpha=0.7)
            plt.fill(i[:, 1], i[:, 0], color='red', alpha=yn[k])
        plt.legend(loc="lower left")
        plt.show()

        # plot result using google maps API
        gPoly = []
        gLine = gmaps.Line(start=start, end=end, stroke_color='blue')
        for grid, polygon in ployGrid.items():
            gPoly.append(
                gmaps.Polygon(list(polygon),
                              stroke_color='black',
                              fill_color='red',
                              fill_opacity=float(yn[grid])))
        fig = gmaps.figure(center=(39.50, -98.35), zoom_level=4)
        fig.add_layer(gmaps.drawing_layer(features=gPoly))
        fig.add_layer(gmaps.drawing_layer(features=[gLine]))
        fig.add_layer(
            gmaps.symbol_layer([start],
                               scale=3,
                               fill_color='green',
                               stroke_color='green',
                               info_box_content='Expected'))
        fig.add_layer(
            gmaps.symbol_layer([end],
                               scale=3,
                               fill_color='yellow',
                               stroke_color='yellow',
                               info_box_content='Predicted: {}'.format(dist)))
        # save and display html page containing google maps API
        embed_minimal_html('gmap.html', views=fig)
        webbrowser.open('gmap.html', new=1)
        return dist
Example #5
0
def generate_map(type, year, month, day, hour, days_ahead):
    # reading data and calculating weights
    infile = cams.get_data(type, year, month, day, hour, days_ahead)[1]
    print(infile)
    satdata = pd.read_csv(infile)
    print("Files successfully read\n --------")
    # satdata = pd.read_csv('data.csv')
    locations = satdata[['Latitude', 'Longitude']]
    weights = 1 - (satdata['Value'] / satdata['Value'].max())
    # print(locations)
    # print(weights)

    # calculating rectangles to be render on the drawing layer
    loc1 = locations - 0.05
    loc1 = loc1.apply(tuple, axis=1)
    loc2 = pd.concat([locations.Latitude - 0.05, locations.Longitude + 0.05],
                     axis=1)
    loc2 = loc2.apply(tuple, axis=1)
    loc3 = locations + 0.05
    loc3 = loc3.apply(tuple, axis=1)
    loc4 = pd.concat([locations.Latitude + 0.05, locations.Longitude - 0.05],
                     axis=1)
    loc4 = loc4.apply(tuple, axis=1)
    loc = pd.concat([loc1, loc2, loc3, loc4], axis=1)

    # print(loc)
    # print(loclist)

    loclist = loc.values.tolist()

    # configuring gmaps
    gmaps.configure(api_key='AIzaSyCZjvcaXP_7Fc3hCr-TWM6-I7SYKHau6Dw')
    # new gmaps figure
    fig = gmaps.figure(center=((51.209381 + 48.431117) / 2,
                               (11.265527 + 19.04932) / 2),
                       zoom_level=7)

    # Boundaries for the Czech and Slovak Republic
    # Latitude    Longitude
    # 51.209381   11.265527
    # 48.431117   11.265527
    # 51.209381   19.04932
    # 48.431117   19.04932
    polys = []
    for x in range(0, len(loclist)):
        if (loclist[x][0][0] < 51.209381 and loclist[x][0][0] > 48.431117
                and loclist[x][1][1] < 19.04932
                and loclist[x][1][1] > 11.265527):
            r = int(0 + weights[x] * 255)
            g = int(255 - weights[x] * 255)
            col = (r, g, 0)
            polys.append(
                gmaps.Polygon(loclist[x],
                              fill_color=col,
                              fill_opacity=0.8,
                              stroke_color=col,
                              stroke_weight=0))
            print(
                str(x) + "/" + str(len(loclist)) + " | Rendering: " +
                str(loclist[x]) + " with color: " + str(col))

    # layer for overlaying pollution
    drawing = gmaps.drawing_layer()
    drawing.features = polys
    fig.add_layer(drawing)

    # start = (51.209381, 11.265527)
    # end = (48.431117, 19.04932)
    # directions = gmaps.directions_layer(start, end, travel_mode='WALKING')
    # fig.add_layer(directions)

    # exporting html file with a Google Map
    if (not os.path.exists("cams_cache/html")):
        try:
            os.mkdir("cams_cache/html")
        except OSError:
            print("Creation of the directory" + "cams_cache/html" + " failed")
    print("Exporting: " + infile.replace('csv', 'html'))
    embed_minimal_html(infile.replace('csv', 'html'), views=[fig])
    return None
Example #6
0
              (41.673009, 45.007487),
              (41.656818, 44.627870)]

DidiDigomiPLY = [(41.801125, 44.726993), 
                 (41.821502, 44.776487),
                 (41.814003, 44.784271), 
                 (41.787966, 44.784622),
                 (41.787665, 44.770549), 
                 (41.760436, 44.768482),
                 (41.766687, 44.709715)]

DidiDigomi = []
poly = Polygon(TbilisiPLY)
for Clat, Clng in coordinates:
    if poly.contains(Point(Clat,Clng)) == True:
        DidiDigomi.append([Clat,Clng])
for i in enumerate():

gmaps.configure(api_key=api_key)
 
fig = gmaps.figure()

fig.add_layer(gmaps.drawing_layer(features=[gmaps.Polygon(tbilisi_ply, stroke_color='red', fill_color=(255, 0, 132)) ]))
fig.add_layer(gmaps.drawing_layer(features=[gmaps.Polygon(saburtalo_ply, stroke_color='blue', fill_color=(255, 0, 132)) ]))

heatmap_layer = gmaps.heatmap_layer(coords)
fig.add_layer(heatmap_layer)

markers = gmaps.symbol_layer(coors, fill_color='green', stroke_color='green', scale=2)
fig.add_layer(markers)
embed_minimal_html('export.html', views=[fig])
Example #7
0
              (41.772717, 44.977507), (41.673009, 45.007487),
              (41.656818, 44.627870)]
DidiDigomiPLY = [(41.801125, 44.726993), (41.821502, 44.776487),
                 (41.814003, 44.784271), (41.787966, 44.784622),
                 (41.787665, 44.770549), (41.760436, 44.768482),
                 (41.766687, 44.709715)]
DidiDigomi = []
poly = Polygon(DidiDigomiPLY)
for Clat, Clng in coordinates:
    if poly.contains(Point(Clat, Clng)) == True:
        DidiDigomi.append([Clat, Clng])

fig = gmaps.figure()
fig.add_layer(
    gmaps.drawing_layer(features=[
        gmaps.Polygon(TbilisiPLY, stroke_color='red', fill_color=(255, 0, 132))
    ]))
fig.add_layer(
    gmaps.drawing_layer(features=[
        gmaps.Polygon(
            DidiDigomiPLY, stroke_color='blue', fill_color=(255, 0, 132))
    ]))

heatmap_layer = gmaps.heatmap_layer(DidiDigomi)
fig.add_layer(heatmap_layer)
markers = gmaps.symbol_layer(DidiDigomi,
                             fill_color='green',
                             stroke_color='green',
                             scale=2)
fig.add_layer(markers)
embed_minimal_html('export.html', views=[fig])
#%%
# Charting Stuff on a Map
with open("./secrets.json") as f:
    data = f.read()
    api_key = json.loads(data)['key']

gmaps.configure(api_key=api_key)
fig = gmaps.figure()
fig.add_layer(gmaps.heatmap_layer(ems[['Location Latitude', 'Location Longitude']], weights=ems['Total Patients']))
fig

#%%
fig = gmaps.figure()
drawing = gmaps.drawing_layer(features=[
     gmaps.Line((46.23, 5.86), (46.44, 5.24), stroke_weight=3.0),
     gmaps.Marker((46.88, 5.45), label='D'),
     gmaps.Polygon(
         [(46.72, 6.06), (46.48, 6.49), (46.79, 6.91)],
         fill_color='red'
     )
])
fig.add_layer(drawing)
fig


#%%
gmaps.__version__

#%%