Exemplo n.º 1
0
    def display(self):
        plt.figure()
        for car in self.cars:
            node0, node1 = car.route[0]
            if car.arrive_to_destination():
                plt.plot(
                    ((nodes[node0]['longitude'] + nodes[node1]['longitude']) /
                     2),
                    ((nodes[node0]['latitude'] + nodes[node1]['latitude']) /
                     2), 'gs')
            else:
                plt.plot(
                    ((nodes[node0]['longitude'] + nodes[node1]['longitude']) /
                     2),
                    ((nodes[node0]['latitude'] + nodes[node1]['latitude']) /
                     2), 'bs')

        for system in self.systems:
            node0, node1 = system.route[0]
            plt.plot(
                ((nodes[node0]['longitude'] + nodes[node1]['longitude']) / 2),
                ((nodes[node0]['latitude'] + nodes[node1]['latitude']) / 2),
                'rs')

        mplleaflet.save_html(
            fileobj='images/{:02d}{:02d}{:02d}_simulation_{}.html'.format(
                self.time_hours_from_beginning,
                self.time_minutes_from_beginning,
                self.time_seconds_from_beginning, self.simulation_id))
Exemplo n.º 2
0
def leafletdo(db):
    uids = []
    lats = []
    longs = []
    tokens = []
    users = db.child("users").get().val()
    for key, value in users.items():
        # print(key, value)
        if "location" in value and "token" in value:
            uids.append(key)
            lats.append(float(value["location"]["lat"]))
            longs.append(float(value["location"]["long"]))
            tokens.append(value["token"]["token"])

    print(uids)

    # plt.figure(figsize=(8,6))
    # fig = plt.figure()
    fig, ax = plt.subplots(figsize=(8, 8))
    for i, uid in enumerate(uids):
        x = longs[i]
        y = lats[i]
        ax.scatter(x, y, marker='x', color='red')
        ax.text(x + 0.3, y + 0.3, uid, fontsize=9)

    #plt.figure(figsize=(8,6))
    #fig = plt.figure()
    #plt.plot(longs, lats, 'ro')

    mplleaflet.save_html(fileobj=os.path.join(dir_path, "templates/map.html"),
                         fig=fig)
Exemplo n.º 3
0
def bikesplorela():
    """Main page"""
    form = LoginForm()
    if form.validate_on_submit():

        session['pointA'] = form.pointA.data

        session['pointB'] = form.pointB.data

        geo_df = gs.read_file('app/static/collisions.geojson')

        locs = {
            'Loc1': [-118.336389, 34.100833],
            'Loc2': [-118.356, 34.0628],
            'Loc3': [-118.3208331, 34.0837995]
        }

        Loc1 = form.pointA.data
        Loc2 = form.pointB.data

        x1, y1 = locs[form.pointA.data]
        x2, y2 = locs[form.pointB.data]

        reqtxt = 'http://router.project-osrm.org/route/v1/driving/{x1},{y1};{x2},{y2}?overview=simplified&exclude=motorway&annotations=true&geometries=geojson'.format(
            x1=x1, y1=y1, x2=x2, y2=y2)

        rout = requests.get(reqtxt)
        route = json.loads(rout.text)

        coords = route['routes'][0]['geometry']['coordinates']
        xs_route = [c[0] for c in coords]
        ys_route = [c[1] for c in coords]

        map_file = 'app/static/map_{loc1}_{loc2}.html'.format(loc1=Loc1,
                                                              loc2=Loc2)

        map_file2 = 'static/map_{loc1}_{loc2}.html'.format(loc1=Loc1,
                                                           loc2=Loc2)

        f, ax = plt.subplots(1)

        geo_df.geometry.plot(alpha=0.9, edgecolor='red',
                             ax=ax)  #plot dangergrid
        ax.plot(xs_route, ys_route, color='blue', linewidth=4, alpha=0.5)

        mplleaflet.save_html(fig=f, crs=geo_df.crs, fileobj=map_file)

        #fname = str(tmp.communicate()[0].strip(b'\n'),'utf-8')

    elif request.method == 'GET':
        form.pointA.data = session.get('pointA', '')
        form.pointB.data = session.get('pointB', '')
        map_file2 = 'static/map.html'

    return render_template('bikesplorela.html', form=form, map_file=map_file2)
