Example #1
0
def main(args):

    path = get_path(args[0])
    date = args[0].strip().split('/')

    airports, commands = handle_args(args)
    print 'Airports: ' + str(airports)
    flightdata = sc.textFile(path).map(parse_flights)
    airportdata = get_airport_data(airports)
    i = 0.5
    if len(airports) == 1:
        i = 1.5
    (lat_range, lon_range) = get_area(airportdata,i)


    flightdata = flightdata.filter(lambda x: x['lat'] >= (lat_range['min']-1) and x['lat'] <= (lat_range['max']+1)
                        and x['lon'] >= (lon_range['min']-1) and x['lon'] <= (lon_range['max']+1))

    boundary_paths = get_boundary_paths({'lat': lat_range, 'lon': lon_range})
    ctr_lat = (lat_range['min']+lat_range['max'])/2
    ctr_lon = (lon_range['min']+lon_range['max'])/2

    gmap = GoogleMapPlotter(ctr_lat, ctr_lon, 8)
    for path in boundary_paths:
        gmap.plot(path['lat_range'], path['lon_range'], 'cornflowerblue', edge_width=10)


    if len(airports) >= 2:
        alldata = flightdata.filter(lambda x: x['arr_airport'] in airports and x['dep_airport'] in airports)
    else:
        alldata = flightdata.filter(lambda x: x['arr_airport'] in airports)

    alldata.cache()
    detect_info = detect_delay(alldata,airports,gmap)
    def draw(self, referential_race_name, comparison_race_name, segment_type, filename):
        """Draw both races and the corresponding best segment"""
        race_manager = self.race_inferer.race_manager
        referential_race = race_manager.races[referential_race_name]
        comparison_race = race_manager.races[comparison_race_name]

        deniv_segment, length_segment, density_segment = self.get_best_segment(referential_race_name)
        segments = deniv_segment + length_segment + density_segment

        segment = None

        for segment_tuple in segments:
            if segment_tuple[0] == comparison_race_name and segment_tuple[1].segment_type == segment_type:
                segment = segment_tuple[1]
                break

        if GOOGLE_MAP_API_KEY is None:
            gmap3 = GoogleMapPlotter(46.98, 6.89, 14)
        else:
            gmap3 = GoogleMapPlotter(46.98, 6.89, 14, apikey=GOOGLE_MAP_API_KEY)

        gmap3.plot(referential_race.df.position_lat, referential_race.df.position_long, 'cornflowerblue',
                   edge_width=2.5)
        gmap3.plot(comparison_race.df.position_lat, comparison_race.df.position_long, 'limegreen',
                   edge_width=2.5)

        segment.draw('red', gmap3)

        gmap3.draw(filename)
Example #3
0
    def plotGridonMap(self, grid):
        def color_scatter(gmap,
                          lats,
                          lngs,
                          values=None,
                          colormap='coolwarm',
                          size=None,
                          marker=False,
                          s=None,
                          **kwargs):
            def rgb2hex(rgb):
                """ Convert RGBA or RGB to #RRGGBB """
                rgb = list(rgb[0:3])  # remove alpha if present
                rgb = [int(c * 255) for c in rgb]
                hexcolor = '#%02x%02x%02x' % tuple(rgb)
                return hexcolor

            if values is None:
                colors = [None for _ in lats]
            else:
                cmap = plt.get_cmap(colormap)
                norm = Normalize(vmin=min(values), vmax=max(values))
                scalar_map = ScalarMappable(norm=norm, cmap=cmap)
                colors = [
                    rgb2hex(scalar_map.to_rgba(value)) for value in values
                ]
            for lat, lon, c in zip(lats, lngs, colors):
                gmap.scatter(lats=[lat],
                             lngs=[lon],
                             c=c,
                             size=size,
                             marker=marker,
                             s=s,
                             **kwargs)

        initial_zoom = 12
        apikey = 'AIzaSyAZ_VZXoJULTFQ9KSPg1ClzHEFjyPbJUro'
        gmap = GoogleMapPlotter(grid[0, 0],
                                grid[0, 1],
                                initial_zoom,
                                apikey=apikey)
        color_scatter(gmap,
                      grid[:, 0],
                      grid[:, 1],
                      np.zeros_like(grid[:, 0]),
                      size=20,
                      colormap='hsv')
        gmap.draw(
            "/Users/yaoling/OneDrive - NTNU/MASCOT_PhD/Missions/MapPlot/map.html"
        )
