tvaLib
Classes | Functions | Variables
lib.vis Namespace Reference

Classes

class  Analysis
 Analysis. More...
 
class  basicPlot
 
class  DrawOther
 Other. More...
 
class  interactionTimeseries
 
class  overheadPlot
 
class  SpeedHistograms
 
class  trajSample
 Trajectory. More...
 
class  visualiseOD
 

Functions

def show ()
 Visualisation library. More...
 
def plotSettings (style='', size=16, weight='normal', family='Arial', tickLabelSize=None, tickLength=4, verbose=0)
 
def close (fig='all')
 
def Save (figures, results_path='', fig_dpi=300, fig_format='png', fig_lan_suffix='', supressClose=False, fig_resize=None, fig_bg_colour='', verbose=0)
 
def plots (X, Y, legend_labels=None, colours=['b', r, g, orange, k, m, y, linewidths=[1], linestyles=['-'], markers=[''], x_bounds=None, y_bounds=None, x_label='', y_label='', local=None, fig_name='Generic plots', figsize=[15.0)
 
def Histo (data, enableBars=True, dist_type='freq', enableHalfStepOffset=True, halfStepSign=1, legendLabels='', linewidth=2, spacing_modifier=1, x_bounds=None, y_bounds=None, x_label='', y_label='', force_one_label_per_bar=False, local=None, fig_name='Generic histogram', figsize=[15.0)
 
def plotWithArrows (x, y, aspace=5, color='b', alpha=1.0, zorder=1, kwargs)
 
def BoxPlotSeries (data, x_label='', y_label='', x_tick_labels=None, y_bounds=None, y_logScale=False, orderByMedian=False, colour=None, sperator_position=None, local=None, fig_name='Generic boxplot', figsize=[15.0, verbose=0)
 
def Scatter (pointList, alignments=False, mask=False, labels=False, local=None, fig_name='Generic scatter', verbose=0, figsize=[15.0)
 
def Map (pointList, colour='hot', xy_bounds=None, gridsize=[60, mincnt=1, sm_scale=None, alignments=False, mask=False, labels=False, local=None, fig_name='Generic Map', verbose=0, figsize=[15.0, full_plot=True)
 
def plotBB (bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, kwargs)
 
def plotSDR (SDR, local=None, outlineOnly=False, alpha=1.00, zorder=1, sdr_bgcolour='0.66', kwargs)
 
def plotVL (virtual_loops, labels=False, colour='#D63E33')
 
def plotAlign (alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None)
 
def plotSatellite (sateliteImage, sateliteResolution, color=False, zorder=0, origin=[0, zoomTo=False)
 
def plotImageWorldSpace (imagePath, scale=1.0, zorder=0, origin=[0)
 
def annotate (text, x=None, y=None, target='bottom-right')
 
def scatterInBins (lists, bins)
 
def pointList2DHisto (data, bins=[60)
 
def traj2D (objects, draw_max_traj=200, xy_bounds=None, alignments=None, draw_connectors=True, mask=None, zone=None, SDR=None, virtual_loops=None, sateliteImage=None, sateliteResolution=None, labels=False, labels_overlap=True, timeStampLabels=False, objects_uncon=None, velocity_vector=False, local=None, constantFramerate=15.0, mps_kmh=3.6, traj_colour='b', traj_colour_alternate='', sm_scale=50, cm_colour='hot', alignAlpha=1.0, fig_name='Vehicle Trajectories', figsize=[15.0, plotSettings=None, kwargs)
 
def traj2DHighlightAlignments (objects, xy_bounds, alignments, marker_size=0.4, labels=True, local=None, fig_name='Trajectory Lane Highlight', figsize=[15.0, plotSettings=None, kwargs)
 
def visTrajImageSpace (objects=None, image='', homography=None, labels=False, start=0, draw_max_traj=200, mask=None, local=None, fig_name='Vehicle Trajectories in Image Space', traj_colour='b', alpha=1.0, figsize=[15.0, kwargs)
 
def traj3D (objects, start=0, draw_max_traj=200, draw_connectors=True, xy_bounds=None, alignments=None, mask=None, labels=False, timeStampLabels=False, local=None, fig_name='Vehicle Trajectories 3D', traj_colour='b', figsize=[15.0)
 
def plotGeometry (alignments, sateliteImage, sateliteResolution, xy_bounds=None, draw_connectors=True, mask=None, zone=None, virtual_loops=None, labels=False, local=None, fig_name='Geometry', figsize=[15.0, plotSettings=None, kwargs)
 
def hourlyFlows (flows_curve_list, speed_data=None, speed_data_stds=None, sm_scale=None, local=None, tickFrequency=4, fig_name='Hourly flows', figsize=[15.0)
 Flows. More...
 
def microTrafficIntensity (objects, startTime, endTime, framerate, local=None, window_s=20.0, maxBins=1000, fig_name='Traffic Intensity', figsize=[15.0, plotSettings=None, kwargs)
 
def speedMap (objects, ptype='heat', sm_scale=None, colour='hot', xy_bounds=None, gridsize=[60, arrowGridReductionFactor=0.3, mincnt=10, virtualLoops=False, zone=False, alignments=False, local=None, fig_name='Speed Heat Map', figsize=[15.0, constantFramerate=15.0, mps_kmh=3.6, duration=0)
 Speed. More...
 
def speedHist (speed_histos, labels='', plotPDF=True, sm_scale=80, enableBars=True, color='k', linestyle='', linewidth=5, minObservations=10, local=None, fig_name='Speed Distribution', figsize=[15.0)
 
def interactionMap (pointColumnList, ptype='hexbin', colour='hot', weightedDensity=False, xy_bounds=None, z_bounds=None, gridsize=[60, minGridSize=1.0, mincnt=1, alignments=False, mask=False, zone=False, labels=False, local=None, zlabel='', fig_name='CP Map', indent=4, verbose=0, figsize=[15.0, plotSettings=None, kwargs)
 Interactions. More...
 
def interactionTTCHist (ttc_histos, fps=15.0, timehorizon=5.0, enableBars=True, linewidth=5, dist_type='pdf', labels=False, label_ratio='', local=None, fig_name='TTC pdf', verbose=0, figsize=[15.0)
 
def visAlignData (sl, slsd, hl_offset=False, local=None, min_obs=10, fig_name='Alignment data', figsize=[15.0, plotSettings=None)
 Alignments. More...
 

Variables

 legend_labels
 

Function Documentation

◆ annotate()

def lib.vis.annotate (   text,
  x = None,
  y = None,
  target = 'bottom-right' 
)
Plot generic text annotation, where x and y denote a fraction of the
    figure if less than 0. 

Definition at line 580 of file vis.py.

580 def annotate(text, x=None, y=None, target='bottom-right'):
581  ''' Plot generic text annotation, where x and y denote a fraction of the
582  figure if less than 0. '''
583  #Pull current axes information
584  ax = plb.gca()
585  if(target=='top-right'):
586  if(not x): x_ = (ax.get_xlim()[1]-ax.get_xlim()[0])*0.95 + ax.get_xlim()[0]
587  elif(x < 1 and y < 1): x_ = (ax.get_xlim()[1]-ax.get_xlim()[0])*x + ax.get_xlim()[0]
588  else: x_ = x
589  if(not y): y_ = (ax.get_ylim()[1]-ax.get_ylim()[0])*0.95 + ax.get_ylim()[0]
590  elif(x < 1 and y < 1): y_ = (ax.get_ylim()[1]-ax.get_ylim()[0])*y + ax.get_ylim()[0]
591  else: y_ = y
592  ha='right'
593  va='bottom'
594  else:
595  if(not x): x_ = (ax.get_xlim()[1]-ax.get_xlim()[0])*0.95 + ax.get_xlim()[0]
596  elif(x < 1 and y < 1): x_ = (ax.get_xlim()[1]-ax.get_xlim()[0])*x + ax.get_xlim()[0]
597  else: x_ = x
598  if(not y): y_ = (ax.get_ylim()[1]-ax.get_ylim()[0])*0.05 + ax.get_ylim()[0]
599  elif(x < 1 and y < 1): y_ = (ax.get_ylim()[1]-ax.get_ylim()[0])*y + ax.get_ylim()[0]
600  else: y_ = y
601  ha='right'
602  va='bottom'
603  plt.annotate(text, xy=(x_,y_), textcoords='offset points', ha=ha, va=va, bbox=dict(boxstyle='Square,pad=0.5', fc='white', alpha=0.5))
604 
605  return True
606 
def annotate(text, x=None, y=None, target='bottom-right')
Definition: vis.py:580

◆ BoxPlotSeries()

def lib.vis.BoxPlotSeries (   data,
  x_label = '',
  y_label = '',
  x_tick_labels = None,
  y_bounds = None,
  y_logScale = False,
  orderByMedian = False,
  colour = None,
  sperator_position = None,
  local = None,
  fig_name = 'Generic boxplot',
  figsize = [15.0,
  verbose = 0 
)
Plot generic Boxplot series. Useful for generating quartiles by
    sequence or site.

    Input:
    ======
    data:              a list of data arrays.
    orderByMedian:     'ascending' (default) | 'descending'
    x_tick_labels:     should be same 0-order dimension as data
    colour:            should be same 0-order dimension as data
    sperator_position: should be an integer index (starting at 0) AFTER which to add a vertical separator, or none to disable

Definition at line 276 of file vis.py.

276 def BoxPlotSeries(data, x_label='', y_label='', x_tick_labels=None, y_bounds=None, y_logScale=False, orderByMedian=False, colour=None, sperator_position=None, local=None, fig_name='Generic boxplot', figsize=[15.0,12.0], verbose=0):
277  ''' Plot generic Boxplot series. Useful for generating quartiles by
278  sequence or site.
279 
280  Input:
281  ======
282  data: a list of data arrays.
283  orderByMedian: 'ascending' (default) | 'descending'
284  x_tick_labels: should be same 0-order dimension as data
285  colour: should be same 0-order dimension as data
286  sperator_position: should be an integer index (starting at 0) AFTER which to add a vertical separator, or none to disable
287  '''
288 
289  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
290  if(not local): local = tvaLocal.Local()
291  if(len(data) != len(x_tick_labels) or len(data) == 0): return False
292  if(colour and len(data) != len(colour)): return False
293 
294  # Enable multiplotting
295  if(type(data[0]) is not list): data = [data]
296 
297 
298  if(orderByMedian):
299  medians=[]
300  for dat in data:
301  medians.append(sorted(dat)[len(dat)/2])
302 
303  if(orderByMedian=='descending'):
304  data = [x for (y,x) in sorted(zip(medians,data),reverse=True)]
305  x_tick_labels = [x for (y,x) in sorted(zip(medians,x_tick_labels),reverse=True)]
306  if(colour):
307  colour = [x for (y,x) in sorted(zip(medians,colour),reverse=True)]
308  else:
309  data = [x for (y,x) in sorted(zip(medians,data))]
310  x_tick_labels = [x for (y,x) in sorted(zip(medians,x_tick_labels))]
311  if(colour):
312  colour = [x for (y,x) in sorted(zip(medians,colour))]
313 
314 
315  bp = plb.boxplot(data, patch_artist=True)
316 
317 
318  if(colour):
319  for Ix in range(len(data)):
320  bp['boxes'][Ix].set(color=colour[Ix], linewidth=1)
321  bp['whiskers'][Ix*2].set(color=colour[Ix], linewidth=1)
322  bp['whiskers'][Ix*2+1].set(color=colour[Ix], linewidth=1)
323  bp['caps'][Ix*2].set(color=colour[Ix], linewidth=1)
324  bp['caps'][Ix*2+1].set(color=colour[Ix], linewidth=1)
325  if(colour[Ix]=='r'): bp['medians'][Ix].set(color='k', linewidth=1)
326 
327 
328  if(sperator_position):
329  plt.axvline(x=sperator_position+1.5, linewidth=2, color='k')
330 
331 
332  if(verbose >= 4):
333  print 'BoxPlot data for '+fig_name
334  print 'Label,25%,Median,75%'
335  for i in range(len(data)):
336  try: print str(x_tick_labels[i])+','+str(min(bp['boxes'][i].get_ydata()))+','+str(bp['medians'][i].get_ydata()[0])+','+str(max(bp['boxes'][i].get_ydata()))
337  except: print str(x_tick_labels[i])+','
338 
339 
340  ax = plb.gca()
341  if(x_label): ax.set_xlabel(x_label)
342  if(y_label): ax.set_ylabel(y_label)
343  if(y_bounds and type(y_bounds) == list): ax.set_ylim(y_bounds)
344  if(y_logScale): ax.set_yscale('log')
345  if(x_tick_labels and type(x_tick_labels) == list):
346  plt.xticks(range(1,len(data)+1), x_tick_labels, rotation=70, ha='right')
347  if(len(data) > 5):
348  for tick in ax.xaxis.get_major_ticks():
349  tick.label.set_fontsize(int(tick.label.get_fontsize()/2.0))
350  return fig
351 
352 
353 
def BoxPlotSeries(data, x_label='', y_label='', x_tick_labels=None, y_bounds=None, y_logScale=False, orderByMedian=False, colour=None, sperator_position=None, local=None, fig_name='Generic boxplot', figsize=[15.0, verbose=0)
Definition: vis.py:276

◆ close()

def lib.vis.close (   fig = 'all')

Definition at line 71 of file vis.py.

71 def close(fig='all'):
72  plt.close(fig)
73  return True
74 
75 
76 
def close(fig='all')
Definition: vis.py:71

◆ Histo()

def lib.vis.Histo (   data,
  enableBars = True,
  dist_type = 'freq',
  enableHalfStepOffset = True,
  halfStepSign = 1,
  legendLabels = '',
  linewidth = 2,
  spacing_modifier = 1,
  x_bounds = None,
  y_bounds = None,
  x_label = '',
  y_label = '',
  force_one_label_per_bar = False,
  local = None,
  fig_name = 'Generic histogram',
  figsize = [15.0 
)
Plot generic histogram.

    Input:
    ======
    data: a histo type object returned by np.histogram(), i.e.
          (array(frequencies), array(bins)). Optionally, multiple histos
          can be passed as a list.

    enableBars==True:  Plots data as a bar graph if true (disabled for CDFs)
    spacing_modifier:  This agjusts the spacing between bar groups. set to one to have one bar length between groups, or 0 to remove

    dist_type=='freq': Plot as a frequency
    dist_type=='pdf':  Plot as a probability distribution function

Definition at line 164 of file vis.py.

164 def Histo(data, enableBars=True, dist_type='freq', enableHalfStepOffset=True, halfStepSign=1, legendLabels='', linewidth=2, spacing_modifier=1, x_bounds=None, y_bounds=None, x_label='', y_label='', force_one_label_per_bar=False, local=None, fig_name='Generic histogram', figsize=[15.0,12.0]):
165  ''' Plot generic histogram.
166 
167  Input:
168  ======
169  data: a histo type object returned by np.histogram(), i.e.
170  (array(frequencies), array(bins)). Optionally, multiple histos
171  can be passed as a list.
172 
173  enableBars==True: Plots data as a bar graph if true (disabled for CDFs)
174  spacing_modifier: This agjusts the spacing between bar groups. set to one to have one bar length between groups, or 0 to remove
175 
176  dist_type=='freq': Plot as a frequency
177  dist_type=='pdf': Plot as a probability distribution function
178  '''
179  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
180  if(not local): local = tvaLocal.Local()
181 
182  # Enable multiplotting
183  if(type(data) is not list): data = [data]
184 
185 
186  rects = []
187  i = 0
188  for histo in data:
189  if(not histo): continue
190  colour=(i/float(len(data)),0,1-i/float(len(data)))
191 
192  # Handle data aggregation
193  histo = [x for x in histo]
194  if(dist_type!='freq' and (sum(histo[0]) < 0.98 or sum(histo[0]) > 1.02)): histo[0] = [x/float(sum(histo[0])) for x in histo[0]]
195  if(dist_type=='cdf'): histo[0] = list(tvaLib.Math.running_sum(histo[0]))
196 
197  # Plotting
198  try:
199  if(enableBars and dist_type!='cdf'):
200  if(type(data) is list and len(data) >= 2): width = (histo[1][2]-histo[1][0])/2.0/float(len(data)+spacing_modifier)
201  else: width = (histo[1][2]-histo[1][0])/2.0
202  if(enableHalfStepOffset): halfStepOffset = halfStepSign*(histo[1][2]-histo[1][0])/4.0
203  else: halfStepOffset = 0
204  rects.append(plt.bar([x+width*i+halfStepOffset for x in histo[1][0:-1]], histo[0], width=width, color=colour))
205  else:
206  rects.append(plt.plot(histo[1][0:-1], histo[0], zorder=20, color=colour, linewidth=linewidth))
207  except: pass
208  i += 1
209 
210 
211  ax = plb.gca()
212  if(x_bounds and type(x_bounds) == list): ax.set_xlim(x_bounds)
213  if(y_bounds and type(y_bounds) == list): ax.set_ylim(y_bounds)
214  if(x_label): ax.set_xlabel(x_label)
215  if(y_label): ax.set_ylabel(y_label)
216  else:
217  if(dist_type=='freq'): ax.set_ylabel(local['vis_hist_frequency'])
218  elif(dist_type=='cdf'): ax.set_ylabel(local['vis_hist_y_cdf'])
219  else: ax.set_ylabel(local['vis_hist_y_pdf'])
220  if(force_one_label_per_bar): ax.set_xticks(histo[1][0:-1])
221 
222  #Legend
223  if(legendLabels):
224  if(type(legendLabels) is not list): legendLabels = [legendLabels]
225  if(dist_type=='cdf'): ax.legend([x[0] for x in rects], legendLabels, loc=4)
226  else: ax.legend([x[0] for x in rects], legendLabels)
227 
228  return fig
229 
230 
def Histo(data, enableBars=True, dist_type='freq', enableHalfStepOffset=True, halfStepSign=1, legendLabels='', linewidth=2, spacing_modifier=1, x_bounds=None, y_bounds=None, x_label='', y_label='', force_one_label_per_bar=False, local=None, fig_name='Generic histogram', figsize=[15.0)
Definition: vis.py:164

◆ hourlyFlows()

def lib.vis.hourlyFlows (   flows_curve_list,
  speed_data = None,
  speed_data_stds = None,
  sm_scale = None,
  local = None,
  tickFrequency = 4,
  fig_name = 'Hourly flows',
  figsize = [15.0 
)

Flows.

Plot hourly flows. flows_curves can be of size 24 or 96

    Input:
    ======
    flows_curve_list:        A list of 24-hour-point flows (a list of lists of flows)

Definition at line 1072 of file vis.py.

1072 def hourlyFlows(flows_curve_list, speed_data=None, speed_data_stds=None, sm_scale=None, local=None, tickFrequency=4, fig_name='Hourly flows', figsize=[15.0,12.0]):
1073  ''' Plot hourly flows. flows_curves can be of size 24 or 96
1074 
1075  Input:
1076  ======
1077  flows_curve_list: A list of 24-hour-point flows (a list of lists of flows)
1078  '''
1079 
1080  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
1081  if(not local): local = tvaLocal.Local()
1082 
1083 
1084  if(type(sm_scale) == list and len(sm_scale) == 2): sm_scale = sm_scale[1]
1085  else: sm_scale = 50
1086  if(len(flows_curve_list[0]) == 96): period = 96
1087  else: period = 24
1088 
1089 
1090  ax = plb.gca()
1091  for flows_curve in flows_curve_list:
1092  ax.plot(range(period), flows_curve, linewidth=2, color='b')
1093 
1094 
1095  if(speed_data):
1096  ax2 = ax.twinx()
1097  for speed_curve in speed_data:
1098  ax2.plot(range(period), speed_curve, linewidth=2, color='k')
1099  if(speed_data_stds):
1100  for speed_curve,speed_stds in zip(speed_data,speed_data_stds):
1101  ax2.plot(range(period), [speed+speed_std if speed else None for speed,speed_std in zip(speed_curve,speed_stds)], linewidth=1, color='k', linestyle='--')
1102  ax2.plot(range(period), [speed-speed_std if speed else None for speed,speed_std in zip(speed_curve,speed_stds)], linewidth=1, color='k', linestyle='--')
1103 
1104  ax.set_xlim([0,period])
1105  ax.set_ylim([0,max([max(y) for y in flows_curve_list])])
1106  ax2.set_ylim([0,sm_scale])
1107  for tl in ax.get_yticklabels():
1108  tl.set_color('b')
1109  for tl in ax2.get_yticklabels():
1110  tl.set_color('k')
1111  ax.xaxis.set_ticks(np.arange(0, period, period/24.0*tickFrequency))
1112  ax.set_xticklabels([str(int(tick/float(period)*24))+':'+"%02d" % (int(tick/float(period)*24%1.0*60)) for tick in np.arange(0, period, period/24.0*tickFrequency)])
1113  for x in np.arange(0, period, period/24.0*tickFrequency):
1114  plt.plot((x, x), (0, max([max(y) for y in flows_curve_list])), color='#CCCCCC')
1115  ax.set_ylabel(local['vis_flow_rate'])
1116  ax2.set_ylabel(local['vis_speed_cm_label_kmh'])
1117 
1118  return fig
1119 
def hourlyFlows(flows_curve_list, speed_data=None, speed_data_stds=None, sm_scale=None, local=None, tickFrequency=4, fig_name='Hourly flows', figsize=[15.0)
Flows.
Definition: vis.py:1072

◆ interactionMap()

def lib.vis.interactionMap (   pointColumnList,
  ptype = 'hexbin',
  colour = 'hot',
  weightedDensity = False,
  xy_bounds = None,
  z_bounds = None,
  gridsize = [60,
  minGridSize = 1.0,
  mincnt = 1,
  alignments = False,
  mask = False,
  zone = False,
  labels = False,
  local = None,
  zlabel = '',
  fig_name = 'CP Map',
  indent = 4,
  verbose = 0,
  figsize = [15.0,
  plotSettings = None,
  kwargs 
)

Interactions.

Plot CP heatmap

    Generally makes use of matplotlib's hexbin. If the number of points is too great, the data will be condensed with condensePointList() and matplotlib's pcolor will be used instead.

    Input:
    ======
    pointColumnList: A list of coordinate columns (each row is a point)
    mode:            'hexbin' for a hexbin plot, 'imshow' for an imshow plot (defaults to hexbin)
    colour:          http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
    gridsize:        Must be a two-item list, preferably square, indicating the size of the hex grid
    minGridSize:     Minimum size of each hex (in metres)
    mincnt:          Bins with fewer than this many points will not be plotted
    zticks:

Definition at line 1467 of file vis.py.

1467 def interactionMap(pointColumnList, ptype='hexbin', colour='hot', weightedDensity=False, xy_bounds=None, z_bounds=None, gridsize=[60,60], minGridSize=1.0, mincnt=1, alignments=False, mask=False, zone=False, labels=False, local=None, zlabel='', fig_name='CP Map', indent=4, verbose=0, figsize=[15.0,12.0], plotSettings=None, **kwargs):
1468  ''' Plot CP heatmap
1469 
1470  Generally makes use of matplotlib's hexbin. If the number of points is too great, the data will be condensed with condensePointList() and matplotlib's pcolor will be used instead.
1471 
1472  Input:
1473  ======
1474  pointColumnList: A list of coordinate columns (each row is a point)
1475  mode: 'hexbin' for a hexbin plot, 'imshow' for an imshow plot (defaults to hexbin)
1476  colour: http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
1477  gridsize: Must be a two-item list, preferably square, indicating the size of the hex grid
1478  minGridSize: Minimum size of each hex (in metres)
1479  mincnt: Bins with fewer than this many points will not be plotted
1480  zticks:
1481  '''
1482  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
1483  if(not local): local = tvaLocal.Local()
1484 
1485 
1486  if(not pointColumnList or type(pointColumnList) != list or len(pointColumnList) == 0 or len(pointColumnList[0]) == 0):
1487  if(verbose >= 2): tvaLib.printWarning('Empty dataset passed in interactionMap "'+fig_name+'".', indent=indent)
1488  return False
1489  if(verbose >= 2): print(''.rjust(indent,' ')+'Conflict points loaded in CP mapping function: '+str(len(pointColumnList[1])))
1490 
1491 
1492  plotBB(mask, labels=labels, boxLabel=local['vis_mask'], outlineOnly=False, zone_bgcolour='0.90', plotSettings=plotSettings, **kwargs)
1493  plotBB(zone, labels=labels, boxLabel=local['vis_analysis_area'], zone_bgcolour='green', alpha=0.5, plotSettings=plotSettings, **kwargs)
1494 
1495 
1497  if(ptype == 'imshow'):
1498  #Experimental
1499  if(weightedDensity): pointColumnList_ = pointList2DHisto([pointColumnList[1], pointColumnList[2], pointColumnList[3]], bins=[60,60])
1500  else: pointColumnList_ = pointList2DHisto([pointColumnList[1], pointColumnList[2]], bins=[30,30])
1501 
1502  #Adjust transparency of colour map
1503  cm = plt.get_cmap(colour)
1504  #cm._init()
1505  #cm._lut[:-3,-1] = np.abs(np.linspace(-1.0, 1.0, cm.N))
1506  #Plot
1507  #import pdb; pdb.set_trace()
1508  extent = [pointColumnList_[1][0],pointColumnList_[1][-1],pointColumnList_[2][0],pointColumnList_[2][-1]]
1509  Map = plt.imshow(np.transpose(pointColumnList_[0]), interpolation='None', cmap=cm, extent=(extent[0], extent[1], extent[2], extent[3]), origin='lower')
1510  else: #(hexbin)
1511 
1512  extent = [max(pointColumnList[1])-min(pointColumnList[1]), max(pointColumnList[2])-min(pointColumnList[2])]
1513  if(extent[0] < gridsize[0]*minGridSize or extent[1] < gridsize[1]*minGridSize): gridsize = [int(extent[0]/minGridSize)+(extent[0] % minGridSize > 0), int(extent[1]/minGridSize)+(extent[1] % minGridSize > 0)]
1514 
1515  if(weightedDensity):
1516  if(z_bounds):
1517  if(type(z_bounds) == list and len(z_bounds) == 2): Map = plt.hexbin(pointColumnList[1], pointColumnList[2], C=pointColumnList[3], gridsize=gridsize, cmap=plt.get_cmap(colour), vmin=z_bounds[0], vmax=z_bounds[1])
1518  else: Map = plt.hexbin(pointColumnList[1], pointColumnList[2], C=pointColumnList[3], gridsize=gridsize, cmap=plt.get_cmap(colour), vmax=z_bounds)
1519  else:
1520  Map = plt.hexbin(pointColumnList[1], pointColumnList[2], C=pointColumnList[3], gridsize=gridsize, cmap=plt.get_cmap(colour))
1521  else:
1522  Map = plt.hexbin(pointColumnList[1], pointColumnList[2], gridsize=gridsize, cmap=plt.get_cmap(colour), mincnt=mincnt)
1523  Map.set_zorder(5)
1524  cb = plt.colorbar()
1525  if(zlabel): cb.set_label(zlabel)
1526  else: cb.set_label(local['vis_cp_label'])
1527 
1528 
1529  plotAlign(alignments, draw_corridors=False, labels=labels, lineAlpha=0.2, annotateAlpha=0.2, plotSettings=plotSettings)
1530 
1531 
1532  ax = plb.gca()
1533  plt.axis('equal')
1534  if(xy_bounds):
1535  ax.set_xlim([xy_bounds[0].lower,xy_bounds[0].upper])
1536  ax.set_ylim([xy_bounds[1].lower,xy_bounds[1].upper])
1537  ax.set_ylim(ax.get_ylim()[::-1])
1538  ax.set_xlabel(local['vis_gen_x_coords_m'])
1539  ax.set_ylabel(local['vis_gen_y_coords_m'])
1540 
1541  return fig
1542 
1543 
def plotBB(bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, kwargs)
Definition: vis.py:422
def plotAlign(alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None)
Definition: vis.py:477
def pointList2DHisto(data, bins=[60)
Definition: vis.py:629
def interactionMap(pointColumnList, ptype='hexbin', colour='hot', weightedDensity=False, xy_bounds=None, z_bounds=None, gridsize=[60, minGridSize=1.0, mincnt=1, alignments=False, mask=False, zone=False, labels=False, local=None, zlabel='', fig_name='CP Map', indent=4, verbose=0, figsize=[15.0, plotSettings=None, kwargs)
Interactions.
Definition: vis.py:1467

◆ interactionTTCHist()

def lib.vis.interactionTTCHist (   ttc_histos,
  fps = 15.0,
  timehorizon = 5.0,
  enableBars = True,
  linewidth = 5,
  dist_type = 'pdf',
  labels = False,
  label_ratio = '',
  local = None,
  fig_name = 'TTC pdf',
  verbose = 0,
  figsize = [15.0 
)
Plot TTC distribution.

    Input:
    ======
    Expects ttc_histos to be in the following format:
    [[[TTC values (X), Frequencies (Y)], 'Name'], ...]
    ttc_histos can be passed as pdfs, cdfs, or frequencies

    timehorizon:     Max TTC value to consider, in seconds
    legend_location: "4" for bottom right, defaults to top right

Definition at line 1544 of file vis.py.

1544 def interactionTTCHist(ttc_histos, fps=15.0, timehorizon=5.0, enableBars=True, linewidth=5, dist_type='pdf', labels=False, label_ratio='', local=None, fig_name='TTC pdf', verbose=0, figsize=[15.0,12.0]):
1545  ''' Plot TTC distribution.
1546 
1547  Input:
1548  ======
1549  Expects ttc_histos to be in the following format:
1550  [[[TTC values (X), Frequencies (Y)], 'Name'], ...]
1551  ttc_histos can be passed as pdfs, cdfs, or frequencies
1552 
1553  timehorizon: Max TTC value to consider, in seconds
1554  legend_location: "4" for bottom right, defaults to top right
1555  '''
1556 
1557  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
1558  if(not local): local = tvaLocal.Local()
1559  if(not ttc_histos or not isinstance(ttc_histos, list) or len(ttc_histos) <= 0 or not isinstance(ttc_histos[0], list) or len(ttc_histos[0]) <= 0 or not ttc_histos[0][0]):
1560  if(verbose): tvaLib.printWarning('Empty or incorrect dataset passed in interactionTTCHist "'+fig_name+'".', indent=4)
1561  return False
1562 
1563 
1565  if(len(ttc_histos) == 1 and enableBars):
1566  plt.bar([x/float(fps) for x in ttc_histos[0][0][0][:-1]], ttc_histos[0][0][1][:], width=(ttc_histos[0][0][0][1]-ttc_histos[0][0][0][0])/float(fps), label=ttc_histos[0][1])
1567  #Plot line graphs
1568  max_y = 0
1569  for ttc_histo in ttc_histos:
1570  plt.plot([x/float(fps) for x in ttc_histo[0][0][:-1]], ttc_histo[0][1][:], label=ttc_histo[1], linewidth=linewidth)
1571  try:
1572  if(max(ttc_histo[0][1]) > max_y): max_y = max(ttc_histo[0][1])
1573  except ValueError: max_y = 1
1574 
1575 
1576  if(labels):
1577  if(dist_type=='cdf'): plt.legend(loc=4)
1578  else: plt.legend()
1579  #plt.annotate(label_ratio, xytext=(float(timehorizon)*0.95, max_y*0.05), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='Square,pad=0.5', fc='white', alpha=0.5))
1580 
1581 
1582  plt.axis([0,timehorizon,0,max_y])
1583  ax = plb.gca()
1584  ax.set_xlabel(local['vis_cp_hist_x'])
1585  if(dist_type=='cdf'): ax.set_ylabel(local['vis_hist_y_cdf'])
1586  else:
1587  try: ax.set_ylabel(local['vis_hist_y_pdf'].format(round((ttc_histos[0][0][1][1]-ttc_histos[0][0][1][0])/float(fps),3)))
1588  except IndexError: ax.set_ylabel(local['vis_hist_y_pdf'].format(0.00))
1589 
1590  return fig
1591 
def interactionTTCHist(ttc_histos, fps=15.0, timehorizon=5.0, enableBars=True, linewidth=5, dist_type='pdf', labels=False, label_ratio='', local=None, fig_name='TTC pdf', verbose=0, figsize=[15.0)
Definition: vis.py:1544

◆ Map()

def lib.vis.Map (   pointList,
  colour = 'hot',
  xy_bounds = None,
  gridsize = [60,
  mincnt = 1,
  sm_scale = None,
  alignments = False,
  mask = False,
  labels = False,
  local = None,
  fig_name = 'Generic Map',
  verbose = 0,
  figsize = [15.0,
  full_plot = True 
)
Generic map with alignment and BB

    Input:
    ======
    colour:    http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
    gridsize:  Must be a two-item list, preferably square
    mincnt:    Bins with fewer than this many points will not be plotted
    sm_scale:  If this is an int or float, bounds the upper maximum of the colour map; if this is a two-item list, bounds the lower and upper maximum of the colour map respectively
    full_plot: Set to false if calling from another vis function

Definition at line 375 of file vis.py.

375 def Map(pointList, colour='hot', xy_bounds=None, gridsize=[60,60], mincnt=1, sm_scale=None, alignments=False, mask=False, labels=False, local=None, fig_name='Generic Map', verbose=0, figsize=[15.0,12.0], full_plot=True):
376  ''' Generic map with alignment and BB
377 
378  Input:
379  ======
380  colour: http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
381  gridsize: Must be a two-item list, preferably square
382  mincnt: Bins with fewer than this many points will not be plotted
383  sm_scale: If this is an int or float, bounds the upper maximum of the colour map; if this is a two-item list, bounds the lower and upper maximum of the colour map respectively
384  full_plot: Set to false if calling from another vis function
385  '''
386  if(not local): local = tvaLocal.Local()
387  if(len(pointList[0]) == 0 or len(pointList[1]) == 0): return False
388 
389  if(full_plot):
390  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
391 
392 
393  plotBB(mask, labels=labels, boxLabel=local['vis_mask'])
394 
395 
396  if(sm_scale):
397  if(type(sm_scale) == list and len(sm_scale) == 2): scale_norm = plt.Normalize(sm_scale[0],sm_scale[1])
398  else: scale_norm = plt.Normalize(0,sm_scale)
399  else: scale_norm = None
400 
401  # Plot hexbin
402  hexBinMap = plt.hexbin(pointList[0], pointList[1], gridsize=gridsize, cmap=plt.get_cmap(colour), mincnt=mincnt, norm=scale_norm)
403  hexBinMap.set_zorder(5)
404  cb = plt.colorbar()
405  cb.set_label(local['vis_map_density'])
406 
407  if(full_plot):
408 
409  plotAlign(alignments, labels=labels)
410 
411 
412  ax = plb.gca()
413  plt.axis('equal')
414  if(xy_bounds):
415  ax.set_xlim([xy_bounds[0].lower,xy_bounds[0].upper])
416  ax.set_ylim([xy_bounds[1].lower,xy_bounds[1].upper])
417  return fig
418  else:
419  return True
420 
421 
def plotBB(bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, kwargs)
Definition: vis.py:422
def plotAlign(alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None)
Definition: vis.py:477
def Map(pointList, colour='hot', xy_bounds=None, gridsize=[60, mincnt=1, sm_scale=None, alignments=False, mask=False, labels=False, local=None, fig_name='Generic Map', verbose=0, figsize=[15.0, full_plot=True)
Definition: vis.py:375

◆ microTrafficIntensity()

def lib.vis.microTrafficIntensity (   objects,
  startTime,
  endTime,
  framerate,
  local = None,
  window_s = 20.0,
  maxBins = 1000,
  fig_name = 'Traffic Intensity',
  figsize = [15.0,
  plotSettings = None,
  kwargs 
)
Plot Traffic Intensity

    Input:
    ======
    objects:     Object space, or a list of objects
    startTime:   A datetime object representing the start time of the first object
    endTime:     A datetime object representing the end time of the last object

Definition at line 1120 of file vis.py.

1120 def microTrafficIntensity(objects, startTime, endTime, framerate, local=None, window_s=20.0, maxBins=1000, fig_name='Traffic Intensity', figsize=[15.0,12.0], plotSettings=None, **kwargs):
1121  ''' Plot Traffic Intensity
1122 
1123  Input:
1124  ======
1125  objects: Object space, or a list of objects
1126  startTime: A datetime object representing the start time of the first object
1127  endTime: A datetime object representing the end time of the last object
1128  '''
1129 
1130  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
1131  if(not local): local = tvaLocal.Local()
1132 
1133  timeDelta = endTime-startTime
1134 
1135  numBins = int(timeDelta.total_seconds()/float(window_s))
1136  if(numBins > maxBins):
1137  numBins = maxBins
1138  window_s = timeDelta.total_seconds()/maxBins
1139  bins = [[0 for x in range(numBins)] for l in local['userTypeNames']]
1140 
1141 
1142  if(hasattr(objects, 'iterateSequences')):
1143  objectStartTimeReference = min([y.getStartTime() for y in tvaLib.flatten_list([x.metadatas for x in objects])])
1144 
1145 
1146  for b in range(numBins):
1147  binFrameStart = b*window_s*framerate
1148  binFrameEnd = (b+1)*window_s*framerate - 1
1149 
1150  if(hasattr(objects, 'iterateSequences')):
1151  for metadata,objs in objects.iterateSequences():
1152  frameOffset = (metadata.getStartTime()-objectStartTimeReference).total_seconds()*framerate
1153  for obj in objs:
1154  if(obj.getFirstInstant()+frameOffset >= binFrameStart):
1155  if(obj.getFirstInstant()+frameOffset < binFrameEnd): bins[obj.getUserType()][b] += 1
1156  elif(obj.getLastInstant()+frameOffset >= binFrameStart): bins[obj.getUserType()][b] += 1
1157  else:
1158  for obj in objects:
1159  if(obj.getFirstInstant() >= binFrameStart):
1160  if(obj.getFirstInstant() < binFrameEnd): bins[obj.getUserType()][b] += 1
1161  elif(obj.getLastInstant() >= binFrameStart): bins[obj.getUserType()][b] += 1
1162 
1163 
1164  artists = []
1165  for cIx in range(len(local['userTypeNames'])):
1166  artists.append(plt.bar(range(numBins), bins[cIx], width=1.0, bottom=[sum(x[:cIx]) for x in zip(*bins)]))
1167 
1168 
1169  ax = plb.gca()
1170  plt.legend([artist[0] for artist in artists], local['userTypeNames'])
1171  ticklabel_interval = 10
1172  ax.set_xticklabels([startTime+timedelta(seconds=int(b*window_s)) for b in range(0, numBins, ticklabel_interval)], rotation=45)
1173  ax.set_ylabel(local['vis_traf_intensity_y'].format(round(window_s,2)))
1174 
1175  return fig
1176 
def microTrafficIntensity(objects, startTime, endTime, framerate, local=None, window_s=20.0, maxBins=1000, fig_name='Traffic Intensity', figsize=[15.0, plotSettings=None, kwargs)
Definition: vis.py:1120

◆ plotAlign()

def lib.vis.plotAlign (   alignments,
  custom_colours = None,
  draw_connectors = True,
  draw_corridors = True,
  labels = False,
  legacyLabels = False,
  distanceBetweenLabels = 20.0,
  highContrastLabels = False,
  lineAlpha = 1.0,
  annotateAlpha = 0.2,
  corridorAlpha = 0.5,
  zorder = 20,
  plotSettings = None 
)
Plot alignments. 

Definition at line 477 of file vis.py.

477 def plotAlign(alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None):
478  ''' Plot alignments. '''
479  if(not alignments or len(alignments) == 0): return False
480 
481  for lane in range(len(alignments)):
482  try:
483  if(hasattr(alignments[lane], 'hasAlignBB') and alignments[lane].hasAlignBB()):
484  x = alignments[lane].getXCoordinatesBB()
485  y = alignments[lane].getYCoordinatesBB()
486  s = alignments[lane].getSCoordinatesBB()
487  else:
488  x = alignments[lane].getXCoordinates()
489  y = alignments[lane].getYCoordinates()
490  s = alignments[lane].getSCoordinates()
491  except:
492  x = alignments[lane].getXCoordinates()
493  y = alignments[lane].getYCoordinates()
494  legacyLabels = True
495 
496  if(lane in alignments.sidewalks): plt.plot(x, y, color='#377220', lw=3, zorder=zorder, alpha=lineAlpha)
497  elif(lane in alignments.bikepaths): plotWithArrows(x, y, color='#700f92', lw=3, zorder=zorder, alpha=lineAlpha)
498  else: plotWithArrows(x, y, color='m', lw=3, zorder=zorder, alpha=lineAlpha)
499  if(labels):
500  if(legacyLabels): plt.annotate(alignments[lane].getPrintShortName(), xy = (x[0], y[0]), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'Square,pad=0.5', fc = 'white', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
501  else:
502  lastDistance = 0
503  for segment in range(len(alignments[lane])-1):
504  lastDistance += s[segment+1] - s[segment]
505  if(lastDistance > distanceBetweenLabels):
506  lastDistance = 0
507 
508  no_labels = max(1,int((s[segment+1] - s[segment])/distanceBetweenLabels))
509  for lIdx in range(no_labels):
510  # The angle needs to be set to negative to compensate for flipping on the vertical (y) axis)
511  try: angle = -m.degrees(m.atan((y[segment+1]-y[segment])/(x[segment+1]-x[segment])))
512  except: angle = -90.0
513  # Choose location
514  location = (x[segment]+(x[segment+1]-x[segment])*(lIdx+1)/float(no_labels+1), y[segment]+(y[segment+1]-y[segment])*(lIdx+1)/float(no_labels+1))
515  # Determine offset
516  if(20 < angle+90 and angle+90 < 60): offset = (5*(1-(angle+90.0)/180.0)+5, 5-5*(1-(angle+90.0)/180.0))
517  else: offset = (-5*(1-(angle+90.0)/180.0)-10, 5+10*(1-(angle+90.0)/180.0))
518  # Set colour
519  if(custom_colours): colour = custom_colours[lane]
520  elif(highContrastLabels): colour = '#FFFFFF'
521  elif(lane in alignments.sidewalks): colour = '#377220'
522  elif(lane in alignments.bikepaths): colour = '#700f92'
523  else: colour = 'm'
524  if(plotSettings):
525  if(highContrastLabels): plt.annotate(alignments[lane].getPrintName(), xy = location, rotation=angle, xytext=offset, textcoords='offset points', ha='center', va='center', color=colour, zorder=zorder+1, bbox=dict(facecolor='#000000', alpha=0.5, boxstyle='Square,pad=0.1'), size=plotSettings['size']*0.5)
526  else: plt.annotate(alignments[lane].getPrintName(), xy = location, rotation=angle, xytext=offset, textcoords='offset points', ha='center', va='center', color=colour, zorder=zorder+1, alpha=annotateAlpha, size=plotSettings['size']*0.5)
527  else:
528  if(highContrastLabels): plt.annotate(alignments[lane].getPrintName(), xy = location, rotation=angle, xytext=offset, textcoords='offset points', ha='center', va='center', color=colour, zorder=zorder+1, bbox=dict(facecolor='#000000', alpha=0.5, boxstyle='Square,pad=0.1'))
529  else: plt.annotate(alignments[lane].getPrintName(), xy = location, rotation=angle, xytext=offset, textcoords='offset points', ha='center', va='center', color=colour, zorder=zorder+1, alpha=annotateAlpha)
530 
531  if(draw_connectors):
532  for link in alignments.getLinks():
533  plb.plot([link[2], link[6]], [link[3], link[7]], 'c', lw=4, alpha=lineAlpha)
534  if(draw_corridors):
535  for corridorSet in alignments.getCorridors():
536  if(alignments[corridorSet[0]].hasAlignBB() and alignments[corridorSet[1]].hasAlignBB()):
537  X2 = alignments[corridorSet[1]].getXCoordinatesBB()
538  X2.reverse()
539  Y2 = alignments[corridorSet[1]].getYCoordinatesBB()
540  Y2.reverse()
541  plt.fill(alignments[corridorSet[0]].getXCoordinatesBB()+X2, alignments[corridorSet[0]].getYCoordinatesBB()+Y2, 'c', alpha=corridorAlpha, zorder=zorder-1)
542  else:
543  X2 = alignments[corridorSet[1]].getXCoordinates()
544  X2.reverse()
545  Y2 = alignments[corridorSet[1]].getYCoordinates()
546  Y2.reverse()
547  plt.fill(alignments[corridorSet[0]].getXCoordinates()+X2, alignments[corridorSet[0]].getYCoordinates()+Y2, 'c', alpha=corridorAlpha, zorder=zorder-1)
548 
549  return True
550 
def plotAlign(alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None)
Definition: vis.py:477
def plotWithArrows(x, y, aspace=5, color='b', alpha=1.0, zorder=1, kwargs)
Definition: vis.py:231

◆ plotBB()

def lib.vis.plotBB (   bounding_boxes,
  labels = False,
  legacyLabels = False,
  boxLabel = None,
  outlineOnly = False,
  alpha = 1.00,
  zorder = 1,
  zone_bgcolour = '0.66',
  plotSettings = None,
  kwargs 
)
Plot bounding_boxes. If outlineOnly is set to an int, will use as line
    thickness (defaults to 2). 

Definition at line 422 of file vis.py.

422 def plotBB(bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, **kwargs):
423  ''' Plot bounding_boxes. If outlineOnly is set to an int, will use as line
424  thickness (defaults to 2). '''
425  if(not bounding_boxes or len(bounding_boxes) == 0): return False
426  if(type(outlineOnly) is int): linewidth = outlineOnly
427  else: linewidth = 2
428  for bounding_box in bounding_boxes:
429  if(outlineOnly): plt.plot([x[0] for x in bounding_box]+[bounding_box[0][0]], [y[1] for y in bounding_box]+[bounding_box[0][1]], color='k', linewidth=linewidth, zorder=zorder)
430  else: plt.fill([x[0] for x in bounding_box], [y[1] for y in bounding_box], zone_bgcolour, alpha=alpha, zorder=zorder)
431  if(boxLabel and labels):
432  if(legacyLabels):
433  plt.annotate(boxLabel, xy = (bounding_boxes[0][0][0], bounding_boxes[0][0][1]), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'Square,pad=0.5', fc = 'white', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
434  else:
435  for bIx in range(len(bounding_boxes)):
436  if(len(bounding_boxes[bIx])>=3): label_vertices = [0,int(len(bounding_boxes[bIx])/2.0)]
437  else: label_vertices = [0]
438  for lpIx in label_vertices:
439  # The angle needs to be set to negative to compensate for flipping on the vertical (y) axis)
440  try: angle = -m.degrees(m.atan((bounding_boxes[bIx][lpIx+1][1]-bounding_boxes[bIx][lpIx][1])/(bounding_boxes[bIx][lpIx+1][0]-bounding_boxes[bIx][lpIx][0])))
441  except: angle = -90.0
442  # Determine offset
443  if(20 < angle+90 and angle+90 < 60): offset = (5*(1-(angle+90.0)/180.0)+5, 5-5*(1-(angle+90.0)/180.0))
444  else: offset = (-5*(1-(angle+90.0)/180.0)-10, 5+10*(1-(angle+90.0)/180.0))
445  # Choose location
446  location = ((bounding_boxes[bIx][lpIx+1][0]+bounding_boxes[bIx][lpIx][0])/2.0, (bounding_boxes[bIx][lpIx+1][1]+bounding_boxes[bIx][lpIx][1])/2.0)
447  if(plotSettings): plt.annotate(boxLabel, xy = location, rotation=angle, xytext=offset, textcoords='offset points', ha='center', va='center', color=zone_bgcolour, zorder=zorder+1, bbox=dict(facecolor='#000000', alpha=0.5, boxstyle='Square,pad=0.1'), size=plotSettings['size']*0.5)
448  else: plt.annotate(boxLabel, xy = location, rotation=angle, xytext=offset, textcoords='offset points', ha='center', va='center', color=zone_bgcolour, zorder=zorder+1, bbox=dict(facecolor='#000000', alpha=0.5, boxstyle='Square,pad=0.1'))
449 
450  return True
451 
def plotBB(bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, kwargs)
Definition: vis.py:422

◆ plotGeometry()

def lib.vis.plotGeometry (   alignments,
  sateliteImage,
  sateliteResolution,
  xy_bounds = None,
  draw_connectors = True,
  mask = None,
  zone = None,
  virtual_loops = None,
  labels = False,
  local = None,
  fig_name = 'Geometry',
  figsize = [15.0,
  plotSettings = None,
  kwargs 
)
Plot geometry

Definition at line 1028 of file vis.py.

1028 def plotGeometry(alignments, sateliteImage, sateliteResolution, xy_bounds=None, draw_connectors=True, mask=None, zone=None, virtual_loops=None, labels=False, local=None, fig_name='Geometry', figsize=[15.0,12.0], plotSettings=None, **kwargs):
1029  ''' Plot geometry
1030  '''
1031  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
1032  if(not local): local = tvaLocal.Local()
1033 
1034 
1035  if(not xy_bounds): zoomToSatelite = True
1036  else: zoomToSatelite = False
1037  if(plotSatellite(sateliteImage, sateliteResolution, color=True, zoomTo=zoomToSatelite)):
1038  fig.forceDPI = 150
1039  fig.forceFormat = 'jpg'
1040  draw_connectors = False #Disable for satellite images or else image is too busy
1041  outlineOnly = True
1042  else: outlineOnly = False
1043 
1044 
1045  plotBB(mask, labels=labels, boxLabel=local['vis_mask'], outlineOnly=outlineOnly, zone_bgcolour='0.90', plotSettings=plotSettings, **kwargs)
1046  plotBB(zone, labels=labels, boxLabel=local['vis_analysis_area'], zone_bgcolour='green', alpha=0.5, plotSettings=plotSettings, **kwargs)
1047  plotVL(virtual_loops, labels=labels)
1048 
1049 
1050  plotAlign(alignments, draw_connectors=draw_connectors, labels=labels, highContrastLabels=True, plotSettings=plotSettings)
1051 
1052 
1053  ax = plb.gca()
1054  if(not zoomToSatelite): plt.axis('equal')
1055  if(xy_bounds):
1056  ax.set_xlim([xy_bounds[0].lower,xy_bounds[0].upper])
1057  ax.set_ylim([xy_bounds[1].lower,xy_bounds[1].upper])
1058  ax.set_ylim(ax.get_ylim()[::-1])
1059  ax.set_xlabel(local['vis_gen_x_coords_m'])
1060  ax.set_ylabel(local['vis_gen_y_coords_m'])
1061 
1062 
1063  fig.tight_layout()
1064 
1065  return fig
1066 
1067 
1068 
def plotBB(bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, kwargs)
Definition: vis.py:422
def plotVL(virtual_loops, labels=False, colour='#D63E33')
Definition: vis.py:464
def plotAlign(alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None)
Definition: vis.py:477
def plotGeometry(alignments, sateliteImage, sateliteResolution, xy_bounds=None, draw_connectors=True, mask=None, zone=None, virtual_loops=None, labels=False, local=None, fig_name='Geometry', figsize=[15.0, plotSettings=None, kwargs)
Definition: vis.py:1028
def plotSatellite(sateliteImage, sateliteResolution, color=False, zorder=0, origin=[0, zoomTo=False)
Definition: vis.py:551

◆ plotImageWorldSpace()

def lib.vis.plotImageWorldSpace (   imagePath,
  scale = 1.0,
  zorder = 0,
  origin = [0 
)
Plot image to world space (scaled to metres). 

Definition at line 570 of file vis.py.

570 def plotImageWorldSpace(imagePath, scale=1.0, zorder=0, origin=[0,0]):
571  ''' Plot image to world space (scaled to metres). '''
572  if(not imagePath): return False
573  try: img = mpimg.imread(imagePath)
574  except: return False
575  x = int(img.shape[1]*scale)
576  y = int(img.shape[0]*scale)
577  plt.imshow(img, extent=(origin[0],x+origin[0],origin[1],y+origin[1]), origin='lower', zorder=zorder)
578  return True
579 
def plotImageWorldSpace(imagePath, scale=1.0, zorder=0, origin=[0)
Definition: vis.py:570

◆ plots()

def lib.vis.plots (   X,
  Y,
  legend_labels = None,
  colours = ['b',
  r,
  g,
  orange,
  k,
  m,
  y,
  linewidths = [1],
  linestyles = ['-'],
  markers = [''],
  x_bounds = None,
  y_bounds = None,
  x_label = '',
  y_label = '',
  local = None,
  fig_name = 'Generic plots',
  figsize = [15.0 
)
Plot generic data series.

    Input:
    ======
    X is an array of X coordinates
    Y is an array of Y coordinates

    X and Y can also be passed as a list of multiple series to plot [[Y1,Y2,...],[Y1,Y2,...],...]

Definition at line 118 of file vis.py.

118 def plots(X, Y, legend_labels=None, colours=['b','r','g','orange','k','m','y'], linewidths=[1], linestyles=['-'], markers = [''], x_bounds=None, y_bounds=None, x_label='', y_label='', local=None, fig_name='Generic plots', figsize=[15.0,12.0]):
119  ''' Plot generic data series.
120 
121  Input:
122  ======
123  X is an array of X coordinates
124  Y is an array of Y coordinates
125 
126  X and Y can also be passed as a list of multiple series to plot [[Y1,Y2,...],[Y1,Y2,...],...]
127  '''
128  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
129  if(not local): local = tvaLocal.Local()
130  if(len(X) != len(Y)): return False
131 
132  # Enable multiplotting
133  if(type(X[0]) is not list): X = [X]
134  if(type(Y[0]) is not list): Y = [Y]
135 
136 
137  rects=[]
138  for x,y,Ix in zip(X,Y,range(len(X))):
139  if(Ix >= len(colours)): colour = (random(),random(),random())
140  else: colour = colours[Ix]
141  if(Ix >= len(linestyles)): linestyle = random_choice(['-', '-', '--', ':','-.'])
142  else: linestyle = linestyles[Ix]
143  if(Ix >= len(markers)): marker = random_choice(['', '', 'o', 'x', 'D'])
144  else: marker = markers[Ix]
145  if(Ix >= len(linewidths)): linewidth = 1
146  else: linewidth = linewidths[Ix]
147  try: rects.append(plt.plot(x, y, linewidth=linewidth, color=colour, linestyle=linestyle, marker=marker, label=legend_labels[Ix]))
148  except: plt.plot(x, y, linewidth=linewidth, color=colour, linestyle=linestyle, marker=marker)
149 
150 
151  ax = plb.gca()
152  if(x_bounds and type(x_bounds) == list): ax.set_xlim(x_bounds)
153  if(y_bounds and type(y_bounds) == list): ax.set_ylim(y_bounds)
154  if(x_label): ax.set_xlabel(x_label)
155  if(y_label): ax.set_ylabel(y_label)
156 
157 
158  ax.legend(handles=[x[0] for x in rects], loc='lower right', prop={'size':16})
159 
160  return fig
161 
162 
163 
def plots(X, Y, legend_labels=None, colours=['b', r, g, orange, k, m, y, linewidths=[1], linestyles=['-'], markers=[''], x_bounds=None, y_bounds=None, x_label='', y_label='', local=None, fig_name='Generic plots', figsize=[15.0)
Definition: vis.py:118

◆ plotSatellite()

def lib.vis.plotSatellite (   sateliteImage,
  sateliteResolution,
  color = False,
  zorder = 0,
  origin = [0,
  zoomTo = False 
)
Plot satellite image 

Definition at line 551 of file vis.py.

551 def plotSatellite(sateliteImage, sateliteResolution, color=False, zorder=0, origin=[0,0], zoomTo=False):
552  ''' Plot satellite image '''
553  if(not sateliteImage or not sateliteResolution): return False
554  try: img = mpimg.imread(sateliteImage)
555  except: return False
556  x = int(img.shape[1]*sateliteResolution)
557  y = int(img.shape[0]*sateliteResolution)
558  if(not color):
559  img = img[:,:,0]
560  plt.imshow(img, extent=(origin[0],x,origin[1],y), origin='lower', cmap="Greys_r", zorder=zorder)
561  else:
562  plt.imshow(img, extent=(origin[0],x,origin[1],y), origin='lower', zorder=zorder)
563  if(zoomTo):
564  ax = plb.gca()
565  ax.set_xlim([0,x])
566  ax.set_ylim([0,y])
567  ax.set_autoscale_on(False)
568  return True
569 
def plotSatellite(sateliteImage, sateliteResolution, color=False, zorder=0, origin=[0, zoomTo=False)
Definition: vis.py:551

◆ plotSDR()

def lib.vis.plotSDR (   SDR,
  local = None,
  outlineOnly = False,
  alpha = 1.00,
  zorder = 1,
  sdr_bgcolour = '0.66',
  kwargs 
)
Plot bounding_boxes. If outlineOnly is set to an int, will use as line
    thickness (defaults to 2).  

Definition at line 452 of file vis.py.

452 def plotSDR(SDR, local=None, outlineOnly=False, alpha=1.00, zorder=1, sdr_bgcolour='0.66', **kwargs):
453  ''' Plot bounding_boxes. If outlineOnly is set to an int, will use as line
454  thickness (defaults to 2). '''
455  if(not local): local = tvaLocal.Local()
456  if(not SDR or len(SDR) == 0): return False
457  if(type(outlineOnly) is int): linewidth = outlineOnly
458  else: linewidth = 2
459  for SDRpoly in SDR:
460  if(outlineOnly): plt.plot([x[0] for x in SDRpoly]+[SDRpoly[0][0]], [y[1] for y in SDRpoly]+[SDRpoly[0][1]], color='k', linewidth=linewidth, zorder=zorder)
461  else: plt.fill([x[0] for x in SDRpoly], [y[1] for y in SDRpoly], sdr_bgcolour, alpha=alpha, zorder=zorder)
462  return True
463 
def plotSDR(SDR, local=None, outlineOnly=False, alpha=1.00, zorder=1, sdr_bgcolour='0.66', kwargs)
Definition: vis.py:452

◆ plotSettings()

def lib.vis.plotSettings (   style = '',
  size = 16,
  weight = 'normal',
  family = 'Arial',
  tickLabelSize = None,
  tickLength = 4,
  verbose = 0 
)
Set matplotlib plotting settings. 

    For styles, see:
        https://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html
        Recommend using "bmh"

Definition at line 44 of file vis.py.

44 def plotSettings(style='', size=16, weight='normal', family='Arial', tickLabelSize=None, tickLength=4, verbose=0):
45  ''' Set matplotlib plotting settings.
46 
47  For styles, see:
48  https://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html
49  Recommend using "bmh"
50  '''
51 
52 
53  if(style): plt.style.use(style)
54 
55  if(not tickLabelSize):
56  tickLabelSize = int(round(size*0.8))
57 
58  if(family): font = {'family' : family, 'weight' : weight, 'size' : size}
59  else: font = {'family' : family, 'weight' : weight, 'size' : size}
60 
61  mpl.rc('xtick', labelsize=tickLabelSize)
62  mpl.rc('xtick.major', size=tickLength)
63  mpl.rc('ytick', labelsize=tickLabelSize)
64  mpl.rc('ytick.major', size=tickLength)
65  mpl.rc('font', **font)
66  if(verbose < 2 and mpl.__version__ == '1.3.1'):
67  mpl.rc('figure', max_open_warning=100)
68  return {'style':style, 'size':size, 'weight':weight, 'family':family, 'tickLabelSize':tickLabelSize}
69 
70 
def plotSettings(style='', size=16, weight='normal', family='Arial', tickLabelSize=None, tickLength=4, verbose=0)
Definition: vis.py:44

◆ plotVL()

def lib.vis.plotVL (   virtual_loops,
  labels = False,
  colour = '#D63E33' 
)
Plot bounding_boxes. 

Definition at line 464 of file vis.py.

464 def plotVL(virtual_loops, labels=False, colour='#D63E33'):
465  ''' Plot bounding_boxes. '''
466  if(not virtual_loops or len(virtual_loops.coordinates) == 0):
467  return False
468  fig = plt.gcf()
469  for i in range(len(virtual_loops.coordinates)):
470  circle = plt.Circle((virtual_loops.coordinates[i].x, virtual_loops.coordinates[i].y), radius=virtual_loops.radius, color=colour, alpha=0.7, zorder=1000)
471  fig.gca().add_artist(circle)
472  #if(labels):
473  plt.annotate('# '+str(i)+' ['+str(round(virtual_loops.coordinates[i].x,2))+', '+str(round(virtual_loops.coordinates[i].y,2))+']', xy = (virtual_loops.coordinates[i].x, virtual_loops.coordinates[i].y), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'Square,pad=0.5', fc = 'white', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
474  return True
475 
476 
def plotVL(virtual_loops, labels=False, colour='#D63E33')
Definition: vis.py:464

◆ plotWithArrows()

def lib.vis.plotWithArrows (   x,
  y,
  aspace = 5,
  color = 'b',
  alpha = 1.0,
  zorder = 1,
  kwargs 
)
Plot spline with arrow heads
    https://stackoverflow.com/questions/8247973/how-do-i-specify-an-arrow-like-linestyle-in-matplotlib

Definition at line 231 of file vis.py.

231 def plotWithArrows(x, y, aspace=5, color='b', alpha=1.0, zorder=1, **kwargs):
232  ''' Plot spline with arrow heads
233  https://stackoverflow.com/questions/8247973/how-do-i-specify-an-arrow-like-linestyle-in-matplotlib
234  '''
235 
236  # r is the distance spanned between pairs of points
237  r = [0]
238  for i in range(1,len(x)):
239  dx = x[i]-x[i-1]
240  dy = y[i]-y[i-1]
241  r.append(np.sqrt(dx*dx+dy*dy))
242  r = np.array(r)
243 
244  # rtot is a cumulative sum of r, it's used to save time
245  rtot = []
246  for i in range(len(r)): rtot.append(r[0:i].sum())
247  rtot.append(r.sum())
248 
249  arrowData = [] # will hold tuples of x,y,theta for each arrow
250  arrowPos = 0 # current point on walk along data
251  rcount = 1
252  while arrowPos < r.sum():
253  x1,x2 = x[rcount-1],x[rcount]
254  y1,y2 = y[rcount-1],y[rcount]
255  da = arrowPos-rtot[rcount]
256  theta = np.arctan2((x2-x1),(y2-y1))
257  ax = np.sin(theta)*da+x1
258  ay = np.cos(theta)*da+y1
259  arrowData.append((ax,ay,theta))
260  arrowPos+=aspace
261  while arrowPos > rtot[rcount+1]:
262  rcount+=1
263  if(arrowPos > rtot[-1]):
264  break
265 
266  arrows = []
267  # could be done in above block if you want
268  for ax,ay,theta in arrowData:
269  # use aspace as a guide for size and length of things
270  # scaling factors were chosen by experimenting a bit
271  arrows.append(plt.arrow(ax,ay, np.sin(theta)*aspace/10.0,np.cos(theta)*aspace/10.0, head_width=aspace/10.0, color=color, alpha=alpha, zorder=zorder))
272  plot = plt.plot(x,y, color=color, alpha=alpha, zorder=zorder, **kwargs)
273  return plot, arrows
274 
275 
def plotWithArrows(x, y, aspace=5, color='b', alpha=1.0, zorder=1, kwargs)
Definition: vis.py:231

◆ pointList2DHisto()

def lib.vis.pointList2DHisto (   data,
  bins = [60 
)
Condense a large list of points into a 2D histogram. Currently only supports 2D data but a third dimension can be used as weight.
    
    Input:
    ======
    data is a list of points with up to three coordinates, or otherwise a list of coordinate columns (each row is a point)
    
    Output:
    =======
    A 2D np.array object or False on fail
    return[0] is the joint data, as a 2D np.array
    return[1] is the x-axis bin values as a 1D np.array
    return[2] is the y-axis bin values as a 1D np.array

Definition at line 629 of file vis.py.

629 def pointList2DHisto(data, bins=[60,60]):
630  ''' Condense a large list of points into a 2D histogram. Currently only supports 2D data but a third dimension can be used as weight.
631 
632  Input:
633  ======
634  data is a list of points with up to three coordinates, or otherwise a list of coordinate columns (each row is a point)
635 
636  Output:
637  =======
638  A 2D np.array object or False on fail
639  return[0] is the joint data, as a 2D np.array
640  return[1] is the x-axis bin values as a 1D np.array
641  return[2] is the y-axis bin values as a 1D np.array
642  '''
643  if(type(data) != list): return False
644  if(len(data) == 2): dimension = 2
645  elif(len(data) == 3): dimension = 3
646  else:
647  data = tvaLib.pointList2ColumnList(data)
648  if(len(data) == 2): dimension = 2
649  elif(len(data) == 3): dimension = 3
650  else: return False
651 
652  if(dimension == 2): return np.histogram2d(data[0], data[1], bins=bins)
653  elif(len(data) == 3): return np.histogram2d(data[0], data[1], weights=data[2], bins=bins)
654  else: return False
655 
def pointList2DHisto(data, bins=[60)
Definition: vis.py:629

◆ Save()

def lib.vis.Save (   figures,
  results_path = '',
  fig_dpi = 300,
  fig_format = 'png',
  fig_lan_suffix = '',
  supressClose = False,
  fig_resize = None,
  fig_bg_colour = '',
  verbose = 0 
)
Save list of figures. 

Definition at line 77 of file vis.py.

77 def Save(figures, results_path='', fig_dpi=300, fig_format='png', fig_lan_suffix='', supressClose=False, fig_resize=None, fig_bg_colour='', verbose=0):
78  ''' Save list of figures. '''
79  if(results_path and not os.path.exists(results_path)): os.makedirs(results_path)
80  if(not isinstance(figures, list)): figures = [figures]
81  if(type(fig_lan_suffix) == str):
82  if(fig_lan_suffix): fig_lan_suffix = '_'+fig_lan_suffix
83  else: fig_lan_suffix = ''
84 
85  for figure in figures:
86  if(type(figure) == plt.Figure):
87  #Determine figure format
88  try: f_format = figure.forceFormat
89  except: f_format = fig_format
90  #Determine dpi
91  try: f_dpi = figure.forceDPI
92  except: f_dpi = fig_dpi
93  #Resize if necessary
94  if(fig_resize):
95  try: figure.set_size_inches(fig_resize[0],fig_resize[1])
96  except: tvaLib.printWarning('Incorrect figure resize specification. It should be in inches and look like: [newX.float,newY.float]', indent=4)
97 
98  try:
99  if(figure.make3D_movie):
100  for ii in xrange(0,360,5):
101  figure.pass_ax.view_init(elev=15., azim=ii)
102  if(fig_bg_colour): figure.savefig(os.path.join(results_path, tvaLib.Parse.clean_file_name(figure.get_label())+'_movie'%ii+'.png'), dpi=f_dpi, format='png', facecolor=fig_bg_colour, bbox_inches='tight')
103  else: figure.savefig(os.path.join(results_path, tvaLib.Parse.clean_file_name(figure.get_label())+'_movie'%ii+'.png'), dpi=f_dpi, format='png', transparent=True, bbox_inches='tight')
104  continue
105  except: pass
106 
107  #Save figure
108  try:
109  if(fig_bg_colour): figure.savefig(os.path.join(results_path, tvaLib.Parse.clean_file_name(figure.get_label())+fig_lan_suffix+'.'+f_format), dpi=f_dpi, format=f_format, facecolor=fig_bg_colour, bbox_inches='tight')
110  else: figure.savefig(os.path.join(results_path, tvaLib.Parse.clean_file_name(figure.get_label())+fig_lan_suffix+'.'+f_format), dpi=f_dpi, format=f_format, transparent=True, bbox_inches='tight')
111  except IOError: tvaLib.printWarning('Figure "'+tvaLib.Parse.clean_file_name(figure.get_label())+'" could not be saved because it is locked down by another process and will be skipped.', indent=4)
112  except Exception:
113  if(verbose >= 2): tvaLib.grabError()
114  tvaLib.printWarning('There was a problem saving the figure "'+figure.get_label()+'" (use verbose>=2 to print traceback).', indent=4)
115  if(not supressClose): plt.close(figure)
116  return True
117 
def Save(figures, results_path='', fig_dpi=300, fig_format='png', fig_lan_suffix='', supressClose=False, fig_resize=None, fig_bg_colour='', verbose=0)
Definition: vis.py:77

◆ Scatter()

def lib.vis.Scatter (   pointList,
  alignments = False,
  mask = False,
  labels = False,
  local = None,
  fig_name = 'Generic scatter',
  verbose = 0,
  figsize = [15.0 
)
Generic point cloud with alignment and BB. 

Definition at line 354 of file vis.py.

354 def Scatter(pointList, alignments=False, mask=False, labels=False, local=None, fig_name='Generic scatter', verbose=0, figsize=[15.0,12.0]):
355  ''' Generic point cloud with alignment and BB. '''
356  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
357  if(not local): local = tvaLocal.Local()
358 
359 
360  plotBB(mask, labels=labels, boxLabel=local['vis_mask'])
361 
362 
363  X = []
364  Y = []
365  for row in pointList:
366  X.append(row[0])
367  Y.append(row[1])
368  plb.scatter(X, Y, s=80, marker=(5,0), c='r')
369 
370  plotAlign(alignments, labels=labels)
371  return fig
372 
373 
374 
def plotBB(bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, kwargs)
Definition: vis.py:422
def plotAlign(alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None)
Definition: vis.py:477
def Scatter(pointList, alignments=False, mask=False, labels=False, local=None, fig_name='Generic scatter', verbose=0, figsize=[15.0)
Definition: vis.py:354

◆ scatterInBins()

def lib.vis.scatterInBins (   lists,
  bins 
)
Randomly scatter columns of data according to a set of bins. (Effectivly blurs mid-point values of a binning operation). Order is maintained.
    
    Example:
    ========
    >>> scatterInBins([1.5,2.5,0.5,2.5,3], [0,1,2,3])
    [1.9358528821939882, 2.8487475428825326, 0.25158512665668165, 2.512719161810347, 3]

Definition at line 607 of file vis.py.

607 def scatterInBins(lists, bins):
608  ''' Randomly scatter columns of data according to a set of bins. (Effectivly blurs mid-point values of a binning operation). Order is maintained.
609 
610  Example:
611  ========
612  >>> scatterInBins([1.5,2.5,0.5,2.5,3], [0,1,2,3])
613  [1.9358528821939882, 2.8487475428825326, 0.25158512665668165, 2.512719161810347, 3]
614  '''
615  if(type(lists) != list): return False
616  bins.sort()
617  return_list = []
618 
619  for i in lists:
620  for bin in range(len(bins)):
621  if(i < bins[bin]):
622  return_list.append(random()*(bins[bin]-bins[bin-1])+bins[bin-1])
623  break
624  elif(bin >= len(bins)-1):
625  return_list.append(i)
626  break
627  return return_list
628 
def scatterInBins(lists, bins)
Definition: vis.py:607

◆ show()

def lib.vis.show ( )

Visualisation library.

This is a matplotlib shorcut. 

Definition at line 39 of file vis.py.

39 def show():
40  ''' This is a matplotlib shorcut. '''
41  plt.show()
42 
43 
def show()
Visualisation library.
Definition: vis.py:39

◆ speedHist()

def lib.vis.speedHist (   speed_histos,
  labels = '',
  plotPDF = True,
  sm_scale = 80,
  enableBars = True,
  color = 'k',
  linestyle = '',
  linewidth = 5,
  minObservations = 10,
  local = None,
  fig_name = 'Speed Distribution',
  figsize = [15.0 
)
Plot speed histogram.

    Input:
    ======
    If plotPDF is set to true, will plot PDF values, otherwise will plot
    frequency (counts).

Definition at line 1377 of file vis.py.

1377 def speedHist(speed_histos, labels='', plotPDF=True, sm_scale=80, enableBars=True, color='k', linestyle='', linewidth=5, minObservations=10, local=None, fig_name='Speed Distribution', figsize=[15.0,12.0]):
1378  ''' Plot speed histogram.
1379 
1380  Input:
1381  ======
1382  If plotPDF is set to true, will plot PDF values, otherwise will plot
1383  frequency (counts).
1384  '''
1385  if(not local): local = tvaLocal.Local()
1386 
1387  if(type(speed_histos[0][0]) is not list): speed_histos = [speed_histos]
1388  if(type(labels) is not list): labels = [labels]
1389  labels = [labels[x] for x in range(len(speed_histos)) if sum(speed_histos[x][1]) > minObservations]
1390  speed_histos = [speed_histos[x] for x in range(len(speed_histos)) if sum(speed_histos[x][1]) > minObservations]
1391  if(not speed_histos): return False
1392 
1393  if(len(speed_histos) <= 2): rows=1; cols=len(speed_histos)
1394  elif(3 <= len(speed_histos) and len(speed_histos) <= 4): rows=2; cols=3
1395  elif(5 <= len(speed_histos) and len(speed_histos) <= 6): rows=2; cols=3
1396  elif(7 <= len(speed_histos) and len(speed_histos) <= 8): rows=2; cols=4
1397  elif(len(speed_histos) == 9): rows=3; cols=3
1398  elif(10 <= len(speed_histos) and len(speed_histos) <= 12): rows=3; cols=4
1399  else: rows=int(m.ceil(m.sqrt(len(speed_histos)))); cols=int(m.ceil(m.sqrt(len(speed_histos))))
1400  fig, axes = plt.subplots(rows, cols, num=fig_name, figsize=(figsize[0], figsize[1]), sharex=True, sharey=True)
1401  if(type(axes) != np.ndarray): axes = np.array(axes)
1402 
1403 
1404  if(plotPDF): y_index = 2
1405  else: y_index = 1
1406 
1407 
1408  axIx = 0
1409  for speed_histo,label in zip(speed_histos,labels):
1410  if(enableBars):
1411  width = (speed_histo[0][1]-speed_histo[0][0])
1412  bar_x_offset = [x-width/2.0 for x in speed_histo[0][1:]]
1413  axes.item(axIx).bar(bar_x_offset, speed_histo[y_index][:], width=width)
1414  axes.item(axIx).plot(speed_histo[0][1:], speed_histo[y_index][:], color=color, linestyle=linestyle, linewidth=linewidth, zorder=20)
1415  if(len(speed_histos) > 1): axes.item(axIx).set_xlabel(label)
1416  axIx += 1
1417 
1418 
1419  axes.item(0).set_xlim([0,sm_scale])
1420  axes.item(0).set_ylim([0,max([max(speed_histo[y_index]) for speed_histo in speed_histos])])
1421  fig.text(0.5, 0.04, local['gen_speed'], ha='center', va='center')
1422  if(plotPDF): fig.text(0.06, 0.5, local['vis_hist_y_pdf'].format(round(speed_histo[0][1]-speed_histo[0][0],3)), ha='center', va='center', rotation='vertical')
1423  else: fig.text(0.06, 0.5, local['vis_hist_y_fre'], ha='center', va='center', rotation='vertical')
1424 
1425  return fig
1426 
def speedHist(speed_histos, labels='', plotPDF=True, sm_scale=80, enableBars=True, color='k', linestyle='', linewidth=5, minObservations=10, local=None, fig_name='Speed Distribution', figsize=[15.0)
Definition: vis.py:1377

◆ speedMap()

def lib.vis.speedMap (   objects,
  ptype = 'heat',
  sm_scale = None,
  colour = 'hot',
  xy_bounds = None,
  gridsize = [60,
  arrowGridReductionFactor = 0.3,
  mincnt = 10,
  virtualLoops = False,
  zone = False,
  alignments = False,
  local = None,
  fig_name = 'Speed Heat Map',
  figsize = [15.0,
  constantFramerate = 15.0,
  mps_kmh = 3.6,
  duration = 0 
)

Speed.

Plot speed heat/vector/stream map

    Input:
    ======
    objects:                 can be passed as an ordinary list or as a nested camera/sequence ObjectSpace type
    ptype:                   [option]
        'heat' (default)
        'vector'
        'stream'
    constantFramerate:        pass this if objects isn't an objectSpace type
    duration:                 pass this if objects isn't an objectSpace type (in seconds)
    colour:                   http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
    gridsize:                 must be a two-item list, preferably square
    arrowGridReductionFactor: if ptype is vector, the gridsize will be multiplied by this factor
    mincnt:                   bins with fewer than this many points will not be plotted
    sm_scale:                 if this is an int or float, bounds the upper maximum of the colour map; if this is a two-item list, bounds the lower and upper maximum of the colour map respectively

Definition at line 1199 of file vis.py.

1199 def speedMap(objects, ptype='heat', sm_scale=None, colour='hot', xy_bounds=None, gridsize=[60,60], arrowGridReductionFactor=0.3, mincnt=10, virtualLoops=False, zone=False, alignments=False, local=None, fig_name='Speed Heat Map', figsize=[15.0,12.0], constantFramerate=15.0, mps_kmh=3.6, duration=0):
1200  ''' Plot speed heat/vector/stream map
1201 
1202  Input:
1203  ======
1204  objects: can be passed as an ordinary list or as a nested camera/sequence ObjectSpace type
1205  ptype: [option]
1206  'heat' (default)
1207  'vector'
1208  'stream'
1209  constantFramerate: pass this if objects isn't an objectSpace type
1210  duration: pass this if objects isn't an objectSpace type (in seconds)
1211  colour: http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
1212  gridsize: must be a two-item list, preferably square
1213  arrowGridReductionFactor: if ptype is vector, the gridsize will be multiplied by this factor
1214  mincnt: bins with fewer than this many points will not be plotted
1215  sm_scale: if this is an int or float, bounds the upper maximum of the colour map; if this is a two-item list, bounds the lower and upper maximum of the colour map respectively
1216  '''
1217  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
1218  if(not local): local = tvaLocal.Local()
1219  plot_success = False
1220 
1221 
1223  if(sm_scale and type(sm_scale) == list and len(sm_scale) == 2):
1224  scale_norm = plt.Normalize(sm_scale[0],sm_scale[1])
1225  sm_scale = sm_scale[1]
1226  elif(sm_scale and (type(sm_scale) is float or type(sm_scale) is int)):
1227  scale_norm = plt.Normalize(0,sm_scale)
1228  else:
1229  sm_scale = max([max(obj.getSpeeds()) for obj in objects])*float(mps_kmh)*float(constantFramerate)
1230  scale_norm = plt.Normalize(0,sm_scale)
1231  # Bounds
1232  if(xy_bounds is None and zone): xy_bounds = [tvaLib.Constructors.SuperBound([min(zone[0].getXCoordinates()),max(zone[0].getXCoordinates())]), tvaLib.Constructors.SuperBound([min(zone[0].getYCoordinates()),max(zone[0].getYCoordinates())])]
1233 
1234 
1235  if(ptype=='heat' or ptype=='vector'):
1236  posX = []
1237  posY = []
1238  speeds = []
1239  if(type(objects) is list):
1240  speed_conv = float(mps_kmh)*float(constantFramerate)
1241  for obj in objects:
1242  posX += obj.getXCoordinates()
1243  posY += obj.getYCoordinates()
1244  speeds += list(obj.getSpeeds()*speed_conv)
1245  else:
1246  for cam_objs in objects:
1247  for seq_objs, camera in zip(cam_objs, objects.metadatas):
1248  speed_conv = float(camera.camera.frameRate)*float(mps_kmh)
1249  duration += camera.getDuration()
1250  for obj in seq_objs:
1251  posX += obj.getXCoordinates()
1252  posY += obj.getYCoordinates()
1253  speeds += list(obj.getSpeeds()*speed_conv)
1254 
1255 
1256  if(ptype=='vector' or ptype=='stream'):
1257  #Find grid bounds
1258  if(type(objects) is list):
1259  x_min = min([min(obj.getXCoordinates()) for obj in objects])
1260  x_max = max([max(obj.getXCoordinates()) for obj in objects])
1261  y_min = min([min(obj.getYCoordinates()) for obj in objects])
1262  y_max = max([max(obj.getYCoordinates()) for obj in objects])
1263  else:
1264  x_min = min([min(obj.getXCoordinates()) for obj in objects.getAll()])
1265  x_max = max([max(obj.getXCoordinates()) for obj in objects.getAll()])
1266  y_min = min([min(obj.getYCoordinates()) for obj in objects.getAll()])
1267  y_max = max([max(obj.getYCoordinates()) for obj in objects.getAll()])
1268  #Split coordinates into grid system (enforce square bins)
1269  if(ptype=='vector'): gridsize_ = min([int(grid*arrowGridReductionFactor) for grid in gridsize])
1270  else: gridsize_ = min(gridsize)
1271  bin_length = max((x_max-x_min)/gridsize_,(y_max-y_min)/gridsize_)
1272  sideLength = bin_length*float(gridsize_)
1273  PX_t = [x+bin_length/2.0 for x in list(np.arange(x_min,x_min+sideLength,bin_length))[:int(gridsize_)]][:-1]
1274  PY_t = [y+bin_length/2.0 for y in list(np.arange(y_min,y_min+sideLength,bin_length))[:int(gridsize_)]][:-1]
1275  #For each object sort speed values into appropriate bin
1276  speedCacheX=[[[] for j in PY_t] for i in PX_t]
1277  speedCacheY=[[[] for j in PY_t] for i in PX_t]
1278  if(type(objects) is list):
1279  speed_conv = float(mps_kmh)*float(constantFramerate)
1280  for obj in objects:
1281  for point in range(len(obj.getXCoordinates())):
1282  x_bin = min(range(len(PX_t)), key=lambda i: abs(PX_t[i]-obj.getXCoordinates()[point]))
1283  y_bin = min(range(len(PY_t)), key=lambda i: abs(PY_t[i]-obj.getYCoordinates()[point]))
1284  speedCacheX[x_bin][y_bin].append(obj.velocities.getXCoordinates()[point]*speed_conv)
1285  speedCacheY[x_bin][y_bin].append(obj.velocities.getYCoordinates()[point]*speed_conv)
1286  else:
1287  for cam_objs in objects:
1288  for seq_objs, camera in zip(cam_objs, objects.metadatas):
1289  speed_conv = float(camera.camera.frameRate)*float(mps_kmh)
1290  duration += camera.getDuration()
1291  for obj in objects:
1292  for point in range(len(obj.getXCoordinates())):
1293  x_bin = min(range(len(PX_t)), key=lambda i: abs(PX_t[i]-obj.getXCoordinates()[point]))
1294  y_bin = min(range(len(PY_t)), key=lambda i: abs(PY_t[i]-obj.getYCoordinates()[point]))
1295  speedCacheX[x_bin][y_bin].append(obj.velocities.getXCoordinates()[point]*speed_conv)
1296  speedCacheY[x_bin][y_bin].append(obj.velocities.getYCoordinates()[point]*speed_conv)
1297  #Compile average speeds
1298  vectorField = {'PX':[],'PY':[],'VX':[],'VY':[],'S':[]}
1299  for x_bin in range(len(PX_t)):
1300  for y_bin in range(len(PY_t)):
1301  if(len(speedCacheX[x_bin][y_bin]) >= mincnt and len(speedCacheY[x_bin][y_bin]) >= mincnt):
1302  vectorField['PX'].append(PX_t[x_bin])
1303  vectorField['PY'].append(PY_t[y_bin])
1304  vectorField['VX'].append(sum(speedCacheX[x_bin][y_bin])/float(len(speedCacheX[x_bin][y_bin])))
1305  vectorField['VY'].append(sum(speedCacheY[x_bin][y_bin])/float(-1*len(speedCacheY[x_bin][y_bin])))
1306  vectorField['S'].append(m.sqrt(vectorField['VX'][-1]**2+vectorField['VX'][-1]**2))
1307  elif(ptype=='stream'):
1308  vectorField['PX'].append(PX_t[x_bin])
1309  vectorField['PY'].append(PY_t[y_bin])
1310  vectorField['VX'].append(0)
1311  vectorField['VY'].append(0)
1312  vectorField['S'].append(0)
1313 
1314 
1315  if(ptype=='heat' or ptype=='vector'):
1316  plt.hexbin(posX, posY, norm=scale_norm, C=speeds, gridsize=gridsize, cmap=plt.get_cmap(colour), mincnt=mincnt)
1317  cb = plt.colorbar()
1318  cb.set_label(local['vis_speed_cm_label_kmh'])
1319  plot_success = True
1320 
1321 
1322  if(ptype=='vector'):
1323  plt.quiver(vectorField['PX'], vectorField['PY'], vectorField['VX'], vectorField['VY'], units='width', width=0.005)
1324  #plt.quiverkey(Q, 0.9, 0.95, 2, r'$2 \frac{m}{s}$', labelpos='E', coordinates='figure', fontproperties={'weight': 'bold'})
1325  plot_success = True
1326 
1327 
1328  if(ptype=='stream'):
1329  if(not hasattr(plt, 'streamplot')):
1330  tvaLib.printWarning('The module streamplot is not available in the currently installed version of matplotlib (needed for figure "'+fig_name+'").')
1331  plot_success = False
1332  else:
1333  X = np.asarray(tvaLib.wrapList2SquareMatrix(vectorField['PX']))
1334  Y = np.asarray(tvaLib.wrapList2SquareMatrix(vectorField['PY']))
1335  U = np.asarray(tvaLib.wrapList2SquareMatrix(vectorField['VX']))
1336  V = np.asarray(tvaLib.wrapList2SquareMatrix([x*-1.0 for x in vectorField['VY']]))
1337  S = np.asarray(tvaLib.wrapList2SquareMatrix(vectorField['S']))
1338  S2 = np.asarray(tvaLib.wrapList2SquareMatrix([x / sm_scale for x in vectorField['S']]))
1339  try:
1340  plt.streamplot(X.transpose(), Y.transpose(), U.transpose(), V.transpose(), color=S.transpose(), density=4, linewidth=S2.transpose(), arrowsize=3, norm=scale_norm, cmap=plt.get_cmap(colour))
1341  cb = plt.colorbar()
1342  cb.set_label(local['vis_speed_cm_label_kmh'])
1343  plot_success = True
1344  except: plot_success = False
1345 
1346 
1347  if(virtualLoops and hasattr(alignments, 'size')):
1348  virtualLoops_halflength = len(virtualLoops)/2
1349  for lane in range(len(alignments)):
1350  if(duration):
1351  in_flow = str(int(round(float(virtualLoops[lane])/duration*3600)))+' '+local['gen_hourly_veh_units']
1352  out_flow = str(int(round(float(virtualLoops[lane+virtualLoops_halflength])/duration*3600)))+' '+local['gen_hourly_veh_units']
1353  else:
1354  in_flow = str(virtualLoops[lane])+' '+local['vis_speed_veh']
1355  out_flow = str(virtualLoops[lane+virtualLoops_halflength])+' '+local['vis_speed_veh']
1356  if(alignments[lane].hasAlignBB()):
1357  plt.annotate(local['vis_speed_flow']+in_flow, xy = (alignments[lane].getXCoordinatesBB()[0], alignments[lane].getYCoordinatesBB()[0]), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'Square,pad=0.5', fc = 'white', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
1358  plt.annotate(local['vis_speed_flow']+out_flow, xy = (alignments[lane].getXCoordinatesBB()[-1], alignments[lane].getYCoordinatesBB()[-1]), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'Square,pad=0.5', fc = 'white', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
1359  else:
1360  plt.annotate(local['vis_speed_flow']+in_flow, xy = (alignments[lane].getXCoordinates()[0], alignments[lane].getYCoordinates()[0]), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'Square,pad=0.5', fc = 'white', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
1361  plt.annotate(local['vis_speed_flow']+out_flow, xy = (alignments[lane].getXCoordinates()[-1], alignments[lane].getYCoordinates()[-1]), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'Square,pad=0.5', fc = 'white', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
1362 
1363 
1364  ax = plb.gca()
1365  plt.axis('equal')
1366  if(xy_bounds):
1367  ax.set_xlim([xy_bounds[0].lower,xy_bounds[0].upper])
1368  ax.set_ylim([xy_bounds[1].lower,xy_bounds[1].upper])
1369  ax.set_ylim(ax.get_ylim()[::-1])
1370  ax.set_xlabel(local['vis_gen_x_coords_m'])
1371  ax.set_ylabel(local['vis_gen_y_coords_m'])
1372 
1373  if(plot_success): return fig
1374  else: return False
1375 
1376 
def speedMap(objects, ptype='heat', sm_scale=None, colour='hot', xy_bounds=None, gridsize=[60, arrowGridReductionFactor=0.3, mincnt=10, virtualLoops=False, zone=False, alignments=False, local=None, fig_name='Speed Heat Map', figsize=[15.0, constantFramerate=15.0, mps_kmh=3.6, duration=0)
Speed.
Definition: vis.py:1199

◆ traj2D()

def lib.vis.traj2D (   objects,
  draw_max_traj = 200,
  xy_bounds = None,
  alignments = None,
  draw_connectors = True,
  mask = None,
  zone = None,
  SDR = None,
  virtual_loops = None,
  sateliteImage = None,
  sateliteResolution = None,
  labels = False,
  labels_overlap = True,
  timeStampLabels = False,
  objects_uncon = None,
  velocity_vector = False,
  local = None,
  constantFramerate = 15.0,
  mps_kmh = 3.6,
  traj_colour = 'b',
  traj_colour_alternate = '',
  sm_scale = 50,
  cm_colour = 'hot',
  alignAlpha = 1.0,
  fig_name = 'Vehicle Trajectories',
  figsize = [15.0,
  plotSettings = None,
  kwargs 
)
Plot all trajectories in 2 dimensions (X, Y).

    Input:
    ======
    objects:       An ordinary list of moving objects.
    objects_uncon: An ordinary list of moving objects, plotted behind, in 
                   gray (useful to highlight objects outside of the 
                   analysis zone).
    traj_colour:   Colour each (primary) trajectory this coulour, following
                   matplotlib conventions. However, some special parameters
                   may be passed instead:
        'speed':   Trajectories will be colour coded according to their 
                   speed using standard speed colour scale.
        'random':  Trajectories will be colour coded randomly. This might be
                   useful in distinguishing individual tracks.
        'class':   Trajectories will be colour coded according to their 
                   road user classification.
            
    **Kwargs:
        -plotBB and plotSDR passthrough
        -Additional objects datasets can be passed as kwargs and plotted 
         with random alternative colours.

Definition at line 723 of file vis.py.

723 def traj2D(objects, draw_max_traj=200, xy_bounds=None, alignments=None, draw_connectors=True, mask=None, zone=None, SDR=None, virtual_loops=None, sateliteImage=None, sateliteResolution=None, labels=False, labels_overlap=True, timeStampLabels=False, objects_uncon=None, velocity_vector=False, local=None, constantFramerate=15.0, mps_kmh=3.6, traj_colour='b', traj_colour_alternate='', sm_scale=50, cm_colour='hot', alignAlpha=1.0, fig_name='Vehicle Trajectories', figsize=[15.0,12.0], plotSettings=None, **kwargs):
724  ''' Plot all trajectories in 2 dimensions (X, Y).
725 
726  Input:
727  ======
728  objects: An ordinary list of moving objects.
729  objects_uncon: An ordinary list of moving objects, plotted behind, in
730  gray (useful to highlight objects outside of the
731  analysis zone).
732  traj_colour: Colour each (primary) trajectory this coulour, following
733  matplotlib conventions. However, some special parameters
734  may be passed instead:
735  'speed': Trajectories will be colour coded according to their
736  speed using standard speed colour scale.
737  'random': Trajectories will be colour coded randomly. This might be
738  useful in distinguishing individual tracks.
739  'class': Trajectories will be colour coded according to their
740  road user classification.
741 
742  **Kwargs:
743  -plotBB and plotSDR passthrough
744  -Additional objects datasets can be passed as kwargs and plotted
745  with random alternative colours.
746  '''
747 
748  from moving import MovingObject
749 
750  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
751  if(not local): local = tvaLocal.Local()
752  class_colours = ['#ff0000','#0000ff','#00cc00','#996633','#cc0099','#cccc00','#000066',]
753 
754  #Suggest plotting a maximum of two or three trajectories with the following options enabled.
755  config_spec_debug = False
756  config_spec_debug_lane_labels = False
757  config_spec_timestamp = True
758 
759 
760  if(not xy_bounds and not objects and not kwargs): zoomToSatelite = True
761  else: zoomToSatelite = False
762  if(plotSatellite(sateliteImage, sateliteResolution, color=True, zoomTo=zoomToSatelite)):
763  fig.forceDPI = 150
764  fig.forceFormat = 'jpg'
765  draw_connectors = False #Disable for satellite images or else image is too busy
766  outlineOnly = True
767  else: outlineOnly = False
768 
769 
770  plotBB(mask, labels=labels, boxLabel=local['vis_mask'], outlineOnly=outlineOnly, zone_bgcolour='0.90', plotSettings=plotSettings, **kwargs)
771  plotBB(zone, labels=labels, boxLabel=local['vis_analysis_area'], zone_bgcolour='green', alpha=0.5, plotSettings=plotSettings, **kwargs)
772  plotSDR(SDR, zone_bgcolour='0.20', **kwargs)
773  plotVL(virtual_loops, labels=labels)
774 
775 
776  if(objects_uncon):
777  if(not draw_max_traj): draw_max_traj_actual = max(len(objects_uncon), 1)
778  else: draw_max_traj_actual = max(min(len(objects_uncon), draw_max_traj),1)
779 
780  for i in range(0,len(objects_uncon),len(objects_uncon)/draw_max_traj_actual):
781  plt.plot(objects_uncon[i].getXCoordinates(), objects_uncon[i].getYCoordinates(),'0.80')
782 
783 
784  if(traj_colour != 'random' and len(objects) == 2):
785  start_ = max(objects[0].timeInterval.first,objects[1].timeInterval.first)
786  end = min(objects[0].timeInterval.last,objects[1].timeInterval.last)
787  if(start_ <= end):
788  difBefore = objects[0].timeInterval.first-objects[1].timeInterval.first
789  label_vector_range=tvaLib.Geo.rotateVector(330.0, [1,0], inputRadians=False)
790  label_vect_rotation = 15
791  label_vect_length = 175.0
792  label_vect_growth = -7
793  for commonPointIx in range(end-start_):
794  if(difBefore > 0):
795  p0 = commonPointIx
796  p1 = commonPointIx+difBefore
797  else:
798  p0 = commonPointIx-difBefore
799  p1 = commonPointIx
800 
801  #plt.scatter([objects[0].getXCoordinates()[p0],objects[1].getXCoordinates()[p1]], [objects[0].getYCoordinates()[p0],objects[1].getYCoordinates()[p1]], color='k', marker='x')
802 
803  if(commonPointIx % 8 == 0):
804  plt.plot([objects[0].getXCoordinates()[p0],objects[1].getXCoordinates()[p1]], [objects[0].getYCoordinates()[p0],objects[1].getYCoordinates()[p1]], color='0.75')
805  if(labels):
806  deltaD = m.sqrt((objects[0].getXCoordinates()[p0]-objects[1].getXCoordinates()[p1])**2+(objects[0].getYCoordinates()[p0]-objects[1].getYCoordinates()[p1])**2)
807  deltaV = m.sqrt((objects[0].velocities.getXCoordinates()[p0]-objects[1].velocities.getXCoordinates()[p1])**2+(objects[0].velocities.getYCoordinates()[p0]-objects[1].velocities.getYCoordinates()[p1])**2)
808  plt.annotate('$\Delta$v = '+str(round(deltaV*constantFramerate,2))+'m/s\nd = '+str(round(deltaD,2))+'m\nt = '+str(round(float(commonPointIx+start_)/constantFramerate,2))+'s', xy = (objects[0].getXCoordinates()[p1], objects[0].getYCoordinates()[p1]), xytext = (label_vector_range[0]*label_vect_length, label_vector_range[1]*label_vect_length), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'Square,pad=0.10', fc = 'white', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'), size=16)
809  label_vector_range=tvaLib.Geo.rotateVector(label_vect_rotation, label_vector_range, inputRadians=False)
810  label_vect_length+=label_vect_growth
811 
812 
813 
814  objects_sets = [objects]
815  if(kwargs): import moving as TrafIntMoving
816  for kwarg in kwargs:
817  if(type(kwargs[kwarg]) == list and len(kwargs[kwarg]) > 0 and (isinstance(kwargs[kwarg][0], MovingObject) or isinstance(kwargs[kwarg][0], TrafIntMoving.BBAnnotation))): objects_sets.append(kwargs[kwarg])
818 
819 
820  ann=[]
821  for objects,j in zip(objects_sets,range(len(objects_sets))):
822  if(len(objects) == 0): continue
823  if(j != 0 and traj_colour != 'speed'):
824  if(traj_colour_alternate): traj_colour = traj_colour_alternate
825  else: traj_colour = random(),random(),random()
826  if(not draw_max_traj): draw_max_traj_actual = max(len(objects),1)
827  else: draw_max_traj_actual = max(min(len(objects), draw_max_traj),1)
828  for i in range(0,len(objects), len(objects)/draw_max_traj_actual):
829  if(traj_colour == 'random'): traj_colour_actual = random(),random(),random()
830  elif(traj_colour == 'speed'): traj_colour_actual = plt.get_cmap(cm_colour)(sum(objects[i].getSpeeds())*mps_kmh*constantFramerate/float(len(objects[i].getSpeeds())*sm_scale))
831  elif(traj_colour == 'class'): traj_colour_actual = class_colours[objects[i].getUserType()]
832  else: traj_colour_actual = traj_colour
833  plt.plot(objects[i].getXCoordinates(), objects[i].getYCoordinates(), color=traj_colour_actual)
834 
835 
836  if(labels):
837  if(plotSettings): ann.append(plt.annotate(objects[i].num, xy=(objects[i].getXCoordinates()[1], objects[i].getYCoordinates()[1]), size=plotSettings['size']*0.5))
838  else: ann.append(plt.annotate(objects[i].num, xy=(objects[i].getXCoordinates()[1], objects[i].getYCoordinates()[1])))
839  yoffset=-2
840  if(timeStampLabels): plt.annotate('t='+str(objects[i].getFirstInstant()), xy=(objects[i].getXCoordinates()[1], objects[i].getYCoordinates()[1]+yoffset), size=12)
841  if(velocity_vector):
842  for point in range(len(objects[i].getXCoordinates())):
843  plt.annotate(' ', xy = (objects[i].getXCoordinates()[point], objects[i].getYCoordinates()[point]), xytext = (objects[i].getXCoordinates()[point]+objects[i].velocities.getXCoordinates()[point], objects[i].getYCoordinates()[point]+objects[i].velocities.getYCoordinates()[point]), arrowprops = dict(arrowstyle = '<-', connectionstyle = 'arc3,rad=0'))
844  #Spec debug level
845  if(config_spec_debug):
846  if(config_spec_debug_lane_labels):
847  for point in range(len(objects[i].getXCoordinates())):
848  plt.annotate(objects[i].curvilinearPositions.getLanes()[point], xy = (objects[i].getXCoordinates()[point], objects[i].getYCoordinates()[point]), xytext = (-10, 10), textcoords = 'offset points', ha = 'right', va = 'bottom')
849  if(config_spec_timestamp):
850  skip = 0
851  for point in range(len(objects[i].getXCoordinates())):
852  if(skip < 5):
853  skip = skip + 1
854  continue
855  else:
856  skip = 0
857  plt.text(objects[i].getXCoordinates()[point], objects[i].getYCoordinates()[point], objects[i].getFirstInstant()+point, color='#FF0000')
858 
859 
860 
861  if(not labels_overlap):
862  mask_ = np.zeros(fig.canvas.get_width_height(), bool)
863  fig.canvas.draw()
864  for a in ann:
865  bbox = a.get_window_extent()
866  x0 = int(bbox.x0)
867  x1 = int(m.ceil(bbox.x1))
868  y0 = int(bbox.y0)
869  y1 = int(m.ceil(bbox.y1))
870 
871  s = np.s_[x0:x1+1, y0:y1+1]
872  if(np.any(mask_[s])): a.set_visible(False)
873  else: mask_[s] = True
874 
875 
876 
877  plotAlign(alignments, draw_connectors=draw_connectors, lineAlpha=alignAlpha, labels=labels, plotSettings=plotSettings)
878 
879 
880  if(traj_colour == 'class'):
881  #Create custom artists
882  dummy_class_colour_prototypes = []
883  for cIx in range(len(local['userTypeNames'])):
884  dummy_class_colour_prototypes.append(plt.Line2D((objects[0].getXCoordinates()[0],objects[0].getYCoordinates()[0]),(objects[0].getXCoordinates()[0],objects[0].getYCoordinates()[0]), color=class_colours[cIx], linewidth=2))
885  plt.legend(dummy_class_colour_prototypes,local['userTypeNames'])
886 
887 
888 
889 
890  ax = plb.gca()
891  if(not zoomToSatelite): plt.axis('equal')
892  if(xy_bounds):
893  ax.set_xlim([xy_bounds[0].lower,xy_bounds[0].upper])
894  ax.set_ylim([xy_bounds[1].lower,xy_bounds[1].upper])
895  ax.set_ylim(ax.get_ylim()[::-1])
896  ax.set_xlabel(local['vis_gen_x_coords_m'])
897  ax.set_ylabel(local['vis_gen_y_coords_m'])
898 
899 
900  fig.tight_layout()
901 
902  return fig
903 
904 
def plotBB(bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, kwargs)
Definition: vis.py:422
def plotVL(virtual_loops, labels=False, colour='#D63E33')
Definition: vis.py:464
def plotAlign(alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None)
Definition: vis.py:477
def plotSDR(SDR, local=None, outlineOnly=False, alpha=1.00, zorder=1, sdr_bgcolour='0.66', kwargs)
Definition: vis.py:452
def plotSatellite(sateliteImage, sateliteResolution, color=False, zorder=0, origin=[0, zoomTo=False)
Definition: vis.py:551
def traj2D(objects, draw_max_traj=200, xy_bounds=None, alignments=None, draw_connectors=True, mask=None, zone=None, SDR=None, virtual_loops=None, sateliteImage=None, sateliteResolution=None, labels=False, labels_overlap=True, timeStampLabels=False, objects_uncon=None, velocity_vector=False, local=None, constantFramerate=15.0, mps_kmh=3.6, traj_colour='b', traj_colour_alternate='', sm_scale=50, cm_colour='hot', alignAlpha=1.0, fig_name='Vehicle Trajectories', figsize=[15.0, plotSettings=None, kwargs)
Definition: vis.py:723

◆ traj2DHighlightAlignments()

def lib.vis.traj2DHighlightAlignments (   objects,
  xy_bounds,
  alignments,
  marker_size = 0.4,
  labels = True,
  local = None,
  fig_name = 'Trajectory Lane Highlight',
  figsize = [15.0,
  plotSettings = None,
  kwargs 
)
Plot trajectories highlighting which alignment it is associate with 

Definition at line 905 of file vis.py.

905 def traj2DHighlightAlignments(objects, xy_bounds, alignments, marker_size=0.4, labels=True, local=None, fig_name='Trajectory Lane Highlight', figsize=[15.0,12.0], plotSettings=None, **kwargs):
906  ''' Plot trajectories highlighting which alignment it is associate with '''
907  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
908  if(not local): local = tvaLocal.Local()
909 
910 
911  colours=['#ff7133','#d3cc18','#33a1ff','#ff0000','#33ff59','#ea14ed','#49a353',
912  '#603c2c','#4018d3','#050906','#7b7b7b','#fb1a8e','#c39d71','#71c3c2',
913  '#f1f33c','#266719','#4b6d87','#9f82cf','#f05ec9','#c3350f']
914 
915  for lane in range(len(alignments)):
916  plt.scatter(tvaLib.flatten_list([[obj.getXCoordinates()[pIx] for pIx in range(len(obj.getXCoordinates())) if obj.curvilinearPositions.getLanes()[pIx] == lane] for obj in objects]), tvaLib.flatten_list([[obj.getYCoordinates()[pIx] for pIx in range(len(obj.getYCoordinates())) if obj.curvilinearPositions.getLanes()[pIx] == lane] for obj in objects]), color=colours[lane], s=marker_size)
917 
918  '''for obj in objects:
919  for pIx in range(len(obj.getXCoordinates())-1):
920  try: plt.plot([obj.getXCoordinates()[pIx],obj.getXCoordinates()[pIx+1]], [obj.getYCoordinates()[pIx],obj.getYCoordinates()[pIx+1]], color=colours[obj.curvilinearPositions.getLanes()[pIx]])
921  except IndexError:
922  tvaLib.printWarning('There are too many alignments to draw this site\'s highlight map', local['gen_warning'])
923  return None'''
924 
925 
926  plotAlign(alignments, custom_colours=colours, labels=labels, highContrastLabels=True, plotSettings=plotSettings)
927 
928 
929  ax = plb.gca()
930  plt.axis('equal')
931  if(xy_bounds):
932  ax.set_xlim([xy_bounds[0].lower,xy_bounds[0].upper])
933  ax.set_ylim([xy_bounds[1].lower,xy_bounds[1].upper])
934  ax.set_ylim(ax.get_ylim()[::-1])
935  ax.set_xlabel(local['vis_gen_x_coords_m'])
936  ax.set_ylabel(local['vis_gen_y_coords_m'])
937 
938 
939  fig.tight_layout()
940 
941  return fig
942 
943 
def plotAlign(alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None)
Definition: vis.py:477
def traj2DHighlightAlignments(objects, xy_bounds, alignments, marker_size=0.4, labels=True, local=None, fig_name='Trajectory Lane Highlight', figsize=[15.0, plotSettings=None, kwargs)
Definition: vis.py:905

◆ traj3D()

def lib.vis.traj3D (   objects,
  start = 0,
  draw_max_traj = 200,
  draw_connectors = True,
  xy_bounds = None,
  alignments = None,
  mask = None,
  labels = False,
  timeStampLabels = False,
  local = None,
  fig_name = 'Vehicle Trajectories 3D',
  traj_colour = 'b',
  figsize = [15.0 
)
Plot all trajectories in 3 dimensions (X, Y, t). 

Definition at line 989 of file vis.py.

989 def traj3D(objects, start=0, draw_max_traj=200, draw_connectors=True, xy_bounds=None, alignments=None, mask=None, labels=False, timeStampLabels=False, local=None, fig_name='Vehicle Trajectories 3D', traj_colour='b', figsize=[15.0,12.0]):
990  ''' Plot all trajectories in 3 dimensions (X, Y, t). '''
991  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
992  ax = Axes3D(plt.gcf())
993  if(not local): local = tvaLocal.Local()
994 
995 
996  plotBB(mask, labels=labels, boxLabel=local['vis_mask'])
997 
998 
999  for i in range(len(objects))[start:min(len(objects),(start+draw_max_traj))]:
1000  if(traj_colour == 'random'): traj_colour_actual = random(),random(),random()
1001  else: traj_colour_actual = traj_colour
1002  ax.plot(objects[i].getXCoordinates(), objects[i].getYCoordinates(), range(objects[i].getTimeInterval().first,objects[i].getTimeInterval().last+1), color=traj_colour_actual)
1003 
1004 
1005  if(labels):
1006  plt.annotate(objects[i].num, xy=(objects[i].getXCoordinates()[1], objects[i].getYCoordinates()[1]))
1007  yoffset=-2
1008  if(timeStampLabels):
1009  plt.annotate('t='+str(objects[i].getFirstInstant()), xy=(objects[i].getXCoordinates()[1], objects[i].getYCoordinates()[1]+yoffset), size=12)
1010 
1011 
1012  plotAlign(alignments, draw_connectors=draw_connectors, labels=labels)
1013 
1014 
1015 
1016  ax = plb.gca()
1017  plt.axis('equal')
1018  if(xy_bounds):
1019  ax.set_xlim([xy_bounds[0].lower,xy_bounds[0].upper])
1020  ax.set_ylim([xy_bounds[1].lower,xy_bounds[1].upper])
1021  ax.set_ylim(ax.get_ylim()[::-1])
1022  ax.set_xlabel(local['vis_gen_x_coords_m'])
1023  ax.set_ylabel(local['vis_gen_y_coords_m'])
1024 
1025  return fig, ax
1026 
1027 
def plotBB(bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, kwargs)
Definition: vis.py:422
def plotAlign(alignments, custom_colours=None, draw_connectors=True, draw_corridors=True, labels=False, legacyLabels=False, distanceBetweenLabels=20.0, highContrastLabels=False, lineAlpha=1.0, annotateAlpha=0.2, corridorAlpha=0.5, zorder=20, plotSettings=None)
Definition: vis.py:477
def traj3D(objects, start=0, draw_max_traj=200, draw_connectors=True, xy_bounds=None, alignments=None, mask=None, labels=False, timeStampLabels=False, local=None, fig_name='Vehicle Trajectories 3D', traj_colour='b', figsize=[15.0)
Definition: vis.py:989

◆ visAlignData()

def lib.vis.visAlignData (   sl,
  slsd,
  hl_offset = False,
  local = None,
  min_obs = 10,
  fig_name = 'Alignment data',
  figsize = [15.0,
  plotSettings = None 
)

Alignments.

Plot alignment speed and observation data

    Greek letter documentation at: http://matplotlib.sourceforge.net/users/mathtext.html

Definition at line 1734 of file vis.py.

1734 def visAlignData(sl, slsd, hl_offset=False, local=None, min_obs=10, fig_name='Alignment data', figsize=[15.0,12.0], plotSettings=None):
1735  ''' Plot alignment speed and observation data
1736 
1737  Greek letter documentation at: http://matplotlib.sourceforge.net/users/mathtext.html
1738  '''
1739 
1740  aligns = {}
1741  for align in range(len(sl)):
1742  #Get mean number of observations
1743  mean_obs = np.mean(slsd[align][0])
1744  if(mean_obs < min_obs): continue
1745  #Get un-nan bounds
1746  for point in range(len(sl[align][2])):
1747  if(not m.isnan(sl[align][2][point])):
1748  x_min_1 = point
1749  break
1750  for point in range(len(slsd[align][0])):
1751  if(slsd[align][0][point] > (mean_obs/3)):
1752  x_min_2 = point
1753  break
1754  x_min=max(x_min_1,x_min_2)
1755 
1756  for point in range(len(sl[align][2])):
1757  i_point = len(sl[align][2]) - point - 1
1758  if(not m.isnan(sl[align][2][i_point])):
1759  x_max_1 = i_point
1760  break
1761  for point in range(len(slsd[align][0])):
1762  i_point = len(slsd[align][0]) - point - 1
1763  if(slsd[align][0][i_point] > (mean_obs/3)):
1764  x_max_2 = i_point
1765  break
1766  x_max=min(x_max_1,x_max_2)
1767 
1768  try: x_min
1769  except NameError:
1770  tvaLib.printWarning('No trajectories found while attempting to plot alignment {0}'.format(align), indent=4)
1771  x_min = 0
1772  try: x_max
1773  except NameError:
1774  tvaLib.printWarning('No trajectories found while attempting to plot alignment {0}'.format(align), indent=4)
1775  x_max = 0
1776 
1777  aligns[align] = [x_min,x_max]
1778 
1779  if(len(aligns)==0): return False
1780  fig, axes = plt.subplots(nrows=len(aligns), ncols=1, num=fig_name, sharex=True, figsize=(figsize[0], figsize[1]))
1781  if(type(axes) is not list and type(axes) is not np.ndarray): axes = [axes]
1782  if(not local): local = tvaLocal.Local()
1783  labelsPlotted=False
1784 
1785  for align,axis in zip(aligns,axes):
1786  x_min = aligns[align][0]
1787  x_max = aligns[align][1]
1788 
1789  axis.plot(sl[align][1][x_min:x_max], sl[align][2][x_min:x_max], 'r', linewidth=2, label=r"$\mu$ "+local['gen_speed_']) y_max = max(sl[align][2][x_min:x_max])
1790  std_up = [sum(pair) for pair in zip(sl[align][2][x_min:x_max], sl[align][3][x_min:x_max])]
1791  std_down = [pair[0]-pair[1] for pair in zip(sl[align][2][x_min:x_max], sl[align][3][x_min:x_max])]
1792  if(std_up and std_down):
1793  axis.plot(sl[align][1][x_min:x_max], std_up, 'b--', label=r"$+1 \sigma$")
1794  axis.plot(sl[align][1][x_min:x_max], std_down, 'b--', label=r"$-1 \sigma$")
1795  y_max = max(std_up)
1796  axis.set_ylim(0, y_max)
1797 
1798 
1799 
1800  ax2 = axis.twinx()
1801  axis.plot(slsd[align][1][x_min], slsd[align][0][x_min], 'k', linewidth=3, label=local['gen_observations'])
1802  ax2.plot(slsd[align][1][x_min:x_max], slsd[align][0][x_min:x_max], 'k', linewidth=3, label=local['gen_observations'])
1803  ax2.set_ylim(max(min((max(slsd[align][0][x_min:x_max])/2),min(slsd[align][0][x_min:x_max]))-10,0), max(slsd[align][0][x_min:x_max])+10)
1804 
1805 
1806  if(hl_offset != False):
1807  X = []
1808  Y = []
1809  for point in hl_offset[align]:
1810  X.append(point[0])
1811  Y.append(point[1])
1812  ay2 = plt.twiny()
1813  #Recalculate axis alignment (e.g. equivalent xmin, xmax)
1814  ay2.set_xticks(X)
1815  ay2.set_xticklabels(Y)
1816  ay2.set_xlabel('Merge region (normalised)')
1817 
1818 
1819 
1820  axis.set_title(local['gen_alignment']+' '+str(align+1), size=plotSettings['size']*0.66)
1821  if(not labelsPlotted):
1822  axis.legend(prop={'size':plotSettings['size']*0.66})
1823  labelsPlotted=True
1824 
1825 
1826 
1827  fig.text(0.5, 0.04, local['vis_align_x_label'], ha='center', va='center')
1828  fig.text(0.06, 0.5, local['gen_speed'], ha='center', va='center', rotation='vertical')
1829  fig.text(0.96, 0.5, local['gen_observations'], ha='center', va='center', rotation='vertical')
1830 
1831  return fig
1832 
1833 
def visAlignData(sl, slsd, hl_offset=False, local=None, min_obs=10, fig_name='Alignment data', figsize=[15.0, plotSettings=None)
Alignments.
Definition: vis.py:1734

◆ visTrajImageSpace()

def lib.vis.visTrajImageSpace (   objects = None,
  image = '',
  homography = None,
  labels = False,
  start = 0,
  draw_max_traj = 200,
  mask = None,
  local = None,
  fig_name = 'Vehicle Trajectories in Image Space',
  traj_colour = 'b',
  alpha = 1.0,
  figsize = [15.0,
  kwargs 
)
Plot all trajectories in projected imagespace.

    Additional objects datasets can be passed as kwargs and plotted with random alternative colours

Definition at line 944 of file vis.py.

944 def visTrajImageSpace(objects=None, image='', homography=None, labels=False, start=0, draw_max_traj=200, mask=None, local=None, fig_name='Vehicle Trajectories in Image Space', traj_colour='b', alpha=1.0, figsize=[15.0,12.0], **kwargs):
945  ''' Plot all trajectories in projected imagespace.
946 
947  Additional objects datasets can be passed as kwargs and plotted with random alternative colours
948  '''
949  fig = plt.figure(fig_name, figsize=(figsize[0], figsize[1]))
950  if(not local): local = tvaLocal.Local()
951 
952 
953  if(objects):
954  for i in range(len(objects)):
955  if(not hasattr(objects[i], 'projectedPositions')):
956  if(homography is None): return None
957  objects[i].projectedPositions = tvaLib.Obj.trajectoryProject(objects[i], homography)
958  if(mask):
959  mask_ = deepcopy(mask)
960  for mIx in range(len(mask_)):
961  for pIx in range(len(mask_[mIx])):
962  x,y = tvaLib.Obj.homographyProject(homography, [[mask_[mIx][pIx][0]],[mask_[mIx][pIx][1]]])
963  mask_[mIx][pIx].x = x[0]
964  mask_[mIx][pIx].y = y[0]
965 
966 
967  if(image):
968  img = mpimg.imread(image)
969  plt.imshow(img, extent=(0,img.shape[1],0,img.shape[0]), origin='lower')
970  alpha = 0.5
971 
972 
973  if(mask): plotBB(mask_, labels=labels, boxLabel=local['vis_mask'], alpha=alpha, **kwargs)
974 
975 
976  if(objects):
977  if(not draw_max_traj): draw_max_traj_actual = max(len(objects),1)
978  else: draw_max_traj_actual = max(min(len(objects),(start+draw_max_traj)),1)
979  for i in range(len(objects))[start:draw_max_traj_actual]:
980  plt.plot(objects[i].projectedPositions.getXCoordinates(), objects[i].projectedPositions.getYCoordinates(), traj_colour)
981 
982 
983  ax = plb.gca()
984  ax.set_ylim(ax.get_ylim()[::-1])
985 
986  return fig
987 
988 
def plotBB(bounding_boxes, labels=False, legacyLabels=False, boxLabel=None, outlineOnly=False, alpha=1.00, zorder=1, zone_bgcolour='0.66', plotSettings=None, kwargs)
Definition: vis.py:422
def visTrajImageSpace(objects=None, image='', homography=None, labels=False, start=0, draw_max_traj=200, mask=None, local=None, fig_name='Vehicle Trajectories in Image Space', traj_colour='b', alpha=1.0, figsize=[15.0, kwargs)
Definition: vis.py:944

Variable Documentation

◆ legend_labels

lib.vis.legend_labels

Definition at line 2385 of file vis.py.