Path: blob/main/tools/contributed/sumopy/plugins/mapmatching/results_mpl.py
169689 views
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo1# Copyright (C) 2016-2025 German Aerospace Center (DLR) and others.2# SUMOPy module3# Copyright (C) 2012-2021 University of Bologna - DICAM4# This program and the accompanying materials are made available under the5# terms of the Eclipse Public License 2.0 which is available at6# https://www.eclipse.org/legal/epl-2.0/7# This Source Code may also be made available under the following Secondary8# Licenses when the conditions for such availability set forth in the Eclipse9# Public License 2.0 are satisfied: GNU General Public License, version 210# or later which is available at11# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html12# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later1314# @file results_mpl.py15# @author Joerg Schweizer16# @date 20121718from numpy.linalg import inv19import os20##import math21import numpy as np22from collections import OrderedDict23import matplotlib.pyplot as plt24from agilepy.lib_base.geometry import *25from matplotlib.path import Path26import matplotlib.patches as patche27from coremodules.demand.origin_to_destination import OdIntervals28from agilepy.lib_base.misc import get_inversemap29from coremodules.misc.matplottools import *30from coremodules.network import network31import agilepy.lib_base.classman as cm32import agilepy.lib_base.arrayman as am33from agilepy.lib_base.geometry import *34from agilepy.lib_base.processes import Process35from mapmatching import COLOR_MATCHED_ROUTE, COLOR_SHORTEST_ROUTE, COLOR_FASTEST_ROUTE36import time37try:38from scipy import interpolate39is_scipy = True40except:41is_scipy = False424344def is_sublist(l, s):45sub_set = False46if s == []:47sub_set = True48elif s == l:49sub_set = True50elif len(s) > len(l):51sub_set = False5253else:54for i in range(len(l)):55if l[i] == s[0]:56n = 157while (n < len(s)) and (l[i+n] == s[n]):58n += 15960if n == len(s):61sub_set = True6263return sub_set646566def kf_update(X, P, Y, H, R):67IM = dot(H, X)68IS = R + dot(H, dot(P, H.T))69K = dot(P, dot(H.T, inv(IS)))70X = X + dot(K, (Y-IM))71P = P - dot(K, dot(IS, K.T))72LH = gauss_pdf(Y, IM, IS)73return (X, P, K, IM, IS, LH)747576def gauss_pdf(X, M, S):77if M.shape()[1] == 1:78DX = X - tile(M, X.shape()[1])79E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0)80E = E + 0.5 * M.shape()[0] * log(2 * pi) + 0.5 * log(det(S))81P = exp(-E)82elif X.shape()[1] == 1:83DX = tile(X, M.shape()[1]) - M84E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0)85E = E + 0.5 * M.shape()[0] * log(2 * pi) + 0.5 * log(det(S))86P = exp(-E)87else:88DX = X-M89E = 0.5 * dot(DX.T, dot(inv(S), DX))90E = E + 0.5 * M.shape()[0] * log(2 * pi) + 0.5 * log(det(S))91P = exp(-E)92return (P[0], E[0])939495SELECTPOINTS = {'FromOrigin': 1,96'ToDestination': 2,97'FromOriginToDestination': 3,98'All': 4,99}100PLOTTYPE = {'Isochrone': 1,101'Heatmap': 2,102}103POINTSTYPE = {'OnlyOriginPoints': 1,104'OnlyDestinationPoints': 2,105'OnlyOriginAndDestinationPoints': 3,106'All': 4,107}108109110class PointresultPlotter(PlotoptionsMixin, Process):111def __init__(self, results, name='Plot point results with Matplotlib',112info="Creates plots of different point results using matplotlib",113logger=None, **kwargs):114115self._init_common('pointresultplotter', parent=results, name=name,116info=info, logger=logger)117118# print 'Resultplotter.__init__',results,self.parent119attrsman = self.get_attrsman()120mapmatching = self.parent.parent121scenario = mapmatching.get_scenario()122self.zones = scenario.landuse.zones123124self.select_points = attrsman.add(cm.AttrConf('select_points', kwargs.get('select_points', SELECTPOINTS['FromOrigin']),125groupnames=['options'],126choices=SELECTPOINTS,127name='Select points',128info='Select trip as indicated',129))130self.plot_type = attrsman.add(cm.AttrConf('plot_type', kwargs.get('plot_type', PLOTTYPE['Heatmap']),131groupnames=['options'],132choices=PLOTTYPE,133name='Plot type',134info='Choice the type of plot',135))136self.points_type = attrsman.add(cm.AttrConf('points_type', kwargs.get('points_type', POINTSTYPE['All']),137groupnames=['options'],138choices=POINTSTYPE,139name='Points type',140info='Plot only trip points of the indicated type',141))142143# self.is_plot_isochrone_generated = attrsman.add(cm.AttrConf( 'is_plot_isochrone_generated', kwargs.get('is_plot_isochrone_generated', True),144## groupnames = ['options'],145## name = 'Plot isochrone map from the origin zone',146## info = 'Plot isochrone map on edge-network for trips starting from the origin zone.',147# ))148# self.is_plot_isochrone_attracted = attrsman.add(cm.AttrConf( 'is_plot_isochrone_attracted', kwargs.get('is_plot_isochrone_attracted', True),149## groupnames = ['options'],150## name = 'Plot isochrone map to the destination zone',151## info = 'Plot isochrone map on edge-network for trips ending to the origin zone.',152# ))153self.is_isochrone = attrsman.add(cm.AttrConf('is_isochrone', kwargs.get('is_isochrone', False),154groupnames=['options'],155name='Plot isochrones in the map',156info='Plot isochrones lines in the map.',157))158self.max_time = attrsman.add(cm.AttrConf('max_time', kwargs.get('max_time', 40),159groupnames=['options'],160perm='wr',161name='Max time',162info='Max time to be considered for the isochrone plot.',163))164self.min_n_values = attrsman.add(cm.AttrConf('min_n_values', kwargs.get('min_n_values', 2),165groupnames=['options'],166perm='wr',167name='Minumun number of values',168info='Minumun number of values to assign a time to each edge.',169))170# self.is_plot_points_gen_heatmap = attrsman.add(cm.AttrConf( 'is_plot_points_gen_heatmap', kwargs.get('is_plot_points_gen_heatmap', False),171## groupnames = ['options'],172## name = 'Plot generated trip points from the origin zone',173## info = 'Plot a density heatmap of generated trip points from a zone.',174# ))175# self.is_plot_points_attr_heatmap = attrsman.add(cm.AttrConf( 'is_plot_points_attr_heatmap', kwargs.get('is_plot_points_attr_heatmap', False),176## groupnames = ['options'],177## name = 'Plot attracted trip points from the destination zone',178## info = 'Plot a density heatmap of attracted trip points from a zone.',179# ))180# self.is_plot_points_od_heatmap = attrsman.add(cm.AttrConf( 'is_plot_points_od_heatmap', kwargs.get('is_plot_points_od_heatmap', False),181## groupnames = ['options'],182## name = 'Plot od trip points heatmap',183## info = 'Plot a density heatmap of trip points from the origin zone to the destination zone.',184# ))185# self.is_plot_points_heatmap = attrsman.add(cm.AttrConf( 'is_plot_points_heatmap', kwargs.get('is_plot_points_heatmap', False),186## groupnames = ['options'],187## name = 'Plot density points heatmap',188## info = 'Plot density heatmap of the selected GPS points.',189# ))190191self.origin_zone_name = attrsman.add(cm.AttrConf('origin_zone_name', kwargs.get('origin_zone_name', self.zones.ids_sumo[0]),192groupnames=['options'],193choices=self.zones.ids_sumo,194name='Origin zone name',195info='Generating zone name.',196))197198self.dest_zone_name = attrsman.add(cm.AttrConf('dest_zone_name', kwargs.get('dest_zone_name', self.zones.ids_sumo[0]),199groupnames=['options'],200choices=self.zones.ids_sumo,201name='Destination zone name',202info='Attracting zone name.',203))204205self.bins = attrsman.add(cm.AttrConf('bins', kwargs.get('bins', 500),206groupnames=['options'],207perm='wr',208name='Bins',209info='Bins for the heatmap of points.',210))211212self.vmin = attrsman.add(cm.AttrConf('vmin', kwargs.get('vmin', 0),213groupnames=['options'],214perm='wr',215name='Min value',216info='Min value of points in a bin for the heatmap of points.',217))218219self.is_net = attrsman.add(cm.AttrConf('is_net', kwargs.get('is_net', False),220groupnames=['options'],221name='Show net',222info='Show the network in the heatmap of points.',223))224225self.titletext = attrsman.add(cm.AttrConf('titletext', kwargs.get('titletext', ''),226groupnames=['options'],227name='Title text',228info='Title text. Empty text means no title.',229))230self.size_titlefont = attrsman.add(cm.AttrConf('size_titlefont', kwargs.get('size_titlefont', 32),231groupnames=['options'],232name='Title fontsize',233info='Title fontsize.',234))235236self.add_plotoptions(**kwargs)237238self.add_save_options(**kwargs)239240def show(self):241# init242self.init_figures()243fig = self.create_figure()244results = self.parent245ax = fig.add_subplot(111)246mapmatching = self.parent.parent247scenario = mapmatching.get_scenario()248points = scenario.demand.mapmatching.points249trips = scenario.demand.mapmatching.trips250zones = scenario.landuse.zones251net = scenario.net252ids_edge = net.edges.get_ids()253ids_trip = trips.get_ids()254zone_shape_origin = zones.shapes[zones.ids_sumo.get_id_from_index(self.origin_zone_name)]255zone_shape_dest = zones.shapes[zones.ids_sumo.get_id_from_index(self.dest_zone_name)]256257# Plot net258if self.is_net:259print 'plot net'260plot_net(ax, net, color_edge="gray", width_edge=2, color_node=None,261alpha=0.5)262# Plot zones263if self.select_points == 1 or self.select_points == 3:264# plot origin zone265plot_zone(ax, zone_shape_origin, color_zone="coral",266color_outline='black', width_line=2,267alpha=0.4, zorder=+201)268if self.select_points == 2 or self.select_points == 3:269# plot destination zone270plot_zone(ax, zone_shape_dest, color_zone="coral",271color_outline='black', width_line=2,272alpha=0.4, zorder=+201)273# deselect points274points.are_selected[points.get_ids()] = False275# Take into account only selected traces with at least two point276ids_trip = ids_trip[(trips.are_selected[ids_trip] == True) & (trips.ids_points[ids_trip] != int)]277ids_points = trips.ids_points[ids_trip]278279# select points280ids_final_point = np.zeros((len(ids_trip)), dtype=np.int32)281ids_initial_point = np.zeros((len(ids_trip)), dtype=np.int32)282for id_trip, ids_point, i in zip(trips.get_ids(), ids_points, range(len(ids_trip))):283ids_final_point[i] = ids_point[-1]284ids_initial_point[i] = ids_point[0]285if self.select_points == 1:286points.are_selected[ids_point] = is_point_in_polygon(287points.coords[ids_initial_point[i]], zone_shape_origin)288if self.select_points == 2:289points.are_selected[ids_point] = is_point_in_polygon(points.coords[ids_final_point[i]], zone_shape_dest)290if self.select_points == 3:291points.are_selected[ids_point] = is_point_in_polygon(292points.coords[ids_initial_point[i]], zone_shape_origin)*is_point_in_polygon(points.coords[ids_final_point[i]], zone_shape_dest)293if self.select_points == 4:294points.are_selected[ids_point] = True295296# consider only selected points297if self.points_type == 1:298ids_point = ids_initial_point[(points.are_selected[ids_initial_point] == True)]299if self.points_type == 2:300ids_point = ids_final_point[(points.are_selected[ids_final_point] == True)]301if self.points_type == 3:302ids_initial_point = ids_initial_point[(points.are_selected[ids_initial_point] == True)]303ids_initial_point.tolist()304ids_final_point = ids_final_point[(points.are_selected[ids_final_point] == True)]305# ids_final_point.tolist()306ids_point = ids_initial_point.tolist()307ids_point.extend(ids_final_point)308print ids_initial_point, ids_final_point, ids_points309if self.points_type == 4:310ids_point = points.get_ids(points.are_selected.get_value() == True)311coords = points.coords[ids_point]312313if self.plot_type == 1:314# Match time points with edges and call isochrone plot, if selected315min_n_values = self.min_n_values316times_edge = np.zeros(np.max(ids_edge))317values = np.zeros(np.max(ids_edge))318valuess = []319for i in range(np.max(ids_edge)-1):320valuess.append([])321count = np.zeros(np.max(ids_edge))322# if self.is_isochrone:323## times_point = np.zeros(np.max(ids_point)+1)324for coord, id_point in zip(coords, ids_point):325coord = np.array([coord[0], coord[1]])326id_closest_edge = net.edges.get_closest_edge(coord)327print 'point', id_point328if id_closest_edge > 0:329if self.select_points == 1:330time = (points.timestamps[id_point] - trips.timestamps[points.ids_trip[id_point]])/60.0331if self.select_points == 2:332time = -(points.timestamps[id_point] -333points.timestamps[trips.ids_points[points.ids_trip[id_point]][-1]])/60.0334if self.select_points == 3:335time = (points.timestamps[id_point] - trips.timestamps[points.ids_trip[id_point]])/60.0336if self.select_points == 4:337time = (points.timestamps[id_point] - trips.timestamps[points.ids_trip[id_point]])/60.0338339if 0 < time < self.max_time:340count[id_closest_edge-1] += 1341times_edge[id_closest_edge-1] += time342if count[id_closest_edge-1] > min_n_values:343values[id_closest_edge-1] = times_edge[id_closest_edge-1]/count[id_closest_edge-1]344345# For the isochrone plot346# if self.is_isochrone:347## times_point[id_point] = time348print 'number of points:', np.sum(count)349350# Plot result on map351print 'plot results on map'352if self.select_points == 1:353title = 'Isochrone from the origin zone'354if self.select_points == 2:355title = 'Isochrone to the destination zone'356if self.select_points == 3:357title = 'Isochrone from the origin to the destination zone'358if self.select_points == 4:359title = 'Isochrone for all trips'360361self.plot_results_on_map(ax, ids_edge=ids_edge,362values=values[ids_edge-1],363title=title,364valuelabel='Minutes',365)366367if self.is_save:368if self.select_points == 1:369self.save_fig('routeana_isochrone_fromO')370if self.select_points == 2:371self.save_fig('routeana_isochrone_toD')372if self.select_points == 3:373self.save_fig('routeana_isochrone_FromOtoD')374if self.select_points == 4:375self.save_fig('routeana_isochrone')376377if self.plot_type == 2:378379# Plot heatmap380x_points = coords[:, 0]381y_points = coords[:, 1]382xedges = np.linspace(0., 14000., num=self.bins)383yedges = np.linspace(0., 11000., num=self.bins)384extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]385H, xedges, yedges = np.histogram2d(x_points, y_points, bins=(xedges, yedges))386X, Y = np.meshgrid(xedges, yedges)387if self.titletext != '':388ax.set_title(self.titletext, fontsize=self.size_titlefont)389else:390if self.select_points == 1:391ax.set_title('Density heatmap of trip points from the origin zone', fontsize=self.size_titlefont)392if self.select_points == 2:393ax.set_title('Density heatmap of trip points to the destination zone', fontsize=self.size_titlefont)394if self.select_points == 3:395ax.set_title('Density heatmap of trip points from the origin zone to the destination zone',396fontsize=self.size_titlefont)397if self.select_points == 4:398ax.set_title('Density heatmap of all trip points', fontsize=self.size_titlefont)399400plt.imshow(list(zip(*reversed(list(zip(*reversed(list(zip(*reversed(H))))))))),401vmin=self.vmin, cmap='Reds', extent=extent, interpolation='bicubic', alpha=0.9)402plt.colorbar()403if self.is_save:404if self.select_points == 1:405self.save_fig('routeana_heatmappoints_fromO')406if self.select_points == 2:407self.save_fig('routeana_heatmappoints_toD')408if self.select_points == 3:409self.save_fig('routeana_heatmappoints_FromOtoD')410if self.select_points == 4:411self.save_fig('routeana_heatmappoints')412413# print isochrone414if self.is_isochrone:415times_point = np.zeros(np.max(ids_point)+1)416for id_point in ids_point:417if self.select_points == 1:418time = (points.timestamps[id_point] - trips.timestamps[points.ids_trip[id_point]])/60.0419if self.select_points == 2:420time = -(points.timestamps[id_point] -421points.timestamps[trips.ids_points[points.ids_trip[id_point]][-1]])/60.0422if self.select_points == 3:423time = (points.timestamps[id_point] - trips.timestamps[points.ids_trip[id_point]])/60.0424if self.select_points == 4:425time = (points.timestamps[id_point] - trips.timestamps[points.ids_trip[id_point]])/60.0426427times_point[id_point] = time428self.plot_isochrone(ax, ids_point, zone_shape_origin, times_point)429430if not self.is_save:431show_plot()432433def plot_isochrone(self, ax, ids_point, zone_shape, times_point):434435mapmatching = self.parent.parent436scenario = mapmatching.get_scenario()437points = scenario.demand.mapmatching.points438zone_g = np.array([np.mean(np.array(zone_shape)[:, 0]), np.mean(np.array(zone_shape)[:, 1])])439coords = points.coords[ids_point]440coords = coords[:][:, :2]441isochrone = []442for coord, id_point, time_point in zip(coords, ids_point, times_point[ids_point]):443if zone_g[0] < coord[0] and zone_g[1] < coord[1]:444angle = np.arctan((coord[0]-zone_g[0])/(coord[1]-zone_g[1]))445if zone_g[0] < coord[0] and zone_g[1] > coord[1]:446angle = np.arctan((zone_g[1]-coord[1])/(coord[0]-zone_g[0])) + np.pi/2447if zone_g[0] > coord[0] and zone_g[1] > coord[1]:448angle = np.arctan((zone_g[0]-coord[0])/(zone_g[1]-coord[1])) + np.pi449if zone_g[0] > coord[0] and zone_g[1] < coord[1]:450angle = np.arctan((coord[1]-zone_g[1])/(zone_g[0]-coord[0])) + np.pi*3/2451dist = np.sqrt(np.sum((coord-zone_g)**2))452isochrone.append([angle, id_point, time_point, dist])453isochrone = np.asarray(isochrone)454isochrone = isochrone[isochrone[:, 0].argsort()]455isochrone = isochrone[(isochrone[:, 2] > 0)]456457n_bins = 200.0458## max_perc_var = 20.459isochrone_times = [5., 10., 15., 20., 25., 30., 35., 40.]460isochrone_shapes = [[]]*len(isochrone_times)461for bin in range(int(n_bins)):462for i in range(len(isochrone_times)):463iso_points = isochrone[(bin*2.0*np.pi/n_bins <= isochrone[:, 0]) & (isochrone[:, 0] < (bin+1)464* 2.0*np.pi/n_bins) & (0 < isochrone[:, 2]) & (isochrone_times[i] > isochrone[:, 2])]465if len(iso_points) > 10:466if len(isochrone_shapes[i]) == 0:467isochrone_shapes[i] = [[(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][0]),468(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][1])]]469else:470isochrone_shapes[i].append([(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][0]),471(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][1])])472print isochrone_shapes473for isochrone_shape in isochrone_shapes:474verts = np.array(isochrone_shape)[:, :2].tolist()475verts.append([0, 0])476codes = [Path.MOVETO]477for i in range(len(verts)-2):478codes.append(Path.LINETO)479codes.append(Path.CLOSEPOLY)480path = Path(verts, codes)481facecolor = 'none'482patch = patche.PathPatch(path, facecolor=facecolor, edgecolor='r', lw=5, alpha=0.8)483ax.add_patch(patch)484485for isochrone_shape in isochrone_shapes:486487if len(isochrone_shape) > 4:488zone_shape = isochrone_shape489print zone_shape490for zone_shape_coords, i in zip(isochrone_shape, range(len(isochrone_shape))):491print i, len(isochrone_shape)492if i == 0:493zone_shape[i] = ((np.array(isochrone_shape[i])+np.array(isochrone_shape[i+1])+np.array(494isochrone_shape[-1])+np.array(isochrone_shape[i+2])+np.array(isochrone_shape[-2]))/5.).tolist()495elif i == (len(isochrone_shape)-1):496zone_shape[i] = ((np.array(isochrone_shape[i])+np.array(isochrone_shape[0])+np.array(497isochrone_shape[i-1])+np.array(isochrone_shape[i-2])+np.array(isochrone_shape[1]))/5.).tolist()498elif i == 1:499zone_shape[i] = ((np.array(isochrone_shape[i])+np.array(isochrone_shape[i+1])+np.array(500isochrone_shape[i-1])+np.array(isochrone_shape[i+2])+np.array(isochrone_shape[-1]))/5.).tolist()501elif i == (len(isochrone_shape)-2):502zone_shape[i] = ((np.array(isochrone_shape[i])+np.array(isochrone_shape[i+1])+np.array(503isochrone_shape[i-1])+np.array(isochrone_shape[i-2])+np.array(isochrone_shape[0]))/5.).tolist()504else:505zone_shape[i] = ((np.array(isochrone_shape[i])+np.array(isochrone_shape[i+1])+np.array(506isochrone_shape[i-1])+np.array(isochrone_shape[i+2])+np.array(isochrone_shape[i-2]))/5.).tolist()507508verts = np.array(zone_shape)[:, :2].tolist()509verts.append([0, 0])510codes = [Path.MOVETO]511for i in range(len(verts)-2):512codes.append(Path.LINETO)513codes.append(Path.CLOSEPOLY)514path = Path(verts, codes)515facecolor = 'none'516patch = patche.PathPatch(path, facecolor=facecolor, edgecolor='b', lw=5, alpha=0.8)517ax.add_patch(patch)518519return True520521def get_scenario(self):522return self.parent.get_scenario()523524525class NoderesultPlotter(PlotoptionsMixin, Process):526def __init__(self, results, name='Node results plotter',527info="Plots nodes related results of GPS trips using matplotlib",528logger=None, **kwargs):529530self._init_common('noderesultplotter', parent=results, name=name,531info=info, logger=logger)532533# print 'Resultplotter.__init__',results,self.parent534attrsman = self.get_attrsman()535536self.plotthemefuncs = OrderedDict([537('times wait', self.plot_times_wait),538])539self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'times wait'),540groupnames=['options'],541choices=self.plotthemefuncs.keys(),542name='Plot theme',543info='Theme or edge attribute to be plottet.',544))545546self.n_min_matched = attrsman.add(cm.AttrConf('n_min_matched', 3,547groupnames=['options'],548name='Minum number of matched for speed analysis',549info='Only nodes contained in almost this number of matched routes\550will be considered for plotting the dynamic\551characteristics of edges (speeds and times).',552))553self.add_plotoptions(**kwargs)554self.add_save_options(**kwargs)555556attrsman.delete('plottype')557attrsman.delete('resultwidth')558attrsman.delete('length_arrowhead')559attrsman.delete('is_widthvalue')560561def plot_all_themes(self):562for plottheme in self.plotthemefuncs.keys():563self.plottheme = plottheme564self.show()565##566# self.is_grid = attrsman.add(cm.AttrConf( 'is_grid', kwargs.get('is_grid', True),567## groupnames = ['options'],568## name = 'Show grid?',569## info = 'If True, shows a grid on the graphical representation.',570# ))571##572# self.titletext = attrsman.add(cm.AttrConf( 'titletext', kwargs.get('titletext', ''),573## groupnames = ['options'],574## name = 'Title text',575## info = 'Title text. Empty text means no title.',576# ))577##578# self.size_titlefont = attrsman.add(cm.AttrConf('size_titlefont', kwargs.get('size_titlefont',32),579## groupnames = ['options'],580## name = 'Title fontsize',581## info = 'Title fontsize.',582# ))583##584# self.size_labelfont = attrsman.add(cm.AttrConf('size_labelfont', kwargs.get('size_labelfont',24),585## groupnames = ['options'],586## name = 'Label fontsize',587## info = 'Label fontsize.',588# ))589##590# self.width_line = attrsman.add(cm.AttrConf( 'width_line', kwargs.get('width_line', 1.0),591## groupnames = ['options'],592## name = 'Line width',593## info = 'Line width of plot.',594# ))595self.add_save_options()596597def get_noderesults(self):598return self.parent.nodesresults599600def show(self):601print 'NoderesultPlotter.show', self.plottheme602# if self.axis is None:603#axis = init_plot()604self.init_figures()605fig = self.create_figure()606axis = fig.add_subplot(111)607self.plotthemefuncs[self.plottheme](axis)608609print ' self.is_save', self.is_save610if not self.is_save:611print ' show_plot'612show_plot()613else:614figname = 'nodeplot_'+self.plottheme615# print ' savefig',figname616617# self.save_fig('edgeplot_'+self.plottheme)618619rootfilepath = self.get_scenario().get_rootfilepath()620621fig.savefig("%s_%s.%s" % (rootfilepath, figname, self.figformat),622format=self.figformat,623dpi=self.resolution,624# orientation='landscape',625orientation='portrait',626transparent=True)627plt.close(fig)628629def plot_times_wait(self, ax):630print 'show noderesults', len(self.parent.nodesresults)631# if self.axis is None:632633nodesresults = self.parent.nodesresults634635if len(nodesresults) == 0:636return False637638mapmatching = self.parent.parent639trips = mapmatching.trips640#points = mapmatching.points641routes = trips.get_routes()642scenario = mapmatching.get_scenario()643edges = scenario.net.edges644nodes = scenario.net.nodes645ids_noderes = nodesresults.select_ids(646nodesresults.numbers_matched_for_speed_analysis.get_value() > self.n_min_matched)647nodetypes = nodes.types[nodesresults.ids_node[ids_noderes]]648times_wait = nodesresults.times_wait[ids_noderes]649nodetypeset = set(nodetypes)650651## map_type_to_typename = get_inversemap(nodes.types.choices)652## map_typename_to_times_wait = {}653# for thistype in nodetypeset:654## map_typename_to_times_wait[map_type_to_typename[thistype]] = np.mean(times_wait[nodetypes == thistype])655656# self.init_figures()657## fig = self.create_figure()658## ax = fig.add_subplot(111)659self.plot_node_results_on_map(ax, ids_noderes,660# edgesresults.differences_dist_tot_shortest[ids_result]/edgesresults.numbers_tot_shortest[ids_result],661times_wait,662title='Average waiting time at intersections',663valuelabel='Average waiting time [s]',664is_node_results=True,)665666667# colors = np.array(COLORS,dtype = np.object)668## inds_plot = np.arange(len(map_typename_to_times_wait), dtype = np.int32)669## bar_width = 0.45670## opacity = 0.5671# error_config = {'ecolor': '0.3'}672# print ' colors',get_colors(inds_plot)673# rects = ax.barh( inds_plot,674# map_typename_to_times_wait.values(),675# align='center',676# alpha=opacity,677# height=bar_width,678# color=get_colors(inds_plot),679# yerr=std_women, error_kw=error_config,680## linewidth = self.width_line,681# facecolor=colors[inds][inds_nz],682# )683##684##685## ax.set_yticks( inds_plot + bar_width / 2)686# ax.set_yticklabels(map_typename_to_times_wait.keys())687# ax.legend()688##689# ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)690# ax.grid(self.is_grid)691# if self.titletext != '':692## ax.set_title(self.titletext, fontsize=self.size_titlefont)693## ax.set_xlabel('Average wait times [s]', fontsize=self.size_labelfont)694## ax.set_ylabel('Intersection type', fontsize=self.size_labelfont)695## ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))696## ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))697# fig.tight_layout()698# if self.is_save:699# self.save_fig('virtualpop_strategy_share_current')700##701##702##703# plt.show()704# show_plot()705706def get_scenario(self):707return self.parent.get_scenario()708709710class SpeedprofilePlotter(PlotoptionsMixin, Process):711def __init__(self, results, name='Speedprofile plotter with Matplotlib',712info="Plots the speed profile of a selected GPS trip using matplotlib",713logger=None, **kwargs):714715self._init_common('speedprofileplotter', parent=results, name=name,716info=info, logger=logger)717718# print 'Resultplotter.__init__',results,self.parent719attrsman = self.get_attrsman()720721self.id_trip = attrsman.add(cm.AttrConf('id_trip', kwargs.get('id_trip', -1),722groupnames=['options'],723name='Trip ID',724info='ID of GPS trip to be plotted.',725))726727self.is_plot_similar_trips = attrsman.add(cm.AttrConf('is_plot_similar_trips', kwargs.get('is_plot_similar_trips', True),728groupnames=['options'],729name='Plot similar trips',730info='If True, plot all trips which contain the same route as the given trip.',731))732733self.method_interp = attrsman.add(cm.AttrConf('method_interp', kwargs.get('method_interp', 'slinear'),734groupnames=['options'],735choices=['linear', 'nearest', 'zero',736'slinear', 'quadratic', 'cubic'],737name='Interpolation method',738info='GPS point interpolation method.',739))740741self.color_point = attrsman.add(cm.AttrConf('color_point', kwargs.get('color_point', np.array([0.0, 0.4, 0.6, 0.6], np.float32)),742groupnames=['options'],743perm='wr',744metatype='color',745name='Point color',746info='Color of GPS-points.',747))748749self.size_point = attrsman.add(cm.AttrConf('size_point', kwargs.get('size_point', 10.0),750groupnames=['options'],751name='Point size',752info='Point size of GPS points.',753))754755self.is_pointlabel = attrsman.add(cm.AttrConf('is_pointlabel', kwargs.get('is_pointlabel', True),756groupnames=['options'],757name='Label points?',758info='If True, shows point ID nex to each point.',759))760761self.is_waitslabel = attrsman.add(cm.AttrConf('is_waitslabel', kwargs.get('is_waitslabel', True),762groupnames=['options'],763name='Show wait times?',764info='If True, shows wait times for each edge.',765))766767self.is_waitslabel_junction = attrsman.add(cm.AttrConf('is_waitslabel_junction', kwargs.get('is_waitslabel_junction', True),768groupnames=['options'],769name='Show wait times at junctions?',770info='If True, shows wait times at junctions for each edge entering a junction.',771))772773self.is_waitslabel_tls = attrsman.add(cm.AttrConf('is_waitslabel_tls', kwargs.get('is_waitslabel_tls', True),774groupnames=['options'],775name='Show wait times at TLS?',776info='If True, shows wait times at traffic light systems (TLS) for each edge entering a traffic light.',777))778779self.color_line = attrsman.add(cm.AttrConf('color_line', kwargs.get('color_line', np.array([1.0, 0.6, 0.0, 1.0], np.float32)),780groupnames=['options'],781perm='wr',782metatype='color',783name='Line color',784info='Color of plotted line in diagram.',785))786787self.width_line = attrsman.add(cm.AttrConf('width_line', kwargs.get('width_line', 3.0),788groupnames=['options'],789name='Line width',790info='Line width of plot.',791))792793self.alpha_line = attrsman.add(cm.AttrConf('alpha_line', kwargs.get('alpha_line', 0.8),794groupnames=['options'],795name='Line transp.',796info='Line transparency of plot.',797))798799self.is_grid = attrsman.add(cm.AttrConf('is_grid', kwargs.get('is_grid', True),800groupnames=['options'],801name='Show grid?',802info='If True, shows a grid on the graphical representation.',803))804805self.titletext = attrsman.add(cm.AttrConf('titletext', kwargs.get('titletext', ''),806groupnames=['options'],807name='Title text',808info='Title text. Empty text means no title.',809))810811self.size_titlefont = attrsman.add(cm.AttrConf('size_titlefont', kwargs.get('size_titlefont', 32),812groupnames=['options'],813name='Title fontsize',814info='Title fontsize.',815))816817self.size_labelfont = attrsman.add(cm.AttrConf('size_labelfont', kwargs.get('size_labelfont', 24),818groupnames=['options'],819name='Label fontsize',820info='Label fontsize.',821))822self.add_save_options()823824def plot_speed_over_time(self, ax, id_trip, id_route, edges, i_min=None, i_max=None,825is_pointlabel=True, alpha=1.0):826print 'plot_speed_over_time', id_trip, type(id_trip), self.parent.parent827828#mapmatching = self.parent.parent829#trips = mapmatching.trips830831routeresults = self.get_routeresults()832833#id_route = trips.ids_route_matched[id_trip]834id_routeres = routeresults.ids_route.get_id_from_index(id_route)835836mapmatching = self.parent.parent837trips = mapmatching.trips838ids_point = routeresults.ids_valid_point_speedana[id_routeres]839840# tripresults.pointsposition[id_routeres],\841# tripresults.pointsspeed[id_routeres],842# tripresults.pointstime[id_routeres],843# ids_pointedges,844845if i_min is None:846#ids_pointedge = routeresults.ids_pointedges[id_routeres]847#pointspositions = routeresults.pointspositions[id_routeres]848speeds = routeresults.speedana_point_speeds[id_routeres]849times = routeresults.speedana_point_times[id_routeres]850else:851#ids_pointedge = routeresults.ids_pointedges[id_routeres][i_min:i_max]852#pointspositions = routeresults.pointspositions[id_routeres][i_min:i_max]853speeds = routeresults.speedana_point_speeds[id_routeres][i_min:i_max]854times = routeresults.speedana_point_times[id_routeres][i_min:i_max]855# print ' id_route,id_routeres',id_route,id_routeres856# print ' ids_pointedge',ids_pointedge857n_point = len(times)858859x = np.array(times, dtype=np.float32)860y = np.array(speeds, dtype=np.float32)*3.6 # in km/h861#ax = init_plot()862# print ' x',x863# print ' y',y864#ax.plot(locations, speeds, color = self.color_line[:2], lw = self.width_line ,alpha=0.9 ,zorder = 0)865866alpha = min(alpha, self.alpha_line)867868if is_scipy & (not (self.method_interp == 'linear')):869870print 'use scipy to interpolate'871#tck = interpolate.splrep(x, y, s=0)872#xnew = np.linspace(np.min(x), np.max(x), 200)873#ynew = interpolate.splev(xnew, tck, der=0)874# if 1:875f_inter = interpolate.interp1d(x, y, kind=self.method_interp)876xnew = np.linspace(np.min(x), np.max(x), 200)877ynew = f_inter(xnew)878879ax.plot(xnew, ynew, color=self.color_line, lw=self.width_line, alpha=alpha)880ax.plot(x, y, 'o', markersize=self.size_point, color=self.color_point, alpha=alpha)881else:882ax.plot(x, y, 'o-', markersize=self.size_point, color=self.color_line,883lw=self.width_line, markerfacecolor=self.color_point, alpha=alpha)884885# label points886if self.is_pointlabel & is_pointlabel:887for id_point, xi, yi in zip(ids_point, x, y):888889ax.text(xi+2, yi, ' %s ' % (str(id_point)),890verticalalignment='top',891horizontalalignment='left',892#rotation = 'vertical',893fontsize=int(0.8*self.size_labelfont)) # baseline894895def plot_speed_over_way(self, ax, id_trip, id_route, edges, i_min=None, i_max=None,896is_pointlabel=True, alpha=1.0):897print 'plot_speed_over_way', id_trip, type(id_trip), self.parent.parent898899#mapmatching = self.parent.parent900#trips = mapmatching.trips901902routeresults = self.get_routeresults()903904#id_route = trips.ids_route_matched[id_trip]905id_routeres = routeresults.ids_route.get_id_from_index(id_route)906907mapmatching = self.parent.parent908trips = mapmatching.trips909ids_point = routeresults.ids_valid_point_speedana[id_routeres]910911# tripresults.pointsposition[id_routeres],\912# tripresults.pointsspeed[id_routeres],913# tripresults.pointstime[id_routeres],914# ids_pointedges,915916if i_min is None:917ids_pointedge = routeresults.ids_pointedges[id_routeres]918pointspositions = routeresults.speedana_point_pos[id_routeres]919speeds = routeresults.speedana_point_speeds[id_routeres]920times = routeresults.speedana_point_times[id_routeres]921else:922ids_pointedge = routeresults.ids_pointedges[id_routeres][i_min:i_max]923pointspositions = routeresults.speedana_point_pos[id_routeres][i_min:i_max]924speeds = routeresults.speedana_point_speeds[id_routeres][i_min:i_max]925times = routeresults.speedana_point_times[id_routeres][i_min:i_max]926# print ' id_route,id_routeres',id_route,id_routeres927# print ' ids_pointedge',ids_pointedge928n_point = len(ids_pointedge)929930alpha = min(alpha, self.alpha_line)931x = pointspositions932y = np.array(speeds, dtype=np.float32)*3.6 # in km/h933934#ax = init_plot()935print ' ids_point', routeresults.ids_valid_point_speedana[id_routeres]936print ' position', pointspositions937print ' x', x938print ' y', y939#ax.plot(locations, speeds, color = self.color_line[:2], lw = self.width_line ,alpha=0.9 ,zorder = 0)940941if is_scipy & (not (self.method_interp == 'linear')):942#tck = interpolate.splrep(x, y, s=0)943#xnew = np.linspace(np.min(x), np.max(x), 200)944#ynew = interpolate.splev(xnew, tck, der=0)945# if 1:946f_inter = interpolate.interp1d(x, y, kind=self.method_interp)947xnew = np.linspace(np.min(x), np.max(x), 200)948ynew = f_inter(xnew)949950ax.plot(xnew, ynew, color=self.color_line, lw=self.width_line, alpha=alpha)951ax.plot(x, y, 'o', markersize=self.size_point, color=self.color_point, alpha=alpha)952else:953ax.plot(x, y, 'o-', markersize=self.size_point, color=self.color_line,954lw=self.width_line, markerfacecolor=self.color_point, alpha=alpha)955if self.is_pointlabel & is_pointlabel:956# label points957for id_point, xi, yi in zip(ids_point, x, y):958959ax.text(xi+2, yi, ' %s ' % (str(id_point)),960verticalalignment='top',961horizontalalignment='left',962#rotation = 'vertical',963fontsize=int(0.8*self.size_labelfont)) # baseline964965def show(self):966print 'show', self.id_trip, type(self.id_trip), self.parent.parent967# if self.axis is None:968969if self.id_trip >= 0:970id_trip = self.id_trip971mapmatching = self.parent.parent972trips = mapmatching.trips973#points = mapmatching.points974routes = trips.get_routes()975scenario = mapmatching.get_scenario()976edges = scenario.net.edges977nodes = scenario.net.nodes978979routeresults = self.get_routeresults()980981if id_trip in trips:982id_route = trips.ids_route_matched[id_trip]983else:984return False985986route = routes.ids_edges[id_route]987988if routeresults.ids_route.has_index(id_route):989id_routeres = routeresults.ids_route.get_id_from_index(id_route)990else:991return False992993edgesresults = self.parent.edgesresults994connectionsresults = self.parent.connectionsresults995996# tripresults.pointsposition[id_routeres],\997# tripresults.pointsspeed[id_routeres],998# tripresults.pointstime[id_routeres],999# ids_pointedges,1000self.init_figures()1001fig = self.create_figure()1002ax = fig.add_subplot(111)10031004fig2 = self.create_figure()1005ax2 = fig2.add_subplot(111)10061007self.plot_speed_over_way(ax, id_trip, id_route, edges)1008self.plot_speed_over_time(ax2, id_trip, id_route, edges)10091010# get_color()1011# is_sublist1012#id_route = trips.ids_route_matched[id_trip]1013#route = routes.ids_edge[id_route]1014ids_pointedge = routeresults.ids_pointedges[id_routeres]1015if self.is_plot_similar_trips:1016#id_routeres = routeresults.ids_route.get_ids_from_indices(ids_route)10171018id_pointedge_first = ids_pointedge[0]1019id_pointedge_last = ids_pointedge[-1]10201021ids_routeres_speed = routeresults.get_ids()1022ids_route_speed = routeresults.ids_route[ids_routeres_speed]1023# print ' route',route1024for id_trip_speed, id_route_speed, route_speed, ids_pointedge_speed in zip(1025routes.ids_trip[ids_route_speed],1026ids_route_speed, routes.ids_edges[ids_route_speed],1027routeresults.ids_pointedges[ids_routeres_speed]):1028# print ' ids_pointedge_speed',ids_pointedge_speed1029# print ' route[0],is_inlist',route[0],ids_pointedge_speed.count(route[0]),type(ids_pointedge_speed)1030# print ' route_speed',route_speed10311032# is_sublist(route,route_speed):# | is_sublist(route_speed,route):1033if is_sublist(route_speed, route):1034i = ids_pointedge_speed.index(id_pointedge_first)1035j = ids_pointedge_speed.index(id_pointedge_last)1036n_pointedge = len(ids_pointedge_speed)1037while (ids_pointedge_speed[j] == id_pointedge_last) & (j < n_pointedge-1):1038j += 11039self.plot_speed_over_way(ax, id_trip_speed, id_route_speed, edges,1040i, j, is_pointlabel=False, alpha=0.5)1041self.plot_speed_over_time(ax2, id_trip_speed, id_route_speed, edges,1042i, j, is_pointlabel=False, alpha=0.5)10431044# plot edge info to speed over time10451046colors = [(0.2, 0.2, 0.2, 0.7), (0.8, 0.8, 0.8, 0.7)]1047ymin, ymax = ax.get_ylim()1048x = 01049x_last = routeresults.speedana_point_pos[id_routeres][0]1050t_last = 01051i = 01052## id_arc_last = routeresults.ids_arc_point[id_routeres][0]1053id_arc_last = 01054i_point = 01055pointstime = routeresults.speedana_point_times[id_routeres]1056print ' len(ids_pointedge)', len(ids_pointedge)1057print ' len(pointstime)', len(pointstime)10581059# if len(pointstime)>1:1060# t_last = pointstime[1]1061# else:1062#t_last_edge = pointstime[0]1063#t_last = pointstime[0]1064# print ' ids_pointedge\n',ids_pointedge1065# print ' pointstime\n',pointstime1066# print ' pointsspeeds\n',routeresults.pointsspeeds[id_routeres]10671068linestyle = '--'10691070for id_arc_point, is_connection_point, t, v, pos in zip(1071routeresults.ids_arc_point[id_routeres],1072routeresults.is_connection_point[id_routeres],1073pointstime,1074routeresults.speedana_point_speeds[id_routeres],1075routeresults.speedana_point_pos[id_routeres],1076):10771078print ' id_arc_point', id_arc_point, 'is_connection_point', is_connection_point, 'id_arc_last', id_arc_last, id_arc_point != id_arc_last, 'pos=%.2fm, t=%.2fs, v=%.2fkm/h' % (pos, t, v*3.6),1079color = 'k'1080if (id_arc_point != id_arc_last):10811082t_last = t # memorize t where edge ids changed1083if not is_connection_point:1084# edges have changed1085# if id_edge != -1:1086# x += edges.lengths[id_edge] # add length of old id_edge10871088ax2.text(t_last+2, ymax, ' ID Edge = %s ' % (str(id_arc_point)),1089verticalalignment='top',1090horizontalalignment='left',1091rotation='vertical',1092fontsize=int(0.8*self.size_labelfont)) # baseline10931094# put wait times, if any available1095if edgesresults.ids_edge.has_index(id_arc_point):1096id_edgeres = edgesresults.ids_edge.get_id_from_index(id_arc_point)1097time_wait = edgesresults.times_wait[id_edgeres]1098time_wait_junc = edgesresults.times_wait_junc[id_edgeres]1099time_wait_tls = edgesresults.times_wait_tls[id_edgeres]1100label = r' '1101# is_waitslabel,is_waitslabel_junction,is_waitslabel_tls1102if self.is_waitslabel & (time_wait > 0):1103label += ' $T_W=%ds$' % time_wait11041105if self.is_waitslabel_junction & (time_wait_junc > 0):1106label += ' $T_J=%ds$' % time_wait_junc11071108if self.is_waitslabel_tls & (time_wait_tls > 0):1109label += ' $T_{\mathrm{TL}}=%ds$' % time_wait_tls11101111ax2.text(t_last+2, ymin, label,1112verticalalignment='bottom',1113horizontalalignment='left',1114rotation='vertical',1115color=color,1116fontsize=int(0.8*self.size_labelfont))11171118ax2.plot([t_last, t_last], [ymin, ymax], color=color, linestyle=linestyle)1119t_last = t # memorize t where edge ids changed11201121else:1122# edges have changed1123# if id_edge != -1:1124# x += edges.lengths[id_edge] # add length of old id_edge11251126ax2.text(t_last+2, ymax, ' ID Connection = %s ' % (str(id_arc_point)),1127verticalalignment='top',1128horizontalalignment='left',1129rotation='vertical',1130fontsize=int(0.8*self.size_labelfont)) # baseline11311132# put wait times, if any available1133if connectionsresults.ids_connection.has_index(id_arc_point):1134id_connectionres = connectionsresults.ids_connection.get_id_from_index(id_arc_point)1135time_wait = connectionsresults.times_wait[id_connectionres]1136## time_wait_junc = connectionsresults.times_wait_junc[id_edgeres]1137time_wait_tls = connectionsresults.times_wait_tls[id_connectionres]1138label = r' '1139# is_waitslabel,is_waitslabel_junction,is_waitslabel_tls1140if self.is_waitslabel & (time_wait > 0):1141label += ' $T_W=%ds$' % time_wait11421143##1144# if self.is_waitslabel_junction & (time_wait_junc>0):1145## label += ' $T_J=%ds$'%time_wait_junc1146##11471148if self.is_waitslabel_tls & (time_wait_tls > 0):1149label += ' $T_{\mathrm{TL}}=%ds$' % time_wait_tls11501151ax2.text(t_last+2, ymin, label,1152verticalalignment='bottom',1153horizontalalignment='left',1154rotation='vertical',1155color=color,1156fontsize=int(0.8*self.size_labelfont))11571158ax2.plot([t_last, t_last], [ymin, ymax], color=color, linestyle=linestyle)11591160id_arc_last = id_arc_point # memorize edge of last point11611162i_point += 111631164#ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)1165ax2.grid(self.is_grid)1166if self.titletext != '':1167ax2.set_title(self.titletext, fontsize=self.size_titlefont)11681169ax2.set_xlabel('Time [s]', fontsize=self.size_labelfont)1170ax2.set_ylabel('Speed [km/h]', fontsize=self.size_labelfont)1171ax2.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))1172ax2.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))11731174# plot edge info to speed over way graph1175# this will put correct edge borders and labels1176linestyle = '--'1177color = 'k'1178cumulative_dists = routeresults.cumulative_dists[id_routeres]1179cumulative_dists = np.delete(cumulative_dists, -1)1180cumulative_dists = np.insert(cumulative_dists, 0, 0.).tolist()1181ids_arc = routeresults.ids_arc[id_routeres]1182are_connections = routeresults.is_connection[id_routeres]1183print cumulative_dists, ids_arc11841185for cumulative_dist, id_arc, is_connection in zip(cumulative_dists, ids_arc, are_connections):11861187#ax.plot([x,x+length],[ymin,ymin],color = colors[i%2],lw = 3*self.width_line)11881189# ax.text( dist, ymax, ' ID= %s '%(str(id_arc)),1190## verticalalignment = 'top',1191## horizontalalignment = 'left',1192## rotation = 'vertical',1193# fontsize = int(0.8*self.size_labelfont))#baseline11941195if not is_connection:1196if edgesresults.ids_edge.has_index(id_arc):1197id_edgeres = edgesresults.ids_edge.get_id_from_index(id_arc)1198time_wait = edgesresults.times_wait[id_edgeres]1199time_wait_junc = edgesresults.times_wait_junc[id_edgeres]1200time_wait_tls = edgesresults.times_wait_tls[id_edgeres]1201label = r' '12021203if self.is_waitslabel & (time_wait > 0):1204label += ' $T_W=%ds$' % time_wait12051206if self.is_waitslabel_junction & (time_wait_junc > 0):1207label += ' $T_J=%ds$' % time_wait_junc12081209if self.is_waitslabel_tls & (time_wait_tls > 0):1210label += ' $T_{\mathrm{TL}}=%ds$' % time_wait_tls12111212print ' id_edge', id_arc, 'pos=%df' % cumulative_dist, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls12131214ax.text(cumulative_dist, ymin, label,1215verticalalignment='bottom',1216horizontalalignment='left',1217rotation='vertical',1218color=color,1219fontsize=int(0.8*self.size_labelfont))1220else:1221print 'the edge', id_arc, 'is not in the edgeresult database'1222else:1223if connectionsresults.ids_connection.has_index(id_arc):1224id_connectionres = connectionsresults.ids_connection.get_id_from_index(id_arc)1225time_wait = connectionsresults.times_wait[id_connectionres]1226## time_wait_junc = connectionsresults.times_wait_junc[id_connectionres]1227time_wait_tls = connectionsresults.times_wait_tls[id_connectionres]1228label = r' '12291230if self.is_waitslabel & (time_wait > 0):1231label += ' $T_W=%ds$' % time_wait12321233# if self.is_waitslabel_junction & (time_wait_junc>0):1234## label += ' $T_J=%ds$'%time_wait_junc12351236if self.is_waitslabel_tls & (time_wait_tls > 0):1237label += ' $T_{\mathrm{TL}}=%ds$' % time_wait_tls12381239print ' id_connection', id_arc, 'pos=%df' % x, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls12401241ax.text(cumulative_dist, ymin, label,1242verticalalignment='bottom',1243horizontalalignment='left',1244rotation='vertical',1245color=color,1246fontsize=int(0.8*self.size_labelfont))1247else:1248print 'the connection', id_arc, 'is not in the connectionresult database'12491250ax.plot([cumulative_dist, cumulative_dist], [ymin, ymax], color=color, linestyle=linestyle)12511252if not is_connection:1253ax.text(cumulative_dist, ymax, ' ID Edge= %s ' % (str(id_arc)),1254verticalalignment='top',1255horizontalalignment='left',1256rotation='vertical',1257fontsize=int(0.8*self.size_labelfont)) # baseline1258else:1259ax.text(cumulative_dist, ymax, ' ID Connection= %s ' % (str(id_arc)),1260verticalalignment='top',1261horizontalalignment='left',1262rotation='vertical',1263fontsize=int(0.8*self.size_labelfont)) # baseline1264## x += edges.lengths[id_edge]12651266#ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)1267ax.grid(self.is_grid)1268if self.titletext != '':1269ax.set_title(self.titletext, fontsize=self.size_titlefont)12701271ax.set_xlabel('Distance [m]', fontsize=self.size_labelfont)1272ax.set_ylabel('Speed [km/h]', fontsize=self.size_labelfont)1273ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))1274ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))12751276# if self.is_save:1277# self.save_fig('routeana_speedprofile')12781279plt.show()1280# show_plot()12811282def get_routeresults(self):1283return self.parent.routesresults_matched12841285def get_scenario(self):1286return self.parent.get_scenario()128712881289class EdgeresultPlotter(PlotoptionsMixin, Process):1290def __init__(self, results, name='Plot edge results with Matplotlib',1291info="Creates plots of different edge results using matplotlib",1292logger=None, **kwargs):12931294self._init_common('routeresultplotter', parent=results, name=name,1295info=info, logger=logger)12961297# print 'Resultplotter.__init__',results,self.parent1298attrsman = self.get_attrsman()12991300self.plotthemefuncs = OrderedDict([1301('average slopes', self.plot_average_slopes),1302('positive climbs', self.plot_positive_climbs),1303('negative climbs', self.plot_negative_climbs),1304('average speeds', self.plot_speeds_average),1305('inmove speeds', self.plot_speeds_inmotion),1306('times wait', self.plot_times_wait),1307('times wait_tls', self.plot_times_wait_tls),1308('number matched_routes', self.plot_numbers_tot_matched),1309('number shortest', self.plot_numbers_tot_shortest),1310('total deviation', self.plot_differences_dist_tot_shortest),1311('relative deviation', self.plot_differences_dist_rel_shortest),1312('usage probabilities by matched routes', self.plot_probabilities_tot_matched),1313('estimated flows from matched routes', self.plot_flows_est_matched_routes),1314])1315self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'average speeds'),1316groupnames=['options'],1317choices=self.plotthemefuncs.keys(),1318name='Plot theme',1319info='Theme or edge attribute to be plottet.',1320))1321self.n_min_matched = attrsman.add(cm.AttrConf('n_min_matched', 3,1322groupnames=['options'],1323name='Minum number of matched for speed analysis',1324info='Only edge contained in almost this number of matched routes\1325will be considered for plotting the dynamic\1326characteristics of edges (speeds and times).',1327))13281329self.add_plotoptions(**kwargs)1330self.add_save_options(**kwargs)13311332def plot_all_themes(self):1333for plottheme in self.plotthemefuncs.keys():1334self.plottheme = plottheme1335self.show()13361337def show(self):1338print 'EdgeresultPlotter.show', self.plottheme1339# if self.axis is None:1340#axis = init_plot()1341self.init_figures()1342fig = self.create_figure()1343axis = fig.add_subplot(111)1344self.plotthemefuncs[self.plottheme](axis)13451346print ' self.is_save', self.is_save1347if not self.is_save:1348print ' show_plot'1349show_plot()1350else:1351figname = 'edgeplot_'+self.plottheme1352# print ' savefig',figname13531354# self.save_fig('edgeplot_'+self.plottheme)13551356rootfilepath = self.get_scenario().get_rootfilepath()13571358fig.savefig("%s_%s.%s" % (rootfilepath, figname, self.figformat),1359format=self.figformat,1360dpi=self.resolution,1361# orientation='landscape',1362orientation='portrait',1363transparent=True)1364plt.close(fig)13651366def get_edgeresults(self):1367return self.parent.edgesresults # must have attribute 'ids_edge'13681369def plot_average_slopes(self, ax):13701371edges = self.parent.parent.parent.parent.net.edges1372ids_edge = edges.get_ids()1373#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1374average_slopes = edges.average_slopes1375print ids_edge, average_slopes[ids_edge]1376self.plot_results_on_map(ax,1377values=average_slopes[ids_edge],1378ids_edge=ids_edge,1379title='Average edge slopes',1380valuelabel='Slope',1381)13821383def plot_positive_climbs(self, ax):13841385edges = self.parent.parent.parent.parent.net.edges1386ids_edge = edges.get_ids()1387#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1388positive_climbs = edges.positive_climbs1389print ids_edge, positive_climbs[ids_edge]1390self.plot_results_on_map(ax,1391values=positive_climbs[ids_edge],1392ids_edge=ids_edge,1393title='Average edge slopes',1394valuelabel='Slope',1395)13961397def plot_negative_climbs(self, ax):13981399edges = self.parent.parent.parent.parent.net.edges1400ids_edge = edges.get_ids()1401#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1402negative_climbs = edges.negative_climbs1403print ids_edge, negative_climbs[ids_edge]1404self.plot_results_on_map(ax,1405values=negative_climbs[ids_edge],1406ids_edge=ids_edge,1407title='Average edge slopes',1408valuelabel='Slope',1409)14101411def plot_differences_dist_rel_shortest(self, ax):1412edgesresults = self.get_edgeresults()1413ids_result = edgesresults.select_ids(edgesresults.differences_dist_rel_shortest.get_value() > 0)14141415#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)14161417self.plot_results_on_map(ax, ids_result,1418# edgesresults.differences_dist_tot_shortest[ids_result]/edgesresults.numbers_tot_shortest[ids_result],1419edgesresults.differences_dist_rel_shortest[ids_result],1420title='Deviation generated per trip',1421valuelabel='Generated deviation per trip [m]',1422)14231424def plot_differences_dist_tot_shortest(self, ax):1425edgesresults = self.get_edgeresults()1426ids_result = edgesresults.get_ids()1427#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1428#deviation_tot = edgesresults.differences_dist_tot_shortest1429self.plot_results_on_map(ax, ids_result,1430edgesresults.differences_dist_tot_shortest[ids_result]/1000,1431# deviation_tot[ids_result]/1000,1432title='Total deviation generated per edge',1433valuelabel='Generated total deviation [km]',1434)14351436def plot_numbers_tot_shortest(self, ax):1437edgesresults = self.get_edgeresults()1438ids_result = edgesresults.get_ids()1439#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1440numbers_tot_shortest = edgesresults.numbers_tot_shortest1441self.plot_results_on_map(ax, ids_result,1442numbers_tot_shortest[ids_result],1443title='Edge usage from shortest routes',1444valuelabel='Usage in number of persons',1445)14461447def plot_numbers_tot_matched(self, ax):1448edgesresults = self.get_edgeresults()1449ids_result = edgesresults.get_ids()1450#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1451numbers_tot_matched = edgesresults.numbers_tot_matched1452self.plot_results_on_map(ax, ids_result,1453numbers_tot_matched[ids_result],1454title='Edge usage from matched routes',1455valuelabel='Usage in number of persons',1456)14571458def plot_speeds_average(self, ax):1459edgesresults = self.parent.edgesresults14601461print 'plot_speeds_average'14621463#ids_result = edgesresults.get_ids()1464ids_result = edgesresults.select_ids(1465edgesresults.numbers_matched_for_speed_analysis.get_value() > self.n_min_matched)14661467#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1468speeds_average = self.parent.edgesresults.speed_average1469# print ' speeds_average',speeds_average[ids_result]1470# print ' ids_result',ids_result14711472self.plot_results_on_map(ax, ids_result,1473speeds_average[ids_result]*3.6,1474title='Average edge speeds',1475valuelabel='Average edge speeds [km/h]',1476)14771478def plot_speeds_inmotion(self, ax):1479edgesresults = self.parent.edgesresults1480#ids_result = edgesresults.get_ids()1481ids_result = edgesresults.select_ids(1482edgesresults.numbers_matched_for_speed_analysis.get_value() > self.n_min_matched)14831484#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1485speeds = self.parent.edgesresults.speed_average_in_motion14861487# print ' speeds_average',speeds[ids_result]1488# print ' ids_result',ids_result14891490self.plot_results_on_map(ax, ids_result,1491speeds[ids_result]*3.6,1492title='Average edge speeds in motion',1493valuelabel='Average edge speeds in motion [km/h]',1494)14951496def plot_times_wait(self, ax):1497edgesresults = self.parent.edgesresults1498#ids_result = edgesresults.get_ids()1499ids_result = edgesresults.select_ids(1500edgesresults.numbers_matched_for_speed_analysis.get_value() > self.n_min_matched)15011502#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1503times = edgesresults.times_wait1504self.plot_results_on_map(ax, ids_result,1505times[ids_result],1506title='Average wait times',1507valuelabel='Average wait times [s]',1508)15091510def plot_times_wait_tls(self, ax):1511#ids_result = self.parent.edgesresults.get_ids()1512#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1513edgesresults = self.parent.edgesresults1514ids_result = edgesresults.select_ids(1515edgesresults.numbers_matched_for_speed_analysis.get_value() > self.n_min_matched)1516times = edgesresults.times_wait_tls1517self.plot_results_on_map(ax, ids_result,1518times[ids_result],1519title='Average wait times at Traffic Lights',1520valuelabel='Average wait times at TLS [s]',1521)15221523def plot_probabilities_tot_matched(self, ax):1524ids_result = self.parent.edgesresults.get_ids()1525#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1526self.plot_results_on_map(ax, ids_result,1527self.parent.edgesresults.probabilities_tot_matched[ids_result],1528title='Probabilities',1529valuelabel=r'Enter probabilities [\%]',1530)15311532def plot_flows_est_matched_routes(self, ax):1533ids_result = self.parent.edgesresults.get_ids()1534#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1535self.plot_results_on_map(ax, ids_result,1536self.parent.edgesresults.flows_est[ids_result],1537title='Flows',1538valuelabel=r'Estimated flows [1/h]',1539)15401541def do(self):1542# print 'do',self.edgeattrname1543self.show()1544return True154515461547class ConnectionresultPlotter(PlotoptionsMixin, Process):1548def __init__(self, results, name='Plot connection results with Matplotlib',1549info="Creates plots of different connection results using matplotlib",1550logger=None, **kwargs):15511552self._init_common('routeresultplotter', parent=results, name=name,1553info=info, logger=logger)15541555# print 'Resultplotter.__init__',results,self.parent1556attrsman = self.get_attrsman()15571558self.plotthemefuncs = OrderedDict([1559('times wait', self.plot_times_wait),1560('times wait_tls', self.plot_times_wait_tls),1561])1562self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'times wait'),1563groupnames=['options'],1564choices=self.plotthemefuncs.keys(),1565name='Plot theme',1566info='Theme or edge attribute to be plottet.',1567))15681569self.n_min_matched = attrsman.add(cm.AttrConf('n_min_matched', 3,1570groupnames=['options'],1571name='Minum number of matched for speed analysis',1572info='Only connectors contained in almost this number of matched routes\1573will be considered for plotting the dynamic\1574characteristics of edges (speeds and times).'))15751576self.add_plotoptions(**kwargs)1577self.add_save_options(**kwargs)15781579def plot_all_themes(self):1580for plottheme in self.plotthemefuncs.keys():1581self.plottheme = plottheme1582self.show()15831584def show(self):1585print 'connectionresultPlotter.show', self.plottheme1586# if self.axis is None:1587#axis = init_plot()1588self.init_figures()1589fig = self.create_figure()1590axis = fig.add_subplot(111)1591self.plotthemefuncs[self.plottheme](axis)15921593print ' self.is_save', self.is_save1594if not self.is_save:1595print ' show_plot'1596show_plot()1597else:1598figname = 'connectionplot_'+self.plottheme1599# print ' savefig',figname16001601# self.save_fig('edgeplot_'+self.plottheme)16021603rootfilepath = self.get_scenario().get_rootfilepath()16041605fig.savefig("%s_%s.%s" % (rootfilepath, figname, self.figformat),1606format=self.figformat,1607dpi=self.resolution,1608# orientation='landscape',1609orientation='portrait',1610transparent=True)1611plt.close(fig)16121613def get_connectionresults(self):1614return self.parent.connectionsresults16151616def plot_times_wait(self, ax):16171618connectionsresults = self.parent.connectionsresults1619#ids_result = edgesresults.get_ids()16201621ids_result = connectionsresults.select_ids(1622connectionsresults.numbers_matched_for_speed_analysis.get_value() > self.n_min_matched)1623#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)1624times = connectionsresults.times_wait1625# print 'TIMES VALUES', times[ids_result]1626self.plot_results_on_map(ax,1627values=times[ids_result],1628title='Average wait times at connectors',1629valuelabel='Average wait times [s]',1630is_connection_results=True,1631ids_connectionres=ids_result)16321633def plot_times_wait_tls(self, ax):16341635connectionsresults = self.parent.connectionsresults1636ids_result = connectionsresults.select_ids(1637connectionsresults.numbers_matched_for_speed_analysis.get_value() > self.n_min_matched)1638times = connectionsresults.times_wait_tls1639# print 'TIMES VALUES', times[ids_result]1640self.plot_results_on_map(ax,1641values=times[ids_result],1642title='Average wait times at tls connectors',1643valuelabel='Average wait times [s]',1644is_connection_results=True,1645ids_connectionres=ids_result)16461647def do(self):1648# print 'do',self.edgeattrname1649self.show()1650return True165116521653class AlternativeRoutesPlotter(PlotoptionsMixin, Process):1654def __init__(self, results, name='Plot edge of alternative routes with Matplotlib',1655info="Creates plots of different edge results using matplotlib",1656logger=None, **kwargs):16571658self._init_common('routeresultplotter', parent=results, name=name,1659info=info, logger=logger)16601661# print 'Resultplotter.__init__',results,self.parent1662attrsman = self.get_attrsman()16631664self.color_chosen = attrsman.add(cm.AttrConf('color_chosen', kwargs.get('color_chosen', np.array([0.9, 0.2, 0.2, 0.99], dtype=np.float32)),1665groupnames=['options'],1666perm='wr',1667metatype='color',1668name='Color Alt. chosen',1669info='Color of chosen alternative.',1670))16711672self.color2 = attrsman.add(cm.AttrConf('color2', kwargs.get('color2', np.array([0.2, 0.9, 0.2, 0.99], dtype=np.float32)),1673groupnames=['options'],1674perm='wr',1675metatype='color',1676name='Color Alt. 2',1677info='Color of second alternative.',1678))16791680kwargs_fixed = {'plottype': 'polygons',1681'is_widthvalue': True,1682'is_colorvalue': False, # colors assigned explicitely1683'is_value_range': True,1684'value_range_min': 0,1685'value_range_max': 2,1686'color_fill': np.array([0.9, 0.2, 0.2, 0.99], dtype=np.float32),1687'printformat': '',1688}1689kwargs.update(kwargs_fixed)16901691self.add_plotoptions(**kwargs)1692self.add_save_options(**kwargs)16931694# configure fixed options as privat (non visible for gui)1695attrsman = self.get_attrsman()1696for attrname in kwargs_fixed.keys():1697attrconf = attrsman.get_config(attrname)1698attrconf.add_groupnames(['_private'])16991700def show(self):1701print 'AlternativeRoutesPlotter.show'1702# if self.axis is None:1703#axis = init_plot()1704title = 'Route alternatives'1705valuelabel = ''1706self.init_figures()1707fig = self.create_figure()1708axis = fig.add_subplot(111)17091710altroutesresults = self.parent.altroutesresults1711ids_res = altroutesresults.get_ids()1712net = self.parent.get_scenario().net1713edges = net.edges17141715axis.set_axis_bgcolor(self.color_background)1716if self.is_show_network:1717plot_net(axis, net, color_edge=self.color_network, width_edge=2,1718color_node=self.color_nodes, alpha=self.alpha_net)17191720if self.is_show_facilities:1721facilities = self.parent.get_scenario().landuse.facilities1722plot_facilities(axis, facilities, color_building=self.color_facilities,1723color_outline=self.color_borders,1724width_line=2, alpha=self.alpha_facilities,1725)1726if self.is_show_maps:1727plot_maps(axis, self.parent.get_scenario().landuse.maps, alpha=self.alpha_maps)17281729# if self.is_value_range:1730# value_range = (self.value_range_min, self.value_range_max)1731# else:1732value_range = (0, 2)17331734for id_trip, id_choice, chosen, ids_edge_all in zip(1735altroutesresults.ids_trip[ids_res],1736altroutesresults.ids_alt[ids_res],1737altroutesresults.choices[ids_res],1738altroutesresults.ids_edges[ids_res]):1739# print ' id_trip',id_trip,'ids_edge',ids_edge_all1740if ids_edge_all is not None:1741if id_choice == 1:1742ids_edge = ids_edge_all17431744else:1745ids_edge = ids_edge_all[1:-1]17461747if chosen:1748color = self.color_chosen # use predefined color sor selected1749elif id_choice == 2:1750color = self.color21751else:1752color = get_color(id_choice)17531754plot_edgevalues_lines(axis,1755ids_edge=ids_edge,1756values=np.ones(len(ids_edge), dtype=np.float32)*(int(chosen)+1),1757edges=net.edges,1758width_max=self.resultwidth,1759alpha=self.alpha_results,1760printformat=self.printformat,1761color_outline=self.color_outline,1762color_fill=color,1763color_label=self.color_label,1764is_antialiased=True,1765is_fill=self.is_colorvalue,1766is_widthvalue=self.is_widthvalue,1767length_arrowhead=self.length_arrowhead,1768fontsize=self.size_labelfont,1769valuelabel=False,1770value_range=value_range,1771is_colorbar=False,1772)1773else:1774print 'WARNING in AlternativeRoutesPlotter.show ids_edge=', ids_edge_all, 'of id_trip', id_trip17751776if self.is_show_title:1777axis.set_title(title, fontsize=self.size_titlefont)17781779axis.axis('equal')1780# ax.legend(loc='best',shadow=True)17811782axis.grid(self.is_grid)1783axis.set_xlabel('West-East [m]', fontsize=self.size_labelfont)1784axis.set_ylabel('South-North [m]', fontsize=self.size_labelfont)1785axis.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))1786axis.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))17871788## save or show1789print ' self.is_save', self.is_save1790if not self.is_save:1791print ' show_plot'1792show_plot()1793else:1794self.save_fig('altroutesplot')1795plt.close(fig)179617971798class RouteresultPlotter(PlotoptionsMixin, Process):1799def __init__(self, results, name='Plot route results with Matplotlib',1800info="Creates plots of different route results using matplotlib",1801logger=None, **kwargs):18021803self._init_common('routeresultplotter', parent=results, name=name,1804info=info, logger=logger)18051806print 'Resultplotter.__init__', results, self.parent1807attrsman = self.get_attrsman()18081809mapmatching = self.parent.parent1810scenario = mapmatching.get_scenario()1811self.zones = scenario.landuse.zones1812self.is_plot_bike_availability_ffbss_zone = attrsman.add(cm.AttrConf('is_plot_bike_availability_ffbss_zone', kwargs.get('is_plot_bike_availability_ffbss_zone', True),1813groupnames=['options'],1814name='Plot bike relative availability for FFBSS in a zone',1815info='Plot the variation of the bike availability in a day for a zone. Either 24 or 96 bins are recommended',1816))18171818if len(self.zones) > 0:18191820self.zone_ffbss = attrsman.add(cm.AttrConf('zone_ffbss', kwargs.get('zone_ffbss', self.zones.ids_sumo[1]),1821groupnames=['options'],1822choices=self.zones.ids_sumo,1823name='Zone for the FFBSS availability analysis',1824info='Select the zone for the FFBSS availability analysis.',1825))18261827self.is_analyze_bike_availability_ffbss_zones = attrsman.add(cm.AttrConf('is_analyze_bike_availability_ffbss_zones', kwargs.get('is_analyze_bike_availability_ffbss_zones', True),1828groupnames=['options'],1829name='Analize bike relative availability for FFBSS in all zones',1830info='Plot the absolute and relative (for zones with almost n_bins trips) variation of the bike availability in a day for all zones. Either 24 or 96 bins are recommended',1831))18321833self.is_plot_bike_availability_ffbss = attrsman.add(cm.AttrConf('is_plot_bike_availability_ffbss', kwargs.get('is_plot_bike_availability_ffbss', False),1834groupnames=['options'],1835name='Plot bike usage distribution',1836info='Plot the number of bikes that are doing a trip simultaneously in the day period. It require an high number of bins',1837))18381839self.is_plot_deptimedistrib = attrsman.add(cm.AttrConf('is_plot_deptimedistrib', kwargs.get('is_plot_deptimedistrib', False),1840groupnames=['options'],1841name='Plot departure time distribution',1842info='Plot cumulative distribution on trip departure time of matched route.',1843))18441845# comprison matched shortest1846self.is_plot_lengthdistrib = attrsman.add(cm.AttrConf('is_plot_lengthdistrib', kwargs.get('is_plot_lengthdistrib', True),1847groupnames=['options'],1848name='Plot length distribution',1849info='Plot cumulative distribution on length of matched route and shortest route.',1850))18511852self.is_plot_lengthprob = attrsman.add(cm.AttrConf('is_plot_lengthprob', kwargs.get('is_plot_lengthprob', False),1853groupnames=['options'],1854name='Plot length probabilities',1855info='Plot probabilities length of matched route and shortest route.',1856))18571858self.is_plot_lengthdistrib_by_class = attrsman.add(cm.AttrConf('is_plot_lengthdistrib_by_class', kwargs.get('is_plot_lengthdistrib_by_class', False),1859groupnames=['options'],1860name='Plot class length distribution',1861info='Plot mean values of length of matched route and shortest route for different trip length classes.',1862))18631864self.distance_class = attrsman.add(cm.AttrConf('distance_class', kwargs.get('distance_class', 2000),1865groupnames=['options'],1866name='Class distance',1867info='Distance to generate trip length classes.',1868))18691870self.is_plot_lengthratio = attrsman.add(cm.AttrConf('is_plot_lengthratio', kwargs.get('is_plot_lengthratio', False),1871groupnames=['options'],1872name='Plot length ratio',1873info='Plot cumulative distribution on length ratio between shortest route and matched route.',1874))18751876self.is_plot_lengthoverlap = attrsman.add(cm.AttrConf('is_plot_lengthoverlap', kwargs.get('is_plot_lengthoverlap', False),1877groupnames=['options'],1878name='Plot overlap with shortest',1879info='Plot cumulative distribution on the realtive length overlap between shortest route and matched route.',1880))18811882self.is_plot_lengthoverlap_fastest = attrsman.add(cm.AttrConf('is_plot_lengthoverlap_fastest', kwargs.get('is_plot_lengthoverlap_fastest', False),1883groupnames=['options'],1884name='Plot overlap with fastest',1885info='Plot cumulative distribution on on the realtive length between fastest route and matched route.',1886))18871888self.is_plot_mixshare = attrsman.add(cm.AttrConf('is_plot_mixshare', kwargs.get('is_plot_mixshare', False),1889groupnames=['options'],1890name='Plot mixed share',1891info='Plot cumulative distribution of share of mixed access roads of shortest route and matched route.',1892))18931894self.is_plot_exclusiveshare = attrsman.add(cm.AttrConf('is_plot_exclusiveshare', kwargs.get('is_plot_exclusiveshare', False),1895groupnames=['options'],1896name='Plot exclusive share',1897info='Plot cumulative distribution of share of exclusive access roads of shortest route and matched route.',1898))18991900self.is_plot_lowpriorityshare = attrsman.add(cm.AttrConf('is_plot_lowpriorityshare', kwargs.get('is_plot_lowpriorityshare', False),1901groupnames=['options'],1902name='Plot low priority share',1903info='Plot cumulative distribution of share of low priority roads of shortest route and matched route.',1904))19051906self.is_plot_nodesdensity = attrsman.add(cm.AttrConf('is_plot_nodesdensity', kwargs.get('is_plot_nodesdensity', False),1907groupnames=['options'],1908name='Plot node ratio',1909info='Plot cumulative distribution of node ratio between shortest route and matched route.',1910))19111912self.is_plot_tldensity = attrsman.add(cm.AttrConf('is_plot_tldensity', kwargs.get('is_plot_tldensity', False),1913groupnames=['options'],1914name='Plot TL ratio',1915info='Plot cumulative distribution of traffic light ratio between shortest route and matched route.',1916))1917self.is_prioritychangedensity = attrsman.add(cm.AttrConf('is_prioritychangedensity', kwargs.get('is_prioritychangedensity', False),1918groupnames=['options'],1919name='Plot prio. change dens.',1920info='Plot cumulative distribution of priority change denities between shortest route and matched route.',1921))19221923# comprison non-overlapping matched and shortest1924self.is_plot_lengthratio_nonoverlap = attrsman.add(cm.AttrConf('is_plot_lengthratio_nonoverlap', kwargs.get('is_plot_lengthratio_nonoverlap', False),1925groupnames=['options'],1926name='Plot length ratio non-overlap',1927info='Plot cumulative distribution on length ratio between non-overlapping parts of shortest route and matched route.',1928))19291930self.is_plot_mixshare_nonoverlap = attrsman.add(cm.AttrConf('is_plot_mixshare_nonoverlap', kwargs.get('is_plot_mixshare_nonoverlap', False),1931groupnames=['options'],1932name='Plot mixed share non-overlap',1933info='Plot cumulative distribution of share of mixed access roads of non-overlapping parts of shortest route and matched route.',1934))19351936self.is_plot_exclusiveshare_nonoverlap = attrsman.add(cm.AttrConf('is_plot_exclusiveshare_nonoverlap', kwargs.get('is_plot_exclusiveshare_nonoverlap', False),1937groupnames=['options'],1938name='Plot exclusive share non-overlap',1939info='Plot cumulative distribution of share of exclusive access roads of non-overlapping parts of shortest route and matched route.',1940))19411942self.is_plot_lowpriorityshare_nonoverlap = attrsman.add(cm.AttrConf('is_plot_lowpriorityshare_nonoverlap', kwargs.get('is_plot_lowpriorityshare_nonoverlap', False),1943groupnames=['options'],1944name='Plot low priority share non-overlap',1945info='Plot cumulative distribution of share of low priority roads of non-overlapping parts of shortest route and matched route.',1946))19471948self.is_plot_nodesdensity_nonoverlap = attrsman.add(cm.AttrConf('is_plot_nodesdensity_nonoverlap', kwargs.get('is_plot_nodesdensity_nonoverlap', False),1949groupnames=['options'],1950name='Plot node ratio non-overlap',1951info='Plot cumulative distribution of node ratio between non-overlapping parts of shortest route and matched route.',1952))19531954self.is_plot_tldensity_nonoverlap = attrsman.add(cm.AttrConf('is_plot_tldensity_nonoverlap', kwargs.get('is_plot_tldensity_nonoverlap', False),1955groupnames=['options'],1956name='Plot TL ratio non-overlap',1957info='Plot cumulative distribution of traffic light ratio between non-overlapping parts of shortest route and matched route.',1958))19591960self.is_prioritychangedensity_nonoverlap = attrsman.add(cm.AttrConf('is_prioritychangedensity_nonoverlap', kwargs.get('is_prioritychangedensity_nonoverlap', False),1961groupnames=['options'],1962name='Plot prio. change dens. non-overlap',1963info='Plot cumulative distribution of priority change denities between non-overlapping parts of shortest route and matched route.',1964))19651966# other1967self.n_bins = attrsman.add(cm.AttrConf('n_bins', kwargs.get('n_bins', 10),1968groupnames=['options'],1969name='Bin number',1970info='Number of bins for histograms.',1971))19721973# self.add_plotoptions(**kwargs)1974self.is_title = attrsman.add(cm.AttrConf('is_title', kwargs.get('is_title', False),1975groupnames=['options'],1976name='Show title',1977info='Show title of diagrams.',1978))19791980self.title = attrsman.add(cm.AttrConf('title', kwargs.get('title', ''),1981groupnames=['options'],1982name='Title',1983info='Title text, if blank then default values are used. Only in combination with show title option.',1984))19851986self.size_titlefont = attrsman.add(cm.AttrConf('size_titlefont', kwargs.get('size_titlefont', 32),1987groupnames=['options'],1988name='Title fontsize',1989info='Title fontsize.',1990))19911992self.size_labelfont = attrsman.add(cm.AttrConf('size_labelfont', kwargs.get('size_labelfont', 24),1993groupnames=['options'],1994name='Label fontsize',1995info='Label fontsize.',1996))19971998self.width_line = attrsman.add(cm.AttrConf('width_line', kwargs.get('width_line', 2),1999groupnames=['options'],2000perm='wr',2001name='Line width',2002info='Width of plotted lines.',2003))20042005self.color_line = attrsman.add(cm.AttrConf('color_line', kwargs.get('color_line', np.array([0, 0, 0, 1], dtype=np.float32)),2006groupnames=['options'],2007perm='wr',2008metatype='color',2009name='Line color',2010info='Color of line in various diagrams.',2011))20122013# COLOR_MATCHED_ROUTE,COLOR_SHORTEST_ROUTE,COLOR_FASTEST_ROUTE2014self.color_matched = attrsman.add(cm.AttrConf('color_matched', kwargs.get('color_matched', COLOR_MATCHED_ROUTE.copy()),2015groupnames=['options'],2016perm='wr',2017metatype='color',2018name='Color matched data',2019info='Color of matched data in various diagrams.',2020))20212022self.color_shortest = attrsman.add(cm.AttrConf('color_shortest', kwargs.get('color_shortest', COLOR_SHORTEST_ROUTE.copy()),2023groupnames=['options'],2024perm='wr',2025metatype='color',2026name='Color shortest route data',2027info='Color of shortest route data in various diagrams.',2028))20292030self.color_fastest = attrsman.add(cm.AttrConf('color_fastest', kwargs.get('color_fastest', COLOR_FASTEST_ROUTE.copy()),2031groupnames=['options'],2032perm='wr',2033metatype='color',2034name='Color fastest route data',2035info='Color of fastest route data in various diagrams.',2036))20372038self.printformat = attrsman.add(cm.AttrConf('printformat', kwargs.get('printformat', '%.1f'),2039choices=OrderedDict([2040('Show no values', ''),2041('x', '%.d'),2042('x.x', '%.1f'),2043('x.xx', '%.2f'),2044('x.xxx', '%.3f'),2045('x.xxxx', '%.4f'),2046]),2047groupnames=['options'],2048name='Label formatting',2049info='Print formatting of value label in graphical representation.',2050))20512052self.color_label = attrsman.add(cm.AttrConf('color_label', kwargs.get('color_label', np.array([0, 0, 0, 1], dtype=np.float32)),2053groupnames=['options'],2054perm='wr',2055metatype='color',2056name='Label color',2057info='Color of value label in graphical representation.',2058))20592060self.is_grid = attrsman.add(cm.AttrConf('is_grid', kwargs.get('is_grid', True),2061groupnames=['options'],2062name='Show grid?',2063info='If True, shows a grid on the graphical representation.',2064))2065self.color_background = attrsman.add(cm.AttrConf('color_background', kwargs.get('color_background', np.array([1, 1, 1, 1], dtype=np.float32)),2066groupnames=['options'],2067perm='wr',2068metatype='color',2069name='Background color',2070info='Background color of schematic network in the background.',2071))20722073self.add_save_options(**kwargs)20742075def show(self):2076# print 'show',self.edgeattrname2077# if self.axis is None:2078self.init_figures()2079plt.rc('lines', linewidth=self.width_line)2080# plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y']) +2081# cycler('linestyle', ['-', '--', ':', '-.'])))2082if self.is_plot_lengthratio:2083self.plot_lengthratio()20842085if self.is_plot_lengthoverlap:2086self.plot_lengthoverlap()20872088if self.is_plot_lengthoverlap_fastest:2089self.plot_lengthoverlap_fastest()20902091if self.is_plot_lengthdistrib:2092self.plot_lengthdistrib()20932094if self.is_plot_lengthprob:2095self.plot_lengthprob()20962097if self.is_plot_lengthdistrib_by_class:2098self.plot_lengthdistrib_by_class()20992100# --2101if self.is_plot_lengthdistrib:2102self.plot_lengthdistrib()21032104if self.is_plot_mixshare:2105self.plot_mixshare()21062107if self.is_plot_exclusiveshare:2108self.plot_exclusiveshare()21092110if self.is_plot_lowpriorityshare:2111self.plot_lowpriorityshare()21122113if self.is_plot_nodesdensity:2114self.plot_nodesdensity()21152116if self.is_plot_tldensity:2117self.plot_tldensity()21182119if self.is_prioritychangedensity:2120self.plot_prioritychangedensity()21212122# non overlapping2123if self.is_plot_lengthratio_nonoverlap:2124self.plot_lengthratio_nonoverlap()21252126if self.is_plot_mixshare_nonoverlap:2127self.plot_mixshare_nonoverlap()21282129if self.is_plot_exclusiveshare_nonoverlap:2130self.plot_exclusiveshare_nonoverlap()21312132if self.is_plot_lowpriorityshare_nonoverlap:2133self.plot_lowpriorityshare_nonoverlap()21342135if self.is_plot_nodesdensity_nonoverlap:2136self.plot_nodesdensity_nonoverlap()21372138if self.is_plot_tldensity_nonoverlap:2139self.plot_tldensity_nonoverlap()21402141if self.is_prioritychangedensity_nonoverlap:2142self.plot_prioritychangedensity_nonoverlap()21432144if self.is_plot_deptimedistrib:2145self.plot_deptimedistrib()21462147if self.is_plot_bike_availability_ffbss:2148self.plot_bike_availability_ffbss()21492150if self.is_plot_bike_availability_ffbss_zone:2151self.plot_bike_availability_ffbss_zone()21522153if self.is_analyze_bike_availability_ffbss_zones:2154self.analyze_bike_availability_ffbss_zones()21552156if not self.is_save:2157show_plot()21582159def plot_bike_availability_ffbss(self):2160print 'plot_bike_availability_ffbss'2161# Print the number of bikes simultaneously used every 24h/n_bins hours by selecting traces of a particular day2162fig = self.create_figure()2163mapmatching = self.parent.parent2164trips = mapmatching.trips2165ids_trip = trips.get_ids()[(trips.are_selected[trips.get_ids()] == True)]2166dep_arr_times = np.zeros((len(ids_trip), 2))2167for i, id_trip in zip(range(len(ids_trip)), ids_trip):2168t = time.localtime(trips.timestamps[id_trip])2169dep_arr_times[i, 0] = t.tm_hour + t.tm_min/60.0 + t.tm_sec/3600.02170dep_arr_times[i, 1] = dep_arr_times[i, 0] + trips.durations_gps[id_trip]/3600.02171self.n_bins2172## dep_arr_times = np.sort(dep_arr_times.sort, axis = 0)2173print dep_arr_times[:1000]2174ax = fig.add_subplot(111)2175x_min = min(dep_arr_times[:, 0])2176x_max = max(dep_arr_times[:, 0])2177bins = np.linspace(x_min, x_max, self.n_bins)2178bike_usage = np.zeros(self.n_bins)21792180for id_trip, dep_arr_time in zip(ids_trip, dep_arr_times):2181for bin, i in zip(bins, range(self.n_bins)):2182if dep_arr_time[0] < bin and dep_arr_time[1] > bin:2183bike_usage[i-1] += 12184print bike_usage2185bincenters = plt.plot(bins, bike_usage, color=self.color_matched,2186label='Bike usage distribution of GPS Mobike traces')2187ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2188ax.grid(self.is_grid)2189if self.is_title:2190ax.set_title('Bike usage distribution of GPS Mobike traces', fontsize=self.size_titlefont)2191ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2192ax.set_ylabel('Bike usage', fontsize=self.size_labelfont)2193ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2194ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2195if self.is_save:2196self.save_fig('bike_usage')21972198def plot_bike_availability_ffbss_zone(self):2199print 'plot_bike_availability_ffbss_zone'2200# Plot the difference between attracted and generated trips froma zone in a day every 24h/n_bins hours2201fig = self.create_figure()2202mapmatching = self.parent.parent2203trips = mapmatching.trips2204points = mapmatching.points2205ids_trip = trips.get_ids()2206ids_trip = ids_trip[(trips.are_selected[ids_trip] == True) & (trips.ids_points[ids_trip] != int)]2207ids_points = trips.ids_points[ids_trip]2208zone = self.zone_ffbss2209scenario = mapmatching.get_scenario()2210zones = scenario.landuse.zones2211zone_shape = zones.shapes[zones.ids_sumo.get_id_from_index(self.zone_ffbss)]2212n_bins = self.n_bins2213generated_trips = np.zeros((n_bins))2214attracted_trips = np.zeros((n_bins))22152216for id_trip, ids_point in zip(ids_trip, ids_points):2217id_initial_point = ids_point[0]2218id_final_point = ids_point[-1]2219print id_trip2220starting_time = np.int(points.timestamps[id_initial_point] % 86400/86400.*np.float(n_bins))2221arriving_time = np.int(points.timestamps[id_final_point] % 86400/86400.*np.float(n_bins))22222223if is_point_in_polygon(mapmatching.points.coords[id_initial_point], zone_shape):2224generated_trips[starting_time] += 122252226if is_point_in_polygon(mapmatching.points.coords[id_final_point], zone_shape):2227attracted_trips[arriving_time] += 122282229availability = np.cumsum(attracted_trips) - np.cumsum(generated_trips)2230bins = np.linspace(0, 24, num=n_bins)2231np.savetxt('generated_trips_%s.txt' % (zone), generated_trips)2232np.savetxt('attracted_trips_%s.txt' % (zone), attracted_trips)22332234ax = fig.add_subplot(131)2235bincenters = plt.plot(bins, availability, color=self.color_matched,2236label='Bikes availability')2237ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2238ax.grid(self.is_grid)2239if self.is_title:2240ax.set_title('Bikes relativeavailability during time', fontsize=self.size_titlefont)2241ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2242ax.set_ylabel('Bike Relative Availability', fontsize=self.size_labelfont)2243ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2244ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))22452246ax = fig.add_subplot(132)2247bincenters = plt.plot(bins, generated_trips, color=self.color_matched,2248label='Generated bikes')2249ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2250ax.grid(self.is_grid)2251if self.is_title:2252ax.set_title('Generated bikes during time', fontsize=self.size_titlefont)2253ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2254ax.set_ylabel('Generated bikes', fontsize=self.size_labelfont)2255ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2256ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))22572258ax = fig.add_subplot(133)2259bincenters = plt.plot(bins, attracted_trips, color=self.color_matched,2260label='Attracted bikes')2261ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2262ax.grid(self.is_grid)2263if self.is_title:2264ax.set_title('Attracted bikes during time', fontsize=self.size_titlefont)2265ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2266ax.set_ylabel('Attracted bikes', fontsize=self.size_labelfont)2267ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2268ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2269if self.is_save:2270self.save_fig('bike_availability')22712272def analyze_bike_availability_ffbss_zones(self):2273print 'analyze_bike_availability_ffbss_zones'2274# Save a .txt file with generated trips and attracted trips every 24h/n_bins hours for each zone with selected trips2275fig = self.create_figure()2276mapmatching = self.parent.parent2277trips = mapmatching.trips2278points = mapmatching.points2279ids_trip = trips.get_ids()2280ids_trip = ids_trip[(trips.are_selected[ids_trip] == True) & (trips.ids_points[ids_trip] != int)]2281ids_points = trips.ids_points[ids_trip]2282zone = self.zone_ffbss2283scenario = mapmatching.get_scenario()2284zones = scenario.landuse.zones2285n_zone = len(zones.get_ids())2286n_bins = self.n_bins2287generated_trips = np.zeros((n_zone, n_bins))2288attracted_trips = np.zeros((n_zone, n_bins))2289for id_trip, ids_point in zip(ids_trip, ids_points):2290id_initial_point = ids_point[0]2291id_final_point = ids_point[-1]2292print id_trip2293starting_time = np.int(points.timestamps[id_initial_point] % 86400/86400.*np.float(n_bins))2294arriving_time = np.int(points.timestamps[id_final_point] % 86400/86400.*np.float(n_bins))2295i = 02296for zone in zones.get_ids():2297zone_shape = zones.shapes[zone]2298if is_point_in_polygon(mapmatching.points.coords[id_initial_point], zone_shape):2299generated_trips[i, starting_time] += 12300break2301i += 12302i = 02303for zone in zones.get_ids():2304zone_shape = zones.shapes[zone]2305if is_point_in_polygon(mapmatching.points.coords[id_final_point], zone_shape):2306attracted_trips[i, arriving_time] += 12307break2308i += 12309np.savetxt('generated_trips.txt', generated_trips)2310np.savetxt('attracted_trips.txt', attracted_trips)23112312availability = attracted_trips - generated_trips2313for row in range(len(availability[:, 0])):2314availability[row, :] = np.cumsum(availability[row, :])23152316bins = np.linspace(0, 24, num=n_bins)2317np.savetxt('generated_trips_%s.txt' % (zone), generated_trips)2318np.savetxt('attracted_trips_%s.txt' % (zone), attracted_trips)23192320ax = fig.add_subplot(231)2321for row in range(len(availability[:, 0])):2322bincenters = plt.plot(bins, availability[row, :], color=self.color_matched)2323ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2324ax.grid(self.is_grid)2325if self.is_title:2326ax.set_title('Bikes relativeavailability during time', fontsize=self.size_titlefont)2327ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2328ax.set_ylabel('Bike Relative Availability', fontsize=self.size_labelfont)2329ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2330ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))23312332ax = fig.add_subplot(232)2333for row in range(len(generated_trips[:, 0])):2334bincenters = plt.plot(bins, generated_trips[row, :], color=self.color_matched)2335ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2336ax.grid(self.is_grid)2337if self.is_title:2338ax.set_title('Generated bikes during time', fontsize=self.size_titlefont)2339ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2340ax.set_ylabel('Generated bikes', fontsize=self.size_labelfont)2341ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2342ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))23432344ax = fig.add_subplot(233)2345for row in range(len(attracted_trips[:, 0])):2346bincenters = plt.plot(bins, attracted_trips[row, :], color=self.color_matched)2347ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2348ax.grid(self.is_grid)2349if self.is_title:2350ax.set_title('Attracted bikes during time', fontsize=self.size_titlefont)2351ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2352ax.set_ylabel('Attracted bikes', fontsize=self.size_labelfont)2353ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2354ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2355if self.is_save:2356self.save_fig('bike_availability')23572358# plot relative values2359availability2 = np.zeros((len(availability[:, 0]), len(availability[0, :])))2360generated_trips2 = np.zeros((len(availability[:, 0]), len(availability[0, :])))2361attracted_trips2 = np.zeros((len(availability[:, 0]), len(availability[0, :])))23622363for row in range(len(availability[:, 0])):2364availability2[row, :] = availability[row, :]/np.sum(np.absolute(availability[row, :]))2365generated_trips2[row, :] = generated_trips[row, :]/np.sum(generated_trips[row, :])2366attracted_trips2[row, :] = attracted_trips[row, :]/np.sum(attracted_trips[row, :])23672368ax = fig.add_subplot(234)2369for row in range(len(availability[:, 0])):2370if np.sum(generated_trips[row, :]) > n_bins and np.sum(attracted_trips[row, :]) > n_bins:2371bincenters = plt.plot(bins, availability2[row, :], color=self.color_matched)2372ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2373ax.grid(self.is_grid)2374if self.is_title:2375ax.set_title('Bikes relativeavailability during time', fontsize=self.size_titlefont)2376ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2377ax.set_ylabel('Bike Relative Availability', fontsize=self.size_labelfont)2378ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2379ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))23802381ax = fig.add_subplot(235)2382for row in range(len(generated_trips[:, 0])):2383if np.sum(generated_trips[row, :]) > n_bins and np.sum(attracted_trips[row, :]) > n_bins:2384bincenters = plt.plot(bins, generated_trips2[row, :], color=self.color_matched)2385ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2386ax.grid(self.is_grid)2387if self.is_title:2388ax.set_title('Generated bikes during time', fontsize=self.size_titlefont)2389ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2390ax.set_ylabel('Generated bikes', fontsize=self.size_labelfont)2391ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2392ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))23932394ax = fig.add_subplot(236)2395for row in range(len(attracted_trips[:, 0])):2396if np.sum(generated_trips[row, :]) > n_bins and np.sum(attracted_trips[row, :]) > n_bins:2397bincenters = plt.plot(bins, attracted_trips2[row, :], color=self.color_matched)2398ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2399ax.grid(self.is_grid)2400if self.is_title:2401ax.set_title('Attracted bikes during time', fontsize=self.size_titlefont)2402ax.set_xlabel('time [h]', fontsize=self.size_labelfont)2403ax.set_ylabel('Attracted bikes', fontsize=self.size_labelfont)2404ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2405ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2406if self.is_save:2407self.save_fig('bike_availability')24082409def plot_deptimedistrib(self):2410print 'plot_deptimedistrib'2411fig = self.create_figure()2412mapmatching = self.parent.parent2413trips = mapmatching.trips2414ids_trip = trips.get_ids()2415hour_departure = np.zeros(len(ids_trip))2416for i, id_trip in zip(range(len(ids_trip)), ids_trip):2417t = time.localtime(trips.timestamps[id_trip])2418hour_departure[i] = t.tm_hour + t.tm_min/60.0 + t.tm_sec/3600.02419# print hour_departure[:1000]24202421ax = fig.add_subplot(111)2422x_min = min(hour_departure)2423x_max = max(hour_departure)2424if self.n_bins < 0:2425bins = np.arange(x_min, x_max + 1, 1)24262427else:2428n_bins = self.n_bins2429bins = np.linspace(x_min, x_max, n_bins)24302431# print ' bins',bins2432bincenters = plt.hist(hour_departure, bins=bins, color=self.color_line,2433density=True,2434histtype='stepfilled',2435label='Departure time (hour) distribution')24362437ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2438ax.grid(self.is_grid)2439if self.is_title:2440if self.title == "":2441title = 'Departure time distribution of GPS traces'2442else:2443title = self.title2444ax.set_title(title, fontsize=self.size_titlefont)2445ax.set_xlabel('Departure time [h]', fontsize=self.size_labelfont)2446ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2447ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2448ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2449if self.is_save:2450self.save_fig('plot_deptimedistrib')24512452def plot_tldensity(self):2453print 'plot_tldensity'2454fig = self.create_figure()2455results = self.parent2456routesresults_shortest = results.routesresults_shortest2457routesresults_matched = results.routesresults_matched2458edgesresults = results.edgesresults24592460ax = fig.add_subplot(111)2461ids_valid = routesresults_matched.select_ids(np.logical_and(2462routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))24632464dists_match = routesresults_matched.distances[ids_valid]2465dists_shortest = routesresults_shortest.distances[ids_valid]24662467matched = routesresults_matched.numbers_nodes_tls[ids_valid]/dists_match*10002468shortest = routesresults_shortest.numbers_nodes_tls[ids_valid]/dists_shortest*100024692470x_min = min(np.min(matched), np.min(shortest))2471x_max = 10.0 # max(np.max(matched),np.max(shortest))2472bins = np.linspace(x_min, x_max, self.n_bins)2473bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +2474'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))2475bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +2476'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))24772478ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2479ax.grid(self.is_grid)2480if self.is_title:2481ax.set_title('Node densities of matched and shortest route', fontsize=self.size_titlefont)2482ax.set_xlabel('Traffic light density [1/km]', fontsize=self.size_labelfont)2483ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2484ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2485ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2486if self.is_save:2487self.save_fig('routeana_tldensity')24882489def plot_nodesdensity(self):2490print 'plot_nodesdensity'2491fig = self.create_figure()2492results = self.parent24932494routesresults_shortest = results.routesresults_shortest2495routesresults_matched = results.routesresults_matched2496edgesresults = results.edgesresults24972498ax = fig.add_subplot(111)2499ids_valid = routesresults_matched.select_ids(np.logical_and(2500routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))25012502dists_match = routesresults_matched.distances[ids_valid]2503dists_shortest = routesresults_shortest.distances[ids_valid]25042505matched = routesresults_matched.numbers_nodes[ids_valid]/dists_match*10002506shortest = routesresults_shortest.numbers_nodes[ids_valid]/dists_shortest*100025072508x_min = min(np.min(matched), np.min(shortest))2509x_max = max(np.max(matched), np.max(shortest))2510bins = np.linspace(x_min, x_max, self.n_bins)2511bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +2512'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))2513bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +2514'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))25152516ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2517ax.grid(self.is_grid)2518if self.is_title:2519ax.set_title('Node densities of matched and shortest route', fontsize=self.size_titlefont)2520ax.set_xlabel('Node density [1/km]', fontsize=self.size_labelfont)2521ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2522ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2523ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2524if self.is_save:2525self.save_fig('routeana_nodesdensity')25262527def plot_prioritychangedensity(self):2528print 'plot_prioritychangedensity'2529fig = self.create_figure()2530results = self.parent2531routesresults_shortest = results.routesresults_shortest2532routesresults_matched = results.routesresults_matched2533edgesresults = results.edgesresults25342535ax = fig.add_subplot(111)2536ids_valid = routesresults_matched.select_ids(np.logical_and(2537routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))25382539dists_match = routesresults_matched.distances[ids_valid]2540dists_shortest = routesresults_shortest.distances[ids_valid]25412542matched = routesresults_matched.numbers_prioritychange[ids_valid]/dists_match*10002543shortest = routesresults_shortest.numbers_prioritychange[ids_valid]/dists_shortest*100025442545x_min = min(np.min(matched), np.min(shortest))2546x_max = max(np.max(matched), np.max(shortest))2547bins = np.linspace(x_min, x_max, self.n_bins)2548bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +2549'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))2550bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +2551'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))25522553ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2554ax.grid(self.is_grid)2555if self.is_title:2556ax.set_title('Priority change dens. of matched and shortest route', fontsize=self.size_titlefont)2557ax.set_xlabel('Priority change density [1/km]', fontsize=self.size_labelfont)2558ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2559ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2560ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2561if self.is_save:2562self.save_fig('routeana_nodesdensity')25632564def plot_lowpriorityshare(self):2565print 'plot_lowpriorityshare'2566fig = self.create_figure()2567results = self.parent2568routesresults_shortest = results.routesresults_shortest2569routesresults_matched = results.routesresults_matched2570edgesresults = results.edgesresults25712572ax = fig.add_subplot(111)2573ids_valid = routesresults_matched.select_ids(np.logical_and(2574routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))25752576dists_match = routesresults_matched.distances[ids_valid]2577dists_shortest = routesresults_shortest.distances[ids_valid]25782579matched = routesresults_matched.lengths_low_priority[ids_valid]/dists_match*1002580shortest = routesresults_shortest.lengths_low_priority[ids_valid]/dists_shortest*10025812582x_min = min(np.min(matched), np.min(shortest))2583x_max = 15.0 # max(np.max(matched),np.max(shortest))2584bins = np.linspace(x_min, x_max, self.n_bins)2585bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +2586'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))2587bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +2588'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))25892590ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2591ax.grid(self.is_grid)2592if self.is_title:2593ax.set_title('Share of low priority roads of matched and shortest route', fontsize=self.size_titlefont)2594ax.set_xlabel('Low priority road share [%]', fontsize=self.size_labelfont)2595ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2596ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2597ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2598if self.is_save:2599self.save_fig('routeana_lowpriorityshare')26002601def plot_exclusiveshare(self):2602print 'plot_exclusiveshare'2603fig = self.create_figure()2604results = self.parent2605routesresults_shortest = results.routesresults_shortest2606routesresults_matched = results.routesresults_matched2607edgesresults = results.edgesresults26082609ax = fig.add_subplot(111)2610ids_valid = routesresults_matched.select_ids(np.logical_and(2611routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))26122613dists_match = routesresults_matched.distances[ids_valid]2614dists_shortest = routesresults_shortest.distances[ids_valid]26152616matched = routesresults_matched.lengths_exclusive[ids_valid]/dists_match*1002617shortest = routesresults_shortest.lengths_exclusive[ids_valid]/dists_shortest*10026182619x_min = min(np.min(matched), np.min(shortest))2620x_max = max(np.max(matched), np.max(shortest))2621bins = np.linspace(x_min, x_max, self.n_bins)2622bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +2623'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))2624bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +2625'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))26262627ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2628ax.grid(self.is_grid)2629if self.is_title:2630ax.set_title('Share of exclusive access roads of matched and shortest route', fontsize=self.size_titlefont)2631ax.set_xlabel('Exclusive access road share [%]', fontsize=self.size_labelfont)2632ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2633ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2634ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2635if self.is_save:2636self.save_fig('routeana_exclusiveshare')26372638def plot_mixshare(self):2639print 'plot_mixshare'2640fig = self.create_figure()2641results = self.parent2642routesresults_shortest = results.routesresults_shortest2643routesresults_matched = results.routesresults_matched2644edgesresults = results.edgesresults26452646ax = fig.add_subplot(111)2647ids_valid = routesresults_matched.select_ids(np.logical_and(2648routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))26492650dists_match = routesresults_matched.distances[ids_valid]2651dists_shortest = routesresults_shortest.distances[ids_valid]26522653matched = routesresults_matched.lengths_mixed[ids_valid]/dists_match*1002654shortest = routesresults_shortest.lengths_mixed[ids_valid]/dists_shortest*10026552656x_min = min(np.min(matched), np.min(shortest))2657x_max = max(np.max(matched), np.max(shortest))2658bins = np.linspace(x_min, x_max, self.n_bins)2659bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +2660'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))2661bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +2662'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))26632664ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2665ax.grid(self.is_grid)2666if self.is_title:2667ax.set_title('Share of mixed reserved access roads of matched and shortest route',2668fontsize=self.size_titlefont)2669ax.set_xlabel('Mixed reserved access road share [%]', fontsize=self.size_labelfont)2670ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2671ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2672ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2673if self.is_save:2674self.save_fig('routeana_mixshare')26752676def plot_lengthdistrib_by_class(self):2677print 'plot_lengthdistrib_by_class'2678fig = self.create_figure()2679results = self.parent2680routesresults_shortest = results.routesresults_shortest2681routesresults_matched = results.routesresults_matched2682edgesresults = results.edgesresults26832684ax = fig.add_subplot(111)2685ids_valid = routesresults_matched.select_ids(np.logical_and(2686routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))26872688dists_match = routesresults_matched.distances[ids_valid]2689dists_shortest = routesresults_shortest.distances[ids_valid]2690x_min = min(np.min(dists_match), np.min(dists_shortest))2691x_max = max(np.max(dists_match), np.max(dists_shortest))26922693dists_class = np.arange(0, int(x_max), self.distance_class)2694dists_class_center = (dists_class+0.5*self.distance_class)[1:]2695n_class = len(dists_class)-12696means_match = np.zeros(n_class, dtype=np.float32)2697stds_match = np.zeros(n_class, dtype=np.float32)2698means_shortest = np.zeros(n_class, dtype=np.float32)2699stds_shortest = np.zeros(n_class, dtype=np.float32)2700xticklabels = []2701ratiolabels = []2702for dist_lower, dist_upper, i in zip(dists_class[:-1], dists_class[1:], range(n_class)):2703xticklabels.append('%d - %d' % (float(dist_lower)/1000, float(dist_upper)/1000))2704inds = np.logical_and(dists_match > dist_lower, dists_match < dist_upper)2705means_match[i] = np.mean(dists_match[inds])2706stds_match[i] = np.std(dists_match[inds])27072708#inds = np.logical_and(dists_shortest>dist_lower,dists_shortest<dist_upper)2709means_shortest[i] = np.mean(dists_shortest[inds])2710stds_shortest[i] = np.std(dists_shortest[inds])27112712ratiolabel = ''2713if (not np.isnan(means_shortest[i])) & (not np.isnan(means_match[i])):2714if means_match[i] > 0:2715ratiolabel = '%d%%' % (means_shortest[i]/means_match[i]*100)2716ratiolabels.append(ratiolabel)27172718print ' dists_class_center', dists_class_center2719print ' means_match', means_match2720print ' stds_match', stds_match2721print ' means_shortest', means_shortest2722print ' stds_shortest', stds_shortest27232724x = np.arange(n_class, dtype=np.float32) # the x locations for the groups2725width = 0.35 # the width of the bars27262727# ax.bar(ind + width, women_means, width, color='y', yerr=women_std)2728bars1 = ax.bar(x-width, means_match, width, color=self.color_matched, yerr=stds_match)2729bars2 = ax.bar(x+0*width, means_shortest, width, color=self.color_shortest, yerr=stds_shortest)2730#bars1 = ax.bar(dists_class_center+0.35*self.distance_class, means_match, 0.25*self.distance_class, color=self.color_matched, yerr=stds_match)2731#bars2 = ax.bar(dists_class_center-0.35*self.distance_class, means_shortest, 0.25*self.distance_class, color=self.color_shortest, yerr=stds_shortest)27322733#ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)2734ax.legend((bars1[0], bars2[0]), ('matched', 'shortest'),2735shadow=True, fontsize=self.size_labelfont, loc='best')27362737# if self.is_grid:2738ax.yaxis.grid(self.is_grid)27392740if self.is_title:2741ax.set_title('Mean length by trip length class', fontsize=self.size_titlefont)2742ax.set_xlabel('Length classes [km]', fontsize=self.size_labelfont)2743ax.set_ylabel('Mean length [m]', fontsize=self.size_labelfont)27442745ax.set_xticks(x)2746ax.set_xticklabels(xticklabels)2747# self._autolabel_bars(ax,bars1,means_match)2748self._autolabel_bars(ax, bars2, ratiolabels)27492750ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2751ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2752if self.is_save:2753self.save_fig('routeana_lengthdistrib_by_class')27542755def _autolabel_bars(self, ax, bars, labels):2756"""2757Attach a text label above each bar displaying its height2758"""2759for rect, label in zip(bars, labels):2760height = rect.get_height()2761if not np.isnan(height):2762ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,2763'%s' % label,2764ha='center', va='bottom',2765fontsize=int(0.8*self.size_labelfont),2766)27672768def plot_lengthdistrib(self):27692770fig = self.create_figure()2771results = self.parent2772routesresults_shortest = results.routesresults_shortest2773routesresults_matched = results.routesresults_matched2774edgesresults = results.edgesresults27752776ax = fig.add_subplot(111)2777ids_valid = routesresults_matched.select_ids(np.logical_and(routesresults_shortest.distances.get_value() > 0,2778time. routesresults_matched.distances.get_value() > 0,2779# routesresults_matched.distances.get_value()<20000)2780))2781print 'plot_lengthdistrib', len(ids_valid)2782# print ' ids_valid',ids_valid2783if len(ids_valid) == 0:2784return False27852786dists_match = routesresults_matched.distances[ids_valid]2787dists_shortest = routesresults_shortest.distances[ids_valid]27882789x_min = min(np.min(dists_match), np.min(dists_shortest))2790x_max = max(np.max(dists_match), np.max(dists_shortest))2791bins = np.linspace(x_min, x_max, self.n_bins)2792bincenters = self.plot_hist(ax, dists_match, bins=bins, color=self.color_matched,2793label='matched:'+'$\mu = %dm$, $\sigma=%dm$' % (np.mean(dists_match), np.std(dists_match)))2794bincenters = self.plot_hist(ax, dists_shortest, bins=bins, color=self.color_shortest, label='shortest:' +2795'$\mu = %dm$, $\sigma=%dm$' % (np.mean(dists_shortest), np.std(dists_shortest)))27962797ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2798ax.grid(self.is_grid)2799if self.is_title:2800ax.set_title('Length distribution of matched and shortest route', fontsize=self.size_titlefont)2801ax.set_xlabel('Length [m]', fontsize=self.size_labelfont)2802ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2803ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2804ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2805if self.is_save:2806self.save_fig('routeana_lengthdistrib')2807return True28082809def plot_timedistrib(self):2810print 'plot_timedistrib'2811fig = self.create_figure()2812results = self.parent2813mapmatching = results.parent2814trips = mapmatching.trips2815#routesresults_fastest = results.routesresults_fastest2816#routesresults_matched = results.routesresults_matched2817edgesresults = results.edgesresults28182819ax = fig.add_subplot(111)2820#ids_overlength = routesresults_matched.select_ids(np.logical_and(routesresults_shortest.distances.get_value()>0, routesresults_matched.distances.get_value()>20000))2821# print ' len(ids_overlength)',len(ids_overlength)2822# print ' ids_overlength',ids_overlength28232824ids_valid = trips.select_ids(2825np.logical_and(trips.lengths_route_matched.get_value() > 0,2826trips.durations_route_fastest.get_value() > 0,2827# routesresults_matched.distances.get_value()<20000)2828))28292830if len(ids_valid) == 0:2831return False28322833times_fastest = trips.durations_route_fastest[ids_valid]2834times_match = times_fastest+trips.timelosses_route_fastest[ids_valid]28352836x_min = min(np.min(times_fastest), np.min(times_match))2837x_max = max(np.max(times_fastest), np.max(times_match))2838bins = np.linspace(x_min, x_max, self.n_bins)2839bincenters = self.plot_hist(ax, times_match, bins=bins, color=self.color_matched,2840label='matched:'+'$\mu = %dm$, $\sigma=%dm$' % (np.mean(times_match), np.std(times_match)))2841bincenters = self.plot_hist(ax, times_fastest, bins=bins, color=self.color_fastest, label='fastest:' +2842'$\mu = %dm$, $\sigma=%dm$' % (np.mean(times_fastest), np.std(times_fastest)))28432844ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2845ax.grid(self.is_grid)2846if self.is_title:2847ax.set_title('Triptime distribution of matched and fastest route', fontsize=self.size_titlefont)2848ax.set_xlabel('Time [s]', fontsize=self.size_labelfont)2849ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2850ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2851ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2852if self.is_save:2853self.save_fig('routeana_timedistrib')28542855return True28562857def plot_lengthprob(self):2858print 'plot_lengthprob'2859fig = self.create_figure()2860results = self.parent2861routesresults_shortest = results.routesresults_shortest2862routesresults_matched = results.routesresults_matched2863edgesresults = results.edgesresults28642865ax = fig.add_subplot(111)2866ids_valid = routesresults_matched.select_ids(np.logical_and(2867routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))28682869dists_match = routesresults_matched.distances[ids_valid]2870dists_shortest = routesresults_shortest.distances[ids_valid]28712872x_min = min(np.min(dists_match), np.min(dists_shortest))2873x_max = max(np.max(dists_match), np.max(dists_shortest))2874bins = np.linspace(x_min, x_max, self.n_bins)2875w_bin = bins[1]-bins[0]2876bincenters = self.plot_hist(ax, dists_match, bins=bins,2877color=self.color_matched,2878label='matched:' +2879'$\mu = %dm$, $\sigma=%dm$' % (np.mean(dists_match), np.std(dists_match)),2880is_rel_frequ=True,2881is_percent=True,2882)2883bincenters = self.plot_hist(ax, dists_shortest, bins=bins,2884color=self.color_shortest,2885label='shortest:' +2886'$\mu = %dm$, $\sigma=%dm$' % (np.mean(dists_shortest), np.std(dists_shortest)),2887is_rel_frequ=True,2888is_percent=True,2889)28902891ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2892ax.grid(self.is_grid)2893if self.is_title:2894ax.set_title('Relative frequency of matched and shortest route', fontsize=self.size_titlefont)2895ax.set_xlabel('Length [m]', fontsize=self.size_labelfont)2896ax.set_ylabel('Relative frequency [%]', fontsize=self.size_labelfont)2897ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2898ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))2899if self.is_save:2900self.save_fig('routeana_lengthprob')29012902def plot_lengthoverlap(self):2903print 'plot_lengthoverlap'2904fig = self.create_figure()2905results = self.parent2906routesresults_shortest = results.routesresults_shortest2907routesresults_matched = results.routesresults_matched2908edgesresults = results.edgesresults29092910ax = fig.add_subplot(111)2911bins = np.linspace(0.0, 1.0, self.n_bins)29122913ids_valid = routesresults_matched.select_ids(np.logical_and(2914routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))2915values = routesresults_shortest.lengths_overlap_matched[ids_valid]/routesresults_matched.distances[ids_valid]2916bincenters = self.plot_hist(ax, values,2917bins=bins, histtype='bar',2918label=r'$\mu = %.2f$, $\sigma=%.2f$' % (np.mean(values), np.std(values))2919)29202921ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2922ax.grid(self.is_grid)2923if self.is_title:2924ax.set_title('Share of overlap between shortest path and matched path', fontsize=self.size_titlefont)2925ax.set_xlabel('Overlap share between shortest and matched path', fontsize=self.size_labelfont)2926ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2927ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2928ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))29292930self.set_figmargins()2931if self.is_save:2932self.save_fig('routeana_lengthoverlap')29332934def plot_lengthoverlap_fastest(self):2935print 'plot_lengthoverlap_fastest'2936fig = self.create_figure()2937results = self.parent2938print 'dir(results)', dir(results)2939routesresults_fastest = results.routesresults_fastest2940routesresults_matched = results.routesresults_matched2941edgesresults = results.edgesresults29422943ax = fig.add_subplot(111)2944bins = np.linspace(0.0, 1.0, self.n_bins)29452946ids_valid = routesresults_matched.select_ids(np.logical_and(2947routesresults_fastest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))2948values = routesresults_fastest.lengths_overlap_matched[ids_valid]/routesresults_matched.distances[ids_valid]2949bincenters = self.plot_hist(ax, values,2950bins=bins, histtype='bar',2951label=r'$\mu = %.2f$, $\sigma=%.2f$' % (np.mean(values), np.std(values))2952)29532954ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2955ax.grid(self.is_grid)2956if self.is_title:2957ax.set_title('Share of overlap between fastest path and matched path', fontsize=self.size_titlefont)2958ax.set_xlabel('Overlap share between fastest and matched path', fontsize=self.size_labelfont)2959ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2960ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2961ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))29622963self.set_figmargins()2964if self.is_save:2965self.save_fig('routeana_lengthoverlap_fastest')29662967def plot_lengthratio(self):2968print 'plot_lengthratio'2969fig = self.create_figure()2970results = self.parent2971routesresults_shortest = results.routesresults_shortest2972routesresults_matched = results.routesresults_matched2973edgesresults = results.edgesresults29742975ax = fig.add_subplot(111)2976bins = np.linspace(0.0, 1.0, self.n_bins)29772978ids_valid = routesresults_matched.select_ids(np.logical_and(2979routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))2980values = routesresults_shortest.distances[ids_valid]/routesresults_matched.distances[ids_valid]2981bincenters = self.plot_hist(ax, values,2982bins=bins, histtype='bar',2983label=r'$\mu = %.2f$, $\sigma=%.2f$' % (np.mean(values), np.std(values))2984)29852986ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)2987ax.grid(self.is_grid)2988if self.is_title:2989ax.set_title('Ratio distance shortest path over matched path', fontsize=self.size_titlefont)2990ax.set_xlabel('Ratio shortest path length/matched path length', fontsize=self.size_labelfont)2991ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)2992ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))2993ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))29942995self.set_figmargins()2996if self.is_save:2997self.save_fig('routeana_lengthratio')299829993000# -------------------------------------------------------------------------------3001# non-overlap30023003def plot_lengthratio_nonoverlap(self):3004print 'plot_lengthratio_nonoverlap'3005fig = self.create_figure()3006results = self.parent3007routesresults_shortest = results.routesresults_shortest3008routesresults_matched = results.routesresults_matched3009routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap3010routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap30113012edgesresults = results.edgesresults30133014ax = fig.add_subplot(111)3015bins = np.linspace(0.0, 1.0, self.n_bins)30163017ids_valid = routesresults_matched.select_ids(np.logical_and(3018routesresults_shortest_nonoverlap.distances.get_value() > 0,3019routesresults_matched_nonoverlap.distances.get_value() > 0)3020)30213022values = routesresults_shortest_nonoverlap.distances[ids_valid] / \3023routesresults_matched_nonoverlap.distances[ids_valid]3024bincenters = self.plot_hist(ax, values,3025bins=bins, histtype='bar',3026label=r'$\mu = %.2f$, $\sigma=%.2f$' % (np.mean(values), np.std(values))3027)30283029ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)3030ax.grid(self.is_grid)3031if self.is_title:3032ax.set_title('Ratio distance of non-overlapping shortest over matched path', fontsize=self.size_titlefont)3033ax.set_xlabel('Ratio shortest n.o. path length/matched path length', fontsize=self.size_labelfont)3034ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)3035ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))3036ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))30373038self.set_figmargins()3039if self.is_save:3040self.save_fig('routeana_lengthratio_nonoverlap')30413042def plot_tldensity_nonoverlap(self):3043print 'plot_tldensity_nonoverlap'3044fig = self.create_figure()3045results = self.parent3046routesresults_shortest = results.routesresults_shortest3047routesresults_matched = results.routesresults_matched3048routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap3049routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap3050edgesresults = results.edgesresults30513052ax = fig.add_subplot(111)3053ids_valid = routesresults_matched.select_ids(np.logical_and(3054routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))30553056dists_match = routesresults_matched_nonoverlap.distances[ids_valid]3057dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]30583059matched = routesresults_matched_nonoverlap.numbers_nodes_tls[ids_valid]/dists_match*10003060shortest = routesresults_shortest_nonoverlap.numbers_nodes_tls[ids_valid]/dists_shortest*100030613062x_min = min(np.min(matched), np.min(shortest))3063x_max = 10.0 # max(np.max(matched),np.max(shortest))3064bins = np.linspace(x_min, x_max, self.n_bins)3065bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +3066'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))3067bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +3068'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))30693070ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)3071ax.grid(self.is_grid)3072if self.is_title:3073ax.set_title('Node densities of non-overlapping matched and shortest route', fontsize=self.size_titlefont)3074ax.set_xlabel('Traffic light density n.o. [1/km]', fontsize=self.size_labelfont)3075ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)3076ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))3077ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))3078if self.is_save:3079self.save_fig('routeana_tldensity_nonoverlap')30803081def plot_nodesdensity_nonoverlap(self):3082print 'plot_nodesdensity_nonoverlap'3083fig = self.create_figure()3084results = self.parent3085routesresults_shortest = results.routesresults_shortest3086routesresults_matched = results.routesresults_matched3087routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap3088routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap3089edgesresults = results.edgesresults30903091ax = fig.add_subplot(111)3092ids_valid = routesresults_matched.select_ids(np.logical_and(3093routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))30943095dists_match = routesresults_matched_nonoverlap.distances[ids_valid]3096dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]30973098matched = routesresults_matched_nonoverlap.numbers_nodes[ids_valid]/dists_match*10003099shortest = routesresults_shortest_nonoverlap.numbers_nodes[ids_valid]/dists_shortest*100031003101x_min = min(np.min(matched), np.min(shortest))3102x_max = max(np.max(matched), np.max(shortest))3103bins = np.linspace(x_min, x_max, self.n_bins)3104bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +3105'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))3106bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +3107'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))31083109ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)3110ax.grid(self.is_grid)3111if self.is_title:3112ax.set_title('Node densities of non-overlapping matched and shortest route', fontsize=self.size_titlefont)3113ax.set_xlabel('Node density n.o. [1/km]', fontsize=self.size_labelfont)3114ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)3115ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))3116ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))3117if self.is_save:3118self.save_fig('routeana_nodesdensity_nonoverlap')31193120def plot_prioritychangedensity_nonoverlap(self):3121print 'plot_prioritychangedensity_nonoverlap'3122fig = self.create_figure()3123results = self.parent3124routesresults_shortest = results.routesresults_shortest3125routesresults_matched = results.routesresults_matched3126routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap3127routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap3128edgesresults = results.edgesresults31293130ax = fig.add_subplot(111)3131ids_valid = routesresults_matched.select_ids(np.logical_and(3132routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))31333134dists_match = routesresults_matched_nonoverlap.distances[ids_valid]3135dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]31363137matched = routesresults_matched_nonoverlap.numbers_prioritychange[ids_valid]/dists_match*10003138shortest = routesresults_shortest_nonoverlap.numbers_prioritychange[ids_valid]/dists_shortest*100031393140x_min = min(np.min(matched), np.min(shortest))3141x_max = max(np.max(matched), np.max(shortest))3142bins = np.linspace(x_min, x_max, self.n_bins)3143bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +3144'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))3145bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +3146'$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))31473148ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)3149ax.grid(self.is_grid)3150if self.is_title:3151ax.set_title('Priority change dens. of non-overlapping matched and shortest route',3152fontsize=self.size_titlefont)3153ax.set_xlabel('Priority change density n.o. [1/km]', fontsize=self.size_labelfont)3154ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)3155ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))3156ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))3157if self.is_save:3158self.save_fig('routeana_nodesdensity_nonoverlap')31593160def plot_lowpriorityshare_nonoverlap(self):3161print 'plot_lowpriorityshare_nonoverlap'3162fig = self.create_figure()3163results = self.parent3164routesresults_shortest = results.routesresults_shortest3165routesresults_matched = results.routesresults_matched3166routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap3167routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap3168edgesresults = results.edgesresults31693170ax = fig.add_subplot(111)3171ids_valid = routesresults_matched.select_ids(np.logical_and(3172routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))31733174dists_match = routesresults_matched_nonoverlap.distances[ids_valid]3175dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]31763177matched = routesresults_matched_nonoverlap.lengths_low_priority[ids_valid]/dists_match*1003178shortest = routesresults_shortest_nonoverlap.lengths_low_priority[ids_valid]/dists_shortest*10031793180x_min = min(np.min(matched), np.min(shortest))3181x_max = 15.0 # max(np.max(matched),np.max(shortest))3182bins = np.linspace(x_min, x_max, self.n_bins)3183bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +3184'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))3185bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +3186'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))31873188ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)3189ax.grid(self.is_grid)3190if self.is_title:3191ax.set_title('Share of low priority roads of non-overlapping matched and shortest route',3192fontsize=self.size_titlefont)3193ax.set_xlabel('Low priority road share n.o. [%]', fontsize=self.size_labelfont)3194ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)3195ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))3196ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))3197if self.is_save:3198self.save_fig('routeana_lowpriorityshare_nonoverlap')31993200def plot_exclusiveshare_nonoverlap(self):3201print 'plot_exclusiveshare_nonoverlap'3202fig = self.create_figure()3203results = self.parent3204routesresults_shortest = results.routesresults_shortest3205routesresults_matched = results.routesresults_matched3206routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap3207routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap3208edgesresults = results.edgesresults32093210ax = fig.add_subplot(111)3211ids_valid = routesresults_matched.select_ids(np.logical_and(3212routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))32133214dists_match = routesresults_matched_nonoverlap.distances[ids_valid]3215dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]32163217matched = routesresults_matched_nonoverlap.lengths_exclusive[ids_valid]/dists_match*1003218shortest = routesresults_shortest_nonoverlap.lengths_exclusive[ids_valid]/dists_shortest*10032193220x_min = min(np.min(matched), np.min(shortest))3221x_max = max(np.max(matched), np.max(shortest))3222bins = np.linspace(x_min, x_max, self.n_bins)3223bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +3224'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))3225bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +3226'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))32273228ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)3229ax.grid(self.is_grid)3230if self.is_title:3231ax.set_title('Share of exclusive access roads of non-overlapping matched and shortest route',3232fontsize=self.size_titlefont)3233ax.set_xlabel('Exclusive access road share n.o. [%]', fontsize=self.size_labelfont)3234ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)3235ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))3236ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))3237if self.is_save:3238self.save_fig('routeana_exclusiveshare_nonoverlap')32393240def plot_mixshare_nonoverlap(self):3241print 'plot_mixshare_nonoverlap'3242fig = self.create_figure()3243results = self.parent3244routesresults_shortest = results.routesresults_shortest3245routesresults_matched = results.routesresults_matched3246routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap3247routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap3248edgesresults = results.edgesresults32493250ax = fig.add_subplot(111)3251ids_valid = routesresults_matched.select_ids(np.logical_and(3252routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))32533254dists_match = routesresults_matched_nonoverlap.distances[ids_valid]3255dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]32563257matched = routesresults_matched_nonoverlap.lengths_mixed[ids_valid]/dists_match*1003258shortest = routesresults_shortest_nonoverlap.lengths_mixed[ids_valid]/dists_shortest*10032593260x_min = min(np.min(matched), np.min(shortest))3261x_max = max(np.max(matched), np.max(shortest))3262bins = np.linspace(x_min, x_max, self.n_bins)3263bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +3264'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))3265bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +3266'$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))32673268ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)3269ax.grid(self.is_grid)3270if self.is_title:3271ax.set_title('Share of mixed reserved access roads of non-overlapping matched and shortest route',3272fontsize=self.size_titlefont)3273ax.set_xlabel('Mixed reserved access road share n.o. [%]', fontsize=self.size_labelfont)3274ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)3275ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))3276ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))3277if self.is_save:3278self.save_fig('routeana_mixshare_nonoverlap')3279# -------------------------------------------------------------------------------32803281def do(self):3282# print 'do',self.edgeattrname3283self.show()32843285def get_scenario(self):3286return self.parent.get_scenario()328732883289class PtFlowdigramPlotter(PlotoptionsMixin, Process):3290def __init__(self, results, name='PT flowdiagram',3291info="Plots the flow diagram of PT lines using matplotlib",3292logger=None, **kwargs):32933294self._init_common('ptrouteresultplotter', parent=results, name=name,3295info=info, logger=logger)32963297print 'PtFlowdigramPlotter.__init__', results, self.parent3298attrsman = self.get_attrsman()32993300self.id_line = attrsman.add(cm.AttrConf('id_line', kwargs.get('id_line', -1),3301groupnames=['options'],3302name='Line ID',3303info='ID of public transport line to be plotted.',3304))33053306self.is_add_similar = attrsman.add(cm.AttrConf('is_add_similar', kwargs.get('is_add_similar', True),3307groupnames=['options'],3308name='include similar lines',3309info='Add also trips on similar PT lines.',3310))33113312self.is_title = attrsman.add(cm.AttrConf('is_title', kwargs.get('is_title', False),3313groupnames=['options'],3314name='Show title',3315info='Show title of diagrams.',3316))33173318self.size_titlefont = attrsman.add(cm.AttrConf('size_titlefont', kwargs.get('size_titlefont', 32),3319groupnames=['options'],3320name='Title fontsize',3321info='Title fontsize.',3322))33233324self.size_labelfont = attrsman.add(cm.AttrConf('size_labelfont', kwargs.get('size_labelfont', 24),3325groupnames=['options'],3326name='Label fontsize',3327info='Label fontsize.',3328))33293330self.width_line = attrsman.add(cm.AttrConf('width_line', kwargs.get('width_line', 2),3331groupnames=['options'],3332perm='wr',3333name='Line width',3334info='Width of plotted lines.',3335))33363337# self.color_outline = attrsman.add(cm.AttrConf( 'color_outline', kwargs.get('color_outline', np.array([0.0,0.0,0.0,0.95], dtype=np.float32)),3338# groupnames = ['options'],3339# perm='wr',3340# metatype = 'color',3341# name = 'Outline color',3342# info = 'Outline color of result arrows in graphical representation. Only valid if no color-fill is chosen.',3343# ))33443345self.color_fill = attrsman.add(cm.AttrConf('color_fill', kwargs.get('color_fill', np.array([0.3, 0.3, 1.0, 0.95], dtype=np.float32)),3346groupnames=['options'],3347perm='wr',3348metatype='color',3349name='Fill color',3350info='Fill color of result arrows in graphical representation.',3351))33523353self.is_grid = attrsman.add(cm.AttrConf('is_grid', kwargs.get('is_grid', False),3354groupnames=['options'],3355name='Show grid?',3356info='If True, shows a grid on the graphical representation.',3357))33583359self.csvfilepath = attrsman.add(cm.AttrConf('csvfilepath', kwargs.get('csvfilepath', ''),3360groupnames=['options'],3361perm='rw',3362name='CSV filename',3363wildcards='CSV file (*.csv)|*.csv|All file (*.*)|*.*',3364metatype='filepaths',3365info="""Filename to export flow results.""",3366))33673368self.add_save_options(**kwargs)33693370def show(self):3371print 'show'3372# if self.axis is None:3373self.init_figures()3374plt.rc('lines', linewidth=self.width_line)3375fig = self.create_figure()3376ax = fig.add_subplot(111)33773378results = self.parent33793380ptlinesresults = results.ptlinesresults33813382# link object3383mapmatching = results.parent3384#trips = mapmatching.trips3385#routes = trips.get_routes()33863387scenario = mapmatching.get_scenario()3388ptstops = scenario.net.ptstops3389demand = scenario.demand3390ptlines = demand.ptlines3391ptlinks = ptlines.get_ptlinks()33923393if not self.id_line in ptlines:3394print 'WARNING: line with ID', self.id_line, 'not found.'3395return False33963397#id_line = ptlines.linenames.get_id_from_index(self.linename)3398if self.is_add_similar:3399linename = ptlines.linenames[self.id_line].split('_')[0]3400else:3401linename = ptlines.linenames[self.id_line]3402ids_stoptuple_line, tripnumbers_line = ptlinesresults.get_flowdiagramm(3403self.id_line, is_add_similar=self.is_add_similar)34043405n_stops = len(ids_stoptuple_line)3406ax.bar(xrange(n_stops), tripnumbers_line,3407width=1.0, bottom=0, align='edge',3408color=self.color_fill,3409#linecolor = self.color_outline,3410linewidth=self.width_line,)34113412stopnames = []3413for id_fromstop, id_tostop in ids_stoptuple_line:3414stopnames.append(ptstops.stopnames_human[id_fromstop])3415# print ' stopnames',stopnames3416ax.set_xticks(xrange(n_stops))3417ax.set_xticklabels(stopnames)34183419#ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)3420ax.grid(self.is_grid)3421if self.is_title:3422ax.set_title('Flow diagram of PT line '+linename, fontsize=self.size_titlefont)3423ax.set_xlabel('Stops', fontsize=self.size_labelfont)3424ax.set_ylabel('Number of Passengers', fontsize=self.size_labelfont)3425ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))3426ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))3427plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="anchor")34283429if len(self.csvfilepath) > 0:3430# export to csv3431f = open(self.csvfilepath, 'w')3432f.write('Flow diagram of PT line '+linename+'\n\n')3433sep = ','3434f.write('Stopname from'+sep+'Stopname from'+sep+'Passengers\n')3435for ids_stoptuple, number in zip(ids_stoptuple_line, tripnumbers_line):3436f.write(ptstops.stopnames_human[ids_stoptuple[0]]+sep +3437ptstops.stopnames_human[ids_stoptuple[1]]+sep+str(number)+'\n')34383439f.close()34403441if self.is_save:3442self.save_fig('_ptrouteana_flowdiagram')3443else:3444show_plot()344534463447