Exemplo n.º 4
0
def _plot_mplleafflet(lats, lons, observable_values_in_minutes,
                      observable_name, scalar_mappable, basename, node_names):
    import mplleaflet
    fig = plt.figure()
    ax = fig.add_subplot(111)
    colors = scalar_mappable.to_rgba(observable_values_in_minutes)

    assert (isinstance(ax, matplotlib.axes.Axes))
    ax.scatter(lons, lats, c=colors, edgecolors=colors, s=10)
    cbar = fig.colorbar(scalar_mappable)
    ax.set_title(observable_name)
    mplleaflet.save_html(fig, basename + observable_name + ".html")
    def leaflet_heatmap(cls, yy, xx, Z, bounds, tiles='cartodb_positron', map_path='_map.html', legend_text='',
                        description_title='', description_text=''):
        """
        Plots a heatmap over a leaflet layer
        Parameters
        ----------
        yy: np.array of y-coordinates
        xx: np.array of x-coordinates
        Z: np.array of Z-coordinates
        bounds: ((x_min, y_min), (x_max, y_max)) or None
        tiles: str
            Name of the tiles to use
        map_path: str
            Where to output html
        legend_text: str
            Text to put on the legend
        description_title: str
            Title of the description box
        description_text: str
            Text used to describe the map
        Returns
        -------

        """

        plt.figure()
        plt.pcolormesh(yy, xx, Z, cmap='YlGnBu', alpha=1)
        plt.xlim(bounds[0][0], bounds[1][0])
        plt.ylim(bounds[0][1], bounds[1][1])

        vmin = Z.min()
        vmax = Z.max()

        if tiles == 'cartodb_positron':
            tiles = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png'
            attr = '&copy; <a href="http://cartodb.com/attributions">CartoDB</a> | ' \
                   '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> | ' \
                   '&copy; Michael Clawar & Raaid Arshad'
            tiles = (tiles, attr)
        elif tiles == 'osm_mapnik':
            tiles = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            attr = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> | ' \
                   '&copy; Michael Clawar & Raaid Arshad</a>'
            tiles = (tiles, attr)
        else:
            raise ValueError

        mplleaflet.save_html(fileobj=map_path, tiles=tiles)
        cls.add_legend_mplleaflet(map_path, legend_text=legend_text, vmin=vmin, vmax=vmax,
                                  description_title=description_title, description_text=description_text)
Exemplo n.º 6
0
	def makeMap(self, linewidth=2.5, output_file='map'):
		for axarr in self.axarr:
			axarr.lines = []

		if self.map:
			raise TrackException('Map background found in the figure', 'Remove it to create an interactive HTML map.')

		if 'Color' in self.track_df.df:
			for point, next_point in self.computePoints(linewidth=linewidth):
				pass
		else:
			self.computeTracks(linewidth=linewidth)

		mplleaflet.save_html(fig=self.fig, tiles='esri_aerial',	 fileobj=output_file + '.html')#, close_mpl=False) # Creating html map
Exemplo n.º 7
0
def save(fig=None, path='_map.html', **kwargs):
    """
    Convert a Matplotlib Figure to a Leaflet map. Open in a browser

    Parameters
    ----------
    fig : figure, default gcf()
        Figure used to convert to map
    path : string, default '_map.html'
        Filename where output html will be saved

    """
    fullpath = os.path.abspath(path)
    with open(fullpath, 'w') as f:
        mplleaflet.save_html(fig, fileobj=f, **kwargs)