Example #4
0
    def draw(self, color='cornflowerblue', gmap3=None):
        if gmap3 is None:
            if GOOGLE_MAP_API_KEY is None:
                gmap3 = GoogleMapPlotter(46.98, 6.89, 14)
            else:
                gmap3 = GoogleMapPlotter(46.98,
                                         6.89,
                                         14,
                                         apikey=GOOGLE_MAP_API_KEY)

        gmap3.plot(self.df.position_lat,
                   self.df.position_long,
                   color,
                   edge_width=2.5)

        filename = os.path.join(st.files["output_folder"], f"{self.name}.html")
        gmap3.draw(filename)
Example #5
0
 def checkGridCoord(lat_origin, lon_origin, lat, lon):
     initial_zoom = 12
     apikey = 'AIzaSyAZ_VZXoJULTFQ9KSPg1ClzHEFjyPbJUro'
     gmap = GoogleMapPlotter(lat_origin,
                             lon_origin,
                             initial_zoom,
                             map_type='satellite',
                             apikey=apikey)
     gmap.scatter(lat, lon, color='#99ff00', size=20, marker=False)
     gmap.draw(
         "/Users/yaoling/OneDrive - NTNU/MASCOT_PhD/Missions/MapPlot/map.html"
     )
Example #6
0
    def draw_race_and_matches(self, race, matches):
        if GOOGLE_MAP_API_KEY is None:
            gmap3 = GoogleMapPlotter(46.98, 6.89, 14)
        else:
            gmap3 = GoogleMapPlotter(46.98, 6.89, 14, apikey=GOOGLE_MAP_API_KEY)

        gmap3.plot(race.df.position_lat, race.df.position_long, 'cornflowerblue', edge_width=2.5)

        for (race_name, match) in matches:
            match.draw('yellow', gmap3=gmap3)

        return gmap3
Example #7
0
 def checkBox(self):
     from gmplot import GoogleMapPlotter
     initial_zoom = 12
     apikey = 'AIzaSyAZ_VZXoJULTFQ9KSPg1ClzHEFjyPbJUro'
     gmap = GoogleMapPlotter(self.lat_origin,
                             self.lon_origin,
                             initial_zoom,
                             map_type='satellite',
                             apikey=apikey)
     gmap.scatter(self.box[:, 0], self.box[:, 1], 'cornflowerblue', size=10)
     gmap.draw(
         "/Users/yaoling/OneDrive - NTNU/MASCOT_PhD/Missions/MapPlot/map.html"
     )
Example #8
0
def plot_location_node(locs, labels):
    mymap = gmp.from_geocode("New York")

    clist = color_dicts.html_color_codes.keys()
    for cur_label in range(np.max(labels)):
        print("cur_label", cur_label)
        path = [[], []]
        color = ''
        for i in range(len(locs)):
            loc = locs[i]
            cluster_label = labels[i]
            assert (loc != 'not applicable')
            if cluster_label == cur_label:
                # print("Color", clist[cluster_label])
                color = clist[cluster_label]
                path[0].append(float(loc.split(' ')[0]))
                path[1].append(-float(loc.split(' ')[2]))

        edge = [tuple(path[0]), tuple(path[1])]
        # mymap.heatmap(edge[0], edge[1], threshold=5, radius=40)
        mymap.scatter(edge[0], edge[1], c=color, s=200, marker=False, alpha=1)
    mymap.draw("cluster_map.html")
