Path: blob/main/tools/contributed/sumopy/coremodules/misc/matplottools.py
169689 views
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo1# Copyright (C) 2016-2025 German Aerospace Center (DLR) and others.2# SUMOPy module3# Copyright (C) 2012-2021 University of Bologna - DICAM4# This program and the accompanying materials are made available under the5# terms of the Eclipse Public License 2.0 which is available at6# https://www.eclipse.org/legal/epl-2.0/7# This Source Code may also be made available under the following Secondary8# Licenses when the conditions for such availability set forth in the Eclipse9# Public License 2.0 are satisfied: GNU General Public License, version 210# or later which is available at11# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html12# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later1314# @file matplottools.py15# @author Joerg Schweizer16# @date 20121718from agilepy.lib_wx.processdialog import ProcessDialog, ProcessDialogInteractive19from agilepy.lib_base.processes import Process20from agilepy.lib_base.geometry import *21import agilepy.lib_base.arrayman as am22import agilepy.lib_base.classman as cm23import os24import numpy as np25from collections import OrderedDict26import matplotlib as mpl27from matplotlib.patches import Arrow, Circle, Wedge, Polygon, FancyArrow28from matplotlib.collections import PatchCollection29import matplotlib.colors as colors30import matplotlib.cm as cmx31import matplotlib.pyplot as plt32import matplotlib.image as image33from matplotlib.ticker import MaxNLocator34import matplotlib.patches as mpatches3536if 0: # change backend...makes problems with plt37gui_env = ['WXAgg', 'GTKAgg', 'Qt4Agg', 'TKAgg', ]38for gui in gui_env:39try:40print "Try Matplotlib backend:", gui41mpl.use(gui, warn=False, force=True)42from mpl.patches import Arrow, Circle, Wedge, Polygon, FancyArrow43from mpl.mpl import PatchCollection44import matplotlib.colors as colors45import mpl.cm as cmx46import mpl.pyplot as plt47import mpl.image as image48from mpl.ticker import MaxNLocator49import mpl.patches as mpatches50break51except:52continue53print "Using Matplotlib backend", mpl.get_backend()545556try:57import wx58except:59print 'WARNING: no wxwindows support'606162COLORS = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c',63'#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5',64'#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f',65'#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']6667LINESTYLES = ['-', '--', '-.', ':', 'None']686970MARKERSTYLES = ['None', 'o', 'v', 's', '*', '^', 'h', 'D', 'p', '<', '>']7172global ind_fig73ind_fig = 0747576def get_color(i):77return COLORS[i % len(COLORS)]787980def get_colors(inds):81return np.array(COLORS, dtype=np.str)[np.mod(inds, len(COLORS))]828384def get_marker(i):85return MARKERSTYLES[i % len(MARKERSTYLES)]868788def get_markers(inds):89return np.array(MARKERSTYLES, dtype=np.str)[np.mod(inds, len(MARKERSTYLES))]909192class ResultDialog(ProcessDialog):93def _get_buttons(self):94buttons = [('Plot and close', self.on_run, 'Plot selected quantity in matplotlib window and close this window thereafter.'),95('Plot', self.on_show, 'Plot selected quantity in matplotlib window.'),96('Save Options...', self.on_save_options, self.on_save_options.__doc__),97('Load Options...', self.on_load_options, self.on_load_options.__doc__),98]99defaultbutton = 'Plot and close'100standartbuttons = ['cancel', ]101102return buttons, defaultbutton, standartbuttons103104def on_show(self, event):105self.process.show()106107108def get_mplicon():109icondir = os.path.join(os.path.dirname(__file__), 'images')110return wx.Bitmap(os.path.join(icondir, 'icon_mpl.png'))111112113def init_plot(tight_layout=True):114plt.close("all")115fig = plt.figure()116ax = fig.add_subplot(111)117if tight_layout:118fig.tight_layout()119return ax120121122def init_plot_fig_ax():123plt.close("all")124fig = plt.figure()125ax = fig.add_subplot(111)126return fig, ax127128129def new_plot(tight_layout=True):130global ind_fig131fig = plt.figure(ind_fig)132ind_fig += 1133ax = fig.add_subplot(111)134if tight_layout:135fig.tight_layout()136return ax137138139def new_doubkeplot(tight_layout=True):140global ind_fig141fig = plt.figure(ind_fig)142ind_fig += 1143if tight_layout:144fig.tight_layout()145return plt.subplot(2, 1, 1), plt.subplot(2, 1, 2)146147148def plot_net(ax, net, color_edge="gray", width_edge=2, color_node=None,149alpha=0.5, is_show_connections=True, mapscale=1.0):150for shape in net.edges.shapes.get_value():151x_vec = np.array(shape)[:, 0]152y_vec = np.array(shape)[:, 1]153ax.plot(x_vec*mapscale, y_vec*mapscale, color=color_edge, lw=width_edge, alpha=alpha, zorder=-100)154if is_show_connections:155for id_connection in net.connections.get_ids():156x_vec = np.array([net.edges.shapes[net.lanes.ids_edge[net.connections.ids_fromlane[id_connection]]]157[-1, 0], net.edges.shapes[net.lanes.ids_edge[net.connections.ids_tolane[id_connection]]][0, 0]])158y_vec = np.array([net.edges.shapes[net.lanes.ids_edge[net.connections.ids_fromlane[id_connection]]]159[-1, 1], net.edges.shapes[net.lanes.ids_edge[net.connections.ids_tolane[id_connection]]][0, 1]])160ax.plot(x_vec*mapscale, y_vec*mapscale, color=color_edge, lw=width_edge*0.8, alpha=alpha, zorder=-100)161162# do nodes163if color_node is None:164is_nodefill = False165color_node = 'none'166else:167is_nodefill = True168169#ax.scatter(x_vec[0], y_vec[0], s=np.pi * (10.0)**2, c=colors, alpha=0.5)170coords = net.nodes.coords.get_value()171radii = net.nodes.radii.get_value()172#ax.scatter(coords[:,0], coords[:,1], s=np.pi * (radii)**2, alpha=0.5)173#patches = []174for coord, radius in zip(coords, radii):175ax.add_patch(Circle(coord*mapscale, radius=radius*mapscale,176linewidth=width_edge,177edgecolor=color_edge,178facecolor=color_node,179fill=is_nodefill,180alpha=alpha,181zorder=-50))182183184def plot_maps(ax, maps, alpha=0.5, mapscale=1.0):185# print 'plot_maps'186net = maps.parent.get_net()187rootdir = os.path.dirname(net.parent.get_rootfilepath())188189for filename, bbox in zip(maps.filenames.get_value(), maps.bboxes.get_value()):190# print ' ',filename,191if filename == os.path.basename(filename):192# filename does not contain path info193filepath = os.path.join(rootdir, filename)194else:195# filename contains path info (can happen if interactively inserted)196filepath = filename197# print ' filepath',filepath198im = image.imread(filepath)199myaximage = ax.imshow(im, aspect='auto', extent=(200bbox[0, 0]*mapscale, bbox[1, 0]*mapscale, bbox[0, 1]*mapscale, bbox[1, 1]*mapscale), alpha=alpha, zorder=-1000)201202# def plot_facilities(ax, facilities, color_building = "gray",203# color_outline = 'white', width_line = 2,204# alpha = 0.5, mapscale=1.0):205206# if color_building is None:207# is_fill = False208# color_building = 'none'209# else:210# is_fill = True211# print mpl.patches.Polygon.__doc__212# for shape in facilities.shapes.get_value():213# #x_vec = np.array(shape)[:,0]214# #y_vec = np.array(shape)[:,1]215# #ax.plot(x_vec, y_vec, color = color_building, lw = width_line,216# # alpha=alpha )217# print ' add shape',shape218# ax.add_patch(mpl.patches.Polygon( np.array(shape)[:,:2]*mapscale,219# linewidth = width_line,220# edgecolor = color_outline,221# facecolor = color_building,222# fill = is_fill,223# alpha = alpha,224# zorder = -200))225226227def plot_facilities(ax, facilities, color_building="gray",228color_outline='white', width_line=2,229alpha=0.5, mapscale=1.0):230231if color_building is None:232is_fill = False233color_building = 'none'234else:235is_fill = True236for shape in facilities.shapes.get_value():237#x_vec = np.array(shape)[:,0]238#y_vec = np.array(shape)[:,1]239# ax.plot(x_vec, y_vec, color = color_building, lw = width_line,240# alpha=alpha )241ax.add_patch(mpl.patches.Polygon(np.array(shape)[:, :2]*mapscale,242linewidth=width_line,243edgecolor=color_outline,244facecolor=color_building,245fill=is_fill,246alpha=alpha,247zorder=-200))248249250def plot_zones(ax, zones, color_zone=None,251color_outline='green', width_line=2,252alpha=0.5, mapscale=1.0):253254if color_zone is None:255is_fill = False256color_zone = 'none'257else:258is_fill = True259for shape in zones.shapes.get_value():260#x_vec = np.array(shape)[:,0]261#y_vec = np.array(shape)[:,1]262# ax.plot(x_vec, y_vec, color = color_building, lw = width_line,263# alpha=alpha )264ax.add_patch(mpl.patches.Polygon(np.array(shape)[:, :2]*mapscale,265linewidth=width_line,266edgecolor=color_outline,267facecolor=color_zone,268fill=is_fill,269alpha=alpha,270zorder=200))271272273def plot_zone(ax, zone_shape, color_zone="gray",274color_outline='white', width_line=2,275alpha=0.5, zorder=-200, mapscale=1.0):276277if color_zone is None:278is_fill = False279color_building = 'none'280else:281is_fill = True282283shape = (np.array(zone_shape)[:, :2]*mapscale).tolist()284print shape285ax.add_patch(Polygon(shape,286linewidth=width_line,287edgecolor=color_outline,288facecolor=color_zone,289fill=is_fill,290alpha=alpha,291zorder=-200))292293294def plot_edgevalues_lines(ax, ids_result=None, config_ids_edge=None, values=[],295ids_edge=None, edges=None,296width_max=10.0, alpha=0.8, printformat='%.2f',297color_outline=None, color_fill=None,298color_label='black', is_antialiased=True,299is_fill=True, is_widthvalue=True,300arrowshape='left', length_arrowhead=10.0,301headwidthstretch=1.3,302fontsize=32,303valuelabel='',304value_range=None,305is_colorbar=True,306mapscale=1.0):307# ATTENTION: do not change order of args for backwards compatibility308309head_width = headwidthstretch*width_max310fontsize_ticks = int(0.8*fontsize)311312if ids_edge is None:313edges = config_ids_edge.get_linktab()314ids_edge = config_ids_edge[ids_result]315#values = config_values[ids_result]316values_norm = np.array(values, dtype=np.float32)/np.max(values)317318patches = []319displacement = float(width_max)/2.0320if is_widthvalue:321linewidths = width_max*values_norm322else:323linewidths = width_max * np.ones(len(values_norm), np.float32)324325deltaangle_text = -np.pi/2.0326displacement_text = displacement+width_max327328jet = cm_jet = plt.get_cmap('jet')329if value_range is None:330c_norm = colors.Normalize(vmin=0, vmax=np.max(values))331else:332c_norm = colors.Normalize(vmin=value_range[0], vmax=value_range[1])333334# http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots/11558629#11558629335sm = cmx.ScalarMappable(norm=c_norm, cmap=jet)336sm.set_array(values_norm)337for id_edge, value, value_norm, linewidth in zip(ids_edge, values, values_norm, linewidths):338if not np.isnan(value):339shape, angles_perb = get_resultshape(edges, id_edge, displacement)340x_vec = np.array(shape)[:, 0]341y_vec = np.array(shape)[:, 1]342deltax = x_vec[-1]-x_vec[0]343deltay = y_vec[-1]-y_vec[0]344if is_fill: # means that fill with value proportional color345color = sm.to_rgba(value)346else:347color = color_fill348349# http://matplotlib.org/users/pyplot_tutorial.html350line = mpl.lines.Line2D(x_vec*mapscale, y_vec*mapscale, color=color,351linewidth=linewidth,352antialiased=is_antialiased,353alpha=alpha,354solid_capstyle='round',355zorder=0,356)357ax.add_line(line)358359if printformat is not '':360angles_text = np.arctan2(deltay, deltax)+deltaangle_text361# print ' angles_text',printformat%value,angles_text/(np.pi)*180,(angles_text>np.pi/2),(angles_text<3*np.pi/2)362if (angles_text > np.pi/2) | (angles_text < -np.pi/2):363angles_text += np.pi364x_label = x_vec[0]+0.66*deltax+displacement_text*np.cos(angles_text)365y_label = y_vec[0]+0.66*deltay+displacement_text*np.sin(angles_text)366367ax.text(x_label*mapscale, y_label*mapscale, printformat % value,368rotation=angles_text/(np.pi)*180,369color=color_label,370fontsize=fontsize_ticks,371zorder=10,372)373374if is_fill & is_colorbar:375cbar = plt.colorbar(sm)376# mpl.setp(cbar.ax.yaxis.get_ticklabels(), fontsize=fontsize)#weight='bold',377# cb.ax.tick_params(labelsize=font_size)378if valuelabel != '':379cbar.ax.set_ylabel(valuelabel, fontsize=fontsize) # , weight="bold")380for l in cbar.ax.yaxis.get_ticklabels():381# l.set_weight("bold")382l.set_fontsize(fontsize_ticks)383384385def plot_connectionvalues_lines(ax, ids_result=None, config_ids_connection=None, values=[],386ids_connection=None, connections=None, net=None,387width_max=10.0, alpha=0.8, printformat='%.2f',388color_outline=None, color_fill=None,389color_label='black', is_antialiased=True,390is_fill=True, is_widthvalue=True,391arrowshape='left', length_arrowhead=10.0,392headwidthstretch=1.3,393fontsize=32,394valuelabel='',395value_range=None,396is_colorbar=True,397mapscale=1.0):398# ATTENTION: do not change order of args for backwards compatibility399400head_width = headwidthstretch*width_max401fontsize_ticks = int(0.8*fontsize)402403#values = config_values[ids_result]404values_norm = np.array(values, dtype=np.float32)/np.max(values)405406patches = []407displacement = float(width_max)/2.0408if is_widthvalue:409linewidths = width_max*values_norm410else:411linewidths = width_max * np.ones(len(values_norm), np.float32)412413deltaangle_text = -np.pi/2.0414displacement_text = displacement+width_max415416jet = cm_jet = plt.get_cmap('jet')417if value_range is None:418c_norm = colors.Normalize(vmin=0, vmax=np.max(values))419else:420c_norm = colors.Normalize(vmin=value_range[0], vmax=value_range[1])421422# http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots/11558629#11558629423sm = cmx.ScalarMappable(norm=c_norm, cmap=jet)424sm.set_array(values_norm)425for id_connection, value, value_norm, linewidth in zip(ids_connection, values, values_norm, linewidths):426if not np.isnan(value):427shape, angles_perb = get_resultshape_connections(net, id_connection, displacement)428x_vec = np.array(shape)[:, 0]429y_vec = np.array(shape)[:, 1]430deltax = x_vec[-1]-x_vec[0]431deltay = y_vec[-1]-y_vec[0]432if is_fill: # means that fill with value proportional color433color = sm.to_rgba(value)434else:435color = color_fill436437# http://matplotlib.org/users/pyplot_tutorial.html438line = mpl.lines.Line2D(x_vec*mapscale, y_vec*mapscale, color=color,439linewidth=linewidth,440antialiased=is_antialiased,441alpha=alpha,442solid_capstyle='round',443zorder=0,444)445ax.add_line(line)446447if printformat is not '':448angles_text = np.arctan2(deltay, deltax)+deltaangle_text449# print ' angles_text',printformat%value,angles_text/(np.pi)*180,(angles_text>np.pi/2),(angles_text<3*np.pi/2)450if (angles_text > np.pi/2) | (angles_text < -np.pi/2):451angles_text += np.pi452x_label = x_vec[0]+0.66*deltax+displacement_text*np.cos(angles_text)453y_label = y_vec[0]+0.66*deltay+displacement_text*np.sin(angles_text)454455ax.text(x_label*mapscale, y_label*mapscale, printformat % value,456rotation=angles_text/(np.pi)*180,457color=color_label,458fontsize=fontsize_ticks,459zorder=10,460)461462if is_fill & is_colorbar:463cbar = plt.colorbar(sm)464# mpl.setp(cbar.ax.yaxis.get_ticklabels(), fontsize=fontsize)#weight='bold',465# cb.ax.tick_params(labelsize=font_size)466if valuelabel != '':467cbar.ax.set_ylabel(valuelabel, fontsize=fontsize) # , weight="bold")468for l in cbar.ax.yaxis.get_ticklabels():469# l.set_weight("bold")470l.set_fontsize(fontsize_ticks)471472473def plot_edgevalues_arrows(ax, ids_result=None, config_ids_edge=None, values=[],474ids_edge=None, edges=None,475width_max=10.0, alpha=0.8, printformat='%.2f',476color_outline=None, color_fill=None,477color_label='black', is_antialiased=True,478is_fill=True, is_widthvalue=True,479arrowshape='left', length_arrowhead=10.0,480headwidthstretch=1.3,481fontsize=32,482valuelabel='',483value_range=None,484mapscale=1.0):485486# ATTENTION: do not change order of args for backwards compatibility487print 'plot_edgevalues_arrows ids_result width_max', width_max488# print ' ids_result',ids_result489# print ' ids_edge',ids_edge490if ids_edge is None:491edges = config_ids_edge.get_linktab()492ids_edge = config_ids_edge[ids_result]493494head_width = headwidthstretch*width_max495fontsize_ticks = int(0.8*fontsize)496497#values = config_values[ids_result]498values_norm = np.array(values, dtype=np.float32)/np.max(values)499500patches = []501displacement = float(width_max)/4.0502if is_widthvalue:503linewidths = width_max*values_norm504else:505linewidths = width_max * np.ones(len(values_norm), np.float32)506507deltaangle_text = -np.pi/2.0508displacement_text = displacement+width_max509for id_edge, value, value_norm, linewidth in zip(ids_edge, values, values_norm, linewidths):510if not np.isnan(value):511shape, angles_perb = get_resultshape(edges, id_edge, displacement)512x_vec = np.array(shape)[:, 0]513y_vec = np.array(shape)[:, 1]514deltax = x_vec[-1]-x_vec[0]515deltay = y_vec[-1]-y_vec[0]516517if printformat is not '':518angles_text = np.arctan2(deltay, deltax)+deltaangle_text519if (angles_text > np.pi/2) | (angles_text < -np.pi/2):520angles_text += np.pi521x_label = x_vec[0]+0.66*deltax+displacement_text*np.cos(angles_text)522y_label = y_vec[0]+0.66*deltay+displacement_text*np.sin(angles_text)523524ax.text(x_label*mapscale, y_label*mapscale, printformat % value,525rotation=angles_text/(np.pi)*180,526color=color_label,527fontsize=fontsize_ticks,528zorder=10,529)530531if is_widthvalue:532head_width = headwidthstretch*linewidth533arrow = FancyArrow(x_vec[0]*mapscale, y_vec[0]*mapscale, deltax*mapscale, deltay*mapscale, width=linewidth*mapscale,534antialiased=is_antialiased,535edgecolor=color_outline, facecolor=color_fill,536head_width=head_width, head_length=length_arrowhead,537length_includes_head=True,538fill=True, shape=arrowshape, zorder=0)539patches.append(arrow)540541if is_fill:542alpha_patch = alpha543patchcollection = PatchCollection(patches, cmap=mpl.cm.jet, alpha=alpha_patch)544patchcollection.set_array(values)545546# custom value range547if value_range is not None:548patchcollection.set_clim(value_range)549550ax.add_collection(patchcollection)551cbar = plt.colorbar(patchcollection)552if valuelabel != '':553cbar.ax.set_ylabel(valuelabel, fontsize=fontsize) # , weight="bold")554for l in cbar.ax.yaxis.get_ticklabels():555# l.set_weight("bold")556l.set_fontsize(fontsize_ticks)557else:558for patch in patches:559ax.add_patch(patch)560561562def plot_connectionvalues_arrows(ax, ids_result=None, config_ids_edge=None, values=[],563ids_connection=None, connections=None, net=None,564width_max=10.0, alpha=0.8, printformat='%.2f',565color_outline=None, color_fill=None,566color_label='black', is_antialiased=True,567is_fill=True, is_widthvalue=True,568arrowshape='left', length_arrowhead=10.0,569headwidthstretch=1.3,570fontsize=32,571valuelabel='',572value_range=None,573mapscale=1.0):574575# ATTENTION: do not change order of args for backwards compatibility576print 'plot_connectionvalues_arrows ids_result'577578head_width = headwidthstretch*width_max579fontsize_ticks = int(0.8*fontsize)580581#values = config_values[ids_result]582values_norm = np.array(values, dtype=np.float32)/np.max(values)583584patches = []585displacement = float(width_max)/4.0586if is_widthvalue:587linewidths = width_max*values_norm588else:589linewidths = width_max * np.ones(len(values_norm), np.float32)590591deltaangle_text = -np.pi/2.0592displacement_text = displacement+width_max593for id_connection, value, value_norm, linewidth in zip(ids_connection, values, values_norm, linewidths):594if not np.isnan(value):595shape, angles_perb = get_resultshape_connections(net, id_connection, displacement)596x_vec = np.array(shape)[:, 0]597y_vec = np.array(shape)[:, 1]598deltax = x_vec[-1]-x_vec[0]599deltay = y_vec[-1]-y_vec[0]600601if printformat is not '':602angles_text = np.arctan2(deltay, deltax)+deltaangle_text603if (angles_text > np.pi/2) | (angles_text < -np.pi/2):604angles_text += np.pi605x_label = x_vec[0]+0.66*deltax+displacement_text*np.cos(angles_text)606y_label = y_vec[0]+0.66*deltay+displacement_text*np.sin(angles_text)607608ax.text(x_label*mapscale, y_label*mapscale, printformat % value,609rotation=angles_text/(np.pi)*180,610color=color_label,611fontsize=fontsize_ticks,612zorder=10,613)614615if is_widthvalue:616head_width = headwidthstretch*linewidth617arrow = FancyArrow(x_vec[0]*mapscale, y_vec[0]*mapscale, deltax*mapscale, deltay*mapscale, width=linewidth*mapscale,618antialiased=is_antialiased,619edgecolor=color_outline, facecolor=color_fill,620head_width=head_width, head_length=length_arrowhead,621length_includes_head=True,622fill=True, shape=arrowshape, zorder=0)623patches.append(arrow)624625if is_fill:626alpha_patch = alpha627patchcollection = PatchCollection(patches, cmap=mpl.cm.jet, alpha=alpha_patch)628patchcollection.set_array(values)629630# custom value range631if value_range is not None:632patchcollection.set_clim(value_range)633634ax.add_collection(patchcollection)635cbar = plt.colorbar(patchcollection)636if valuelabel != '':637cbar.ax.set_ylabel(valuelabel, fontsize=fontsize) # , weight="bold")638for l in cbar.ax.yaxis.get_ticklabels():639# l.set_weight("bold")640l.set_fontsize(fontsize_ticks)641else:642for patch in patches:643ax.add_patch(patch)644645646def plot_nodevalues(ax, ids_result=None, config_ids_edge=None, values=[],647ids_node=None, nodes=None, net=None,648## width_max = 10.0,649alpha=0.8,650printformat='%.2f',651## color_outline = None,652## color_fill = None,653## color_label = 'black',654## is_antialiased = True,655is_fill=True,656## is_widthvalue = True,657## arrowshape = 'left',658## length_arrowhead = 10.0,659## headwidthstretch = 1.3,660fontsize=32,661valuelabel='',662value_range=None,663mapscale=1.0):664665# ATTENTION: do not change order of args for backwards compatibility666print 'plot_nodevalues ids_result'667fontsize_ticks = int(0.8*fontsize)668669patches = []670for id_node, value, in zip(ids_node, values):671672if not np.isnan(value):673poly = mpl.patches.Polygon(np.transpose(np.stack((np.array(net.nodes.shapes[id_node])[674:][:, 0]*mapscale, np.array(net.nodes.shapes[id_node])[:][:, 1]*mapscale))))675patches.append(poly)676677if is_fill:678alpha_patch = alpha679patchcollection = PatchCollection(patches, cmap=mpl.cm.jet, alpha=alpha_patch)680patchcollection.set_array(values)681682# custom value range683if value_range is not None:684patchcollection.set_clim(value_range)685686ax.add_collection(patchcollection)687cbar = plt.colorbar(patchcollection)688if valuelabel != '':689cbar.ax.set_ylabel(valuelabel, fontsize=fontsize) # , weight="bold")690for l in cbar.ax.yaxis.get_ticklabels():691# l.set_weight("bold")692l.set_fontsize(fontsize_ticks)693else:694for patch in patches:695ax.add_patch(patch)696697698def plot_pointvalues(ax, x_coords, y_coords, values,699net=None,700width_max=10.0,701alpha=0.8,702printformat='%.2f',703## color_outline = None,704## color_fill = None,705## color_label = 'black',706## is_antialiased = True,707is_fill=True,708is_widthvalue=True,709## arrowshape = 'left',710## length_arrowhead = 10.0,711## headwidthstretch = 1.3,712fontsize=32,713valuelabel='',714value_range=None,715mapscale=1.0716):717718# ATTENTION: do not change order of args for backwards compatibility719print 'plot_pointvalues ids_result'720fontsize_ticks = int(0.8*fontsize)721## i = 0722patches = []723for x, y, value in zip(x_coords*mapscale, y_coords*mapscale, values):724725if not np.isnan(value):726if is_widthvalue:727poly = mpl.patches.Circle([x, y], radius=value*width_max/np.max(values)*mapscale, )728else:729poly = mpl.patches.Circle([x, y], radius=width_max*mapscale)730patches.append(poly)731# print i732# i+=1733734if is_fill:735alpha_patch = alpha736patchcollection = PatchCollection(patches, cmap=mpl.cm.jet, alpha=alpha_patch)737patchcollection.set_array(values)738739# custom value range740if value_range is not None:741patchcollection.set_clim(value_range)742743ax.add_collection(patchcollection)744cbar = plt.colorbar(patchcollection)745if valuelabel != '':746cbar.ax.set_ylabel(valuelabel, fontsize=fontsize) # , weight="bold")747for l in cbar.ax.yaxis.get_ticklabels():748# l.set_weight("bold")749l.set_fontsize(fontsize_ticks)750else:751for patch in patches:752ax.add_patch(patch)753754755def get_resultshape(edges, id_edge, dispacement):756"""757Return resultshape coords for this edge.758"""759# print 'get_resultshape',edges,'id_edge',id_edge,'dispacement', dispacement760shape = np.array(edges.shapes[id_edge], np.float32)761n_vert = len(shape)762resultshape = np.zeros(shape.shape, np.float32)763#laneshapes = np.zeros((n_lanes,n_vert,3), np.float32)764angles_perb = get_angles_perpendicular(shape)765if edges.types_spread[id_edge] == 0: # right spread766767resultshape[:, 0] = shape[:, 0] + np.cos(angles_perb) * dispacement768resultshape[:, 1] = shape[:, 1] + np.sin(angles_perb) * dispacement769return resultshape, angles_perb770else:771return shape.copy(), angles_perb772773774def get_resultshape_connections(net, id_connection, dispacement):775"""776Return resultshape coords for this edge.777"""778print 'get_resultshape', 'connections', 'id_connection', id_connection, 'dispacement', dispacement779x0 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_fromlane[id_connection]]][-1, 0]780y0 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_fromlane[id_connection]]][-1, 1]781x1 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_tolane[id_connection]]][0, 0]782y1 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_tolane[id_connection]]][0, 1]783if x0 != x1 or y0 != y1:784shape = np.array([[x0, y0, 0.], [x1, y1, 0.]])785else:786shape = np.array([[x0, y0, 0.], [x1 + 1., y1 + 1., 0.]])787print 'connection', id_connection, 'has no shape'788n_vert = len(shape)789resultshape = np.zeros(shape.shape, np.float32)790#laneshapes = np.zeros((n_lanes,n_vert,3), np.float32)791angles_perb = get_angles_perpendicular(shape)792793return shape.copy(), angles_perb794795796def show_plot():797plt.show()798799800class PlotoptionsMixin:801802def add_plotoptions(self, **kwargs):803"""804[depricated]805These are plotoptions for edge results shown on a map.806"""807attrsman = self.get_attrsman()808self.add_edgeresultoptions(**kwargs)809self.add_networkoptions(**kwargs)810self.add_facilityoptions(**kwargs)811self.add_zoneoptions(**kwargs)812self.add_plotoptions_mapbase(**kwargs)813self.add_plotoptions_base(**kwargs)814815def add_edgeresultoptions(self, **kwargs):816attrsman = self.get_attrsman()817plottypes = ['arrows', 'polygons']818self.plottype = attrsman.add(cm.AttrConf('plottype', kwargs.get('plottype', 'polygons'),819choices=plottypes,820groupnames=['options'],821name='Plot types',822info='Plot type representing the results.',823))824825self.resultwidth = attrsman.add(cm.AttrConf('resultwidth', kwargs.get('resultwidth', 4.0),826groupnames=['options'],827name='Result width',828unit='m',829info='Maximum width of graphical resuls on map.',830))831832self.length_arrowhead = attrsman.add(cm.AttrConf('length_arrowhead', kwargs.get('length_arrowhead', 10.0),833groupnames=['options'],834name='Arrow length',835unit='m',836info='Length of arrowhead on result map.',837))838839self.is_widthvalue = attrsman.add(cm.AttrConf('is_widthvalue', kwargs.get('is_widthvalue', True),840groupnames=['options'],841name='Value width?',842info='If True, the arrow width of the graphical representation is proportional to the result value.',843))844845self.is_colorvalue = attrsman.add(cm.AttrConf('is_colorvalue', kwargs.get('is_colorvalue', True),846groupnames=['options'],847name='Value color?',848info='If True, the arrows of the graphical representation are filled with a colour representing the result value.',849))850851self.is_value_range = attrsman.add(cm.AttrConf('is_value_range', kwargs.get('is_value_range', False),852groupnames=['options'],853name='Manual value range?',854info='If True, value range is set manually, otherwise value range is adjusted according to values.',855))856857self.value_range_min = attrsman.add(cm.AttrConf('value_range_min', kwargs.get('value_range_min', 1.0),858groupnames=['options'],859name='Min. value range',860info='Minimum value range, if manual value range is selected.',861))862863self.value_range_max = attrsman.add(cm.AttrConf('value_range_max', kwargs.get('value_range_max', 40.0),864groupnames=['options'],865name='Max. value range',866info='Maximum value range, if manual value range is selected.',867))868self.color_outline = attrsman.add(cm.AttrConf('color_outline', kwargs.get('color_outline', np.array([0.0, 0.0, 0.0, 0.95], dtype=np.float32)),869groupnames=['options'],870perm='wr',871metatype='color',872name='Outline color',873info='Outline color of result arrows in graphical representation. Only valid if no color-fill is chosen.',874))875876self.color_fill = attrsman.add(cm.AttrConf('color_fill', kwargs.get('color_fill', np.array([0.3, 0.3, 1.0, 0.95], dtype=np.float32)),877groupnames=['options'],878perm='wr',879metatype='color',880name='Fill color',881info='Fill color of result arrows in graphical representation.',882))883884self.valuelabel = attrsman.add(cm.AttrConf('valuelabel', kwargs.get('valuelabel', ''),885groupnames=['options'],886name='Value label',887info='Label of results, as shown in the plot. Leave blank for default values.',888))889890self.alpha_results = attrsman.add(cm.AttrConf('alpha_results', kwargs.get('alpha_results', 0.5),891groupnames=['options'],892name='Result transparency',893info='Transparency of result objects in graphical representation.',894))895896def add_networkoptions(self, **kwargs):897"""898Network plot options899"""900attrsman = self.get_attrsman()901self.is_show_network = attrsman.add(cm.AttrConf('is_show_network', kwargs.get('is_show_network', True),902groupnames=['options', 'network'],903name='Show network',904info='Shows a schematic network in the background.',905))906907self.is_show_connections = attrsman.add(cm.AttrConf('is_show_connections', kwargs.get('is_show_connections', False),908groupnames=['options', 'network'],909name='Show network-connections',910info='Shows connections between edges in the network.',911))912913self.color_network = attrsman.add(cm.AttrConf('color_network', kwargs.get('color_network', np.array([0.8, 0.8, 0.8, 0.8], dtype=np.float32)),914groupnames=['options', 'network'],915perm='wr',916metatype='color',917name='Network color',918info='Outline color of schematic network in the background.',919))920921self.color_nodes = attrsman.add(cm.AttrConf('color_nodes', kwargs.get('color_nodes', np.array([1, 1, 1, 1], dtype=np.float32)),922groupnames=['options', 'network'],923perm='wr',924metatype='color',925name='Nodes color',926info='Color of simplified nodes (or juctions in the background.',927))928self.alpha_net = attrsman.add(cm.AttrConf('alpha_net', kwargs.get('alpha_net', 0.5),929groupnames=['options', 'network'],930name='Net transparency',931info='Transparency of network (edges and nodes) in graphical representation.',932))933self.is_show_maps = attrsman.add(cm.AttrConf('is_show_maps', kwargs.get('is_show_maps', False),934groupnames=['options', 'network'],935name='Show map?',936info='If True, shows map as background in graphical representation. This feature requires that maps have been previously downloaded.',937))938939self.alpha_maps = attrsman.add(cm.AttrConf('alpha_maps', kwargs.get('alpha_maps', 0.5),940groupnames=['options', 'network'],941name='Map transparency',942info='Transparency of background maps in graphical representation.',943))944945def add_facilityoptions(self, **kwargs):946attrsman = self.get_attrsman()947self.is_show_facilities = attrsman.add(cm.AttrConf('is_show_facilities', kwargs.get('is_show_facilities', False),948groupnames=['options', 'facilities'],949name='Show facilities',950info='Shows a schematic facilities (buildings, parks, etc.) in the background.',951))952953self.color_facilities = attrsman.add(cm.AttrConf('color_facilities', kwargs.get('color_facilities', np.array([1, 1, 1, 1], dtype=np.float32)),954groupnames=['options', 'facilities'],955perm='wr',956metatype='color',957name='Facilities color',958info='Color of schematic facilities in the background.',959))960961self.alpha_facilities = attrsman.add(cm.AttrConf('alpha_facilities', kwargs.get('alpha_facilities', 0.5),962groupnames=['options', 'facilities'],963name='Facility transparency',964info='Transparency of facilities in graphical representation.',965))966967self.color_borders = attrsman.add(cm.AttrConf('color_borders', kwargs.get('color_borders', np.array([0.7, 0.7, 0.7, 0.8], dtype=np.float32)),968groupnames=['options', 'facilities'],969perm='wr',970metatype='color',971name='Facility border color',972info='Facility border (or building walls) color of schematic facilities in the background.',973))974975def add_zoneoptions(self, **kwargs):976attrsman = self.get_attrsman()977self.is_show_zones = attrsman.add(cm.AttrConf('is_show_zones', kwargs.get('is_show_zones', False),978groupnames=['options', 'zones'],979name='Show Zones',980info='Show zone polygons.',981))982983self.color_zones = attrsman.add(cm.AttrConf('color_zones', kwargs.get('color_zones', np.array([0.2, 0.8, 0.2, 1.0], dtype=np.float32)),984groupnames=['options', 'zones'],985perm='wr',986metatype='color',987name='Zone color',988info='Fill color of Zone.',989))990991self.alpha_zones = attrsman.add(cm.AttrConf('alpha_zones', kwargs.get('alpha_zones', 0.1),992groupnames=['options', 'zones'],993name='Zone transparency',994info='Transparency of color of zones.',995))996997self.color_zoneborders = attrsman.add(cm.AttrConf('color_zoneborders', kwargs.get('color_zoneborders', np.array([0.0, 0.7, 0.0, 1.0], dtype=np.float32)),998groupnames=['options', 'zones'],999perm='wr',1000metatype='color',1001name='Zone border color',1002info='Color of zone border.',1003))10041005def add_plotoptions_lineplot(self, is_marker_only=False, **kwargs):1006"""1007These are plotoptions for y over x oriented graphs.1008"""1009attrsman = self.get_attrsman()10101011if not is_marker_only:1012self.color_line = attrsman.add(cm.AttrConf('color_line', kwargs.get('color_line', np.array([1, 0, 0, 1], dtype=np.float32)),1013groupnames=['options'],1014perm='wr',1015metatype='color',1016name='Line color',1017info='Color of line in various diagrams.',1018))10191020self.width_line = attrsman.add(cm.AttrConf('width_line', kwargs.get('width_line', 2),1021groupnames=['options'],1022perm='wr',1023name='Line width',1024info='Width of plotted lines.',1025))10261027self.style_line = attrsman.add(cm.AttrConf('style_line', kwargs.get('style_line', '-'),1028choices=LINESTYLES,1029groupnames=['options'],1030name='Line Style',1031info='Line styles used for plots.',1032))10331034self.alpha_line = attrsman.add(cm.AttrConf('alpha_line', kwargs.get('alpha_line', 0.9),1035groupnames=['options'],1036name='Line transparency',1037info='Line transparency used for plots.',1038))10391040if is_marker_only:1041style_marker_default = 'o'1042else:1043style_marker_default = 'o'10441045self.style_marker = attrsman.add(cm.AttrConf('style_marker', kwargs.get('style_marker', style_marker_default),1046choices=MARKERSTYLES,1047groupnames=['options'],1048name='Marker Style',1049info='Marker style used for plots.',1050))10511052self.color_marker = attrsman.add(cm.AttrConf('color_marker', kwargs.get('color_marker', np.array([0, 0, 1, 1], dtype=np.float32)),1053groupnames=['options'],1054perm='wr',1055metatype='color',1056name='Marker color',1057info='Color of marker in plot.',1058))10591060self.size_marker = attrsman.add(cm.AttrConf('size_marker', kwargs.get('size_marker', 16),1061groupnames=['options'],1062perm='wr',1063name='Marker size',1064info='Size of marker in plot.',1065))10661067self.xlabel = attrsman.add(cm.AttrConf('xlabel', kwargs.get('xlabel', ''),1068groupnames=['options'],1069name='X label',1070info='X-axis label text, if blank then default values are used.',1071))10721073self.ylabel = attrsman.add(cm.AttrConf('ylabel', kwargs.get('ylabel', ''),1074groupnames=['options'],1075name='Y label',1076info='Y-axis label text, if blank then default values are used.',1077))1078self.add_plotoptions_base(**kwargs)10791080def add_plotoptions_mapbase(self, **kwargs):1081"""1082These are all necessary option to plot whatever on a map.1083"""1084attrsman = self.get_attrsman()1085self.unit_mapscale = attrsman.add(cm.AttrConf('unit_mapscale', kwargs.get('unit_mapscale', 'm'),1086groupnames=['options', 'network'],1087choices=['m', 'km'],1088mapscales={'m': 1.0, 'km': 0.001},1089name='Unit',1090info='Unit used for map.',1091))10921093def add_plotoptions_base(self, **kwargs):1094attrsman = self.get_attrsman()1095self.axis = None1096self.color_background = attrsman.add(cm.AttrConf('color_background', kwargs.get('color_background', np.array([1, 1, 1, 1], dtype=np.float32)),1097groupnames=['options'],1098perm='wr',1099metatype='color',1100name='Background color',1101info='Background color of schematic network in the background.',1102))11031104self.is_grid = attrsman.add(cm.AttrConf('is_grid', kwargs.get('is_grid', False),1105groupnames=['options'],1106name='Show grid?',1107info='If True, shows a grid on the graphical representation.',1108))11091110self.is_show_title = attrsman.add(cm.AttrConf('is_show_title', kwargs.get('is_show_title', True),1111groupnames=['options'],1112name='Show title',1113info='Shows title on top of figure.',1114))11151116self.title = attrsman.add(cm.AttrConf('title', kwargs.get('title', ''),1117groupnames=['options'],1118name='Title',1119info='Title text, if blank then default values are used.',1120))11211122self.size_titlefont = attrsman.add(cm.AttrConf('size_titlefont', kwargs.get('size_titlefont', 16),1123groupnames=['options'],1124name='Title fontsize',1125info='Title fontsize.',1126))11271128self.size_labelfont = attrsman.add(cm.AttrConf('size_labelfont', kwargs.get('size_labelfont', 14),1129groupnames=['options'],1130name='Label fontsize',1131info='Label fontsize.',1132))11331134self.printformat = attrsman.add(cm.AttrConf('printformat', kwargs.get('printformat', ''),1135choices=OrderedDict([1136('Show no values', ''),1137('x', '%.d'),1138('x.x', '%.1f'),1139('x.xx', '%.2f'),1140('x.xxx', '%.3f'),1141('x.xxxx', '%.4f'),1142]),1143groupnames=['options'],1144name='Label formatting',1145info='Print formatting of value label in graphical representation.',1146))11471148self.color_label = attrsman.add(cm.AttrConf('color_label', kwargs.get('color_label', np.array([0, 0, 0, 1], dtype=np.float32)),1149groupnames=['options'],1150perm='wr',1151metatype='color',1152name='Label color',1153info='Color of value label in graphical representation.',1154))11551156def add_save_options(self, **kwargs):11571158attrsman = self.get_attrsman()1159self.is_save = attrsman.add(cm.AttrConf('is_save', kwargs.get('is_save', False),1160groupnames=['options'],1161name='Save plots',1162info='If true, save plots instead of showing on screen.',1163))11641165self.figformat = attrsman.add(cm.AttrConf('figformat', kwargs.get('figformat', 'png'),1166groupnames=['options'],1167choices=['png', 'pdf', 'jpg', 'svg'],1168name='Graphics format',1169info='Format of saved graphic.',1170))1171self.resolution = attrsman.add(cm.AttrConf('resolution', kwargs.get('resolution', 300),1172groupnames=['options'],1173name='Resolution',1174unit='dpi',1175info='Resolution of saved graphic in dots per inch (dpi).',1176))1177self.figwidth = attrsman.add(cm.AttrConf('figwidth', kwargs.get('figwidth', 40.0),1178groupnames=['options'],1179name='Figure width',1180unit='cm',1181info='Figure width.',1182))1183self.figheight = attrsman.add(cm.AttrConf('figheight', kwargs.get('figheight', 30.0),1184groupnames=['options'],1185name='Figure height',1186unit='cm',1187info='Figure height.',1188))11891190def get_scenario(self):1191return self.parent.get_scenario()11921193def init_figures(self):1194self._i_fig = 01195plt.close("all")11961197def create_figure(self):1198self._i_fig += 11199fig = plt.figure(self._i_fig,1200# dpi=self.resolution,#this may cause huge windows in interactive mode1201tight_layout=True,1202figsize=(self.figwidth*0.393701, self.figheight*0.393701)1203)1204return fig12051206def _autolabel_bars(self, ax, bars, labels):1207"""1208Helperfunction: Attach a text label above each bar displaying its height1209"""1210for rect, label in zip(bars, labels):1211height = rect.get_height()1212if not np.isnan(height):1213ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,1214'%s' % label,1215ha='center', va='bottom',1216fontsize=int(0.8*self.size_labelfont),1217)12181219def do(self):1220""""This method calls the show method which should be overriden1221by to execute class specific plot actions."""1222# print 'do',self.edgeattrname1223self.show()1224return True12251226def set_figmargins(self):1227plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)12281229def save_fig(self, figname):12301231rootfilepath = self.get_scenario().get_rootfilepath()1232filepath = "%s_%s.%s" % (rootfilepath, figname, self.figformat)1233print 'save_fig', filepath1234plt.savefig(filepath, format=self.figformat,1235dpi=self.resolution,1236# orientation='landscape',1237orientation='portrait',1238transparent=True)12391240def get_edgeresults(self):1241"""1242Returns table with results which must have the attribute 'ids_edge'1243"""1244return self.parent.edgeresults12451246def set_axisborder(self, ax):1247ax.spines['top'].set_visible(False)1248ax.spines['right'].set_visible(False)1249ax.spines['bottom'].set_linewidth(0.5)1250ax.spines['left'].set_linewidth(0.5)12511252def plot_hist(self, ax, x, bins=None, range=None,1253color='blue', facecolor=None,1254alpha=0.75, label=None,1255histtype='step', # {'bar', 'barstacked', 'step', 'stepfilled'}1256is_normed=True,1257is_cumulative=True,1258is_show_mean=True,1259is_show_std=False,1260is_rel_frequ=False,1261is_percent=False,1262):12631264# the histogram of the data1265# print 'plot_hist',bins,range1266if bins is None:1267bins = self.n_bins12681269if color is None:1270color = self.color_line12711272if is_rel_frequ:1273is_cumulative = False1274is_normed = False1275weights = np.zeros_like(x) + 1. / x.size1276else:1277weights = np.zeros_like(x) + 1.12781279if is_percent:1280weights *= 10012811282n, bins0, patches = ax.hist(x, bins, range=range,1283normed=is_normed,1284cumulative=is_cumulative,1285histtype=histtype,1286linewidth=self.width_line,1287color=color, facecolor=facecolor,1288alpha=alpha, label=label,1289weights=weights,1290)12911292mean = np.mean(x)1293std = np.std(x)1294y_min, y_max = ax.get_ylim()1295x_min = np.min(x)1296x_max = np.max(x)1297dy = 0.05*(y_max-y_min)1298dx = 0.05*(x_max-x_min)1299if is_show_mean:1300ax.plot([mean, mean], [y_min, y_max], color=color, linestyle='-.', linewidth=2*self.width_line)1301# very good: https://matplotlib.org/users/text_intro.html1302# ax.text(3, 8, 'boxed italics text in data coords', style='italic',1303# bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})1304# ax.annotate(r'$\mu=%.2f$'%mean, xy=(mean, y_max-dy),1305# xytext=(mean-dx, y_max-2*dy),1306# fontsize=int(0.8*self.size_labelfont),1307# arrowprops=dict(facecolor='black', shrink=0.05)1308# )13091310if is_show_std:1311ax.plot([mean-std, mean-std], [y_min, y_max], color=color, linestyle='--', linewidth=self.width_line)1312ax.plot([mean+std, mean+std], [y_min, y_max], color=color, linestyle='--', linewidth=self.width_line)13131314# hist uses np.histogram under the hood to create 'n' and 'bins'.1315# np.histogram returns the bin edges, so there will be 50 probability1316# density values in n, 51 bin edges in bins and 50 patches. To get1317# everything lined up, we'll compute the bin centers1318bincenters = 0.5*(bins0[1:]+bins0[:-1])1319return bincenters13201321def plot_results_on_map(self, axis, ids_edgeres=None, values=[],1322ids_edge=None,1323title='', valuelabel='',1324is_connection_results=False, ids_connectionres=None, ids_connection=None):13251326# axis, ids, resultattrconf[ids] , title, valuelabel = resultattrconf.format_symbol()13271328if self.valuelabel != "":1329valuelabel = self.valuelabel13301331if is_connection_results:1332if ids_connection is None:1333ids_connection = self.get_connectionresults().ids_connection[ids_connectionres]1334else:1335if ids_edge is None:1336ids_edge = self.get_edgeresults().ids_edge[ids_edgeres]13371338net = self.get_scenario().net13391340unit = self.unit_mapscale1341mapscale = self.get_attrsman().get_config('unit_mapscale').mapscales[unit]1342# print ' unit',unit1343# print ' mapscale',mapscale1344#xticks =axis.get_xticks()1345#yticks =axis.get_yticks()1346# print 'xticks',xticks1347# print 'yticks',yticks1348self.plot_net(axis, mapscale=mapscale, unit=unit, is_configure=False)13491350if self.is_value_range:1351value_range = (self.value_range_min, self.value_range_max)1352else:1353value_range = None13541355if is_connection_results:1356if self.plottype == 'arrows': # = ['Arrows','Polygons']1357plot_connectionvalues_arrows(axis,1358# ids,1359# edgesresults.ids_edge,1360ids_connection=ids_connection,1361values=values,1362connections=net.connections,1363net=net,1364width_max=self.resultwidth,1365alpha=self.alpha_results,1366printformat=self.printformat,1367color_outline=self.color_outline,1368color_fill=self.color_fill,1369color_label=self.color_label,1370is_antialiased=True,1371is_fill=self.is_colorvalue,1372is_widthvalue=self.is_widthvalue,1373length_arrowhead=self.length_arrowhead,1374fontsize=self.size_labelfont,1375valuelabel=valuelabel,1376value_range=value_range,1377mapscale=mapscale)1378elif self.plottype == 'polygons':1379plot_connectionvalues_lines(axis,1380# ids,1381# edgesresults.ids_edge,1382ids_connection=ids_connection,1383values=values,1384connections=net.connections,1385net=net,1386width_max=self.resultwidth,1387alpha=self.alpha_results,1388printformat=self.printformat,1389color_outline=self.color_outline,1390color_fill=self.color_fill,1391color_label=self.color_label,1392is_antialiased=True,1393is_fill=self.is_colorvalue,1394is_widthvalue=self.is_widthvalue,1395length_arrowhead=self.length_arrowhead,1396fontsize=self.size_labelfont,1397valuelabel=valuelabel,1398value_range=value_range,1399mapscale=mapscale)1400else:1401if len(ids_edge) > 0:1402if self.plottype == 'arrows': # = ['Arrows','Polygons']1403plot_edgevalues_arrows(axis,1404# ids,1405# edgesresults.ids_edge,1406ids_edge=ids_edge,1407values=values,1408edges=net.edges,1409width_max=self.resultwidth,1410alpha=self.alpha_results,1411printformat=self.printformat,1412color_outline=self.color_outline,1413color_fill=self.color_fill,1414color_label=self.color_label,1415is_antialiased=True,1416is_fill=self.is_colorvalue,1417is_widthvalue=self.is_widthvalue,1418length_arrowhead=self.length_arrowhead,1419fontsize=self.size_labelfont,1420valuelabel=valuelabel,1421value_range=value_range,1422mapscale=mapscale)1423elif self.plottype == 'polygons':1424plot_edgevalues_lines(axis,1425# ids,1426# edgesresults.ids_edge,1427ids_edge=ids_edge,1428values=values,1429edges=net.edges,1430width_max=self.resultwidth,1431alpha=self.alpha_results,1432printformat=self.printformat,1433color_outline=self.color_outline,1434color_fill=self.color_fill,1435color_label=self.color_label,1436is_antialiased=True,1437is_fill=self.is_colorvalue,1438is_widthvalue=self.is_widthvalue,1439length_arrowhead=self.length_arrowhead,1440fontsize=self.size_labelfont,1441valuelabel=valuelabel,1442value_range=value_range,1443mapscale=mapscale)14441445self.configure_map(axis, title, unit=unit)14461447def configure_map(self, axis, title=None, unit='m'):14481449if self.is_show_title:1450if self.title != "":1451title = self.title14521453axis.set_title(title, fontsize=self.size_titlefont)14541455axis.axis('equal')1456# ax.legend(loc='best',shadow=True)14571458axis.grid(self.is_grid)1459axis.set_xlabel('West-East ['+unit+']', fontsize=self.size_labelfont)1460axis.set_ylabel('South-North ['+unit+']', fontsize=self.size_labelfont)1461axis.tick_params(axis='x', labelsize=int(0.8*self.size_labelfont))1462axis.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))14631464# get borders right, this seems to work1465plt.subplots_adjust(left=0.12, bottom=0.1, right=0.86, top=0.9, wspace=0.2, hspace=0.2)14661467# show_plot()14681469#x_min,y_min,x_max,y_max = net.get_boundaries(is_netboundaries = True)1470# axis.set_autoscaley_on(False)1471# axis.set_xlim([x_min,x_max])1472# axis.set_ylim([y_min,y_max])14731474def plot_net(self, axis=None, title="", unit='', mapscale=None, is_configure=True):1475print 'plot_net mapscale', mapscale1476if mapscale is None:1477unit = self.unit_mapscale1478mapscale = self.get_attrsman().get_config('unit_mapscale').mapscales[unit]14791480if axis is None:1481axis = init_plot()14821483if hasattr(self, 'is_show_network'):1484if self.is_show_network:1485net = self.get_scenario().net1486plot_net(axis, net, color_edge=self.color_network, width_edge=2,1487color_node=self.color_nodes, alpha=self.alpha_net, is_show_connections=self.is_show_connections, mapscale=mapscale)14881489if hasattr(self, 'is_show_facilities'):1490if self.is_show_facilities:1491facilities = self.get_scenario().landuse.facilities1492plot_facilities(axis, facilities, color_building=self.color_facilities,1493color_outline=self.color_borders,1494width_line=2, alpha=self.alpha_facilities,1495mapscale=mapscale)1496if hasattr(self, 'is_show_maps'):1497if self.is_show_maps:1498plot_maps(axis, self.get_scenario().landuse.maps, alpha=self.alpha_maps, mapscale=mapscale)14991500if hasattr(self, 'is_show_zones'):1501if self.is_show_zones:1502zones = self.get_scenario().landuse.zones1503plot_zones(axis, zones, color_zone=self.color_zones,1504color_outline=self.color_zoneborders,1505width_line=2, alpha=self.alpha_zones,1506mapscale=mapscale)1507if is_configure:1508self.configure_map(axis, title=title, unit=unit)15091510def plot_node_results_on_map(self, axis, ids_noderes=None, values=[],1511ids_node=None,1512title='', valuelabel='',1513is_node_results=False, ):15141515if ids_node is None:1516ids_node = self.get_noderesults().ids_node[ids_noderes]15171518net = self.get_scenario().net15191520unit = self.unit_mapscale1521mapscale = self.get_attrsman().get_config('unit_mapscale').mapscales[unit]1522self.plot_net(axis, mapscale=mapscale, unit=unit, is_configure=False)15231524if self.is_value_range:1525value_range = (self.value_range_min, self.value_range_max)1526else:1527value_range = None15281529if is_node_results:1530plot_nodevalues(axis,1531# ids,1532# edgesresults.ids_edge,1533ids_node=ids_node,1534values=values,1535nodes=net.nodes,1536## width_max = self.resultwidth,1537alpha=self.alpha_results,1538## printformat = self.printformat,1539## color_outline = self.color_outline,1540## color_fill = self.color_fill,1541## color_label = self.color_label,1542## is_antialiased = True,1543is_fill=self.is_colorvalue,1544## is_widthvalue = self.is_widthvalue,1545## length_arrowhead = self.length_arrowhead,1546fontsize=self.size_labelfont,1547valuelabel=valuelabel,1548value_range=value_range,1549net=net1550)15511552self.configure_map(axis, title, unit=unit)15531554def plot_point_results_on_map(self, net, axis, x_coords, y_coords, values=[],1555title='', valuelabel='',1556):15571558unit = self.unit_mapscale1559mapscale = self.get_attrsman().get_config('unit_mapscale').mapscales[unit]1560self.plot_net(axis, mapscale=mapscale, unit=unit, is_configure=False)15611562if self.is_value_range:1563value_range = (self.value_range_min, self.value_range_max)1564else:1565value_range = None15661567plot_pointvalues(axis,1568# ids,1569# edgesresults.ids_edge,1570x_coords=x_coords,1571y_coords=y_coords,1572values=values,1573width_max=self.resultwidth,1574alpha=self.alpha_results,1575## printformat = self.printformat,1576## color_outline = self.color_outline,1577## color_fill = self.color_fill,1578## color_label = self.color_label,1579## is_antialiased = True,1580is_fill=self.is_colorvalue,1581is_widthvalue=self.is_widthvalue,1582## length_arrowhead = self.length_arrowhead,1583fontsize=self.size_labelfont,1584valuelabel=valuelabel,1585value_range=value_range,1586net=net1587)15881589self.configure_map(axis, title, unit=unit)159015911592