Exemplo n.º 8
0
def plot_train(trip, data_date, route):
    print trip

    data_path = 'data/user_data/' + data_date

    u = 'u_' + trip[0]
    f = open(os.path.join(data_path, u), "r")
    data = [[row[0], int(row[4]),
             float(row[2]), float(row[3])]
            for row in csv.reader(f, delimiter='|')
            ]  #[imsi, unix_time, lon, lat]
    data_df = pandas.DataFrame(data, columns=['imsi', 'time', 'lon', 'lat'])
    data_df = data_df.sort_values(['time'])
    data = data_df.values.tolist()
    #data = np.array([row.rstrip().split("|") for row in f])  #-1943160471|16:57:03,966,490|121.526|25.088|1483520223
    f.close()

    start = int(trip[1])
    end = int(trip[2])
    user = []
    for row in data:
        if (row[1] >= start) and (row[1] <= end):
            user.append([row[2], row[3]])
    print user

    ### plot user data ###
    user = np.array(user)
    plt.hold(True)
    plt.plot(user[:, 0], user[:, 1], 'mo', ms=15)
    plt.plot(user[:, 0], user[:, 1], 'r--', linewidth=5)

    ### plot train station ###
    rail_station = np.array(
        [[rail[station]['position'][0], rail[station]['position'][1]]
         for station in trip[3:5]])
    print rail_station
    plt.plot(rail_station[:, 0], rail_station[:, 1], 'bo', ms=15)

    try:
        os.makedirs('plot_train/' + data_date)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    mplleaflet.save_html(fileobj="./plot_train/%s/%s_%s_%s.html" %
                         (data_date, u, trip[1], trip[2]))
    print
def myshow(fig=None, path='_map.html', **kwargs):
    """
    Convert a Matplotlib Figure to a Leaflet map. Open in a browser

    Parameters
    ----------
    fig : figure, default gcf()
        Figure used to convert to map
    path : string, default '_map.html'
        Filename where output html will be saved

    See fig_to_html() for description of keyword args.

    """
    import webbrowser
    import os
    fullpath = os.path.abspath(path)
    with open(fullpath, 'w') as f:
        mplleaflet.save_html(fig, fileobj=f, **kwargs)
Exemplo n.º 10
0
def draw_map():
    stations = get_stations()
    stations = pd.json_normalize(stations)
    longitude = stations["lon"]
    latitude = stations["lat"]

    status = get_status()
    status = pd.json_normalize(status)
    available_bikes = status["num_bikes_available"]

    fig = plt.figure()
    plt.scatter(longitude,
                latitude,
                s=stations["capacity"] * 3,
                c=available_bikes,
                cmap="RdYlGn",
                vmin=0,
                vmax=10)

    for lon, lat, no_available in zip(longitude, latitude, available_bikes):
        label = str(no_available)
        plt.annotate(label, (lon, lat))
    mplleaflet.save_html(fileobj="static/map/map.html")
Exemplo n.º 11
0
    def plot_map(self):
        '''
        
        Utility function that plots a route on a map
        
        Returns
        -------
        None.

        '''
        fig, ax = plt.subplots()
        df = self.map_df

        df = df.dropna()
        ax.plot(df['lon'],
                df['lat'],
                color='darkorange',
                linewidth=5,
                alpha=0.5)
        mplleaflet.save_html(fig, fileobj="map.html")
        opener = "xdg-open"
        x = os.fork()
        if (x == 0):
            subprocess.call([opener, "map.html"])
