1# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
2# Copyright (C) 2016-2019 German Aerospace Center (DLR) and others.
3# SUMOPy module
4# Copyright (C) 2012-2017 University of Bologna - DICAM
5# This program and the accompanying materials
6# are made available under the terms of the Eclipse Public License v2.0
7# which accompanies this distribution, and is available at
8# http://www.eclipse.org/legal/epl-v20.html
9# SPDX-License-Identifier: EPL-2.0
10
11# @file    results_mpl-02-iddesaster.py
12# @author  Joerg Schweizer
13# @date
14# @version $Id$
15
16import os
17import numpy as np
18from collections import OrderedDict
19#import  matplotlib as mpl
20from agilepy.lib_base.geometry import *
21from agilepy.lib_base.misc import get_inversemap
22from coremodules.misc.matplottools import *
23import agilepy.lib_base.classman as cm
24import agilepy.lib_base.arrayman as am
25from agilepy.lib_base.geometry import *
26from agilepy.lib_base.processes import Process
27
28try:
29    from scipy import interpolate
30    is_scipy = True
31except:
32    is_scipy = False
33
34
35def is_sublist(l, s):
36    sub_set = False
37    if s == []:
38        sub_set = True
39    elif s == l:
40        sub_set = True
41    elif len(s) > len(l):
42        sub_set = False
43
44    else:
45        for i in range(len(l)):
46            if l[i] == s[0]:
47                n = 1
48                while (n < len(s)) and (l[i+n] == s[n]):
49                    n += 1
50
51                if n == len(s):
52                    sub_set = True
53
54    return sub_set
55
56
57from numpy.linalg import inv
58
59
60def kf_update(X, P, Y, H, R):
61    IM = dot(H, X)
62    IS = R + dot(H, dot(P, H.T))
63    K = dot(P, dot(H.T, inv(IS)))
64    X = X + dot(K, (Y-IM))
65    P = P - dot(K, dot(IS, K.T))
66    LH = gauss_pdf(Y, IM, IS)
67    return (X, P, K, IM, IS, LH)
68
69
70def gauss_pdf(X, M, S):
71    if M.shape()[1] == 1:
72        DX = X - tile(M, X.shape()[1])
73        E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0)
74        E = E + 0.5 * M.shape()[0] * log(2 * pi) + 0.5 * log(det(S))
75        P = exp(-E)
76    elif X.shape()[1] == 1:
77        DX = tile(X, M.shape()[1]) - M
78        E = 0.5 * sum(DX * (dot(inv(S), DX)), axis=0)
79        E = E + 0.5 * M.shape()[0] * log(2 * pi) + 0.5 * log(det(S))
80        P = exp(-E)
81    else:
82        DX = X-M
83        E = 0.5 * dot(DX.T, dot(inv(S), DX))
84        E = E + 0.5 * M.shape()[0] * log(2 * pi) + 0.5 * log(det(S))
85        P = exp(-E)
86    return (P[0], E[0])
87
88
89class NoderesultPlotter(PlotoptionsMixin, Process):
90    def __init__(self, results, name='Node results plotter',
91                 info="Plots nodes related results of GPS trips using matplotlib",
92                 logger=None, **kwargs):
93
94        self._init_common('noderesultplotter', parent=results, name=name,
95                          info=info, logger=logger)
96
97        # print 'Resultplotter.__init__',results,self.parent
98        attrsman = self.get_attrsman()
99
100        self.is_grid = attrsman.add(cm.AttrConf('is_grid', kwargs.get('is_grid', True),
101                                                groupnames=['options'],
102                                                name='Show grid?',
103                                                info='If True, shows a grid on the graphical representation.',
104                                                ))
105
106        self.titletext = attrsman.add(cm.AttrConf('titletext', kwargs.get('titletext', ''),
107                                                  groupnames=['options'],
108                                                  name='Title text',
109                                                  info='Title text. Empty text means no title.',
110                                                  ))
111
112        self.size_titlefont = attrsman.add(cm.AttrConf('size_titlefont', kwargs.get('size_titlefont', 32),
113                                                       groupnames=['options'],
114                                                       name='Title fontsize',
115                                                       info='Title fontsize.',
116                                                       ))
117
118        self.size_labelfont = attrsman.add(cm.AttrConf('size_labelfont', kwargs.get('size_labelfont', 24),
119                                                       groupnames=['options'],
120                                                       name='Label fontsize',
121                                                       info='Label fontsize.',
122                                                       ))
123
124        self.width_line = attrsman.add(cm.AttrConf('width_line', kwargs.get('width_line', 1.0),
125                                                   groupnames=['options'],
126                                                   name='Line width',
127                                                   info='Line width of plot.',
128                                                   ))
129        self.add_save_options()
130
131    def show(self):
132        print 'show noderesults', len(self.parent.nodesresults)
133        # if self.axis  is None:
134
135        nodesresults = self.parent.nodesresults
136
137        if len(nodesresults) == 0:
138            return False
139
140        mapmatching = self.parent.parent
141        trips = mapmatching.trips
142        #points = mapmatching.points
143        routes = trips.get_routes()
144        scenario = mapmatching.get_scenario()
145        edges = scenario.net.edges
146        nodes = scenario.net.nodes
147
148        ids_noderes = nodesresults.get_ids()
149        nodetypes = nodes.types[nodesresults.ids_node[ids_noderes]]
150        times_wait = nodesresults.times_wait[ids_noderes]
151        nodetypeset = set(nodetypes)
152
153        map_type_to_typename = get_inversemap(nodes.types.choices)
154        map_typename_to_times_wait = {}
155        for thistype in nodetypeset:
156            map_typename_to_times_wait[map_type_to_typename[thistype]] = np.mean(times_wait[nodetypes == thistype])
157
158        self.init_figures()
159        fig = self.create_figure()
160        ax = fig.add_subplot(111)
161
162        #colors = np.array(COLORS,dtype = np.object)
163        inds_plot = np.arange(len(map_typename_to_times_wait), dtype=np.int32)
164        bar_width = 0.45
165        opacity = 0.5
166        #error_config = {'ecolor': '0.3'}
167
168        rects = ax.barh(inds_plot,
169                        map_typename_to_times_wait.values(),
170                        # align='center',
171                        alpha=opacity,
172                        height=bar_width, color=get_colors(inds_plot),
173                        #yerr=std_women, error_kw=error_config,
174                        linewidth=self.width_line,
175                        # facecolor=colors[inds][inds_nz],
176                        )
177
178        ax.set_yticks(inds_plot + bar_width / 2)
179        ax.set_yticklabels(map_typename_to_times_wait.keys())
180        ax.legend()
181
182        #ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)
183        ax.grid(self.is_grid)
184        if self.titletext != '':
185            ax.set_title(self.titletext, fontsize=self.size_titlefont)
186        ax.set_xlabel('Average wait times [s]', fontsize=self.size_labelfont)
187        ax.set_ylabel('Intersection type', fontsize=self.size_labelfont)
188        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
189        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
190        # fig.tight_layout()
191        if self.is_save:
192            self.save_fig('virtualpop_strategy_share_current')
193
194        plt.show()
195        # show_plot()
196
197    def get_scenario(self):
198        return self.parent.get_scenario()
199
200
201class SpeedprofilePlotter(PlotoptionsMixin, Process):
202    def __init__(self, results, name='Speedprofile plotter with Matplotlib',
203                 info="Plots the speed profile of a selected GPS trip using matplotlib",
204                 logger=None, **kwargs):
205
206        self._init_common('speedprofileplotter', parent=results, name=name,
207                          info=info, logger=logger)
208
209        # print 'Resultplotter.__init__',results,self.parent
210        attrsman = self.get_attrsman()
211
212        self.id_trip = attrsman.add(cm.AttrConf('id_trip', kwargs.get('id_trip', -1),
213                                                groupnames=['options'],
214                                                name='Trip ID',
215                                                info='ID of GPS trip to be plotted.',
216                                                ))
217
218        self.is_plot_similar_trips = attrsman.add(cm.AttrConf('is_plot_similar_trips', kwargs.get('is_plot_similar_trips', True),
219                                                              groupnames=['options'],
220                                                              name='Plot similar trips',
221                                                              info='If True, plot all trips which contain the same route as the given trip.',
222                                                              ))
223
224        self.method_interp = attrsman.add(cm.AttrConf('method_interp', kwargs.get('method_interp', 'slinear'),
225                                                      groupnames=['options'],
226                                                      choices=['linear', 'nearest', 'zero',
227                                                               'slinear', 'quadratic', 'cubic'],
228                                                      name='Interpolation method',
229                                                      info='GPS point interpolation method.',
230                                                      ))
231
232        self.color_point = attrsman.add(cm.AttrConf('color_point', kwargs.get('color_point', np.array([0.0, 0.4, 0.6, 0.6], np.float32)),
233                                                    groupnames=['options'],
234                                                    perm='wr',
235                                                    metatype='color',
236                                                    name='Point color',
237                                                    info='Color of GPS-points.',
238                                                    ))
239
240        self.size_point = attrsman.add(cm.AttrConf('size_point', kwargs.get('size_point', 10.0),
241                                                   groupnames=['options'],
242                                                   name='Point size',
243                                                   info='Point size of GPS points.',
244                                                   ))
245
246        self.color_line = attrsman.add(cm.AttrConf('color_line', kwargs.get('color_line', np.array([1.0, 0.4, 0.0, 0.6], np.float32)),
247                                                   groupnames=['options'],
248                                                   perm='wr',
249                                                   metatype='color',
250                                                   name='Line color',
251                                                   info='Color of plotted line in diagram.',
252                                                   ))
253
254        self.width_line = attrsman.add(cm.AttrConf('width_line', kwargs.get('width_line', 3.0),
255                                                   groupnames=['options'],
256                                                   name='Line width',
257                                                   info='Line width of plot.',
258                                                   ))
259
260        self.alpha_line = attrsman.add(cm.AttrConf('alpha_line', kwargs.get('alpha_line', 0.3),
261                                                   groupnames=['options'],
262                                                   name='Line transp.',
263                                                   info='Line transparency of plot.',
264                                                   ))
265
266        self.is_grid = attrsman.add(cm.AttrConf('is_grid', kwargs.get('is_grid', True),
267                                                groupnames=['options'],
268                                                name='Show grid?',
269                                                info='If True, shows a grid on the graphical representation.',
270                                                ))
271
272        self.titletext = attrsman.add(cm.AttrConf('titletext', kwargs.get('titletext', ''),
273                                                  groupnames=['options'],
274                                                  name='Title text',
275                                                  info='Title text. Empty text means no title.',
276                                                  ))
277
278        self.size_titlefont = attrsman.add(cm.AttrConf('size_titlefont', kwargs.get('size_titlefont', 32),
279                                                       groupnames=['options'],
280                                                       name='Title fontsize',
281                                                       info='Title fontsize.',
282                                                       ))
283
284        self.size_labelfont = attrsman.add(cm.AttrConf('size_labelfont', kwargs.get('size_labelfont', 24),
285                                                       groupnames=['options'],
286                                                       name='Label fontsize',
287                                                       info='Label fontsize.',
288                                                       ))
289        self.add_save_options()
290
291    def plot_speed_over_time(self, ax, id_trip, id_route, edges, i_min=None, i_max=None):
292        print 'plot_speed_over_time', id_trip, type(id_trip), self.parent.parent
293
294        #mapmatching = self.parent.parent
295        #trips = mapmatching.trips
296
297        routeresults = self.get_routeresults()
298
299        #id_route = trips.ids_route_matched[id_trip]
300        id_routeres = routeresults.ids_route.get_id_from_index(id_route)
301
302        # tripresults.pointsposition[id_routeres],\
303        # tripresults.pointsspeed[id_routeres],
304        # tripresults.pointstime[id_routeres],
305        # ids_pointedges,
306
307        if i_min is None:
308            #ids_pointedge = routeresults.ids_pointedges[id_routeres]
309            #pointspositions = routeresults.pointspositions[id_routeres]
310            speeds = routeresults.pointsspeeds[id_routeres]
311            times = routeresults.pointstimes[id_routeres]
312        else:
313            #ids_pointedge = routeresults.ids_pointedges[id_routeres][i_min:i_max]
314            #pointspositions = routeresults.pointspositions[id_routeres][i_min:i_max]
315            speeds = routeresults.pointsspeeds[id_routeres][i_min:i_max]
316            times = routeresults.pointstimes[id_routeres][i_min:i_max]
317        # print '  id_route,id_routeres',id_route,id_routeres
318        # print '  ids_pointedge',ids_pointedge
319        n_point = len(times)
320
321        x = np.array(times, dtype=np.float32)
322        y = np.array(speeds, dtype=np.float32)*3.6  # in km/h
323        #ax = init_plot()
324        print '  x', x
325        print '  y', y
326        #ax.plot(locations, speeds, color = self.color_line[:2], lw = self.width_line ,alpha=0.9 ,zorder = 0)
327
328        if is_scipy:
329            #tck = interpolate.splrep(x, y, s=0)
330            #xnew = np.linspace(np.min(x), np.max(x), 200)
331            #ynew = interpolate.splev(xnew, tck, der=0)
332            # if 1:
333            f_inter = interpolate.interp1d(x, y, kind=self.method_interp)
334            xnew = np.linspace(np.min(x), np.max(x), 200)
335            ynew = f_inter(xnew)
336
337            ax.plot(xnew, ynew, color=self.color_line, lw=self.width_line, alpha=self.alpha_line)
338            ax.plot(x, y, 'o', markersize=self.size_point, color=self.color_point, alpha=self.alpha_line)
339        else:
340            ax.plot(x, y, 'o-', markersize=self.size_point, color=self.color_line,
341                    lw=self.width_line, markerfacecolor=self.color_point, alpha=self.alpha_line)
342
343    def plot_speed_over_way(self, ax, id_trip, id_route, edges, i_min=None, i_max=None):
344        print 'plot_speed_over_way', id_trip, type(id_trip), self.parent.parent
345
346        #mapmatching = self.parent.parent
347        #trips = mapmatching.trips
348
349        routeresults = self.get_routeresults()
350
351        #id_route = trips.ids_route_matched[id_trip]
352        id_routeres = routeresults.ids_route.get_id_from_index(id_route)
353
354        # tripresults.pointsposition[id_routeres],\
355        # tripresults.pointsspeed[id_routeres],
356        # tripresults.pointstime[id_routeres],
357        # ids_pointedges,
358
359        if i_min is None:
360            ids_pointedge = routeresults.ids_pointedges[id_routeres]
361            pointspositions = routeresults.pointspositions[id_routeres]
362            speeds = routeresults.pointsspeeds[id_routeres]
363            times = routeresults.pointstimes[id_routeres]
364        else:
365            ids_pointedge = routeresults.ids_pointedges[id_routeres][i_min:i_max]
366            pointspositions = routeresults.pointspositions[id_routeres][i_min:i_max]
367            speeds = routeresults.pointsspeeds[id_routeres][i_min:i_max]
368            times = routeresults.pointstimes[id_routeres][i_min:i_max]
369        # print '  id_route,id_routeres',id_route,id_routeres
370        # print '  ids_pointedge',ids_pointedge
371        n_point = len(ids_pointedge)
372        offsets = np.zeros(n_point, dtype=np.float32)
373        offset = 0
374        id_edge_last = ids_pointedge[0]
375        for i, id_edge in zip(np.arange(n_point), ids_pointedge):
376            if id_edge != id_edge_last:
377                offset += edges.lengths[ids_pointedge[i-1]]
378                id_edge_last = id_edge
379            offsets[i] = offset
380
381        x = offsets+pointspositions
382        y = np.array(speeds, dtype=np.float32)*3.6  # in km/h
383        #ax = init_plot()
384        print '  offsets', offsets
385        print '  position', pointspositions
386        print '  x', x
387        print '  y', y
388        #ax.plot(locations, speeds, color = self.color_line[:2], lw = self.width_line ,alpha=0.9 ,zorder = 0)
389
390        if is_scipy:
391            #tck = interpolate.splrep(x, y, s=0)
392            #xnew = np.linspace(np.min(x), np.max(x), 200)
393            #ynew = interpolate.splev(xnew, tck, der=0)
394            # if 1:
395            f_inter = interpolate.interp1d(x, y, kind=self.method_interp)
396            xnew = np.linspace(x.min(), x.max(), 200)
397            ynew = f_inter(xnew)
398
399            ax.plot(xnew, ynew, color=self.color_line, lw=self.width_line, alpha=self.alpha_line)
400            ax.plot(x, y, 'o', markersize=self.size_point, color=self.color_point, alpha=self.alpha_line)
401        else:
402            ax.plot(x, y, 'o-', markersize=self.size_point, color=self.color_line,
403                    lw=self.width_line, markerfacecolor=self.color_point, alpha=self.alpha_line)
404
405    def show(self):
406        print 'show', self.id_trip, type(self.id_trip), self.parent.parent
407        # if self.axis  is None:
408
409        if self.id_trip >= 0:
410            id_trip = self.id_trip
411            mapmatching = self.parent.parent
412            trips = mapmatching.trips
413            #points = mapmatching.points
414            routes = trips.get_routes()
415            scenario = mapmatching.get_scenario()
416            edges = scenario.net.edges
417            nodes = scenario.net.nodes
418
419            routeresults = self.get_routeresults()
420            id_route = trips.ids_route_matched[id_trip]
421            route = routes.ids_edges[id_route]
422            id_routeres = routeresults.ids_route.get_id_from_index(id_route)
423
424            # tripresults.pointsposition[id_routeres],\
425            # tripresults.pointsspeed[id_routeres],
426            # tripresults.pointstime[id_routeres],
427            # ids_pointedges,
428            self.init_figures()
429            fig = self.create_figure()
430            ax = fig.add_subplot(111)
431
432            fig2 = self.create_figure()
433            ax2 = fig2.add_subplot(111)
434
435            self.plot_speed_over_way(ax, id_trip, id_route, edges)
436            self.plot_speed_over_time(ax2, id_trip, id_route, edges)
437
438            # get_color()
439            # is_sublist
440            #id_route = trips.ids_route_matched[id_trip]
441            #route = routes.ids_edge[id_route]
442            ids_pointedge = routeresults.ids_pointedges[id_routeres]
443            if self.is_plot_similar_trips:
444                #id_routeres = routeresults.ids_route.get_ids_from_indices(ids_route)
445
446                id_pointedge_first = ids_pointedge[0]
447                id_pointedge_last = ids_pointedge[-1]
448
449                ids_routeres_speed = routeresults.get_ids()
450                ids_route_speed = routeresults.ids_route[ids_routeres_speed]
451                # print '  route',route
452                for id_trip_speed, id_route_speed, route_speed, ids_pointedge_speed in zip(
453                        routes.ids_trip[ids_route_speed],
454                        ids_route_speed, routes.ids_edges[ids_route_speed],
455                        routeresults.ids_pointedges[ids_routeres_speed]):
456                    # print '    ids_pointedge_speed',ids_pointedge_speed
457                    # print '    route[0],is_inlist',route[0],ids_pointedge_speed.count(route[0]),type(ids_pointedge_speed)
458                    # print '    route_speed',route_speed
459
460                    # is_sublist(route,route_speed):# |  is_sublist(route_speed,route):
461                    if is_sublist(route_speed, route):
462                        i = ids_pointedge_speed.index(id_pointedge_first)
463                        j = ids_pointedge_speed.index(id_pointedge_last)
464                        n_pointedge = len(ids_pointedge_speed)
465                        while (ids_pointedge_speed[j] == id_pointedge_last) & (j < n_pointedge-1):
466                            j += 1
467                        self.plot_speed_over_way(ax, id_trip_speed, id_route_speed, edges, i, j)
468                        self.plot_speed_over_time(ax2, id_trip_speed, id_route_speed, edges, i, j)
469
470            # plot edge info
471            colors = [(0.2, 0.2, 0.2, 0.7), (0.8, 0.8, 0.8, 0.7)]
472            ymin, ymax = ax.get_ylim()
473            x = 0
474            i = 0
475            id_edge = -1
476            i_point = 0
477            pointstime = routeresults.pointstimes[id_routeres]
478            print '  len(ids_pointedge)', len(ids_pointedge)
479            print '  len(pointstime)', len(pointstime), pointstime
480
481            # if len(pointstime)>1:
482            #    t_last = pointstime[1]
483            # else:
484            #t_last_edge = pointstime[0]
485            #t_last = pointstime[0]
486            print '  ids_pointedge\n', ids_pointedge
487            print '  pointstime\n', pointstime
488            for id_pointedge,  t in zip(
489                    ids_pointedge,
490                    pointstime):
491
492                if id_pointedge != id_edge:
493                    # edges have changed
494                    if id_edge != -1:
495                        x = + edges.lengths[id_edge]  # add length of old id_edge
496                    #ax.plot([x,x+length],[ymin,ymin],color = colors[i%2],lw = 3*self.width_line)
497                    ax.plot([x, x], [ymin, ymax], 'k--')
498                    ax.text(x, ymin, '  Edge:'+str(id_pointedge),
499                            verticalalignment='bottom',
500                            horizontalalignment='left',
501                            rotation='vertical',
502                            fontsize=int(0.8*self.size_labelfont))  # baseline
503
504                    t_last = t
505                    ax2.plot([t_last, t_last], [ymin, ymax], 'k--')
506                    ax2.text(t_last, ymin, '  Edge:'+str(id_pointedge),
507                             verticalalignment='bottom',
508                             horizontalalignment='left',
509                             rotation='vertical',
510                             fontsize=int(0.8*self.size_labelfont))  # baseline
511
512                    i += 1
513
514                    #t_last_edge = t
515
516                    id_edge = id_pointedge
517
518                i_point += 1
519
520            #ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)
521            ax2.grid(self.is_grid)
522            if self.titletext != '':
523                ax2.set_title(self.titletext, fontsize=self.size_titlefont)
524
525            ax2.set_xlabel('Time [s]', fontsize=self.size_labelfont)
526            ax2.set_ylabel('Speed [km/h]', fontsize=self.size_labelfont)
527            ax2.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
528            ax2.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
529
530            #ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)
531            ax.grid(self.is_grid)
532            if self.titletext != '':
533                ax.set_title(self.titletext, fontsize=self.size_titlefont)
534
535            ax.set_xlabel('Location [m]', fontsize=self.size_labelfont)
536            ax.set_ylabel('Speed [km/h]', fontsize=self.size_labelfont)
537            ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
538            ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
539
540            # if self.is_save:
541            #    self.save_fig('routeana_speedprofile')
542
543            plt.show()
544            # show_plot()
545
546    def get_routeresults(self):
547        return self.parent.routesresults_matched
548
549    def get_scenario(self):
550        return self.parent.get_scenario()
551
552
553class EdgeresultPlotter(PlotoptionsMixin, Process):
554    def __init__(self, results, name='Plot edge results with Matplotlib',
555                 info="Creates plots of different edge results using matplotlib",
556                 logger=None, **kwargs):
557
558        self._init_common('routeresultplotter', parent=results, name=name,
559                          info=info, logger=logger)
560
561        # print 'Resultplotter.__init__',results,self.parent
562        attrsman = self.get_attrsman()
563
564        self.plotthemefuncs = {'average_speeds': self.plot_speeds_average,
565                               'inmove_speeds': self.plot_speeds_inmotion,
566                               'times_wait': self.plot_times_wait,
567                               'times_wait_tls': self.plot_times_wait_tls,
568                               'number_matched_routes': self.plot_numbers_tot_matched,
569                               'number_shortest': self.plot_numbers_tot_shortest,
570                               'total_deviation': self.plot_differences_dist_tot_shortest,
571                               'relative_deviation': self.plot_differences_dist_rel_shortest,
572                               'probabilities_matched_routes': self.plot_probabilities_tot_matched,
573                               'flows_est_matched_routes': self.plot_flows_est_matched_routes,
574                               }
575        self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'average_speeds'),
576                                                  groupnames=['options'],
577                                                  choices=self.plotthemefuncs.keys(),
578                                                  name='Plot theme',
579                                                  info='Theme  or edge attribute to be plottet.',
580                                                  ))
581
582        self.add_plotoptions(**kwargs)
583        self.add_save_options(**kwargs)
584
585    def plot_all_themes(self):
586        for plottheme in self.plotthemefuncs.keys():
587            self.plottheme = plottheme
588            self.show()
589
590    def show(self):
591        print 'EdgeresultPlotter.show', self.plottheme
592        # if self.axis  is None:
593        #axis = init_plot()
594        self.init_figures()
595        fig = self.create_figure()
596        axis = fig.add_subplot(111)
597        self.plotthemefuncs[self.plottheme](axis)
598
599        print '  self.is_save', self.is_save
600        if not self.is_save:
601            print '  show_plot'
602            show_plot()
603        else:
604            figname = 'edgeplot_'+self.plottheme
605            # print '  savefig',figname
606
607            # self.save_fig('edgeplot_'+self.plottheme)
608
609            rootfilepath = self.get_scenario().get_rootfilepath()
610
611            fig.savefig("%s_%s.%s" % (rootfilepath, figname, self.figformat),
612                        format=self.figformat,
613                        dpi=self.resolution,
614                        # orientation='landscape',
615                        orientation='portrait',
616                        transparent=True)
617            plt.close(fig)
618
619    def get_edgeresults(self):
620        return self.parent.edgesresults  # must have attribute 'ids_edge'
621
622    def plot_differences_dist_rel_shortest(self, ax):
623        edgesresults = self.get_edgeresults()
624        ids_result = edgesresults.select_ids(edgesresults.numbers_tot_shortest.get_value() > 0)
625        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
626
627        self.plot_results_on_map(ax, ids_result,
628                                 edgesresults.differences_dist_tot_shortest[ids_result] /
629                                 edgesresults.numbers_tot_shortest[ids_result],
630                                 title='Deviation generated per user',
631                                 valuelabel='Generated deviation per trip [m]',
632                                 )
633
634    def plot_differences_dist_tot_shortest(self, ax):
635        edgesresults = self.get_edgeresults()
636        ids_result = edgesresults.get_ids()
637        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
638        deviation_tot = edgesresults.differences_dist_tot_shortest
639        self.plot_results_on_map(ax, ids_result,
640                                 deviation_tot[ids_result]/1000,
641                                 title='Total deviation generated per edge',
642                                 valuelabel='Generated total deviation [km]',
643                                 )
644
645    def plot_numbers_tot_shortest(self, ax):
646        edgesresults = self.get_edgeresults()
647        ids_result = edgesresults.get_ids()
648        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
649        numbers_tot_shortest = edgesresults.numbers_tot_shortest
650        self.plot_results_on_map(ax, ids_result,
651                                 numbers_tot_shortest[ids_result],
652                                 title='Edge usage from shortest routes',
653                                 valuelabel='Usage in number of persons',
654                                 )
655
656    def plot_numbers_tot_matched(self, ax):
657        edgesresults = self.get_edgeresults()
658        ids_result = edgesresults.get_ids()
659        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
660        numbers_tot_matched = edgesresults.numbers_tot_matched
661        self.plot_results_on_map(ax, ids_result,
662                                 numbers_tot_matched[ids_result],
663                                 title='Edge usage from matched routes',
664                                 valuelabel='Usage in number of persons',
665                                 )
666
667    def plot_speeds_average(self, ax):
668        edgesresults = self.parent.edgesresults
669
670        print 'plot_speeds_average'
671
672        #ids_result = edgesresults.get_ids()
673        ids_result = edgesresults.select_ids(edgesresults.numbers_tot_matched.get_value() > 0)
674
675        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
676        speeds_average = self.parent.edgesresults.speeds_average
677        print '  speeds_average', speeds_average[ids_result]
678        print '  ids_result', ids_result
679
680        self.plot_results_on_map(ax, ids_result,
681                                 speeds_average[ids_result]*3.6,
682                                 title='Average edge speeds',
683                                 valuelabel='Average edge speeds [km/h]',
684                                 )
685
686    def plot_speeds_inmotion(self, ax):
687        edgesresults = self.parent.edgesresults
688        #ids_result = edgesresults.get_ids()
689        ids_result = edgesresults.select_ids(edgesresults.numbers_tot_matched.get_value() > 0)
690
691        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
692        speeds = self.parent.edgesresults.speeds_inmotion
693
694        print '  speeds_average', speeds[ids_result]
695        print '  ids_result', ids_result
696
697        self.plot_results_on_map(ax, ids_result,
698                                 speeds[ids_result]*3.6,
699                                 title='Average edge speeds in motion',
700                                 valuelabel='Average edge speeds in motion [km/h]',
701                                 )
702
703    def plot_times_wait(self, ax):
704        edgesresults = self.parent.edgesresults
705        #ids_result = edgesresults.get_ids()
706        ids_result = edgesresults.select_ids(edgesresults.numbers_tot_matched.get_value() > 0)
707
708        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
709        times = edgesresults.times_wait
710        self.plot_results_on_map(ax, ids_result,
711                                 times[ids_result],
712                                 title='Average wait times',
713                                 valuelabel='Average wait times [s]',
714                                 )
715
716    def plot_times_wait_tls(self, ax):
717        #ids_result = self.parent.edgesresults.get_ids()
718        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
719        edgesresults = self.parent.edgesresults
720        ids_result = edgesresults.select_ids(edgesresults.numbers_tot_matched.get_value() > 0)
721        times = edgesresults.times_wait_tls
722        self.plot_results_on_map(ax, ids_result,
723                                 times[ids_result],
724                                 title='Average wait times at Traffic Lights',
725                                 valuelabel='Average wait times at TLS [s]',
726                                 )
727
728    def plot_probabilities_tot_matched(self, ax):
729        ids_result = self.parent.edgesresults.get_ids()
730        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
731        self.plot_results_on_map(ax, ids_result,
732                                 self.parent.edgesresults.probabilities_tot_matched[ids_result],
733                                 title='Probabilities',
734                                 valuelabel=r'Enter probabilities [\%]',
735                                 )
736
737    def plot_flows_est_matched_routes(self, ax):
738        ids_result = self.parent.edgesresults.get_ids()
739        #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
740        self.plot_results_on_map(ax, ids_result,
741                                 self.parent.edgesresults.flows_est[ids_result],
742                                 title='Flows',
743                                 valuelabel=r'Estimated flows [1/h]',
744                                 )
745
746    def do(self):
747        # print 'do',self.edgeattrname
748        self.show()
749        return True
750
751
752class RouteresultPlotter(PlotoptionsMixin, Process):
753    def __init__(self, results, name='Plot route results with Matplotlib',
754                 info="Creates plots of different route results using matplotlib",
755                 logger=None, **kwargs):
756
757        self._init_common('routeresultplotter', parent=results, name=name,
758                          info=info, logger=logger)
759
760        print 'Resultplotter.__init__', results, self.parent
761        attrsman = self.get_attrsman()
762
763        # comprison matched shortest
764        self.is_plot_lengthdistrib = attrsman.add(cm.AttrConf('is_plot_lengthdistrib', kwargs.get('is_plot_lengthdistrib', True),
765                                                              groupnames=['options'],
766                                                              name='Plot length distribution',
767                                                              info='Plot cumulative distribution on length of matched route and shortest route.',
768                                                              ))
769
770        self.is_plot_lengthprob = attrsman.add(cm.AttrConf('is_plot_lengthprob', kwargs.get('is_plot_lengthprob', True),
771                                                           groupnames=['options'],
772                                                           name='Plot length probabilities',
773                                                           info='Plot probabilities length of matched route and shortest route.',
774                                                           ))
775
776        self.is_plot_lengthdistrib_by_class = attrsman.add(cm.AttrConf('is_plot_lengthdistrib_by_class', kwargs.get('is_plot_lengthdistrib_by_class', True),
777                                                                       groupnames=['options'],
778                                                                       name='Plot class length distribution',
779                                                                       info='Plot mean values of length of matched route and shortest route for different trip length classes.',
780                                                                       ))
781
782        self.distance_class = attrsman.add(cm.AttrConf('distance_class', kwargs.get('distance_class', 2000),
783                                                       groupnames=['options'],
784                                                       name='Class distance',
785                                                       info='Distance to generate trip length classes.',
786                                                       ))
787
788        self.is_plot_lengthratio = attrsman.add(cm.AttrConf('is_plot_lengthratio', kwargs.get('is_plot_lengthratio', True),
789                                                            groupnames=['options'],
790                                                            name='Plot length ratio',
791                                                            info='Plot  cumulative distribution  on length ratio between shortest route and matched route.',
792                                                            ))
793
794        self.is_plot_lengthoverlap = attrsman.add(cm.AttrConf('is_plot_lengthoverlap', kwargs.get('is_plot_lengthoverlap', True),
795                                                              groupnames=['options'],
796                                                              name='Plot length overlap',
797                                                              info='Plot  cumulative distribution  on overlap between shortest route and matched route.',
798                                                              ))
799
800        self.is_plot_mixshare = attrsman.add(cm.AttrConf('is_plot_mixshare', kwargs.get('is_plot_mixshare', True),
801                                                         groupnames=['options'],
802                                                         name='Plot mixed share',
803                                                         info='Plot  cumulative distribution of share of mixed access roads of shortest route and matched route.',
804                                                         ))
805
806        self.is_plot_exclusiveshare = attrsman.add(cm.AttrConf('is_plot_exclusiveshare', kwargs.get('is_plot_exclusiveshare', True),
807                                                               groupnames=['options'],
808                                                               name='Plot exclusive share',
809                                                               info='Plot  cumulative distribution of share of exclusive access roads of shortest route and matched route.',
810                                                               ))
811
812        self.is_plot_lowpriorityshare = attrsman.add(cm.AttrConf('is_plot_lowpriorityshare', kwargs.get('is_plot_lowpriorityshare', True),
813                                                                 groupnames=['options'],
814                                                                 name='Plot low priority share',
815                                                                 info='Plot  cumulative distribution of share of elow priority roads of shortest route and matched route.',
816                                                                 ))
817
818        self.is_plot_nodesdensity = attrsman.add(cm.AttrConf('is_plot_nodesdensity', kwargs.get('is_plot_nodesdensity', True),
819                                                             groupnames=['options'],
820                                                             name='Plot node ratio',
821                                                             info='Plot  cumulative distribution of node ratio between shortest route and matched route.',
822                                                             ))
823
824        self.is_plot_tldensity = attrsman.add(cm.AttrConf('is_plot_tldensity', kwargs.get('is_plot_tldensity', True),
825                                                          groupnames=['options'],
826                                                          name='Plot TL ratio',
827                                                          info='Plot  cumulative distribution of traffic light ratio between shortest route and matched route.',
828                                                          ))
829        self.is_prioritychangedensity = attrsman.add(cm.AttrConf('is_prioritychangedensity', kwargs.get('is_prioritychangedensity', True),
830                                                                 groupnames=['options'],
831                                                                 name='Plot prio. change dens.',
832                                                                 info='Plot  cumulative distribution of priority change denities between shortest route and matched route.',
833                                                                 ))
834
835        # comprison  non-overlapping matched and shortest
836        self.is_plot_lengthratio_nonoverlap = attrsman.add(cm.AttrConf('is_plot_lengthratio_nonoverlap', kwargs.get('is_plot_lengthratio_nonoverlap', True),
837                                                                       groupnames=['options'],
838                                                                       name='Plot length ratio non-overlap',
839                                                                       info='Plot cumulative distribution  on length ratio between non-overlapping parts of  shortest route and matched route.',
840                                                                       ))
841
842        self.is_plot_mixshare_nonoverlap = attrsman.add(cm.AttrConf('is_plot_mixshare_nonoverlap', kwargs.get('is_plot_mixshare_nonoverlap', True),
843                                                                    groupnames=['options'],
844                                                                    name='Plot mixed share non-overlap',
845                                                                    info='Plot  cumulative distribution of share of mixed access roads of non-overlapping parts of shortest route and matched route.',
846                                                                    ))
847
848        self.is_plot_exclusiveshare_nonoverlap = attrsman.add(cm.AttrConf('is_plot_exclusiveshare_nonoverlap', kwargs.get('is_plot_exclusiveshare_nonoverlap', True),
849                                                                          groupnames=['options'],
850                                                                          name='Plot exclusive share non-overlap',
851                                                                          info='Plot  cumulative distribution of share of exclusive access roads of non-overlapping parts of shortest route and matched route.',
852                                                                          ))
853
854        self.is_plot_lowpriorityshare_nonoverlap = attrsman.add(cm.AttrConf('is_plot_lowpriorityshare_nonoverlap', kwargs.get('is_plot_lowpriorityshare_nonoverlap', True),
855                                                                            groupnames=['options'],
856                                                                            name='Plot low priority share non-overlap',
857                                                                            info='Plot  cumulative distribution of share of low priority roads of non-overlapping parts of shortest route and matched route.',
858                                                                            ))
859
860        self.is_plot_nodesdensity_nonoverlap = attrsman.add(cm.AttrConf('is_plot_nodesdensity_nonoverlap', kwargs.get('is_plot_nodesdensity_nonoverlap', True),
861                                                                        groupnames=['options'],
862                                                                        name='Plot node ratio non-overlap',
863                                                                        info='Plot  cumulative distribution of node ratio between non-overlapping parts of shortest route and matched route.',
864                                                                        ))
865
866        self.is_plot_tldensity_nonoverlap = attrsman.add(cm.AttrConf('is_plot_tldensity_nonoverlap', kwargs.get('is_plot_tldensity_nonoverlap', True),
867                                                                     groupnames=['options'],
868                                                                     name='Plot TL ratio non-overlap',
869                                                                     info='Plot  cumulative distribution of traffic light ratio between non-overlapping parts of shortest route and matched route.',
870                                                                     ))
871
872        self.is_prioritychangedensity_nonoverlap = attrsman.add(cm.AttrConf('is_prioritychangedensity_nonoverlap', kwargs.get('is_prioritychangedensity_nonoverlap', True),
873                                                                            groupnames=['options'],
874                                                                            name='Plot prio. change dens. non-overlap',
875                                                                            info='Plot  cumulative distribution of priority change denities between non-overlapping parts of shortest route and matched route.',
876                                                                            ))
877
878        # other
879        self.n_bins = attrsman.add(cm.AttrConf('n_bins', kwargs.get('n_bins', 10),
880                                               groupnames=['options'],
881                                               name='Bin number',
882                                               info='Number of bins for histograms.',
883                                               ))
884
885        # self.add_plotoptions(**kwargs)
886        self.is_title = attrsman.add(cm.AttrConf('is_title', kwargs.get('is_title', False),
887                                                 groupnames=['options'],
888                                                 name='Show title',
889                                                 info='Show title of diagrams.',
890                                                 ))
891
892        self.size_titlefont = attrsman.add(cm.AttrConf('size_titlefont', kwargs.get('size_titlefont', 32),
893                                                       groupnames=['options'],
894                                                       name='Title fontsize',
895                                                       info='Title fontsize.',
896                                                       ))
897
898        self.size_labelfont = attrsman.add(cm.AttrConf('size_labelfont', kwargs.get('size_labelfont', 24),
899                                                       groupnames=['options'],
900                                                       name='Label fontsize',
901                                                       info='Label fontsize.',
902                                                       ))
903
904        self.width_line = attrsman.add(cm.AttrConf('width_line', kwargs.get('width_line', 2),
905                                                   groupnames=['options'],
906                                                   perm='wr',
907                                                   name='Line width',
908                                                   info='Width of plotted lines.',
909                                                   ))
910
911        self.color_line = attrsman.add(cm.AttrConf('color_line', kwargs.get('color_line', np.array([0, 0, 0, 1], dtype=np.float32)),
912                                                   groupnames=['options'],
913                                                   perm='wr',
914                                                   metatype='color',
915                                                   name='Line color',
916                                                   info='Color of line in various diagrams.',
917                                                   ))
918
919        self.color_matched = attrsman.add(cm.AttrConf('color_matched', kwargs.get('color_matched', np.array([1.0, 0.4, 0.0, 0.6], np.float32)),
920                                                      groupnames=['options'],
921                                                      perm='wr',
922                                                      metatype='color',
923                                                      name='Color matched data',
924                                                      info='Color of matched data in various diagrams.',
925                                                      ))
926
927        self.color_shortest = attrsman.add(cm.AttrConf('color_shortest', kwargs.get('color_shortest', np.array([0.23529412, 1.0, 0.0, 0.6], np.float32)),
928                                                       groupnames=['options'],
929                                                       perm='wr',
930                                                       metatype='color',
931                                                       name='Color shortest route data',
932                                                       info='Color of shortest route data in various diagrams.',
933                                                       ))
934
935        self.printformat = attrsman.add(cm.AttrConf('printformat', kwargs.get('printformat', '%.1f'),
936                                                    choices=OrderedDict([
937                                                        ('Show no values', ''),
938                                                        ('x', '%.d'),
939                                                        ('x.x', '%.1f'),
940                                                        ('x.xx', '%.2f'),
941                                                        ('x.xxx', '%.3f'),
942                                                        ('x.xxxx', '%.4f'),
943                                                    ]),
944                                                    groupnames=['options'],
945                                                    name='Label formatting',
946                                                    info='Print formatting of value label in graphical representation.',
947                                                    ))
948
949        self.color_label = attrsman.add(cm.AttrConf('color_label', kwargs.get('color_label', np.array([0, 0, 0, 1], dtype=np.float32)),
950                                                    groupnames=['options'],
951                                                    perm='wr',
952                                                    metatype='color',
953                                                    name='Label color',
954                                                    info='Color of value label in graphical representation.',
955                                                    ))
956
957        self.is_grid = attrsman.add(cm.AttrConf('is_grid', kwargs.get('is_grid', True),
958                                                groupnames=['options'],
959                                                name='Show grid?',
960                                                info='If True, shows a grid on the graphical representation.',
961                                                ))
962        self.color_background = attrsman.add(cm.AttrConf('color_background', kwargs.get('color_background', np.array([1, 1, 1, 1], dtype=np.float32)),
963                                                         groupnames=['options'],
964                                                         perm='wr',
965                                                         metatype='color',
966                                                         name='Background color',
967                                                         info='Background color of schematic network in the background.',
968                                                         ))
969
970        self.add_save_options(**kwargs)
971
972    def show(self):
973        # print 'show',self.edgeattrname
974        # if self.axis  is None:
975        self.init_figures()
976        plt.rc('lines', linewidth=self.width_line)
977        # plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y']) +
978        #                    cycler('linestyle', ['-', '--', ':', '-.'])))
979        if self.is_plot_lengthratio:
980            self.plot_lengthratio()
981
982        if self.is_plot_lengthoverlap:
983            self.plot_lengthoverlap()
984
985        if self.is_plot_lengthdistrib:
986            self.plot_lengthdistrib()
987
988        if self.is_plot_lengthprob:
989            self.plot_lengthprob()
990
991        if self.is_plot_lengthdistrib_by_class:
992            self.plot_lengthdistrib_by_class()
993
994        # --
995        if self.is_plot_lengthdistrib:
996            self.plot_lengthdistrib()
997
998        if self.is_plot_mixshare:
999            self.plot_mixshare()
1000
1001        if self.is_plot_exclusiveshare:
1002            self.plot_exclusiveshare()
1003
1004        if self.is_plot_lowpriorityshare:
1005            self.plot_lowpriorityshare()
1006
1007        if self.is_plot_nodesdensity:
1008            self.plot_nodesdensity()
1009
1010        if self.is_plot_tldensity:
1011            self.plot_tldensity()
1012
1013        if self.is_prioritychangedensity:
1014            self.plot_prioritychangedensity()
1015
1016        # non overlapping
1017        if self.is_plot_lengthratio_nonoverlap:
1018            self.plot_lengthratio_nonoverlap()
1019
1020        if self.is_plot_mixshare_nonoverlap:
1021            self.plot_mixshare_nonoverlap()
1022
1023        if self.is_plot_exclusiveshare_nonoverlap:
1024            self.plot_exclusiveshare_nonoverlap()
1025
1026        if self.is_plot_lowpriorityshare_nonoverlap:
1027            self.plot_lowpriorityshare_nonoverlap()
1028
1029        if self.is_plot_nodesdensity_nonoverlap:
1030            self.plot_nodesdensity_nonoverlap()
1031
1032        if self.is_plot_tldensity_nonoverlap:
1033            self.plot_tldensity_nonoverlap()
1034
1035        if self.is_prioritychangedensity_nonoverlap:
1036            self.plot_prioritychangedensity_nonoverlap()
1037
1038        if not self.is_save:
1039            show_plot()
1040
1041    def plot_tldensity(self):
1042        print 'plot_tldensity'
1043        fig = self.create_figure()
1044        results = self.parent
1045        routesresults_shortest = results.routesresults_shortest
1046        routesresults_matched = results.routesresults_matched
1047        edgesresults = results.edgesresults
1048
1049        ax = fig.add_subplot(111)
1050        ids_valid = routesresults_matched.select_ids(np.logical_and(
1051            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1052
1053        dists_match = routesresults_matched.distances[ids_valid]
1054        dists_shortest = routesresults_shortest.distances[ids_valid]
1055
1056        matched = routesresults_matched.numbers_nodes_tls[ids_valid]/dists_match*1000
1057        shortest = routesresults_shortest.numbers_nodes_tls[ids_valid]/dists_shortest*1000
1058
1059        x_min = min(np.min(matched), np.min(shortest))
1060        x_max = 10.0  # max(np.max(matched),np.max(shortest))
1061        bins = np.linspace(x_min, x_max, self.n_bins)
1062        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1063                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))
1064        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1065                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))
1066
1067        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1068        ax.grid(self.is_grid)
1069        if self.is_title:
1070            ax.set_title('Node densities of matched and shortest route', fontsize=self.size_titlefont)
1071        ax.set_xlabel('Traffic light density [1/km]', fontsize=self.size_labelfont)
1072        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1073        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1074        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1075        if self.is_save:
1076            self.save_fig('routeana_tldensity')
1077
1078    def plot_nodesdensity(self):
1079        print 'plot_nodesdensity'
1080        fig = self.create_figure()
1081        results = self.parent
1082        routesresults_shortest = results.routesresults_shortest
1083        routesresults_matched = results.routesresults_matched
1084        edgesresults = results.edgesresults
1085
1086        ax = fig.add_subplot(111)
1087        ids_valid = routesresults_matched.select_ids(np.logical_and(
1088            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1089
1090        dists_match = routesresults_matched.distances[ids_valid]
1091        dists_shortest = routesresults_shortest.distances[ids_valid]
1092
1093        matched = routesresults_matched.numbers_nodes[ids_valid]/dists_match*1000
1094        shortest = routesresults_shortest.numbers_nodes[ids_valid]/dists_shortest*1000
1095
1096        x_min = min(np.min(matched), np.min(shortest))
1097        x_max = max(np.max(matched), np.max(shortest))
1098        bins = np.linspace(x_min, x_max, self.n_bins)
1099        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1100                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))
1101        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1102                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))
1103
1104        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1105        ax.grid(self.is_grid)
1106        if self.is_title:
1107            ax.set_title('Node densities of matched and shortest route', fontsize=self.size_titlefont)
1108        ax.set_xlabel('Node density [1/km]', fontsize=self.size_labelfont)
1109        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1110        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1111        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1112        if self.is_save:
1113            self.save_fig('routeana_nodesdensity')
1114
1115    def plot_prioritychangedensity(self):
1116        print 'plot_prioritychangedensity'
1117        fig = self.create_figure()
1118        results = self.parent
1119        routesresults_shortest = results.routesresults_shortest
1120        routesresults_matched = results.routesresults_matched
1121        edgesresults = results.edgesresults
1122
1123        ax = fig.add_subplot(111)
1124        ids_valid = routesresults_matched.select_ids(np.logical_and(
1125            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1126
1127        dists_match = routesresults_matched.distances[ids_valid]
1128        dists_shortest = routesresults_shortest.distances[ids_valid]
1129
1130        matched = routesresults_matched.numbers_prioritychange[ids_valid]/dists_match*1000
1131        shortest = routesresults_shortest.numbers_prioritychange[ids_valid]/dists_shortest*1000
1132
1133        x_min = min(np.min(matched), np.min(shortest))
1134        x_max = max(np.max(matched), np.max(shortest))
1135        bins = np.linspace(x_min, x_max, self.n_bins)
1136        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1137                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))
1138        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1139                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))
1140
1141        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1142        ax.grid(self.is_grid)
1143        if self.is_title:
1144            ax.set_title('Priority change dens. of matched and shortest route', fontsize=self.size_titlefont)
1145        ax.set_xlabel('Priority change density [1/km]', fontsize=self.size_labelfont)
1146        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1147        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1148        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1149        if self.is_save:
1150            self.save_fig('routeana_nodesdensity')
1151
1152    def plot_lowpriorityshare(self):
1153        print 'plot_lowpriorityshare'
1154        fig = self.create_figure()
1155        results = self.parent
1156        routesresults_shortest = results.routesresults_shortest
1157        routesresults_matched = results.routesresults_matched
1158        edgesresults = results.edgesresults
1159
1160        ax = fig.add_subplot(111)
1161        ids_valid = routesresults_matched.select_ids(np.logical_and(
1162            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1163
1164        dists_match = routesresults_matched.distances[ids_valid]
1165        dists_shortest = routesresults_shortest.distances[ids_valid]
1166
1167        matched = routesresults_matched.lengths_low_priority[ids_valid]/dists_match*100
1168        shortest = routesresults_shortest.lengths_low_priority[ids_valid]/dists_shortest*100
1169
1170        x_min = min(np.min(matched), np.min(shortest))
1171        x_max = 15.0  # max(np.max(matched),np.max(shortest))
1172        bins = np.linspace(x_min, x_max, self.n_bins)
1173        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1174                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))
1175        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1176                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))
1177
1178        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1179        ax.grid(self.is_grid)
1180        if self.is_title:
1181            ax.set_title('Share of low priority roads of matched and shortest route', fontsize=self.size_titlefont)
1182        ax.set_xlabel('Low priority road share [%]', fontsize=self.size_labelfont)
1183        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1184        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1185        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1186        if self.is_save:
1187            self.save_fig('routeana_lowpriorityshare')
1188
1189    def plot_exclusiveshare(self):
1190        print 'plot_exclusiveshare'
1191        fig = self.create_figure()
1192        results = self.parent
1193        routesresults_shortest = results.routesresults_shortest
1194        routesresults_matched = results.routesresults_matched
1195        edgesresults = results.edgesresults
1196
1197        ax = fig.add_subplot(111)
1198        ids_valid = routesresults_matched.select_ids(np.logical_and(
1199            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1200
1201        dists_match = routesresults_matched.distances[ids_valid]
1202        dists_shortest = routesresults_shortest.distances[ids_valid]
1203
1204        matched = routesresults_matched.lengths_exclusive[ids_valid]/dists_match*100
1205        shortest = routesresults_shortest.lengths_exclusive[ids_valid]/dists_shortest*100
1206
1207        x_min = min(np.min(matched), np.min(shortest))
1208        x_max = max(np.max(matched), np.max(shortest))
1209        bins = np.linspace(x_min, x_max, self.n_bins)
1210        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1211                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))
1212        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1213                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))
1214
1215        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1216        ax.grid(self.is_grid)
1217        if self.is_title:
1218            ax.set_title('Share of exclusive access roads of matched and shortest route', fontsize=self.size_titlefont)
1219        ax.set_xlabel('Exclusive access road share [%]', fontsize=self.size_labelfont)
1220        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1221        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1222        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1223        if self.is_save:
1224            self.save_fig('routeana_exclusiveshare')
1225
1226    def plot_mixshare(self):
1227        print 'plot_mixshare'
1228        fig = self.create_figure()
1229        results = self.parent
1230        routesresults_shortest = results.routesresults_shortest
1231        routesresults_matched = results.routesresults_matched
1232        edgesresults = results.edgesresults
1233
1234        ax = fig.add_subplot(111)
1235        ids_valid = routesresults_matched.select_ids(np.logical_and(
1236            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1237
1238        dists_match = routesresults_matched.distances[ids_valid]
1239        dists_shortest = routesresults_shortest.distances[ids_valid]
1240
1241        matched = routesresults_matched.lengths_mixed[ids_valid]/dists_match*100
1242        shortest = routesresults_shortest.lengths_mixed[ids_valid]/dists_shortest*100
1243
1244        x_min = min(np.min(matched), np.min(shortest))
1245        x_max = max(np.max(matched), np.max(shortest))
1246        bins = np.linspace(x_min, x_max, self.n_bins)
1247        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1248                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))
1249        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1250                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))
1251
1252        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1253        ax.grid(self.is_grid)
1254        if self.is_title:
1255            ax.set_title('Share of mixed reserved access roads of matched and shortest route',
1256                         fontsize=self.size_titlefont)
1257        ax.set_xlabel('Mixed reserved access road share [%]', fontsize=self.size_labelfont)
1258        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1259        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1260        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1261        if self.is_save:
1262            self.save_fig('routeana_mixshare')
1263
1264    def plot_lengthdistrib_by_class(self):
1265        print 'plot_lengthdistrib_by_class'
1266        fig = self.create_figure()
1267        results = self.parent
1268        routesresults_shortest = results.routesresults_shortest
1269        routesresults_matched = results.routesresults_matched
1270        edgesresults = results.edgesresults
1271
1272        ax = fig.add_subplot(111)
1273        ids_valid = routesresults_matched.select_ids(np.logical_and(
1274            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1275
1276        dists_match = routesresults_matched.distances[ids_valid]
1277        dists_shortest = routesresults_shortest.distances[ids_valid]
1278        x_min = min(np.min(dists_match), np.min(dists_shortest))
1279        x_max = max(np.max(dists_match), np.max(dists_shortest))
1280
1281        dists_class = np.arange(0, int(x_max), self.distance_class)
1282        dists_class_center = (dists_class+0.5*self.distance_class)[1:]
1283        n_class = len(dists_class)-1
1284        means_match = np.zeros(n_class, dtype=np.float32)
1285        stds_match = np.zeros(n_class, dtype=np.float32)
1286        means_shortest = np.zeros(n_class, dtype=np.float32)
1287        stds_shortest = np.zeros(n_class, dtype=np.float32)
1288        xticklabels = []
1289        ratiolabels = []
1290        for dist_lower, dist_upper, i in zip(dists_class[:-1], dists_class[1:], range(n_class)):
1291            xticklabels.append('%d - %d' % (float(dist_lower)/1000, float(dist_upper)/1000))
1292            inds = np.logical_and(dists_match > dist_lower, dists_match < dist_upper)
1293            means_match[i] = np.mean(dists_match[inds])
1294            stds_match[i] = np.std(dists_match[inds])
1295
1296            #inds = np.logical_and(dists_shortest>dist_lower,dists_shortest<dist_upper)
1297            means_shortest[i] = np.mean(dists_shortest[inds])
1298            stds_shortest[i] = np.std(dists_shortest[inds])
1299
1300            ratiolabel = ''
1301            if (not np.isnan(means_shortest[i])) & (not np.isnan(means_match[i])):
1302                if means_match[i] > 0:
1303                    ratiolabel = '%d%%' % (means_shortest[i]/means_match[i]*100)
1304            ratiolabels.append(ratiolabel)
1305
1306        print '  dists_class_center', dists_class_center
1307        print '  means_match', means_match
1308        print '  stds_match', stds_match
1309        print '  means_shortest', means_shortest
1310        print '  stds_shortest', stds_shortest
1311
1312        x = np.arange(n_class, dtype=np.float32)  # the x locations for the groups
1313        width = 0.35       # the width of the bars
1314
1315        #        ax.bar(ind + width, women_means, width, color='y', yerr=women_std)
1316        bars1 = ax.bar(x-width, means_match, width, color=self.color_matched, yerr=stds_match)
1317        bars2 = ax.bar(x+0*width, means_shortest, width, color=self.color_shortest, yerr=stds_shortest)
1318        #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)
1319        #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)
1320
1321        #ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)
1322        ax.legend((bars1[0], bars2[0]), ('matched', 'shortest'),
1323                  shadow=True, fontsize=self.size_labelfont, loc='best')
1324
1325        # if self.is_grid:
1326        ax.yaxis.grid(self.is_grid)
1327
1328        if self.is_title:
1329            ax.set_title('Mean length by trip length class', fontsize=self.size_titlefont)
1330        ax.set_xlabel('Length classes [km]', fontsize=self.size_labelfont)
1331        ax.set_ylabel('Mean length [m]', fontsize=self.size_labelfont)
1332
1333        ax.set_xticks(x)
1334        ax.set_xticklabels(xticklabels)
1335        # self._autolabel_bars(ax,bars1,means_match)
1336        self._autolabel_bars(ax, bars2, ratiolabels)
1337
1338        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1339        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1340        if self.is_save:
1341            self.save_fig('routeana_lengthdistrib_by_class')
1342
1343    def _autolabel_bars(self, ax, bars, labels):
1344        """
1345        Attach a text label above each bar displaying its height
1346        """
1347        for rect, label in zip(bars, labels):
1348            height = rect.get_height()
1349            if not np.isnan(height):
1350                ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
1351                        '%s' % label,
1352                        ha='center', va='bottom',
1353                        fontsize=int(0.8*self.size_labelfont),
1354                        )
1355
1356    def plot_lengthdistrib(self):
1357        print 'plot_lengthdistrib'
1358        fig = self.create_figure()
1359        results = self.parent
1360        routesresults_shortest = results.routesresults_shortest
1361        routesresults_matched = results.routesresults_matched
1362        edgesresults = results.edgesresults
1363
1364        ax = fig.add_subplot(111)
1365        ids_overlength = routesresults_matched.select_ids(np.logical_and(
1366            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 20000))
1367        print '  len(ids_overlength)', len(ids_overlength)
1368        print '  ids_overlength', ids_overlength
1369
1370        ids_valid = routesresults_matched.select_ids(np.logical_and(routesresults_shortest.distances.get_value(
1371        ) > 0, routesresults_matched.distances.get_value() > 0, routesresults_matched.distances.get_value() < 20000))
1372
1373        dists_match = routesresults_matched.distances[ids_valid]
1374        dists_shortest = routesresults_shortest.distances[ids_valid]
1375
1376        x_min = min(np.min(dists_match), np.min(dists_shortest))
1377        x_max = max(np.max(dists_match), np.max(dists_shortest))
1378        bins = np.linspace(x_min, x_max, self.n_bins)
1379        bincenters = self.plot_hist(ax, dists_match, bins=bins, color=self.color_matched,
1380                                    label='matched:'+'$\mu = %dm$, $\sigma=%dm$' % (np.mean(dists_match), np.std(dists_match)))
1381        bincenters = self.plot_hist(ax, dists_shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1382                                    '$\mu = %dm$, $\sigma=%dm$' % (np.mean(dists_shortest), np.std(dists_shortest)))
1383
1384        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1385        ax.grid(self.is_grid)
1386        if self.is_title:
1387            ax.set_title('Length distribution of matched and shortest route', fontsize=self.size_titlefont)
1388        ax.set_xlabel('Length [m]', fontsize=self.size_labelfont)
1389        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1390        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1391        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1392        if self.is_save:
1393            self.save_fig('routeana_lengthdistrib')
1394
1395    def plot_lengthprob(self):
1396        print 'plot_lengthprob'
1397        fig = self.create_figure()
1398        results = self.parent
1399        routesresults_shortest = results.routesresults_shortest
1400        routesresults_matched = results.routesresults_matched
1401        edgesresults = results.edgesresults
1402
1403        ax = fig.add_subplot(111)
1404        ids_valid = routesresults_matched.select_ids(np.logical_and(
1405            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1406
1407        dists_match = routesresults_matched.distances[ids_valid]
1408        dists_shortest = routesresults_shortest.distances[ids_valid]
1409
1410        x_min = min(np.min(dists_match), np.min(dists_shortest))
1411        x_max = max(np.max(dists_match), np.max(dists_shortest))
1412        bins = np.linspace(x_min, x_max, self.n_bins)
1413        w_bin = bins[1]-bins[0]
1414        bincenters = self.plot_hist(ax, dists_match, bins=bins,
1415                                    color=self.color_matched,
1416                                    label='matched:' +
1417                                    '$\mu = %dm$, $\sigma=%dm$' % (np.mean(dists_match), np.std(dists_match)),
1418                                    is_rel_frequ=True,
1419                                    is_percent=True,
1420                                    )
1421        bincenters = self.plot_hist(ax, dists_shortest, bins=bins,
1422                                    color=self.color_shortest,
1423                                    label='shortest:' +
1424                                    '$\mu = %dm$, $\sigma=%dm$' % (np.mean(dists_shortest), np.std(dists_shortest)),
1425                                    is_rel_frequ=True,
1426                                    is_percent=True,
1427                                    )
1428
1429        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1430        ax.grid(self.is_grid)
1431        if self.is_title:
1432            ax.set_title('Relative frequency of matched and shortest route', fontsize=self.size_titlefont)
1433        ax.set_xlabel('Length [m]', fontsize=self.size_labelfont)
1434        ax.set_ylabel('Relative frequency [%]', fontsize=self.size_labelfont)
1435        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1436        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1437        if self.is_save:
1438            self.save_fig('routeana_lengthprob')
1439
1440    def plot_lengthoverlap(self):
1441        print 'plot_lengthoverlap'
1442        fig = self.create_figure()
1443        results = self.parent
1444        routesresults_shortest = results.routesresults_shortest
1445        routesresults_matched = results.routesresults_matched
1446        edgesresults = results.edgesresults
1447
1448        ax = fig.add_subplot(111)
1449        bins = np.linspace(0.0, 1.0, self.n_bins)
1450
1451        ids_valid = routesresults_matched.select_ids(np.logical_and(
1452            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1453        values = routesresults_shortest.lengths_overlap_matched[ids_valid]/routesresults_matched.distances[ids_valid]
1454        bincenters = self.plot_hist(ax, values,
1455                                    bins=bins, histtype='bar',
1456                                    label=r'$\mu = %.2f$, $\sigma=%.2f$' % (np.mean(values), np.std(values))
1457                                    )
1458
1459        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1460        ax.grid(self.is_grid)
1461        if self.is_title:
1462            ax.set_title('Share of overlap between shortest path and matched path', fontsize=self.size_titlefont)
1463        ax.set_xlabel('Overlap share between shortest and matched path', fontsize=self.size_labelfont)
1464        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1465        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1466        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1467
1468        self.set_figmargins()
1469        if self.is_save:
1470            self.save_fig('routeana_lengthoverlap')
1471
1472    def plot_lengthratio(self):
1473        print 'plot_lengthratio'
1474        fig = self.create_figure()
1475        results = self.parent
1476        routesresults_shortest = results.routesresults_shortest
1477        routesresults_matched = results.routesresults_matched
1478        edgesresults = results.edgesresults
1479
1480        ax = fig.add_subplot(111)
1481        bins = np.linspace(0.0, 1.0, self.n_bins)
1482
1483        ids_valid = routesresults_matched.select_ids(np.logical_and(
1484            routesresults_shortest.distances.get_value() > 0, routesresults_matched.distances.get_value() > 0))
1485        values = routesresults_shortest.distances[ids_valid]/routesresults_matched.distances[ids_valid]
1486        bincenters = self.plot_hist(ax, values,
1487                                    bins=bins, histtype='bar',
1488                                    label=r'$\mu = %.2f$, $\sigma=%.2f$' % (np.mean(values), np.std(values))
1489                                    )
1490
1491        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1492        ax.grid(self.is_grid)
1493        if self.is_title:
1494            ax.set_title('Ratio distance shortest path over matched path', fontsize=self.size_titlefont)
1495        ax.set_xlabel('Ratio shortest path length/matched path length', fontsize=self.size_labelfont)
1496        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1497        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1498        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1499
1500        self.set_figmargins()
1501        if self.is_save:
1502            self.save_fig('routeana_lengthratio')
1503
1504
1505# -------------------------------------------------------------------------------
1506    # non-overlap
1507
1508    def plot_lengthratio_nonoverlap(self):
1509        print 'plot_lengthratio_nonoverlap'
1510        fig = self.create_figure()
1511        results = self.parent
1512        routesresults_shortest = results.routesresults_shortest
1513        routesresults_matched = results.routesresults_matched
1514        routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap
1515        routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap
1516
1517        edgesresults = results.edgesresults
1518
1519        ax = fig.add_subplot(111)
1520        bins = np.linspace(0.0, 1.0, self.n_bins)
1521
1522        ids_valid = routesresults_matched.select_ids(np.logical_and(
1523            routesresults_shortest_nonoverlap.distances.get_value() > 0,
1524            routesresults_matched_nonoverlap.distances.get_value() > 0)
1525        )
1526
1527        values = routesresults_shortest_nonoverlap.distances[ids_valid] / \
1528            routesresults_matched_nonoverlap.distances[ids_valid]
1529        bincenters = self.plot_hist(ax, values,
1530                                    bins=bins, histtype='bar',
1531                                    label=r'$\mu = %.2f$, $\sigma=%.2f$' % (np.mean(values), np.std(values))
1532                                    )
1533
1534        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1535        ax.grid(self.is_grid)
1536        if self.is_title:
1537            ax.set_title('Ratio distance of non-overlapping shortest over matched path', fontsize=self.size_titlefont)
1538        ax.set_xlabel('Ratio shortest n.o. path length/matched path length', fontsize=self.size_labelfont)
1539        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1540        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1541        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1542
1543        self.set_figmargins()
1544        if self.is_save:
1545            self.save_fig('routeana_lengthratio_nonoverlap')
1546
1547    def plot_tldensity_nonoverlap(self):
1548        print 'plot_tldensity_nonoverlap'
1549        fig = self.create_figure()
1550        results = self.parent
1551        routesresults_shortest = results.routesresults_shortest
1552        routesresults_matched = results.routesresults_matched
1553        routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap
1554        routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap
1555        edgesresults = results.edgesresults
1556
1557        ax = fig.add_subplot(111)
1558        ids_valid = routesresults_matched.select_ids(np.logical_and(
1559            routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))
1560
1561        dists_match = routesresults_matched_nonoverlap.distances[ids_valid]
1562        dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]
1563
1564        matched = routesresults_matched_nonoverlap.numbers_nodes_tls[ids_valid]/dists_match*1000
1565        shortest = routesresults_shortest_nonoverlap.numbers_nodes_tls[ids_valid]/dists_shortest*1000
1566
1567        x_min = min(np.min(matched), np.min(shortest))
1568        x_max = 10.0  # max(np.max(matched),np.max(shortest))
1569        bins = np.linspace(x_min, x_max, self.n_bins)
1570        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1571                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))
1572        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1573                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))
1574
1575        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1576        ax.grid(self.is_grid)
1577        if self.is_title:
1578            ax.set_title('Node densities of non-overlapping matched and shortest route', fontsize=self.size_titlefont)
1579        ax.set_xlabel('Traffic light density  n.o. [1/km]', fontsize=self.size_labelfont)
1580        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1581        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1582        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1583        if self.is_save:
1584            self.save_fig('routeana_tldensity_nonoverlap')
1585
1586    def plot_nodesdensity_nonoverlap(self):
1587        print 'plot_nodesdensity_nonoverlap'
1588        fig = self.create_figure()
1589        results = self.parent
1590        routesresults_shortest = results.routesresults_shortest
1591        routesresults_matched = results.routesresults_matched
1592        routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap
1593        routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap
1594        edgesresults = results.edgesresults
1595
1596        ax = fig.add_subplot(111)
1597        ids_valid = routesresults_matched.select_ids(np.logical_and(
1598            routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))
1599
1600        dists_match = routesresults_matched_nonoverlap.distances[ids_valid]
1601        dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]
1602
1603        matched = routesresults_matched_nonoverlap.numbers_nodes[ids_valid]/dists_match*1000
1604        shortest = routesresults_shortest_nonoverlap.numbers_nodes[ids_valid]/dists_shortest*1000
1605
1606        x_min = min(np.min(matched), np.min(shortest))
1607        x_max = max(np.max(matched), np.max(shortest))
1608        bins = np.linspace(x_min, x_max, self.n_bins)
1609        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1610                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))
1611        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1612                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))
1613
1614        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1615        ax.grid(self.is_grid)
1616        if self.is_title:
1617            ax.set_title('Node densities of non-overlapping matched and shortest route', fontsize=self.size_titlefont)
1618        ax.set_xlabel('Node density  n.o. [1/km]', fontsize=self.size_labelfont)
1619        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1620        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1621        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1622        if self.is_save:
1623            self.save_fig('routeana_nodesdensity_nonoverlap')
1624
1625    def plot_prioritychangedensity_nonoverlap(self):
1626        print 'plot_prioritychangedensity_nonoverlap'
1627        fig = self.create_figure()
1628        results = self.parent
1629        routesresults_shortest = results.routesresults_shortest
1630        routesresults_matched = results.routesresults_matched
1631        routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap
1632        routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap
1633        edgesresults = results.edgesresults
1634
1635        ax = fig.add_subplot(111)
1636        ids_valid = routesresults_matched.select_ids(np.logical_and(
1637            routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))
1638
1639        dists_match = routesresults_matched_nonoverlap.distances[ids_valid]
1640        dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]
1641
1642        matched = routesresults_matched_nonoverlap.numbers_prioritychange[ids_valid]/dists_match*1000
1643        shortest = routesresults_shortest_nonoverlap.numbers_prioritychange[ids_valid]/dists_shortest*1000
1644
1645        x_min = min(np.min(matched), np.min(shortest))
1646        x_max = max(np.max(matched), np.max(shortest))
1647        bins = np.linspace(x_min, x_max, self.n_bins)
1648        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1649                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(matched), np.std(matched)))
1650        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1651                                    '$\mu = %.2f/km$, $\sigma=%.2f/km$' % (np.mean(shortest), np.std(shortest)))
1652
1653        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1654        ax.grid(self.is_grid)
1655        if self.is_title:
1656            ax.set_title('Priority change dens. of non-overlapping matched and shortest route',
1657                         fontsize=self.size_titlefont)
1658        ax.set_xlabel('Priority change density  n.o. [1/km]', fontsize=self.size_labelfont)
1659        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1660        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1661        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1662        if self.is_save:
1663            self.save_fig('routeana_nodesdensity_nonoverlap')
1664
1665    def plot_lowpriorityshare_nonoverlap(self):
1666        print 'plot_lowpriorityshare_nonoverlap'
1667        fig = self.create_figure()
1668        results = self.parent
1669        routesresults_shortest = results.routesresults_shortest
1670        routesresults_matched = results.routesresults_matched
1671        routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap
1672        routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap
1673        edgesresults = results.edgesresults
1674
1675        ax = fig.add_subplot(111)
1676        ids_valid = routesresults_matched.select_ids(np.logical_and(
1677            routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))
1678
1679        dists_match = routesresults_matched_nonoverlap.distances[ids_valid]
1680        dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]
1681
1682        matched = routesresults_matched_nonoverlap.lengths_low_priority[ids_valid]/dists_match*100
1683        shortest = routesresults_shortest_nonoverlap.lengths_low_priority[ids_valid]/dists_shortest*100
1684
1685        x_min = min(np.min(matched), np.min(shortest))
1686        x_max = 15.0  # max(np.max(matched),np.max(shortest))
1687        bins = np.linspace(x_min, x_max, self.n_bins)
1688        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1689                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))
1690        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1691                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))
1692
1693        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1694        ax.grid(self.is_grid)
1695        if self.is_title:
1696            ax.set_title('Share of low priority roads of non-overlapping matched and shortest route',
1697                         fontsize=self.size_titlefont)
1698        ax.set_xlabel('Low priority road share  n.o. [%]', fontsize=self.size_labelfont)
1699        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1700        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1701        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1702        if self.is_save:
1703            self.save_fig('routeana_lowpriorityshare_nonoverlap')
1704
1705    def plot_exclusiveshare_nonoverlap(self):
1706        print 'plot_exclusiveshare_nonoverlap'
1707        fig = self.create_figure()
1708        results = self.parent
1709        routesresults_shortest = results.routesresults_shortest
1710        routesresults_matched = results.routesresults_matched
1711        routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap
1712        routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap
1713        edgesresults = results.edgesresults
1714
1715        ax = fig.add_subplot(111)
1716        ids_valid = routesresults_matched.select_ids(np.logical_and(
1717            routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))
1718
1719        dists_match = routesresults_matched_nonoverlap.distances[ids_valid]
1720        dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]
1721
1722        matched = routesresults_matched_nonoverlap.lengths_exclusive[ids_valid]/dists_match*100
1723        shortest = routesresults_shortest_nonoverlap.lengths_exclusive[ids_valid]/dists_shortest*100
1724
1725        x_min = min(np.min(matched), np.min(shortest))
1726        x_max = max(np.max(matched), np.max(shortest))
1727        bins = np.linspace(x_min, x_max, self.n_bins)
1728        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1729                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))
1730        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1731                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))
1732
1733        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1734        ax.grid(self.is_grid)
1735        if self.is_title:
1736            ax.set_title('Share of exclusive access roads of non-overlapping matched and shortest route',
1737                         fontsize=self.size_titlefont)
1738        ax.set_xlabel('Exclusive access road share  n.o. [%]', fontsize=self.size_labelfont)
1739        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1740        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1741        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1742        if self.is_save:
1743            self.save_fig('routeana_exclusiveshare_nonoverlap')
1744
1745    def plot_mixshare_nonoverlap(self):
1746        print 'plot_mixshare_nonoverlap'
1747        fig = self.create_figure()
1748        results = self.parent
1749        routesresults_shortest = results.routesresults_shortest
1750        routesresults_matched = results.routesresults_matched
1751        routesresults_shortest_nonoverlap = results.routesresults_shortest_nonoverlap
1752        routesresults_matched_nonoverlap = results.routesresults_matched_nonoverlap
1753        edgesresults = results.edgesresults
1754
1755        ax = fig.add_subplot(111)
1756        ids_valid = routesresults_matched.select_ids(np.logical_and(
1757            routesresults_shortest_nonoverlap.distances.get_value() > 0, routesresults_matched_nonoverlap.distances.get_value() > 0))
1758
1759        dists_match = routesresults_matched_nonoverlap.distances[ids_valid]
1760        dists_shortest = routesresults_shortest_nonoverlap.distances[ids_valid]
1761
1762        matched = routesresults_matched_nonoverlap.lengths_mixed[ids_valid]/dists_match*100
1763        shortest = routesresults_shortest_nonoverlap.lengths_mixed[ids_valid]/dists_shortest*100
1764
1765        x_min = min(np.min(matched), np.min(shortest))
1766        x_max = max(np.max(matched), np.max(shortest))
1767        bins = np.linspace(x_min, x_max, self.n_bins)
1768        bincenters = self.plot_hist(ax, matched, bins=bins, color=self.color_matched, label='matched:' +
1769                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(matched), np.std(matched)))
1770        bincenters = self.plot_hist(ax, shortest, bins=bins, color=self.color_shortest, label='shortest:' +
1771                                    '$\mu = %.2f$%%, $\sigma=%.2f$%%' % (np.mean(shortest), np.std(shortest)))
1772
1773        ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
1774        ax.grid(self.is_grid)
1775        if self.is_title:
1776            ax.set_title('Share of mixed reserved access roads of non-overlapping matched and shortest route',
1777                         fontsize=self.size_titlefont)
1778        ax.set_xlabel('Mixed reserved access road share n.o. [%]', fontsize=self.size_labelfont)
1779        ax.set_ylabel('Probability distribution', fontsize=self.size_labelfont)
1780        ax.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))
1781        ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
1782        if self.is_save:
1783            self.save_fig('routeana_mixshare_nonoverlap')
1784# -------------------------------------------------------------------------------
1785
1786    def do(self):
1787        # print 'do',self.edgeattrname
1788        self.show()
1789
1790    def get_scenario(self):
1791        return self.parent.get_scenario()
1792