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
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
def route_explorer_from_file(): global reff_fig global reff_drawing global reff_dropdown global reff_routes reff_routes = open('routes.ipts').read().splitlines() reff_dropdown = widgets.Dropdown( options=[''] + reff_routes, description='Route', disabled=False, ) def route_changed(r): global reff_drawing if r.new != '': map_plot(list(map(int, r.new.split(','))), reff_drawing) else: reff_drawing.features = [] reff_dropdown.observe(route_changed, 'value') reff_fig = gmaps.figure(center=(55.785822, 12.521520), zoom_level=16, layout={ 'height': '800px', 'width': '800px' }) reff_drawing = gmaps.drawing_layer(show_controls=False) reff_fig.add_layer(reff_drawing) display(reff_dropdown) display(reff_fig)
def plot_route_map(self, freq): station_pairs = [sorted(i) for i in (self.route_dis.index)] bs = self.bikesystem fig = gmaps.figure(center=tuple(bs.locate(bs.mp.index[0])), zoom_level=11) layer = gmaps.drawing_layer(features=[ gmaps.Line(start=tuple(bs.locate(i)), end=tuple(bs.locate(j))) for i, j in self.highfreq_routes(freq) ]) fig.add_layer(layer) return fig
def __init__(self): self._figure = gmaps.figure() self._drawing = gmaps.drawing_layer() self._drawing.on_new_feature(self._new_feature_callback) self._figure.add_layer(self._drawing) self._address_box = widgets.Text(description='Address: ', disabled=True, layout={ 'width': '95%', 'margin': '10px 0 0 0' }) self._geocoder = geopy.geocoders.GoogleV3(api_key=API_KEY) self._container = widgets.VBox([self._figure, self._address_box])
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
def route(start, end, fig, color, stroke_weight_line, mode='walking'): directions_result = google_maps.directions(start, end, mode=mode) polyline_directions = polyline.decode( directions_result[0]['overview_polyline']['points']) polyline_result = [ (a, b) for a, b in zip(polyline_directions, polyline_directions[1:]) ] for i in range(len(polyline_result)): line_drawing = gmaps.Line(start=polyline_result[i][0], end=polyline_result[i][1], stroke_weight=stroke_weight_line, stroke_color=color, stroke_opacity=1.0) drawing = gmaps.drawing_layer(features=[line_drawing], show_controls=False) fig.add_layer(drawing)
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
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
(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])
(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__ #%%
def route_explorer(): global re_circular global re_stops global re_fig global re_drawing global re_button_stops global re_button_circular global re_box global re_label def reset(): global re_label global re_drawing re_label.value = ', '.join(map(str, re_stops)) if len(re_stops) >= 2: map_plot(re_stops, re_drawing) else: re_drawing.features = [] def stop_toggled(b): global re_stops if b['new']: if re_circular: re_stops.insert(len(re_stops) - 1, int(b['owner'].description)) else: re_stops.append(int(b['owner'].description)) else: stop = int(b['owner'].description) if re_circular and stop == re_stops[0]: re_stops.remove(stop) re_stops.remove(stop) if len(re_stops) == 0: global re_button_circular re_button_circular.value = False else: re_stops.append(stops[0]) else: re_stops.remove(stop) reset() def circular_toggled(b): global re_circular global re_stops re_circular = b['new'] if re_circular: b['owner'].button_style = 'success' if len(re_stops) > 0: re_stops.append(stops[0]) else: b['owner'].button_style = '' if len(re_stops) > 1: re_stops.pop(-1) reset() re_circular = False re_stops = [] re_fig = gmaps.figure(center=(55.785822, 12.521520), zoom_level=16, layout={ 'height': '800px', 'width': '800px' }) re_drawing = gmaps.drawing_layer(show_controls=False) re_fig.add_layer(re_drawing) re_buttons_stops = [ widgets.ToggleButton( description=str(i), disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '', layout={ 'width': '30px', 'height': '30px' }) for i in range(n_candidate_stops) ] re_button_circular = widgets.ToggleButton(description='C', disabled=False, layout={ 'width': '30px', 'height': '30px' }) re_box = widgets.Box([widgets.Label('Stops')] + re_buttons_stops + [re_button_circular]) re_label = widgets.Label('') for button in re_buttons_stops: button.observe(stop_toggled, 'value') re_button_circular.observe(circular_toggled, 'value') display(re_box) display(re_label) display(re_fig)