Exemplo n.º 12
0
def gen_map_html(OUTPUT_HTML_FILE):
    """
    visualize using mplleaflet
    Map data can be downloaded at: mapzen/metro-extracts, https://www.interline.io/osm/extracts/
    in imposm-geojson format.
    :return:
    """
    # overlay map
    admin = gpd.GeoDataFrame.from_file('singapore.imposm-geojson/singapore_admin.geojson')
    singapore = admin.iloc[0]
    print(singapore)
    print("done")

    # draw base map
    gpd.GeoSeries(singapore.geometry).plot()


    # places of interest
    places = gpd.GeoDataFrame.from_file('singapore.imposm-geojson/singapore_corona.geojson')
    print(places)
    print("done")

    # bounded inside the map
    places = places[places.geometry.within(singapore.geometry)]
    print(places)

    # draw places
    ax = places.geometry.plot(color='red')

    #### Output

    #mplleaflet.display(fig=ax.figure) # To display it right at the notebook.

    #mplleaflet.show(fig=ax.figure) # To output _map.html file and display it in your browser.

    mplleaflet.save_html(fig=ax.figure, fileobj=OUTPUT_HTML_FILE)
    def leaflet_heatmap(cls,
                        yy,
                        xx,
                        Z,
                        bounds,
                        tiles='cartodb_positron',
                        map_path='_map.html',
                        legend_text='',
                        description_title='',
                        description_text=''):
        """
        Plots a heatmap over a leaflet layer
        Parameters
        ----------
        yy: np.array of y-coordinates
        xx: np.array of x-coordinates
        Z: np.array of Z-coordinates
        bounds: ((x_min, y_min), (x_max, y_max)) or None
        tiles: str
            Name of the tiles to use
        map_path: str
            Where to output html
        legend_text: str
            Text to put on the legend
        description_title: str
            Title of the description box
        description_text: str
            Text used to describe the map
        Returns
        -------

        """

        plt.figure()
        plt.pcolormesh(yy, xx, Z, cmap='YlGnBu', alpha=1)
        plt.xlim(bounds[0][0], bounds[1][0])
        plt.ylim(bounds[0][1], bounds[1][1])

        vmin = Z.min()
        vmax = Z.max()

        if tiles == 'cartodb_positron':
            tiles = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png'
            attr = '&copy; <a href="http://cartodb.com/attributions">CartoDB</a> | ' \
                   '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> | ' \
                   '&copy; Michael Clawar & Raaid Arshad'
            tiles = (tiles, attr)
        elif tiles == 'osm_mapnik':
            tiles = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            attr = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> | ' \
                   '&copy; Michael Clawar & Raaid Arshad</a>'
            tiles = (tiles, attr)
        else:
            raise ValueError

        mplleaflet.save_html(fileobj=map_path, tiles=tiles)
        cls.add_legend_mplleaflet(map_path,
                                  legend_text=legend_text,
                                  vmin=vmin,
                                  vmax=vmax,
                                  description_title=description_title,
                                  description_text=description_text)
Exemplo n.º 14
0
def save(fig=None, path='_map.html', template='base.html' ,**kwargs):
    fullpath = os.path.abspath(path)
    with open(fullpath, 'w') as f:
        mplleaflet.save_html(fig, fileobj=f, template =template, **kwargs)
Exemplo n.º 15
0
troop_positions = pd.read_fwf("../../data/napoloen/troops.txt")
troop_positions = gpd.GeoDataFrame(data=troop_positions,
                                   geometry=troop_positions\
                                       .apply(lambda srs: Point(srs['long'], srs['lat']),
                                              axis='columns'))

subsrs = []
for a, b in zip(range(len(troop_positions) - 1), range(1, len(troop_positions))):
    srs = troop_positions.iloc[b]
    srs = srs.rename({'geometry': 'from'})
    srs['to'] = troop_positions.iloc[a].geometry
    subsrs.append(srs)
troop_movements = pd.concat(subsrs, axis=1).T
troop_movements = troop_movements[['survivors', 'direction', 'group', 'from', 'to']]
troop_movements['direction'] = troop_movements.direction.map(lambda d: 0 if d == 'A' else 1)


# Plot the data.

# We'll use a custom colormap, to match the one that Minard uses.
from matplotlib.colors import LinearSegmentedColormap
colors = [(215/255, 193/255, 126/255), (37/255, 37/255, 37/255)]
cm = LinearSegmentedColormap.from_list('minard', colors)


gplt.sankey(troop_movements, start='from', end='to',
            scale='survivors', limits=(0.5, 45),
            hue='direction', categorical=True, cmap=cm)
fig = plt.gcf()
mplleaflet.save_html(fig, fileobj='minard-napoleon-russia.html')
Exemplo n.º 16
0
# Load the data (uses the `quilt` package).
import geopandas as gpd
from quilt.data.ResidentMario import geoplot_data

troop_movements = gpd.read_file(geoplot_data.napoleon_troop_movements())
troop_movements['from'] = troop_movements.geometry.map(lambda v: v[0])
troop_movements['to'] = troop_movements.geometry.map(lambda v: v[1])

# Plot the data. We'll use a custom colormap, to match the one that Minard uses.
import geoplot as gplt
import matplotlib.pyplot as plt
import mplleaflet

from matplotlib.colors import LinearSegmentedColormap
colors = [(215 / 255, 193 / 255, 126 / 255), (37 / 255, 37 / 255, 37 / 255)]
cm = LinearSegmentedColormap.from_list('minard', colors)