Example #9
0
 def checkGridCoord(self):
     from gmplot import GoogleMapPlotter
     initial_zoom = 12
     apikey = 'AIzaSyAZ_VZXoJULTFQ9KSPg1ClzHEFjyPbJUro'
     gmap = GoogleMapPlotter(self.lat_origin,
                             self.lon_origin,
                             initial_zoom,
                             map_type='satellite',
                             apikey=apikey)
     gmap.scatter(self.grid_coord[:, 0],
                  self.grid_coord[:, 1],
                  color='#99ff00',
                  size=20,
                  marker=False)
     gmap.draw(
         "/Users/yaoling/OneDrive - NTNU/MASCOT_PhD/Missions/MapPlot/map.html"
     )
Example #10
0
    def draw(self):
        if self.density_segment is None or self.length_segment is None or self.deniv_segment is None:
            print("Need to call all 3 get_..._segment before draw()")
            return -1

        if GOOGLE_MAP_API_KEY is None:
            gmap3 = GoogleMapPlotter(46.98, 6.89, 14)
        else:
            gmap3 = GoogleMapPlotter(46.98, 6.89, 14, apikey=GOOGLE_MAP_API_KEY)

        self.length_segment.draw('purple', gmap3=gmap3)
        self.density_segment.draw('red', gmap3=gmap3)
        self.deniv_segment.draw('yellow', gmap3=gmap3)

        filename = os.path.join(st.files["output_folder"], f"best_segment_{self.referential_race_name}.html")
        gmap3.draw(filename)

        return 0
Example #11
0
    def draw(self):
        if GOOGLE_MAP_API_KEY is None:
            gmap3 = GoogleMapPlotter(46.98, 6.89, 14)
        else:
            gmap3 = GoogleMapPlotter(46.98,
                                     6.89,
                                     14,
                                     apikey=GOOGLE_MAP_API_KEY)

        self.race1.draw(color='cornflowerblue', gmap3=gmap3)
        self.race2.draw(color='limegreen', gmap3=gmap3)

        # Plot segment
        for segment in self.segments:
            segment.draw(color='red', gmap3=gmap3)

        output_folder = st.files["output_folder"]
        filename = f'{output_folder}/{self.name}.html'

        gmap3.draw(filename)
Example #12
0
# import gmplot
from gmplot import GoogleMapPlotter

mymap = GoogleMapPlotter(37.428, -122.145, 16)
# mymap.marker(37.427, -122.145, "yellow")
# mymap.marker(37.428, -122.146, "cornflowerblue")
path = [(37.429, 37.428, 37.427, 37.427, 37.427),
             (-122.145, -122.145, -122.145, -122.146, -122.146)]
path2 = [[i+.01 for i in path[0]], [i+.02 for i in path[1]]]
path3 = [(37.433302 , 37.431257 , 37.427644 , 37.430303), (-122.14488, -122.133121, -122.137799, -122.148743)]
path4 = [(37.423074, 37.422700, 37.422410, 37.422188, 37.422274, 37.422495, 37.422962, 37.423552, 37.424387, 37.425920, 37.425937),
     (-122.150288, -122.149794, -122.148936, -122.148142, -122.146747, -122.14561, -122.144773, -122.143936, -122.142992, -122.147863, -122.145953)]
# mymap.plot(path[0], path[1], "plum", edge_width=10)
# mymap.plot(path2[0], path2[1], "red")
# mymap.polygon(path3[0], path3[1], edge_color="cyan", edge_width=5, face_color="blue", face_alpha=0.1)
# mymap.heatmap(path4[0], path4[1], threshold=10, radius=40)
# mymap.heatmap(path3[0], path3[1], threshold=10, radius=40, dissipating=False, gradient=[(30,30,30,0), (30,30,30,1), (50, 50, 50, 1)])
# mymap.scatter(path4[0], path4[1], c='r', marker=True)
# mymap.scatter(path4[0], path4[1], s=90, marker=False, alpha=0.1)

edge = [(37.429, 37.428),(-122.145, -122.145)]
mymap.plot(edge[0], edge[1], "plum", edge_width=20)

