-
Notifications
You must be signed in to change notification settings - Fork 3
/
qtm_plot.py
3316 lines (2938 loc) · 126 KB
/
qtm_plot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import division
import matplotlib.pyplot as pl
import matplotlib as mp
import matplotlib.image as mpimg
from matplotlib.patches import Arc,Arrow,Circle
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.collections import LineCollection
import numpy as np
import ujson as json
import sys
import argparse
import os
import os.path
import numpy as np
import scipy.interpolate as interp
import math as math
import zipfile
import zlib
import pandas as pd
from IPython.display import display
import time as clock_time
import gc
def find_paths(data):
paths = []
for flow in data["Flows"].keys():
f = flow.split('_')
q1 = int(f[0])
q2 = int(f[1])
found_q1 = False
found_q2 = False
p1 = None
p2 = None
for p in paths:
if q1 in p:
found_q1 = True
p1 = p
if q2 in p:
found_q2 = True
p2 = p
if found_q1 and found_q2:
if p1 == p2:
print "Error! queue %d->%d already added!" % (q1,q2)
else:
paths.remove(p2)
p1 += p2
elif found_q1:
p1.insert(p1.index(q1)+1,q2)
elif found_q2:
p2.insert(p2.index(q2),q1)
else:
paths.append([q1,q2])
#print paths
return paths
def calc_total_stops(data,results):
Queues = data['Queues']
time=results['t']
stops=0
for i,q in enumerate(Queues):
for n,t in enumerate(time[1:-1]):
stops+=abs(results['q_%d' %i ][n] - results['q_%d' %i ][n-1])
return 0.5 * stops
def calc_total_travel_time(data,results):
Queues = data['Queues']
time=results['t']
sum_in=0
sum_out=0
for i,q in enumerate(Queues):
for n,t in enumerate(time):
if Queues[i]['Q_IN'] > 0:
sum_in+=(t*results['q_{%d,in}' %i ][n])
if Queues[i]['Q_OUT'] > 0:
sum_out+=(t*results['q_{%d,out}' %i ][n])
return sum_out-sum_in
def calc_total_traffic(data,results,lanes):
total_in_flow = 0
for lane in lanes:
in_flow = sum(results['q_{%d,in}' % lane[0]])
total_in_flow+=in_flow
return total_in_flow
def calc_free_flow_travel_time(data,results,lanes):
queue = data['Queues']
lane_free_flow_travel_time = []
total_in_flow = 0
for lane in lanes:
q_delay = 0
in_flow = sum(results['q_{%d,in}' % lane[0]])
#print '%d in_flow' % lane[0],in_flow
total_in_flow+=in_flow
for i in lane:
q_delay += queue[i]['Q_DELAY']
lane_free_flow_travel_time.append(q_delay*in_flow)
#print total_in_flow
return sum(lane_free_flow_travel_time)
def calc_total_free_flow_travel_time(data,results):
total_free_flow_travel_time = 0
for queue in data['Queues']:
total_free_flow_travel_time += queue['Q_DELAY'] * args.time_factor
return total_free_flow_travel_time
def calc_in_flow_duration(data,results):
Queues = data['Queues']
time=results['t']
max_time = 0
EPSILON = 1e-6
for i,queue in enumerate(Queues):
if queue['Q_IN'] > 0:
for n,q_in in enumerate(results['q_{%d,in}' % i]):
if q_in > EPSILON and time[n] > max_time:
max_time = time[n]
return max_time
def calc_delay(data, results, queues=[], dp=6, dt=1):
Queues = data['Queues']
time=results['t']
cumu_in = []
cumu_out= []
cumu_delay=[]
in_q=[]
out_q=[]
q_delay=0
EPSILON = 1e-6
if not queues or len(queues) == 0:
for i,q in enumerate(Queues):
if Queues[i]['Q_IN'] > 0:
in_q.append(results['q_{%d,in}' %i ])
if Queues[i]['Q_OUT'] > 0:
out_q.append(results['q_{%d,out}' %i ])
else:
in_q.append(results['q_{%d,in}' % int(queues[0]) ])
out_q.append(results['q_{%d,out}' % int(queues[-1]) ])
for i in queues:
q_delay+=Queues[i]['Q_DELAY']
for i,t in enumerate(time):
if i==0:
cumu_in.append(0)
cumu_out.append(0)
else:
cumu_in.append(cumu_in[-1])
cumu_out.append(cumu_out[-1])
for q in in_q:
cumu_in[i] += q[i]
#if abs(cumu_in[i - 1] - cumu_in[i]) < EPSILON:
# cumu_in[i] = cumu_in[i - 1]
for q in out_q:
cumu_out[i]+=q[i]
#if abs(cumu_out[i - 1] - cumu_out[i]) < EPSILON:
# cumu_out[i] = cumu_out[i - 1]
cumu_in = np.array(cumu_in)
cumu_out = np.array(cumu_out)
cumu_in = np.around(cumu_in,dp) #cumu_in[cumu_in < EPSILON] = 0
cumu_out = np.around(cumu_out,dp) #cumu_out[cumu_out < EPSILON] = 0
n0_in=0
while n0_in + 1 < len(cumu_in) and cumu_in[n0_in] == 0 and cumu_in[n0_in + 1] == 0: n0_in += 1
n1_in = len(cumu_in) - 1
while n1_in > 0 and abs(cumu_in[n1_in - 1] - cumu_in[n1_in]) < EPSILON: n1_in -= 1
icumu_in_f = interp.interp1d(cumu_in[n0_in:], time[n0_in:], assume_sorted = True, bounds_error = False, fill_value = time[n1_in])
icars = np.linspace(cumu_in[n0_in], max(cumu_in), (max(cumu_in) + 1) * 20, endpoint=True)
icars_in = icumu_in_f(icars)
n0_out=0
while n0_out + 1 < len(cumu_out) and cumu_out[n0_out] == 0 and cumu_out[n0_out + 1] == 0: n0_out += 1
n1_out = len(cumu_out) - 1
while n1_out > 0 and abs(cumu_out[n1_out - 1] - cumu_out[n1_out]) < EPSILON: n1_out -= 1
icumu_out_f = interp.interp1d(cumu_out[n0_out:], time[n0_out:], assume_sorted = True, bounds_error = False, fill_value = time[n1_out])
icars = np.linspace(cumu_out[n0_out], max(cumu_out), (max(cumu_out) + 1) * 20, endpoint=True)
icars_out = icumu_out_f(icars)
cumu_cars_in = cumu_in[n0_in:n1_in + 1]
cumu_cars_out = cumu_cars_in
tcars_in = np.copy(icumu_in_f(cumu_cars_in))
tcars_out = np.copy(icumu_out_f(cumu_cars_out))
#print len(tcars_in),len(tcars_out)
#tcars_in.resize(max(len(tcars_in),len(tcars_out)))
#tcars_out.resize(max(len(tcars_in),len(tcars_out)))
trimmed_cumu_delay = tcars_out - tcars_in - q_delay
trimmed_cumu_delay[trimmed_cumu_delay < 0] = 0
cumu_delay = np.zeros(len(time))
cumu_delay[n0_in:n0_in+len(trimmed_cumu_delay)] = trimmed_cumu_delay
#pl.figure()
#pl.plot(trimmed_cumu_delay,'rx-')
cumu_cars_in = np.linspace(dt, max(cumu_in), max(cumu_in)/dt, endpoint=True)
#print cumu_cars_in
cumu_cars_out = cumu_cars_in
tcars_in = np.copy(icumu_in_f(cumu_cars_in))
tcars_out = np.copy(icumu_out_f(cumu_cars_out))
delay_by_car = tcars_out - tcars_in - q_delay
delay_by_car[delay_by_car < 0] = 0
#pl.plot(delay_by_car,'.-')
#pl.show()
#print tcars_in,tcars_out
#print len(trimmed_cumu_delay),len(delay_by_car)
#cumu_delay = np.zeros(len(time))
#cumu_delay[n0_in:n0_in+len(delay_by_car)] = delay_by_car
#print delay_by_car
#print n0_in,cumu_in[:100]
#print n0_out,cumu_out[:100]
#print tcars_in[:100]
#print tcars_out[:100]
#print cumu_delay[:100]
#print cumu_delay
return time,cumu_in,cumu_out,cumu_delay.tolist(),delay_by_car.tolist(),trimmed_cumu_delay.tolist()
def trim_delay(cumu_data):
"""
:param cumu_data: tuple of cumulative data=(time vector,cumulative arrivals,cumulative depatures,delay)
:return: a delay curve trimmed of leading and trailing zero's
"""
cumu_in = cumu_data[1]
#print cumu_in
cumu_delay = cumu_data[4]
EPSILON = 1e-6
j = 0
while j+1 < len(cumu_in) and (cumu_in[j+1] - cumu_in[j]) < EPSILON: j += 1
in_start = j
j = len(cumu_in) - 2
#print (cumu_in[j] - cumu_in[j+1])
while j > 0 and (cumu_in[j+1] - cumu_in[j]) < EPSILON:
#print (cumu_in[j] - cumu_in[j+1])
j -= 1
#print
in_end = j+1
#print in_start,in_end,cumu_delay[0:in_start],cumu_delay[in_end+1:-1]
#print '-----'
#print cumu_delay[in_start:in_end+1]
#print '*****'
return cumu_delay[in_start:in_end+1]
def calc_histogram_delay(data, step, width, queues=[],oversample=10):
results = data['Out']
if step != None:
if 'Step' in results:
results = data['Out']['Step'][step]
label = results['label']
time = results['t']
total_time = time[-1] - time[0]
N = int(total_time / width)
bins = [0 for x in range(N)]
bin_ranges = [width*x for x in range(N+1)]
M = N * oversample
Q = 1
if not queues:
queues = [range(len(data['Queues']))]
Q = len(queues)
for q in queues:
cumu_time,cumu_in,cumu_out,cumu_delay,delay_by_car,delay = calc_delay(data,step, q)
in_start=0
in_end=1
for j in range(len(cumu_in)):
if cumu_in[j] > cumu_in[in_end]: in_end=j
j=0
while cumu_in[in_start+1]<1e-6 and in_start<in_end-1: in_start+=1
t=time[in_start]
dt = (time[in_end] - time[in_start])/M
k=in_start
while t<time[in_end]:
alpha = (t- time[k]) / (time[k+1] - time[k])
delay = (1-alpha) * cumu_delay[k] + alpha * cumu_delay[k+1]
j=0
while delay>bin_ranges[j+1] and j<N: j+=1
w = 1/((cumu_in[-1]) /(bin_ranges[j+1]-bin_ranges[j]))
bins[j]+=1/oversample
t+=dt
if t>time[k+1]: k+=1
return bins,bin_ranges
def plot_delay_gt(data, step, width, threshold, queues=[],plots=None,line_style=['-'],colours='krgb'):
pl.clf()
fig, ax = pl.subplots(nrows=1, ncols=1, sharex=True, sharey=False)
fig.set_size_inches(15, 7)
titles=[]
i=0
c_i=0
if plots == None: plots = [1]
offset=0
for num_files in plots:
plot_data = dict()
plot_label=''
for file in range(num_files):
d=data[offset+file]
title = d['Title']
titles.append(d['Title'])
results = d['Out']
label = d['Out']['label']
if 'Step' in results:
N = len(d['Out']['Step'][0]['t'])-1
else:
N = len(results['t'])-1
if step != None:
if 'Step' in results:
results = d['Out']['Step'][step]
label = results['label']
if len(plot_label)==0:
plot_label = '$'+label.split('$')[1]+'$'
time = results['t']
total_time = time[-1] - time[0]
x_range = 0
bins,bin_ranges = calc_histogram_delay(d, step, width, queues,10)
total = sum(bins)
#bins = [x/total /(bin_ranges[j+1]-bin_ranges[j]) for j,x in enumerate(bins)]
above = 0
below = 0
for j,x in enumerate(bins):
bins[j] = x * (bin_ranges[j+1]-bin_ranges[j])
if bin_ranges[j]>threshold:
above+=bins[j]
else:
below+=bins[j]
plot_data[N]=above
X = sorted(plot_data)
Y = [plot_data[x] for x in X]
ax.plot(X,Y,c=colours[c_i], label=plot_label)
if i+1 < len(line_style): i += 1
if c_i+1 < len(colours): c_i += 1
offset+=num_files
#ax.set_xlim(0, x_range)
ax.grid()
ax.set_xlabel('N (Samples)')
ax.set_ylabel('Number of vehicles delayed > %0.8g' % threshold)
if not args.no_legend:
ax.legend(loc='best')
pl.title('Delay > %0.1g Histogram for Queues %s' % (threshold,', '.join([str(q) for q in queues])) )
def plot_delay_histogram(data, step, width, queues=[],line_style=['--'],colours='krgb',args=None):
pl.clf()
fig, ax = pl.subplots(nrows=1, ncols=1, sharex=True, sharey=False)
fig.set_size_inches(15, 7)
titles=[]
i=0
c_i=0
for d in data:
title = d['Title']
titles.append(d['Title'])
results = d['Out']
label = d['Out']['label']
if step != None:
if 'Step' in results:
results = d['Out']['Step'][step]
label = results['label']
time = results['t']
total_time = time[-1] - time[0]
x_range = 0
bins,bin_ranges = calc_histogram_delay(d, step, width, queues,10)
total = sum(bins)
for j,x in enumerate(bins):
bins[j] = x *(bin_ranges[j+1]-bin_ranges[j])
if bins[j]>1e-5 and x_range<bin_ranges[j+1]:
if j<len(bin_ranges)-2:
x_range=bin_ranges[j+2]
else:
x_range=bin_ranges[j+1]
#bins = [x/total /(bin_ranges[j+1]-bin_ranges[j]) for j,x in enumerate(bins)]
ax.plot(bin_ranges[:-1],bins,c=colours[c_i], linestyle=line_style[i], label=label)
if i+1 < len(line_style): i += 1
if c_i+1 < len(colours): c_i += 1
#ax.set_xlim(0, x_range)
ax.grid()
ax.set_xlabel('Delay (sec)')
ax.set_ylabel('Frequency')
if args.x_limit != None:
ax.set_xlim(args.x_limit[0], args.x_limit[1])
if args.y_limit != None:
ax.set_ylim(args.y_limit[0], args.y_limit[1])
if not args.no_legend:
ax.legend(loc='best')
pl.title('Delay Histogram for Queues %s' % ', '.join([str(q) for q in queues]) )
def label_distance(theta,i):
dx = 0
dy = 0
if theta > 155 or theta < -155: # Vertical down
if i>9: dx = -3
else: dx = 3
elif theta > -25 and theta < 25: # Vertical up
dx = -13
elif theta > -115 and theta < -65: # horizontal left
dy = 10
elif theta > 65 and theta < 115: # horzontal right
dy = -6
else: # Default
dx = -7
return dx,dy
def plot_circle_label(ax,label,x,y,r):
p = Circle((x,y), r,ec='k',fc='w')
ax.add_patch(p)
ax.text(x-2,y-2,label,fontsize=10,color='k')
def plot_network_figure(data,figsize=None,type='arrow',index_label_base=0,delay=False,debug=False):
fig, ax = pl.subplots(nrows=1, ncols=1, sharex=True, sharey=False)
green_red = LinearSegmentedColormap('green_red', {'red': ((0.0, 0.0, 0.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'green': ((0.0, 1.0, 1.0),
(0.5, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0))})
black_green_red = LinearSegmentedColormap('black_green_red', {'red': ((0.0, 0.0, 0.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'green': ((0.0, 0.0,0.0),
(0.1, 1.0, 1.0),
(0.5, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0))})
mp.cm.register_cmap('green_red',green_red)
mp.cm.register_cmap('black_green_red',black_green_red)
cmap_name = args.colormap
gamma = args.gamma
cmap = pl.get_cmap(cmap_name)
cmap.set_gamma(gamma)
Z = [[0,0],[0,0]]
levels = range(0,110,10)
CS3 = pl.contourf(Z, levels, cmap=cmap)
pl.clf()
pl.close('all')
cNorm = mp.colors.Normalize(vmin=0, vmax=1)
scalarMap = mp.cm.ScalarMappable(norm=cNorm,cmap=cmap)
#fig.set_size_inches(10, 5)
cNorm = mp.colors.Normalize(vmin=0, vmax=1)
scalarMap = mp.cm.ScalarMappable(norm=cNorm,cmap=cmap)
line_width = 1
tail_width = 0
head_width = 5
r=15 # radius of intersection nodes
label_space=15 # label spacing from line
d=5 # distance to space two edges that share a pair of nodes
width = 3 # width of bar
track_width = 2 # width of track
track_spacing = 5 # spacing between sleepers along track
lx = 3 # light label x offset
ly = 3 # light label y offset
line_color = 'k'
edge_color = 'k'
light_color = 'w'
text_color = 'k'
font_size = 16
ext = [-200,200,-110,110]
bg_ext = ext
img = None
if 'Plot' in data:
ext = data['Plot']['extent']
if 'bg_image' in data['Plot']:
if data['Plot']['bg_image'] != None:
img = mpimg.imread(data['Plot']['bg_image'])
if 'bg_extent' in data['Plot']:
bg_ext = data['Plot']['bg_extent']
bg_alpha = 1.0
if 'bg_alpha' in data['Plot']:
if data['Plot']['bg_alpha'] != None:
bg_alpha = data['Plot']['bg_alpha']
#pl.imshow(img,extent=ext,alpha=bg_alpha)
if figsize is None and 'fig_size' in data['Plot']:
figsize = tuple(data['Plot']['fig_size'])
if 'line_width' in data['Plot']:
line_width = data['Plot']['line_width']
if 'head_width' in data['Plot']:
head_width = data['Plot']['head_width']
if 'tail_width' in data['Plot']:
tail_width = data['Plot']['tail_width']
if 'line_color' in data['Plot']:
line_color = data['Plot']['line_color']
if 'edge_color' in data['Plot']:
edge_color = data['Plot']['edge_color']
if 'light_color' in data['Plot']:
light_color = data['Plot']['light_color']
if 'text_color' in data['Plot']:
text_color = data['Plot']['text_color']
if 'font_size' in data['Plot']:
font_size = data['Plot']['font_size']
if 'label_space' in data['Plot']:
label_space = data['Plot']['label_space']
if 'r_light' in data['Plot']:
r = data['Plot']['r_light']
if 'd_edges' in data['Plot']:
d = data['Plot']['d_edges']
if 'width_bar' in data['Plot']:
width = data['Plot']['width_bar']
if 'track_width' in data['Plot']:
track_width = data['Plot']['track_width']
if 'track_spacing' in data['Plot']:
track_spacing = data['Plot']['track_spacing']
if 'lx' in data['Plot']:
lx = data['Plot']['lx']
if 'ly' in data['Plot']:
ly = data['Plot']['ly']
if figsize is None:
figsize = (10,5)
print figsize
fig, ax = pl.subplots(nrows=1, ncols=1, sharex=True, sharey=False,figsize=figsize)
if img is not None:
pl.imshow(img,extent=bg_ext,alpha=bg_alpha)
nodes = []
edges = {}
if "Annotations" in data:
for a in data['Annotations']:
p = a['point']
ax.text(p[0],p[1],a['label'],fontsize=font_size,color=text_color)
x_min=data['Nodes'][0]['p'][0]
y_min=data['Nodes'][0]['p'][1]
x_max=x_min
y_max=y_min
for i,n in enumerate(data['Nodes']):
nodes.append({'n':n,'e':0,'l':None})
x=n['p'][0]
y=n['p'][1]
x_min=min(x_min,x)
y_min=min(x_min,y)
x_max=max(x_max,x)
y_max=max(x_max,y)
for i,q in enumerate(data['Queues']):
n0=q['edge'][0]
n1=q['edge'][1]
pair = (n0,n1)
if n1<n0 : pair = (n1,n0)
if pair in edges:
edges[pair]+=1
else:
edges[pair]=1
q['pair']=pair
if 'Transits' in data:
for transit in data['Transits']:
for i in range(1,len(transit['links'])):
n0 = transit['links'][i-1]
n1 = transit['links'][i]
pair = (n0, n1)
if n1 < n0 : pair = (n1, n0)
if pair in edges:
edges[pair] += 1
else:
edges[pair] = 1
data['Queues'].append({'transit': True, 'edge': [n0,n1], 'pair': pair})
for i,l in enumerate(data['Lights']):
n=data['Nodes'][l['node']]
nodes[l['node']]['l']=i
n['light']=i
x=n['p'][0]
y=n['p'][1]
if type == 'arrow':
p = Circle((x,y), r, fc=light_color)
ax.add_patch(p)
ax.text(x-lx,y-ly,r'$l_{%d}$' % int(i+index_label_base),fontsize=font_size)
else:
r=15
for i,q in enumerate(data['Queues']):
pair = edges[q['pair']] > 1
if 'label' in q:
label = q['label']
else:
label = ''
n0= data['Nodes'][q['edge'][0]]
n1= data['Nodes'][q['edge'][1]]
rx0=n0['p'][0]
ry0=n0['p'][1]
rx1=n1['p'][0]
ry1=n1['p'][1]
rx = rx0-rx1
ry = ry0-ry1
lth = math.sqrt(rx*rx+ry*ry)
rx/=lth
ry/=lth
trx0=rx0
try0=ry0
if 'light' in n0:
if pair and 'transit' not in q:
theta = -math.asin(d/r)
trx = rx * math.cos(theta) - ry * math.sin(theta);
ry = rx * math.sin(theta) + ry * math.cos(theta);
rx=trx
trx0-=rx * r; try0-=ry * r
elif pair and 'transit' not in q:
trx0-=ry * d; try0+=rx * d
rx = rx1-rx0
ry = ry1-ry0
lth = math.sqrt(rx*rx+ry*ry)
rx/=lth
ry/=lth
if 'light' in n1:
if pair and 'transit' not in q:
theta = math.asin(d/r)
trx = rx * math.cos(theta) - ry * math.sin(theta);
ry = rx * math.sin(theta) + ry * math.cos(theta);
rx=trx
if type == 'arrow':
rx1-=rx * (r+line_width); ry1-=ry * (r+line_width)
else:
rx1-=rx * (r); ry1-=ry * (r)
elif pair and 'transit' not in q:
rx1+=ry * d; ry1-=rx * d
rx0=trx0
ry0=try0
rx = rx1-rx0
ry = ry1-ry0
lth = math.sqrt(rx*rx+ry*ry)
theta = math.degrees(math.atan2(rx,ry))
dx,dy = label_distance(theta,i)
#if debug:
# dx *= 3
# dy *= 3
tx=ry/lth * label_space + dx; ty=rx/lth * label_space + dy
tc = 0.5
if 'text_pos' in q:
tc = q['text_pos']
rx = rx0+(rx1-rx0)*tc
ry = ry0+(ry1-ry0)*tc
qtext_color = text_color
qline_width = line_width
qhead_width = head_width
qtail_width = tail_width
qedge_color = edge_color
qline_color = line_color
qfont_weight = None
qfont_size = font_size
qoutline = None
qtrack_width = track_width
qtrack_spacing = track_spacing
if 'text_color' in q:
qtext_color = q['text_color']
if 'line_width' in q:
qline_width = q['line_width']
if 'head_width' in q:
qhead_width = q['head_width']
if 'tail_width' in q:
qtail_width = q['tail_width']
if 'edge_color' in q:
qedge_color = q['edge_color']
if 'line_color' in q:
qline_color = q['line_color']
if 'font_weight' in q:
qfont_weight = q['font_weight']
if 'font_size' in q:
qfont_size = q['font_size']
if 'outline' in q:
qoutline = q['outline']
if qfont_weight == 'bold':
qlabel = r'$\mathbf{q_{%d}}$' % int(i+index_label_base)
else:
qlabel = r'$q_{%d}$' % int(i+index_label_base)
if 'track_width' in q:
qtrack_width = q['track_width']
if 'track_spacing' in q:
qtrack_spacing = q['track_spacing']
if debug and not 'transit' in q:
#qlabel += ',$%d,%ss$' % (q['Q_MAX'],q['Q_DELAY'])
#if q['Q_P'] is not None:
# qlabel += '\n$%s$' % (q['Q_P'])
#if q['Q_IN'] > 0:
# ax.text(rx0-5,ry0-5,r'%d' % q['Q_IN'],fontsize=10)
#if q['Q_OUT'] > 0:
# ax.text(rx1-5,ry1-5,r'%d' % q['Q_OUT'],fontsize=10)
#for j in range(len(data['Queues'])):
# flow = '%d_%d' % (i,j)
# if flow in data['Flows']:
# qlabel += '\n$f_{out,%d}=%s$' % (j,data['Flows'][flow]['F_MAX'])
# flow = '%d_%d' % (j,i)
# if flow in data['Flows']:
# qlabel += '\n$f_{%d,in}=%s$' % (j,data['Flows'][flow]['F_MAX'])
rx = rx1-rx0
ry = ry1-ry0
plot_circle_label(ax,q['Q_MAX'],rx0+0.5*rx,ry0+0.5*ry,10)
#qfont_size = 12
if 'transit' in q:
rx = rx1-rx0
ry = ry1-ry0
tx=(rx/lth) * qtrack_width; ty=(ry/lth) * qtrack_width
N = int(lth / qtrack_spacing)
dt = 1.0 / N
t=0
for j in range(N):
qrx0 = rx0 + t * rx
qry0 = ry0 + t * ry
qrx1 = rx0 + (t+dt) * rx
qry1 = ry0 + (t+dt) * ry
ax.plot([qrx0+ty,qrx0-ty],[qry0-tx,qry0+tx], lw=qline_width,color=qline_color)
t += dt
ax.plot([rx0,rx1],[ry0,ry1], lw=qline_width*2,color=qline_color)
else:
if type == 'arrow':
if qoutline != None:
ax.text(rx+(tx),ry-(ty), qlabel, fontsize=qfont_size+1, color=qoutline)
ax.text(rx+(tx),ry-(ty), qlabel, fontsize=qfont_size, color=qtext_color)
rx = rx1-rx0
ry = ry1-ry0
rx=(rx/lth); ry=(ry/lth)
if 'label_inflow' in q or args.label_inflow and q['Q_IN'] > 0:
rx0 = rx0 - rx*3
ry0 = ry0 - ry*3
#plot([rx,rx+ty],[ry,ry-tx])
arrow = ax.arrow(rx0,ry0,rx1-rx0,ry1-ry0, shape='full', lw=qline_width,color=qline_color,length_includes_head=True, head_width=qhead_width, width=qtail_width)
if 'label_inflow' in q or args.label_inflow:
if q['Q_IN'] > 0:
qin_label_radius = 7
plot_circle_label(ax,q['Q_IN'],rx0 - rx * qin_label_radius,ry0 - ry * qin_label_radius,qin_label_radius)
arrow.set_ec(qedge_color)
arrow.set_fc(qline_color)
elif type == 'bar' or type == 'carrow':
#qfont_weight = None
#ax.text(rx+(tx),ry-(ty),'%d' % int(i+index_label_base),fontsize=font_size, fontweight=qfont_weight,color=scalarMap.to_rgba(0))
ax.text(rx+(tx),ry-(ty),qlabel,fontsize=qfont_size, fontweight=qfont_weight,color=scalarMap.to_rgba(0))
N=len(q['cmap'])
t=0
#q=0.0
rx = rx1-rx0
ry = ry1-ry0
tx=(rx/lth) * width; ty=(ry/lth) * width
qrx0=rx1 #- rx * q
qry0=ry1 #- ry * q
if N == 1:
dt = 1
else:
dt=(1.0)/(N)
# for j in range(N):
# qrx0=rx0 + t * rx
# qry0=ry0 + t * ry
# qrx1=rx0 + (t+dt) * rx
# qry1=ry0 + (t+dt) * ry
# colorVal = scalarMap.to_rgba(q['cmap'][j])
# if type == 'bar':
# ax.add_patch(mp.patches.Polygon([[qrx0-ty,qry0+tx],[qrx1-ty,qry1+tx],[qrx1+ty,qry1-tx],[qrx0+ty,qry0-tx]],closed=True,fill='y',color=colorVal,ec='none',lw=0.9))
# else:
# arrow = ax.arrow(qrx0,qry0,rx1-qrx0,ry1-qry0, shape='full', lw=line_width,color=colorVal,length_includes_head=True, head_width=head_width, width=tail_width)
# arrow.set_ec(colorVal)
# arrow.set_fc(colorVal)
# t+=dt
t = np.linspace(0,1,N)
x =rx0 + t * rx
y =ry0 + t * ry
points = np.array([x,y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
bar_cmap = np.array([scalarMap.to_rgba(q['cmap'][j]) for j in range(N)])
bar_widths = 1 + np.array(q['cmap'])*2*width
lc = LineCollection(segments,linewidths=bar_widths,colors=bar_cmap)
ax.add_collection(lc)
if type == 'bar' or type == 'carrow':
for i,l in enumerate(data['Lights']):
n=data['Nodes'][l['node']]
nodes[l['node']]['l']=i
n['light']=i
x=n['p'][0]
y=n['p'][1]
p = Circle((x,y), r,ec=scalarMap.to_rgba(0),fc='w')
ax.add_patch(p)
ax.text(x-3,y-3,r'%d' % int(i+index_label_base),fontsize=10,color=scalarMap.to_rgba(0))
pl.axis('scaled')
#ax.set_ylim([x_min-10,x_max+10])
#ax.set_xlim([y_min-10,y_max+10])
#[-200,200,-110,110]
#ax.set_ylim([-110,110])
#ax.set_xlim([-200,200])
#if debug:
# ax.set_ylim((ext[2]-50,ext[3]+50))
# ax.set_xlim((ext[0]-50,ext[1]+50))
#else:
ax.set_ylim(ext[2:4])
ax.set_xlim(ext[0:2])
pl.axis('off')
if type == 'bar' or type == 'carrow':
cax = fig.add_axes([0.9, 0.1, 0.03, 0.8])
pl.colorbar(CS3,cax=cax)
pl.tight_layout()
def plot_network(args):
for f in args.files:
data = open_data_file(f)
if data is not None:
plot_network_figure(data,args.figsize,index_label_base=args.index_label_base,debug=args.debug_network)
def plot_network_delay(args):
"""
:param args:
:return:
"""
type = args.plot_network_delay
if type == 'arrow': type = 'carrow'
for f in args.files:
data = open_data_file(f)
if data is not None:
results = data['Out']
if 'Run' in results:
if args.run:
results = data['Out']['Run'][args.run]
else:
results = data['Out']['Run'][0]
#if len(data['Out']['Run']) > 1:
# del data['Out']['Run'][1:-1]
NQ=-1
DT = float(results['DT'][0])
max_delay = 10
if args.delay_lt:
max_delay = args.delay_lt
if args.n <= 0:
for i,q in enumerate(data['Queues']):
qi = results['q_%d' %i]
qi_in = np.array(results['q_{%d,in}' %i])
qi_out = results['q_{%d,out}' %i]
Q_DELAY = q['Q_DELAY']
N = len(qi)
c_in = np.zeros(N)
c_out = np.zeros(N)
c_in[0] = qi_in[0]
c_out[0] = qi_out[0]
for n in range(1,N):
c_in[n]=c_in[n-1] + qi_in[n]
c_out[n]=c_out[n-1] + qi_out[n]
if i==NQ:
#pl.figure()
pl.plot(range(0,N),c_in)
pl.plot(range(0,N),c_out)
delay = ( np.sum((c_in - c_out) * DT) - (np.sum(qi_in) * Q_DELAY) ) / np.sum(qi_in)
q['cmap'] = [delay / max_delay]
#print 'q_%d' % i,'\tdelay: %f' % delay,'\tcars: %d' % np.sum(qi_in),'\tQ_DELAY: %d' %Q_DELAY
else:
N_dt = args.n
dt = DT/N_dt
print 'DT=',results['DT'][0]
print 'dt=',dt
t=dt
nq = len(data['Queues'])
qdat = []
cdat = []
#max_delay = 0
for i,q in enumerate(data['Queues']):
qi = results['q_%d' %i]
qi_in = np.array(results['q_{%d,in}' %i]) * (dt/DT)
qi_out = np.array(results['q_{%d,out}' %i])* (dt/DT)
qi_in_total = np.sum(qi_in)*(DT/dt)
#print 'sum(q_in)=',np.sum(qi_in)
#print 'sum(q_out)=',np.sum(qi_out)
Q_DELAY = q['Q_DELAY']
Nt = int(len(qi_in)*N_dt)
N = int(math.ceil(Q_DELAY / dt))
#print 'N=',N
q_delay = float(Q_DELAY)/N
Q = q['Q_MAX']/N
#print i,N,Q
qs = np.zeros((N,Nt))
ys = np.zeros((N,Nt))
cy = np.zeros((N+1,Nt))
#ys[0,0] = qi_in[0]*q_delay
#ys[N-1,0] = qi_out[0]*dt_q
y0 = np.interp(np.linspace(0,len(qi),Nt,endpoint=False),np.linspace(0,len(qi),len(qi),endpoint=False),qi_in)
ys[N-1,:] = np.interp(np.linspace(0,len(qi),Nt,endpoint=False),np.linspace(0,len(qi),len(qi),endpoint=False),qi_out)
#print sum(qi_in)
for k in range(1,Nt):
#ys[0,k] = qi_in[int(k/N)]*dt
#ys[N-1,k] = qi_out[int(k/N)]
qs[0,k] = qs[0,k-1] + y0[k-1] - ys[0,k-1]
#qs[0,k] = qs[0,k-1] + qi_in[int(k/N)]*dt_q - ys[0,k-1]
for n in range(1,N):
qs[n,k] = qs[n,k-1] + ys[n-1,k-1] - ys[n,k-1]
qs[n,k] = max(qs[n,k],0)
##qs[1:,k] = qs[1:,k-1] + ys[:-1,k-1] - ys[1:,k-1]
##qs[1:,k] = np.fmax(qs[1:,k],0)
for n in range(0,N-1):
ys[n,k] = min(qs[n,k], Q-qs[n+1,k])
ys[n,k] = max(ys[n,k],0)
##ys[:-1,k] = np.fmin(qs[:-1,k], Q-qs[1:,k])
##ys[:-1,k] = np.fmax(ys[:-1,k],0)
#ys[N-1,k] = qi_out[int(k/N)]*dt_q
cy[0] = np.cumsum(y0)
#cy[1:,k] = cy[1:,k-1]+ys[0:,k]
cy[1:] = np.cumsum(ys,axis=1)
#print len(np.linspace(0,len(qi),len(qi)*N))
#y0 = np.interp(np.linspace(0,len(qi),len(qi)*N,endpoint=False),np.linspace(0,len(qi),len(qi),endpoint=False),qi_in*dt_q)
#print y0
#for k in range(1,ys.shape[1]):
# cy[0,k] = cy[0,k-1]+y0[k]
# cy[1:,k] = cy[1:,k-1]+ys[0:,k]
delay = (np.sum((cy[:-1,:] - cy[1:,:]) *dt ,axis=1 ) - qi_in_total*q_delay)# / qi_in_total
#print 'delay %d' %i, np.sum(delay)
#print 'q_%d' % i,'\tdelay: %f' % (np.sum(delay) ),'\tcars: %d' % (qi_in_total),'\tQ_DELAY: %d' % Q_DELAY
#pl.figure()
#pl.plot(range(0,len(delay)),delay)
#pl.title(r'$q_%d$' % i)
#pl.ylim(0,200)
#pl.figure()
q['cmap'] = delay / max_delay#qs[:,qs.shape[1]*0.25]/np.max(qs)#[j/float(N) for j in range(0,N)]
#max_delay = max(max_delay,np.max(delay))
#max_delay = 3.0
#print np.max(qs)
qdat.append(qs)
cdat.append(cy)
#if i == 0:
# print len(qi)*N
# print len(np.linspace(0,len(qi),len(qi)*N))
# print cdat[0].shape[1]
#pl.plot(range(0,len(qi_in)),qi_in)
#pl.plot(range(0,len(qi_in)),qi_out)
#pl.plot(range(0,len(qi_in)),qi)
#pl.figure()
#pl.plot(range(0,qdat[0].shape[1]),qdat[0][0,:])
#pl.plot(range(0,qdat[0].shape[1]),qdat[0][-1,:])
#pl.figure()
#pl.plot(np.linspace(0,len(qi),cdat[NQ].shape[1],endpoint=False),cdat[NQ][0,:])
#pl.plot(np.linspace(0,len(qi),cdat[NQ].shape[1],endpoint=False),cdat[NQ][1,:])
#pl.plot(np.linspace(0,len(qi),cdat[NQ].shape[1],endpoint=False),cdat[NQ][-2,:] - cdat[NQ][-1,:])
print 'max_delay',max_delay
#max_delay = 2
#q['cmap'] = q['cmap'] / max_delay
for i,q in enumerate(data['Queues']):
qi = results['q_%d' %i]