gplt.sankey(troop_movements,
            start='from',
            end='to',
            scale='survivors',
            limits=(0.5, 45),
            hue='direction',
            categorical=True,
            cmap=cm)
fig = plt.gcf()
mplleaflet.save_html(fig, fileobj='minard-napoleon-russia.html')
Exemplo n.º 17
0
def main():

    ##### READ IN COMMAND LINE ARGUMENTS

    parser = argparse.ArgumentParser(
        description="""
        Purpose: Script to calculate validation metrics for EASOS model output with respect to observations from
        satellite measurements or coastal reports. Minimum input requirement is a pair of GeoJSON files valid at a given time instance,
        one containing the validation data (either from satellites or coastal reports) and the other the corresponding model prediction data.
        Each GeoJSON file should contain a geodataframe with geometries that define the oil spill area/extent.
        Both deterministic (i.e. 'Best Estimate') and probabilistic model output are supported. """,
        epilog=
        "Example of use: ./Calc_2D_MOE_GeoJSON.py <obsFile> <modelFile> <modelType> <valType> [--noOilFile NOOILFILE] [--crs CRS] ",
    )
    parser.add_argument(
        "obsFile",
        help=
        "Required. Absolute or relative path to observation data file in GeoJSON format",
        type=str,
    )
    parser.add_argument(
        "modelFile",
        help=
        "Required. Absolute/relative path to model output file (either deterministic or probabilistic) in GeoJSON format",
        type=str,
    )
    parser.add_argument(
        "modelType",
        help=
        "Required. Type of model output, either 'BE' (best estimate, aka deterministic) or 'Prob' (probabilistic). Model contours \
                            are assumed to be cut-outs, i.e. no overlap with contours of a higher level.",
        type=str,
    )
    parser.add_argument(
        "valType",
        help=
        "Required. Type of validation to be performed, either 'Satellite' or 'Coastal'",
        type=str,
    )
    parser.add_argument(
        "--noOilFile",
        help=
        "Optional path to a file in GeoJSON format defining the region where oil was not observed in the satellite image. \
                            If this is specified, any model output that lies outside this detection region will be excluded from the analysis.",
        type=str,
    )
    parser.add_argument(
        "--crs",
        help=
        "Optional integer specifying the crs code to convert obs and model data to. Default value is 3857. \
                            See http://epsg.io/3857 for more details",
        type=int,
        default=3857,
    )

    args = parser.parse_args()
    obsFile = args.obsFile
    modelFile = args.modelFile
    modelType = args.modelType
    valType = args.valType
    noOilFile = args.noOilFile
    crs = args.crs

    #####

    ##### READ IN GEOJSON FILES, CHECK VALIDITY, AND RETURN AS GEODATAFRAMES

    oil, model, no_oil, casename, time, plevs = read_geojson(
        obsFile, modelFile, noOilFile, modelType, valType, crs)

    if valType == "Coastal":
        #  Do a basic plot of the model coastal prediction with the obs regions highlighted and save as a png file
        modelplot, ax = plot_coastal_maps(oil,
                                          model,
                                          casename,
                                          time,
                                          modelType,
                                          noOil=no_oil,
                                          levels=plevs)
        modelplot.savefig(
            "/media/Coastal_map_" + str(casename) + "_" + str(modelType) +
            "_" + str(time) + ".png",
            bbox_inches="tight",
        )
        if modelType == "BE":
            leaf.save_html(
                fig=ax.figure,
                fileobj="/media/Interactive_map_" + str(casename) + "_" +
                str(modelType) + "_" + str(time) + ".html",
            )

    #####

    ##### PREPARE AND UPDATE GEODATAFRAMES WITH OBS AREA, MODEL AREA AND OVERLAP AREA

    oil, model_known, overlap, plevs = calc_poly_overlap(
        oil, model, no_oil, casename, time, noOilFile, modelType, valType, crs)

    if overlap.empty:
        Aob = oil["obs_area"]
        Apr = model_known["area_full_contour"]
        print("Overlap geodataframe is empty; skipping 2-D MOE calculation")

    else:
        if valType == "Satellite":
            #  Produce a basic map of the obs, model and overlap regions and save in png format
            modelplot = plot_area_maps(oil,
                                       model_known,
                                       overlap,
                                       casename,
                                       time,
                                       modelType,
                                       levels=plevs)
            modelplot.savefig(
                "/media/Area_maps_" + str(casename) + "_" + str(modelType) +
                "_" + str(time) + ".png",
                bbox_inches="tight",
            )

        ##### CALCULATE THE 2-D MEASURE OF EFFECTIVENESS AND GENERATE PLOTS
        ##### For details, see Warner et al 2004., J. Appl. Met

        Aob = overlap["obs_area"]
        Apr = overlap["area_full_contour"]
        Aov = overlap["overlap_full_contour"]

        #  Call function to return x and y components of the 2-D MOE
        (x, y) = calc_2DMOE(Aob, Apr, Aov)

        #  Generate 2-D MOE space diagram and save in png format
        olevs = (overlap.contourlev).to_numpy()
        if modelType == "BE":
            MOEfig = plot_2D_MOE_scat(x, y, modelType, casename, time)
        elif modelType == "Prob":
            MOEfig = plot_2D_MOE_scat(x,
                                      y,
                                      modelType,
                                      casename,
                                      time,
                                      levels=olevs)

        MOEfig.savefig(
            "/media/2D_MOE_" + str(casename) + "_" + str(modelType) + "_" +
            str(valType) + "_" + str(time) + ".png",
            bbox_inches="tight",
        )

    #####

    ##### FOR SATELLITE VALIDATION AGAINST DETERMINISTIC OUTPUT, CALCULATE ADDITIONAL SKILL SCORES

    if valType == "Satellite" and modelType == "BE":
        from calc_metrics import calc_area_ss, calc_centroid_ss
        from plot_maps_metrics import plot_ss_scat, plot_centroid_map

        print("Area (in km^2) of observed spill is : ", Aob[0])
        print("Area (in km^2) of modelled spill is : ", Apr[0])

        #  Call function to calcluate Area Skill Score, Ass
        Ass = calc_area_ss(Aob[0], Apr[0])
        print("Area skill score is : ", Ass)

        #  Call function to calculate Centroid Skill Score, Css
        Css, obs_centroid, model_centroid, minpoint, maxpoint = calc_centroid_ss(
            oil, model_known)
        print("Centroid skill score is : ", Css)

        #  Plot the modelled and observed oil spill areas, with centroids and distances indicated
        centroidfig = plot_centroid_map(
            oil,
            obs_centroid,
            model_known,
            model_centroid,
            minpoint,
            maxpoint,
            casename,
            time,
        )
        centroidfig.savefig(
            "/media/Centroid_map_" + str(casename) + "_" + str(time) + ".png",
            bbox_inches="tight",
        )

        #  Proceed to plot skill score results on a scatter diagram
        SSfig = plot_ss_scat(Ass, Css, casename, time)
        SSfig.savefig(
            "/media/Skillscores_scatterplot_" + str(casename) + "_" +
            str(time) + ".png",
            bbox_inches="tight",
        )