mymap.draw("mymap.html")
 def __init__(self, location, file_path):
     self._file_path = file_path
     self._gmap = GoogleMapPlotter.from_geocode(location)
     self._marker_list = []
     self._jpg_paths = []
     self._per_dir_jpg_paths = {}
Example #14
0
            elif DB[tweet]['place']['place_type'] == 'poi':
                longitude = float(DB[tweet]['place'][u'bounding_box'][u'coordinates'][0][0][0])
                latitude = float(DB[tweet]['place'][u'bounding_box'][u'coordinates'][0][0][1])
                if (category == 'PO'):
                    po_lon.append(longitude)
                    po_lat.append(latitude)
                elif category == 'PL':
                    pl_lon.append(longitude)
                    pl_lat.append(latitude)

    po_scatter_path = (po_lat,po_lon)
    pl_scatter_path = (pl_lat,pl_lon)

    if (city is 'US'):
        mymap = GoogleMapPlotter(39.908213, -99.675441, 4)
    else:
        mymap = GoogleMapPlotter.from_geocode(city, 12)
        lat, lng = mymap.geocode(city)
    for group in ultralist:
        drawGroupBox(group,mymap)
        
    mymap.scatter(po_scatter_path[0], po_scatter_path[1], c='tomato', marker=True)
    mymap.scatter(pl_scatter_path[0], pl_scatter_path[1], c='lemonchiffon', marker=True)
    mymap.draw('./mymap.html')
    webbrowser.open(tweetMap)
        
    
if (searchType == 'real'):
    startDate = raw_input('Enter todays date: ')
Example #15
0
    def segment_density(self, referential_race_name, verbose=0):
        all_segments = list(self.all_seg_of_one_race[referential_race_name])

        points = np.array(all_segments[0].positions[:2, :])

        for segment in all_segments[1:]:
            try:
                points = np.append(points, segment.positions[:2, :], axis=1)
            except:
                print("Probably zero size array...")

        max_lat = np.max(points[0, :])
        max_long = np.max(points[1, :])
        min_lat = np.min(points[0, :])
        min_long = np.min(points[1, :])

        delta = 0.0005  # degré

        lat = np.arange(min_lat, max_lat, delta)
        long = np.arange(min_long, max_long, delta)
        density = np.zeros([3, lat.shape[0] * long.shape[0]])  # [lat,long,nbpoint]

        i = 0
        for x in lat:
            for y in long:
                # parcours et remplissage de la "grid" de densité

                density[0, i] = x
                density[1, i] = y

                for segment in all_segments:

                    seg = segment.positions

                    x_less = np.where(seg[0, :] >= (x - delta / 2))
                    x_more = np.where(seg[0, :] < (x + delta / 2))
                    count_x = np.intersect1d(x_less, x_more)

                    y_less = np.where(seg[1, :] >= (y - delta / 2))
                    y_more = np.where(seg[1, :] < (y + delta / 2))
                    count_y = np.intersect1d(y_less, y_more)

                    valid_coordinate = np.intersect1d(count_x, count_y).shape[0]

                    if valid_coordinate > 0:
                        # on ajoute 1 si le segment est dedans (la case de la grid)
                        density[2, i] = density[2, i] + 1

                i += 1

        # repasser tous les segment et ajouter leur propre densité max,min,mean pour chacun
        max_seg_density = dict()
        min_seg_density = dict()
        mean_seg_density = dict()
        seg_present_in = dict()

        for segment in all_segments:
            # FIXME convention --> le nom du segment c'est le timestamp de début de la course 1 (devrait ^etre unique)
            seg_name = segment.times1[0]
            min_seg_density[seg_name] = 100
            max_seg_density[seg_name] = 0
            mean_seg_density[seg_name] = 0
            seg_present_in[seg_name] = 0

        i = 0
        for x in lat:
            for y in long:
                # parcours de la "grid" et regarder combien de point il y a pour chaque segment

                for segment in all_segments:

                    seg_name = segment.times1[0]
                    seg = segment.positions

                    x_less = np.where(seg[0, :] >= (x - delta / 2))
                    x_more = np.where(seg[0, :] < (x + delta / 2))
                    count_x = np.intersect1d(x_less, x_more)

                    y_less = np.where(seg[1, :] >= (y - delta / 2))
                    y_more = np.where(seg[1, :] < (y + delta / 2))
                    count_y = np.intersect1d(y_less, y_more)

                    valid_coordinate = np.intersect1d(count_x, count_y).shape[0]

                    if valid_coordinate > 0:
                        if density[2, i] > max_seg_density[seg_name]:
                            # si le segment est dedans (la case de la grid)
                            max_seg_density[seg_name] = density[2, i]

                        if density[2, i] < min_seg_density[seg_name]:
                            min_seg_density[seg_name] = density[2, i]

                        mean_seg_density[seg_name] += density[2, i]
                        seg_present_in[seg_name] += 1

                i += 1

        for segment in all_segments:
            seg_name = segment.times1[0]

            mean_seg_density[seg_name] = mean_seg_density[seg_name] / seg_present_in[seg_name]

        # print(max_seg_density)
        # print(min_seg_density)
        # print(seg_present_in)
        # print(mean_seg_density)

        # Print denstiy seg map
        if GOOGLE_MAP_API_KEY is None:
            gmap3 = GoogleMapPlotter(46.98, 6.89, 14)
        else:
            gmap3 = GoogleMapPlotter(46.98, 6.89, 14, apikey=GOOGLE_MAP_API_KEY)

        self.races[referential_race_name].draw(color='cornflowerblue', gmap3=gmap3)

        # Plot segment
        for segment in all_segments:
            segment.draw(color='purple', gmap3=gmap3)

        # Plot density grid
        for i in range(density.shape[1]):
            if density[2, i] > 2:
                gmap3.scatter([density[0, i]], [density[1, i]], "yellow", size=density[2, i], marker=False)

        filename = os.path.join(st.files["output_folder"], f"seg_density_{referential_race_name}.html")
        gmap3.draw(filename)

        self.race_segment_density[referential_race_name] = density
        self.race_density_delta[referential_race_name] = delta
        self.race_mean_seg_density[referential_race_name] = mean_seg_density