Exemplo n.º 18
0
    overlay = nx.read_gml(overlay_path).to_undirected()

    mapping = {}
    for ii, node in enumerate(underlay.nodes()):
        mapping[str(ii)] = node

    overlay = nx.relabel_nodes(overlay, mapping).to_undirected()

    fig, ax = plt.subplots()

    nx.draw_networkx_nodes(overlay,
                           pos=pos_dict,
                           node_size=10,
                           node_color='red',
                           edge_color='k',
                           alpha=.5,
                           with_labels=True)
    nx.draw_networkx_edges(overlay,
                           pos=pos_dict,
                           edge_color='blue',
                           alpha=1,
                           width=5.0)
    nx.draw_networkx_labels(overlay, pos=pos_dict, label_pos=10.3)

    mplleaflet.display(fig=ax.figure)
    mplleaflet.save_html(fig=ax.figure,
                         fileobj=os.path.join(
                             "results", args.underlay,
                             "{}.html".format(args.architecture)))
Exemplo n.º 19
0
        if grppviz.has_edge(n1, n2):
            grppviz[n1][n2][0]['linewidth'] += 2
            grppviz[n1][n2][0]['cnt'] += 1
        else:
            grppviz.add_edge(n1, n2, linewidth=2.5)
            grppviz[n1][n2][0]['color_st'] = 'black' if g_t.has_edge(
                n1, n2) else 'red'
            grppviz[n1][n2][0]['cnt'] = 1
            grppviz.add_node(n1, lat=g.node[n1]['lat'], lon=g.node[n1]['lon'])
            grppviz.add_node(n2, lat=g.node[n2]['lat'], lon=g.node[n2]['lon'])