Example #16
0
for c in cameras:
    count, density = gen.generate_features(c)
    traffic_stat = clf.predict([count, density])
    if traffic_stat == 2:
        print(c, ' : High traffic')
    elif traffic_stat == 1:
        print(c, ' : Medium traffic')
    else:
        print(c, ' : Low traffic')
    traffic.append(traffic_stat)

count = [traffic.count(0), traffic.count(1), traffic.count(2)]
status = count.index(max(count))

color = ['green', 'yellow', 'red']
gmap = gmp.from_geocode(
    "Veermata Jijabai Technological Institute, Mumbai, Maharashtra")
gmap.scatter([19.018892, 19.024714], [72.855786, 72.856964],
             color[status],
             size=40,
             marker=False)
gmap.scatter(
    [19.019693, 19.020433, 19.021336, 19.022432, 19.024055, 19.023030],
    [72.856173, 72.856409, 72.856570, 72.856763, 72.857053, 72.856914],
    color[status],
    size=10,
    marker=False)

##this will generate html file of google map
gmap.draw("map.html")
def ua_map(datax, datay, sales):
    ua_map = GoogleMapPlotter.from_geocode("Ukraine", 7)
    for (x, y, s) in zip(datax, datay, sales):
        ua_map.scatter([x], [y], c='#%02x%02x%02x' % convert_to_rgb(s+1, maxval=10), size=1000+10*s, marker=False, alpha=0.5)    
    #ua_map.heatmap(datax, datay, radius=40)
    ua_map.draw("mymap.html")