for e in grppviz.edges(data=True):
    e[2]['color_cnt'] = color_seq[1] if 'cnt' not in e[2] else color_seq[
        e[2]['cnt']]

fig, ax = plt.subplots(figsize=(1, 10))

pos = {
    k: (grppviz.node[k]['lon'], grppviz.node[k]['lat'])
    for k in grppviz.nodes()
}
e_width = [e[2]['linewidth'] for e in grppviz.edges(data=True)]
e_color = [e[2]['color_cnt'] for e in grppviz.edges(data=True)]
nx.draw_networkx_edges(grppviz,
                       pos,
                       width=e_width,
                       edge_color=e_color,
                       alpha=0.7)

mplleaflet.save_html(fig, 'maps/solutions.html', tiles='cartodb_positron')
Exemplo n.º 20
0
def plot_bus(trip, data_date, route):
    # trip: [-1003216209,1483537823,1483539806,NWT16595,1,11,42]
    # trip: [imsi,start_time,end_time,bus_number,go_or_back,start_stop,end_stop]
    print trip

    data_path = 'data/user_data/' + data_date

    u = 'u_' + trip[0]
    f = open(os.path.join(data_path, u), "r")
    data = [[row[0], int(row[4]),
             float(row[2]), float(row[3])]
            for row in csv.reader(f, delimiter='|')
            ]  #[imsi, unix_time, lon, lat]
    data_df = pandas.DataFrame(data, columns=['imsi', 'time', 'lon', 'lat'])
    data_df = data_df.sort_values(['time'])
    data = data_df.values.tolist()
    #data = np.array([row.rstrip().split("|") for row in f])  #-1943160471|16:57:03,966,490|121.526|25.088|1483520223
    f.close()
    '''
    year = int(data_date[0:4])
    month = int(data_date[5])
    date = int(data_date[7])

    ### sort user data by datetime ###
    for n,row in enumerate(data,0):
        hour,minute,second = row[1].split(",")[0].split(":")
        unix_time = int(time.mktime(time.strptime('%d-%d-%d %s:%s:%s'%(year,month,date,hour,minute,second), '%Y-%m-%d %H:%M:%S')))
        data[n][4] = str(unix_time)

    data = sorted(data,key=lambda x:x[4])
    data = [[row[0],int(row[4]),float(row[2]),float(row[3])] for row in data] #imsi,unixtime,lon,lat
    '''

    start = int(trip[1])
    end = int(trip[2])
    user = []
    for row in data:
        if (row[1] >= start) & (row[1] <= end):
            user.append([row[2], row[3]])
    print user

    ### plot user data ###
    user = np.array(user)
    plt.hold(True)
    plt.plot(user[:, 0], user[:, 1], 'go', ms=15)
    plt.plot(user[:, 0], user[:, 1], 'r--', linewidth=5)

    ### plot route data ###
    route_name = trip[3] + "_" + trip[4]
    route_list = route[route_name][int(trip[5]):int(trip[6]) +
                                   1]  #from start_stop to end_stop
    bus_line = np.array([[float(item[2]), float(item[3])]
                         for item in route_list])  #lon,lat => bus route
    plt.plot(bus_line[:, 0], bus_line[:, 1], 'co', ms=15)
    plt.plot(bus_line[:, 0], bus_line[:, 1], 'b--', linewidth=5)

    try:
        os.makedirs('plot_bus/' + data_date)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    mplleaflet.save_html(fileobj="./plot_bus/%s/%s_%s_%s.html" %
                         (data_date, u, trip[1], trip[2]))
    print