Example #18
0
    def service_cb(self, request):
        dt = (rospy.Time.now() - self.last_called_stamp).to_sec()
        if dt < self.MIN_TIME_BETWEEN_CALLS:
            raise rospy.ServiceException(
                "Minimum time between plot requests is %f seconds.  It's only been %f seconds"
                % (self.MIN_TIME_BETWEEN_CALLS, dt))

        if len(request.points) == 0:
            raise rospy.ServiceException('No points present in request')

        # Sort points into sequential groups of like types
        plot_groups = []
        for p in request.points:
            added_to_group = False
            # See if next point belongs in an existing group
            for group in plot_groups:
                added_to_group = group.add_to_group(p)

            # Create new plotting group if current point hasn't been added
            # to an existing one
            if not added_to_group:
                plot_groups.append(PlotGroup(p))

        # Initialize Google Maps plot
        map_type = 'satellite' if request.satellite_view else None
        gplot = GoogleMapPlotter(request.center_lat,
                                 request.center_lon,
                                 request.zoom,
                                 map_type=map_type)

        # Loop through plotting groups to add plots to map
        for group in plot_groups:
            lats = [p.lat for p in group.members]
            lons = [p.lon for p in group.members]
            colors = [p.color for p in group.members]
            texts = [p.text for p in group.members]

            if group.type == PlotPoint.SCATTER_POINT:
                gplot.scatter(lats,
                              lons,
                              group.color,
                              size=group.size,
                              marker=False)
            elif group.type == PlotPoint.LINE:
                gplot.plot(lats, lons, group.color, edge_width=group.size)
            elif group.type == PlotPoint.MARKER:
                gplot.scatter(lats, lons, group.color, marker=True)
            elif group.type == PlotPoint.TEXT_LABEL or group.type == PlotPoint.MARKER_WITH_TEXT:
                for i in xrange(len(group.members)):
                    gplot.text(
                        lats[i],
                        lons[i],
                        colors[i],
                        text=texts[i],
                        marker=(group.type == PlotPoint.MARKER_WITH_TEXT))
            else:
                raise rospy.ServiceException(
                    'Tried to plot an unsupported type')

        self.last_called_stamp = rospy.Time.now()
        if request.save_map:
            # Just write map to designated file and be done
            gplot.draw(request.filename, self.api_key)
            rospy.loginfo('Saving map to: %s' % request.filename)
        else:
            # Write the map to the temporary file and immediately open default
            # browser to view it
            gplot.draw(self.tmp.name, self.api_key)
            os.system('xdg-open ' + self.tmp.name)

        return PlotMapResponse()
        
            xy = X[class_member_mask & ~core_samples_mask]
            plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,
                     markeredgecolor='k', markersize=2)
        
        plt.title('Estimated number of clusters: %d, %d' % (n_clusters_, len(labels[labels == -1])))
        plt.show()
    print('Singled: %d, max: %d' % (data.groupby(by='cluster').count().query('Customer_Code == 1').count()[0], data.groupby(by='cluster').count().max()[0]))
    return data, last_index

#Кластеризуем дважды, при этом запоминаем номер последнего кластера, чтобы кластера не пересекались
kiev_loc, index = cluster(kiev_loc)
kiev_loc_singles = kiev_loc[kiev_loc.cluster.isin(kiev_loc.groupby(by='cluster').count().query('Customer_Code == 1').reset_index()['cluster'])]
kiev_loc_singles, index = cluster(kiev_loc_singles, e=0.00441, cluster_last_index=index)

kiev_loc.update(kiev_loc_singles)
kiev_loc.cluster = kiev_loc.cluster.astype(int)

print('Result: Singled: %d, max: %d' % (kiev_loc.groupby(by='cluster').count().query('Customer_Code == 1').count()[0], kiev_loc.groupby(by='cluster').count().max()[0]))
#points are near each to other?
kiev_loc.groupby(by='cluster').agg(np.std).plot()


ua_map = GoogleMapPlotter.from_geocode("Ukraine, Kiev", 12)
for (code, x, y, cluster) in kiev_loc.as_matrix():
    ua_map.scatter([y], [x], c='#%02x%02x%02x' % convert_to_rgb(cluster, minval=kiev_loc.cluster.min(), maxval=kiev_loc.cluster.max()), size=50, marker=False, alpha=0.5)
    
ua_map.draw("clustered.html")


#50.41916499 30.51916459