-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlot_cFeAR.py
More file actions
2601 lines (2018 loc) · 89.3 KB
/
Plot_cFeAR.py
File metadata and controls
2601 lines (2018 loc) · 89.3 KB
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
import copy
import numpy as np
# -----------------------------------------------------------------------------
# figures.py needed to make some example plots
from math import sqrt
from shapely import affinity
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from shapely.plotting import plot_polygon, plot_points, plot_line, patch_from_polygon
from matplotlib import cm
import seaborn as sns
import matplotlib.colors as mcolors
import matplotlib.ticker as ticker
from matplotlib.ticker import MaxNLocator
from mpl_toolkits.axes_grid1 import make_axes_locatable
import cmcrameri.cm as cmc
import networkx as nx
import os
from collections.abc import Iterable
import PlotGWorld
from PlotGWorld import special_spectral_cmap
import ContinuousFeAR as cfear
SIZE = (10, 12)
# SIZE = (5, 6)
# BLUE = '#6699cc'
BLUE = '#407e9c'
# RED = '#ff3333'
RED = '#c3553a'
GRAY = '#999999'
LIGHTGRAY = '#cccccc'
DARKGRAY = '#333333'
YELLOW = '#ffcc33'
GREEN = '#339933'
BLACK = '#000000'
WHITE = '#ffffff'
CMAP = cm.get_cmap('Spectral')
def add_origin(ax, geom, origin):
x, y = xy = affinity.interpret_origin(geom, origin, 2)
ax.plot(x, y, 'o', color=GRAY, zorder=1)
ax.annotate(str(xy), xy=xy, ha='center',
textcoords='offset points', xytext=(0, 8))
def set_limits(ax, x0, xN, y0, yN):
ax.set_xlim(x0, xN)
ax.set_xticks(range(x0, xN + 1))
ax.set_ylim(y0, yN)
ax.set_yticks(range(y0, yN + 1))
ax.set_aspect("equal")
ax.grid(True, linestyle=':')
def match_xylims_to_fit(ax1=None, ax2=None):
"""
Function to match the xlim and ylim of two axes so that the new lims fit all the content of both axes
Parameters
----------
ax1 : Matplotlib ax object
ax2 : Matplotlib ax object
Returns
-------
None
"""
if ax1 is None:
print('Missing ax1 !')
return False
if ax2 is None:
print('Missing ax2 !')
return False
# Get current xlim and ylim for both figures
xlim1 = ax1.get_xlim()
ylim1 = ax1.get_ylim()
xlim2 = ax2.get_xlim()
ylim2 = ax2.get_ylim()
# Determine the combined xlim and ylim
combined_xlim = (min(xlim1[0], xlim2[0]), max(xlim1[1], xlim2[1]))
combined_ylim = (min(ylim1[0], ylim2[0]), max(ylim1[1], ylim2[1]))
# Set the combined xlim and ylim to both axes
ax1.set_xlim(combined_xlim)
ax1.set_ylim(combined_ylim)
ax2.set_xlim(combined_xlim)
ax2.set_ylim(combined_ylim)
def synchronize_axes_limits(fig):
# Initialize variables to store the combined limits
combined_xlim = [float('inf'), float('-inf')]
combined_ylim = [float('inf'), float('-inf')]
# Iterate through all axes in the figure to find the min and max limits
for ax in fig.get_axes():
xlim = ax.get_xlim()
ylim = ax.get_ylim()
combined_xlim = [min(combined_xlim[0], xlim[0]), max(combined_xlim[1], xlim[1])]
combined_ylim = [min(combined_ylim[0], ylim[0]), max(combined_ylim[1], ylim[1])]
# Set the combined limits to all axes
for ax in fig.get_axes():
ax.set_xlim(combined_xlim)
ax.set_ylim(combined_ylim)
# -----------------------------------------------------------------------------
def main():
pass
if __name__ == "__main__":
main()
def get_new_fig(arg=111, figsize=SIZE, dpi=300):
fig = plt.figure(figsize=figsize, dpi=dpi)
ax = fig.add_subplot(arg)
ax.grid(True, linestyle=':')
ax.set_aspect("equal")
make_axes_gray(ax)
return fig, ax
def plot_box(ax=None, x=0, y=0, lx=0.1, ly=0.1, colour=BLUE, linewidth=1):
if ax is None:
fig = plt.figure(figsize=SIZE, dpi=90)
ax = fig.add_subplot(121)
xl = x - lx / 2
xu = x + lx / 2
yl = y - ly / 2
yu = y + ly / 2
ax.plot([xl, xu, xu, xl, xl], [yl, yl, yu, yu, yl], color=colour, linewidth=linewidth)
ax.set_aspect('equal')
ax.grid(True, linestyle=':')
def plot_traj_boxes_from_xy(ax=None, x=np.array([0]), y=np.array([0]), lx=1, ly=1, colour=BLUE, label=None,
linewidth=None, stripped_axes=True):
# For plotting the trajectory of one agent from the trajectory (x, y)
if ax is None:
fig = plt.figure(figsize=SIZE, dpi=90)
ax = fig.add_subplot(121)
boxes = cfear.get_boxes_for_a_traj(x, y, lx, ly)
plot_box(ax, x=x[0], y=y[0], lx=lx, ly=ly, colour=BLACK, linewidth=1)
for ii, box in enumerate(boxes):
if ii == 0:
plot_polygon(box, ax=ax, add_points=False, color=colour, label=label, linewidth=linewidth)
else:
plot_polygon(box, ax=ax, add_points=False, color=colour, linewidth=linewidth)
ax.set_aspect("equal")
ax.grid(True, linestyle=':')
set_xy_labels(ax)
make_axes_gray(ax)
if stripped_axes:
strip_axes(ax=ax, strip_title=False)
return boxes, ax
def plot_boxes_for_traj(traj_boxes, ax=None, colour=BLUE, label=None, linewidth=None, hatch=None, \
facecolor=None, stripped_axes=True):
# For plotting the trajectory of one agent
if ax is None:
fig = plt.figure(figsize=SIZE, dpi=90)
ax = fig.add_subplot(121)
for ii, box in enumerate(traj_boxes):
if ii == 0:
plot_polygon(box, ax=ax, add_points=False, color=colour, label=label, linewidth=linewidth, hatch=hatch,
facecolor=facecolor)
else:
plot_polygon(box, ax=ax, add_points=False, color=colour, linewidth=linewidth, hatch=hatch,
facecolor=facecolor)
# plot_polygon_outline(traj_boxes[0], color=DARKGRAY, ax=ax, linewidth=2)
plot_polygon_outline(traj_boxes[0].buffer(0.2), color=BLACK, ax=ax, linewidth=2)
ax.set_aspect("equal")
ax.grid(True, linestyle=':')
set_xy_labels(ax)
make_axes_gray(ax)
if stripped_axes:
strip_axes(ax=ax, strip_title=False)
return ax
def make_all_axes_gray(ax):
for ax_ in ax.get_figure().axes:
make_axes_gray(ax_)
def make_axes_gray(ax):
plt.setp(ax.spines.values(), color='lightgray')
ax.tick_params(labelcolor='dimgray', colors='lightgray')
ax.xaxis.label.set_color('darkgray')
ax.yaxis.label.set_color('darkgray')
# ax.tick_params(axis='x', colors='lightgray')
# ax.tick_params(axis='y', colors='lightgray')
def plot_boxes_for_trajs(trajs_boxes, obstacle=None, ax=None, title='', padding=10, colour=None, labels=None,
scale_scenario_size=1, show_legend=True,
linewidth=1.5, do_hatch=True, facecolor=None):
# For plotting the trajectory of all agents
if ax is None:
fig = plt.figure(figsize=tuple(s * 0.75 * scale_scenario_size for s in SIZE))
ax = fig.add_subplot()
try:
n_trajs, _ = trajs_boxes.shape
except AttributeError:
trajs_boxes = np.array(trajs_boxes)
n_trajs, _ = trajs_boxes.shape
if labels is not None:
if len(labels) != n_trajs:
print('Number of labels do not match the number of trajs. Reverting to default labels.')
labels = None
# show_legend = True
# colours = special_spectral_cmap(n_colours=n_trajs)
# colours = special_cmap(n_colours=n_trajs)
colours = scientific_cmap(n_colours=n_trajs)
for ii in range(n_trajs):
# color = CMAP(ii / n_trajs)
if colour is None:
# color = CMAP(ii / len(trajs_hulls))
color = colours[ii]
else:
color = colour
if labels is None:
show_legend = False # Do not plot legend when no labels passed and all of them are the same colour
# print(f'{trajs_boxes[ii, :]=}')
if do_hatch is False:
hatch = None
# Cycling through Hatches for the agents to help distinguish them when their colours are similar
elif ii % 3 == 0:
hatch = None
elif ii % 3 == 1:
hatch = '....'
else:
hatch = '\\\\\\'
if labels is None:
plot_boxes_for_traj(traj_boxes=trajs_boxes[ii, :], ax=ax, colour=color, label=f'Agent {ii + 1}',
linewidth=linewidth, hatch=hatch, facecolor=facecolor)
else:
plot_boxes_for_traj(traj_boxes=trajs_boxes[ii, :], ax=ax, colour=color, label=f'Agent {labels[ii]}',
linewidth=linewidth, hatch=hatch, facecolor=facecolor)
ax.grid(True, linestyle=':')
ax.set_title(title)
plt.axis()
if show_legend:
ax.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
plot_obstacle(obstacle=obstacle, ax=ax, padding=padding)
ax.set_aspect(1)
extend_axis_limits(ax=ax, padding=padding)
# plt.show()
return ax
def plot_traj_hulls(traj_hulls, traj_boxes=None, ax=None, colour=BLUE, label=None, show_plot=False,
show_first=True, show_last=False, scale_scenario_size=1,
linewidth=None, hatch=None, facecolor=None, stripped_axes=False):
if ax is None:
fig = plt.figure(figsize=tuple(s * 0.75 * scale_scenario_size for s in SIZE))
ax = fig.add_subplot()
for ii, hull in enumerate(traj_hulls):
if ii == 0:
plot_polygon(hull, ax=ax, add_points=False, color=colour, label=label, linewidth=linewidth,
hatch=hatch, facecolor=facecolor)
else:
plot_polygon(hull, ax=ax, add_points=False, color=colour, linewidth=linewidth,
hatch=hatch, facecolor=facecolor)
if show_first:
if traj_boxes is not None: # Plot outline of first box if available
plot_polygon_outline(traj_boxes[0].buffer(0.2), color=BLACK, ax=ax, linewidth=2)
else:
plot_polygon_outline(traj_hulls[0].buffer(0.2), color=BLACK, ax=ax, linewidth=2)
if show_last:
if traj_boxes is not None: # Plot outline of first box if available
plot_polygon_outline(traj_boxes[-1].buffer(0.1), color=BLACK, ax=ax, linewidth=0.5)
else:
plot_polygon_outline(traj_hulls[-1].buffer(0.1), color=BLACK, ax=ax, linewidth=0.5)
ax.set_aspect(1)
ax.grid(True, linestyle=':')
set_xy_labels(ax)
make_axes_gray(ax)
if stripped_axes:
strip_axes(ax=ax, strip_title=False)
if show_plot:
plt.show()
def plot_hulls_for_trajs(trajs_hulls, trajs_boxes=None, obstacle=None, ax=None, padding=1,
title='', colour=None, show_plot=False, labels=None, linewidth=1.5,
show_legend=True, legend_inside=False, show_last=False, agents_to_colour=None,
scale_scenario_size=1, show_first=True,
do_hatch=True, facecolor=None):
if ax is None:
fig = plt.figure(figsize=tuple(s * 0.75 * scale_scenario_size for s in SIZE))
ax = fig.add_subplot()
if labels is not None:
if len(labels) != len(trajs_hulls):
print('Number of labels do not match the number of trajs. Reverting to default labels.')
labels = None
if colour is None:
agents_to_colour = range(len(trajs_hulls)) # Colour all
elif agents_to_colour is None:
agents_to_colour = [] # Colour none
# Check if colour is an array-like object
if isinstance(colour, Iterable) and not isinstance(colour, (str, bytes)):
# Ensure colour is a NumPy array (optional for easier handling)
colour = np.array(colour)
if len(colour) != len(trajs_hulls):
raise ValueError("The length of the 'colour' array must match the number of trajs_hulls.")
colours = colour # Use the provided array of colours
agents_to_colour = range(len(trajs_hulls)) # Colour all
else:
# colours = special_spectral_cmap(n_colours=len(trajs_hulls))
# colours = special_cmap(n_colours=len(trajs_hulls))
colours = scientific_cmap(n_colours=len(trajs_hulls)) # Default colour map
# # colours = special_spectral_cmap(n_colours=len(trajs_hulls))
# # colours = special_cmap(n_colours=len(trajs_hulls))
# colours = scientific_cmap(n_colours=len(trajs_hulls))
for ii, traj_hulls in enumerate(trajs_hulls):
if ii in agents_to_colour:
# color = CMAP(ii / len(trajs_hulls))
color = colours[ii]
else:
color = colour
if labels is None:
show_legend = False # Do not plot legend when no labels passed and all of them are the same colour
# print(f'{color=}')
if do_hatch is False:
hatch = None
# Cycling through Hatches for the agents to help distinguish them when their colours are similar
elif ii % 3 == 0:
hatch = None
elif ii % 3 == 1:
hatch = '....'
else:
hatch = '\\\\\\'
if show_first and (trajs_boxes is None): # No box information
show_first = True # Show first hull if no boxes are given.
else:
show_first = False
if labels is None:
plot_traj_hulls(ax=ax, traj_hulls=traj_hulls, colour=color, label=f'Agent {ii + 1}', show_first=show_first,
linewidth=linewidth, hatch=hatch, facecolor=facecolor)
else:
plot_traj_hulls(ax=ax, traj_hulls=traj_hulls, colour=color, label=f'Agent {labels[ii] + 1}',
show_first=show_first, linewidth=linewidth, hatch=hatch, facecolor=facecolor)
if trajs_boxes is not None: # Plot outline of first box
plot_polygon_outline(trajs_boxes[ii][0].buffer(0.2), color=BLACK, ax=ax, linewidth=2)
if show_last:
# plot_polygon_outline(trajs_boxes[ii][-1].buffer(0.2), color=WHITE, ax=ax, linewidth=2, zorder=10)
# plot_polygon_outline(trajs_boxes[ii][-1].buffer(0.2), color=GRAY, ax=ax, linewidth=0.5, zorder=10)
# plot_polygon_outline(trajs_boxes[ii][-1].buffer(0.1), color=WHITE, ax=ax, linewidth=3, zorder=4)
plot_polygon_outline(trajs_boxes[ii][-1].buffer(0.1), color=color, ax=ax, linewidth=2, zorder=4)
plot_obstacle(obstacle=obstacle, ax=ax, padding=padding)
set_xy_labels(ax)
ax.set_title(title)
ax.grid(True, linestyle=':')
plt.axis()
# print(f'{show_legend=}')
if show_legend:
if legend_inside:
ax.legend(bbox_to_anchor=(0.98, 0.98), loc='upper right')
else:
# ax.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
ax.legend(bbox_to_anchor=(1.0, 1.0), loc='lower right')
ax.set_aspect(1)
extend_axis_limits(ax=ax, padding=padding)
if show_plot:
plt.show()
return ax
def set_xy_labels(ax, fontsize=16):
# ax.set_xlabel('Location along x', fontsize=fontsize)
# ax.set_ylabel('Location along y', fontsize=fontsize)
ax.set_xlabel('x position', fontsize=fontsize)
ax.set_ylabel('y position', fontsize=fontsize)
def plot_velocity(x, y, vx, vy, ax=None, color='black', arrow_width=0.1, scale=1, markersize=5):
if ax is None:
_, ax = get_new_fig()
print('Creating fig, ax.')
ax.plot(x - vx * scale, y - vy * scale, marker='o', color='white', zorder=5, markersize=markersize + 2)
ax.plot(x - vx * scale, y - vy * scale, marker='o', color=color, zorder=5, markersize=markersize)
ax.arrow(x - vx * scale, y - vy * scale, vx * scale, vy * scale, ls='-', color=color, zorder=5,
width=arrow_width, head_width=arrow_width * 3,
length_includes_head=True)
return ax
def set_fontsizes(ax, title_fontsize=20, other_fontsize=16, legend_fontsize=None):
"""
Set the font sizes of all elements in the given Matplotlib Axes object.
Parameters:
- ax: Matplotlib Axes object
- title_fontsize: Font size for the title
- other_fontsize: Font size for all other elements (labels, tick labels, legend, annotations)
- legend_fontsize: Font size for legend ( set to other_fontsize by default)
"""
if legend_fontsize is None:
legend_fontsize = other_fontsize
# Set title font size
ax.title.set_fontsize(title_fontsize)
# Set label font sizes
ax.xaxis.label.set_size(other_fontsize)
ax.yaxis.label.set_size(other_fontsize)
# Set tick label font sizes
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(other_fontsize)
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(other_fontsize)
# Set legend font size
if ax.get_legend():
for text in ax.get_legend().get_texts():
text.set_fontsize(legend_fontsize)
# Set annotation font sizes
for text in ax.texts:
text.set_fontsize(other_fontsize)
def set_figure_fontsizes(obj, title_fontsize=20, other_fontsize=16):
"""
Set the font sizes of all elements in all Axes objects in the given Matplotlib Figure or Axes.
Parameters:
- obj: Matplotlib Figure or Axes object
- title_fontsize: Font size for the titles
- other_fontsize: Font size for all other elements (labels, tick labels, legend, annotations)
"""
if isinstance(obj, plt.Figure):
axes = obj.get_axes()
elif isinstance(obj, plt.Axes):
axes = obj.figure.get_axes() # Get all axes from the figure that contains this ax
else:
raise TypeError("Input must be a Matplotlib Figure or Axes object")
for ax in axes:
set_fontsizes(ax, title_fontsize, other_fontsize)
def plot_velocities_for_agents(x, y, vx, vy, ax=None, colour=None, arrow_width=0.45, scale=3, markersize=8,
padding=1,
mark_location=True):
if ax is None:
_, ax = get_new_fig()
print('Creating fig, ax.')
x = x.flatten()
y = y.flatten()
vx = vx.flatten()
vy = vy.flatten()
if colour is None:
# colours = special_spectral_cmap(n_colours=len(x))
# colours = special_cmap(n_colours=len(x))
colours = scientific_cmap(n_colours=len(x))
for ii in range(len(x)):
# ax = plot_velocity(x=x[ii][0], y=y[ii][0], vx=vx[ii][0], vy=vy[ii][0], ax=ax, arrow_width=arrow_width,
# markersize=markersize, scale=scale, color=adjust_lightness(colours[ii]))
ax = plot_velocity(x=x[ii], y=y[ii], vx=vx[ii], vy=vy[ii], ax=ax, arrow_width=arrow_width,
markersize=markersize, scale=scale, color=adjust_lightness(colours[ii]))
else:
for ii in range(len(x)):
# ax = plot_velocity(x=x[ii][0], y=y[ii][0], vx=vx[ii][0], vy=vy[ii][0], ax=ax, arrow_width=0.5,
# markersize=markersize, scale=scale, color=colour)
ax = plot_velocity(x=x[ii], y=y[ii], vx=vx[ii], vy=vy[ii], ax=ax, arrow_width=0.5,
markersize=markersize, scale=scale, color=colour)
if mark_location:
for ii in range(len(x)):
ax.plot(x[ii], y[ii], marker='+', color='black', zorder=3, markersize=markersize)
extend_axis_limits(ax=ax, padding=padding, reFit=True)
return ax
def plot_accelerations_for_agents(x, y, a, theta, ax=None, colour=None, arrow_width=0.5, scale=3, markersize=9,
padding=1):
if ax is None:
_, ax = get_new_fig()
print('Creating fig, ax.')
x = x.flatten()
y = y.flatten()
a = a.flatten()
theta = theta.flatten()
if colour is None:
colours = scientific_cmap(n_colours=len(x))
for ii in range(len(x)):
ax = plot_acceleration(x=x[ii], y=y[ii], a=a[ii], theta=theta[ii], ax=ax,
color=adjust_lightness(colours[ii]), arrow_width=arrow_width,
scale=scale, markersize=markersize)
else:
for ii in range(len(x)):
ax = plot_acceleration(x=x[ii], y=y[ii], a=a[ii], theta=theta[ii], ax=ax,
color=colour, arrow_width=arrow_width,
scale=scale, markersize=markersize)
extend_axis_limits(ax=ax, padding=padding, reFit=True)
return ax
def plot_acceleration(x, y, a, theta, ax=None, color='grey', arrow_width=0.05, scale=1, markersize=4):
if ax is None:
_, ax = get_new_fig()
print('Creating fig, ax.')
a_x = a * np.cos(theta)
a_y = a * np.sin(theta)
ax.plot(x, y, marker='o', color='white', zorder=4, markersize=markersize + 2)
ax.plot(x, y, marker='o', color=color, zorder=4, markersize=markersize)
ax.arrow(x, y, a_x * scale, a_y * scale, ls='-', color=color, zorder=4,
width=arrow_width, head_width=arrow_width * 3,
length_includes_head=True)
return ax
def plot_trajectories(x=None, y=None, obstacle=None, ax=None, lim_threshold=10, scale_scenario_size=1):
"""Plot the trajectories of nn agents.
Parameters
----------
x : ndarray
x coordinates of trajectories
y : ndarray
y coordinates of trajectories
obstacle: shapely Polygon with all the static obstacles
ax : Matplotlib Axes object
lim_threshold : float
Minimum threshold for the length of either axis
Returns
-------
ax : Matplotlib Axes object
Plot of the directed fear graph.
"""
if x is None:
print('No x passed!')
return False
if y is None:
print('No y passed!')
return False
if ax is None:
fig = plt.figure(figsize=tuple(s * 0.75 * scale_scenario_size for s in SIZE))
ax = fig.add_subplot(121)
# _, ax = get_new_fig()
print('Creating fig, ax.')
# colours = special_spectral_cmap(n_colours=len(x))
# colours = special_cmap(n_colours=len(x))
colours = scientific_cmap(n_colours=len(x))
for ii, xx in enumerate(x):
color = colours[ii]
plt.plot(x[ii], y[ii], label=f'Trajectory {ii + 1}', color=color, marker='o')
plt.plot(x[ii][0], y[ii][0], color='k', marker='.')
ax.grid(True, linestyle=':')
ax.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
ax.set_aspect('equal')
set_xy_labels(ax, fontsize=16)
# Making sure that the x-axis has at least some length
xlim = ax.get_xlim()
xlength = xlim[1] - xlim[0]
if xlength < lim_threshold:
new_xlim = get_newlim_with_min_thresholds(lim=xlim, threshold=lim_threshold)
ax.set_xlim(new_xlim)
if obstacle is not None:
plot_obstacle(obstacle, ax=ax)
# Making sure that the y-axis has at least some length
ylim = ax.get_ylim()
ylength = ylim[1] - ylim[0]
if ylength < lim_threshold:
new_ylim = get_newlim_with_min_thresholds(lim=ylim, threshold=lim_threshold)
ax.set_ylim(new_ylim)
return ax
def get_newlim_with_min_thresholds(lim, threshold=2):
axis_length = lim[1] - lim[0]
# Calculate the expansion needed on both sides
expansion_needed = max(0, threshold - axis_length) / 2
# Adjust the limits symmetrically
new_lim = (
lim[0] - expansion_needed,
lim[1] + expansion_needed
)
return new_lim
def plot_squares(squares, color=BLUE, ax=None, title='Squares Multipolygon'):
if ax is None:
fig, ax = plt.subplots()
print('Creating fig, ax.')
for square in squares:
plot_polygon(square, ax=ax, add_points=False, color=color)
# ax.set_xlim(-12, 12)
# ax.set_ylim(-12, 12)
ax.set_aspect('equal', 'box')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title(title)
def plot_polygon_outline(polygon, ax=None, color=BLUE, linewidth=1, **kwargs):
if ax is None:
fig, ax = plt.subplots()
print('Creating fig, ax.')
patch = patch_from_polygon(
polygon, facecolor=color, edgecolor=color, linewidth=linewidth, fill=False, **kwargs
)
ax.add_patch(patch)
def plot_intersecting_polygons_one_by_one(intersection, ii, not_ii, other_squares_fixed=None, square_no=0, ax=None):
if intersection:
color = RED
else:
color = BLUE
if ax is None:
fig, ax = plt.subplots()
plot_squares(not_ii, ax=ax, color=YELLOW)
plot_squares([ii], color=color, ax=ax, title=f'Intersections for Polygon ii= {square_no}')
if other_squares_fixed is not None:
# fig, ax = plt.subplots()
plot_squares([other_squares_fixed], color=DARKGRAY, ax=ax, title=f'Fixed Multi_polygon= {square_no}')
strip_axes(ax=ax, strip_title=False)
make_axes_gray(ax=ax)
return ax
def plot_intersecting_polygons(intersections, polygons, ax=None, title=''):
if ax is None:
fig, ax = plt.subplots()
for intersection, polygon in zip(intersections, polygons):
if intersection:
color = RED
else:
color = BLUE
plot_squares([polygon], color=color, ax=ax, title=title)
strip_axes(ax=ax, strip_title=False)
make_axes_gray(ax=ax)
return ax
def plot_directed_fear_graph(fear, x0, y0, fear_threshold=0.05, ax=None,
hide_cbar=False, horizontal_cbar=False, normalise_cmap=False,
arrowsize=20, arrow_width=3,
zorder_lift=0, game_mode=False):
"""Plot a directed graph with edges colored and sized based on the fear values.
Parameters
----------
game_mode: bool
Whether to plot for the Game of FeAR
zorder_lift: int
Layers to lift the plot by
hide_cbar: bool
Whether to hide to colorbar
horizontal_cbar : bool
If True, the colorbar will have horizontal orientation. Else, it will be vertical.
normalise_cmap: bool
Whether to normalise the cmap to [-1,1]
fear : ndarray
Array containing Feasible Action-Space Reduction values
x0 : ndarray
x coordinate of the starting locations of agents
y0 : ndarray
y coordinate of the starting locations of agents
fear_threshold : float, optional
If the absolute value of fear is below the fear_threshold, then these are not plotted
arrowsize: int
size of the arrows of the directed graph
arrow_width: int
width of the arrows of the directed graph
ax : Matplotlib Axes object, optional
Returns
-------
ax : Matplotlib Axes object
Plot of the directed fear graph.
"""
if game_mode:
hide_cbar = True
zorder_lift = 10
x0 = x0.squeeze()
y0 = y0.squeeze()
if ax is None:
fig, ax = plt.subplots()
else:
fig = ax.get_figure()
if normalise_cmap:
fear_min = -1
fear_max = 1
print(f'{fear_min=},{fear_max=}')
else:
non_diag = ~np.eye(fear.shape[0], dtype=bool) # Create a boolean mask for off-diagonal elements
fear_max = np.max(np.abs(fear[non_diag]))
fear_min = - fear_max
print(f'{fear_min=},{fear_max=}')
# Create a directed graph
G = nx.DiGraph()
# Add nodes to the graph
n_agents = len(x0)
for i in range(n_agents):
G.add_node(i, pos=(x0[i], y0[i]))
# Add edges to the graph based on fear values
for actor in range(n_agents):
for affected in range(n_agents):
if actor != affected:
fear_value = fear[actor, affected]
if abs(fear_value) > fear_threshold:
# Only add edge if fear values with abs() greater than a threshold
G.add_edge(actor, affected, weight=fear_value)
# Get positions of nodes
pos = nx.get_node_attributes(G, 'pos')
# Create colormap
cmap = sns.diverging_palette(220, 20, as_cmap=True, sep=1)
# Draw node labels as i + 1
labels = {i: str(i + 1) for i in G.nodes()}
# Draw the graph
weights = [G[u][v]['weight'] for u, v in G.edges()]
nx.draw(G, pos, with_labels=True, node_size=300, node_color='moccasin', labels=labels,
edge_color=weights, width=2, ax=ax, alpha=0.8,
edge_cmap=cmap, edge_vmin=fear_min, edge_vmax=fear_max,
horizontalalignment='center', verticalalignment='center_baseline',
connectionstyle='arc3, rad = 0.1')
# nodes_drawn = nx.draw_networkx_nodes(G, pos, node_size=300, node_color='moccasin', ax=ax, alpha=0.75)
# nx.draw_networkx_labels(G, pos, labels=labels, alpha=0.75, ax=ax)
edges_drawn = nx.draw_networkx_edges(G, pos, edge_color=weights, width=arrow_width, arrowsize=arrowsize,
ax=ax,
edge_cmap=cmap, edge_vmin=fear_min, edge_vmax=fear_max,
connectionstyle='arc3, rad = 0.1')
# nx.draw_networkx_labels(G, pos, labels=labels)
if zorder_lift > 0:
nodes_drawn = nx.draw_networkx_nodes(G, pos, node_size=300, node_color='moccasin',
ax=ax, alpha=0.75)
labels_drawn = nx.draw_networkx_labels(G, pos, labels=labels,
horizontalalignment='center', verticalalignment='center_baseline')
nodes_drawn.set_zorder(zorder_lift + 2)
for _, label_drawn in labels_drawn.items():
label_drawn.set_zorder(zorder_lift + 4)
for edge in edges_drawn:
edge.set_zorder(zorder_lift)
# Add colorbar for edge colors
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=fear_min, vmax=fear_max))
sm.set_array([])
if not hide_cbar:
divider = make_axes_locatable(ax)
if horizontal_cbar:
cax = divider.append_axes('bottom', size='5%', pad=1)
cbar = fig.colorbar(sm, orientation='horizontal', cax=cax, shrink=0.7)
cbar.ax.axvline(x=fear_threshold, ymin=0.1, ymax=0.9, c='grey')
cbar.ax.axvline(x=-fear_threshold, ymin=0.1, ymax=0.9, c='grey')
cbar.ax.axvspan(xmin=-fear_threshold, xmax=fear_threshold, ymin=0, ymax=1, color='w')
else: # Vertical Colour Bar
# cax = divider.append_axes('right', size='5%', pad=1)
# cbar = fig.colorbar(sm, orientation='vertical', cax=cax, shrink=0.7)
cbar = fig.colorbar(sm, orientation='vertical', shrink=0.7)
cbar.ax.axhline(y=fear_threshold, xmin=0.1, xmax=0.9, c='grey')
cbar.ax.axhline(y=-fear_threshold, xmin=0.1, xmax=0.9, c='grey')
cbar.ax.axhspan(ymin=-fear_threshold, ymax=fear_threshold, xmin=0, xmax=1, color='w')
# --------------------
ticks = [fear_min, -fear_threshold, fear_threshold, fear_max] # Set the ticks manually
# Set the font size of the colorbar ticks
cbar.ax.tick_params(labelsize=16)
if not horizontal_cbar:
tweak_cbar_ticklabels(cbar=cbar, ticks=ticks, fontsize=16)
# --------------------
cbar.outline.set_visible(False) # Remove the black outline
make_axes_gray(cbar.ax)
cbar.set_label('Fear Value', fontsize=16)
ax.set_aspect(1)
if not game_mode:
ax.set_title('Directed Graph with Fear Values')
return ax
def tweak_cbar_ticklabels(cbar, ticks=None, scale=0.7, v_offset=0.1, scale_width=1, fontsize=None):
if ticks is None:
# Get current ticks and labels
ticks = cbar.get_ticks()
tick_labels = [f'{t:.2g}' for t in ticks] # Convert the original ticks to string labels
# Customize -1 and +1 labels
# tick_labels = ['-1 Courteous' if t == -1 else '+1 Assertive' if t == 1 else label for t, label in
# zip(ticks, tick_labels)]
# cbar.shrink(0.7)
rescale_cbar(cbar=cbar, scale=scale, scale_width=scale_width)
if fontsize is None:
cbar.ax.text(0.5, 0 - v_offset, 'Courteous', ha='left', va='center', transform=cbar.ax.transAxes,
color='dimgray')
cbar.ax.text(0.5, 1 + v_offset, 'Assertive', ha='left', va='center', transform=cbar.ax.transAxes,
color='dimgray')
else:
cbar.ax.text(0.5, 0 - v_offset, 'Courteous', ha='left', va='center', transform=cbar.ax.transAxes,
color='dimgray', fontsize=fontsize)
cbar.ax.text(0.5, 1 + v_offset, 'Assertive', ha='left', va='center', transform=cbar.ax.transAxes,
color='dimgray', fontsize=fontsize)
# Set the tick locations and apply custom labels
cbar.ax.set_yticks(ticks) # Explicitly set tick locations
cbar.ax.set_yticklabels(tick_labels) # Apply custom tick labels
def plot_fear(fear=None, for_print=True, cbar=None, agent_coloured_ticks=True,
fmt='.1f',
swap_colours_2_3=True):
"""
Function to plot the fear values - where the feal values are included as the diagonal elements
Parameters
----------
fmt
swap_colours_2_3
agent_coloured_ticks
cbar
for_print
fear : ndarray
Returns
-------
ax : Matplotlib axis
"""
if fear is None:
print('No fear passed!')
return False
nn, _ = fear.shape
if for_print:
if nn <= 2:
finer = False
elif 2 < nn <= 6:
finer = True
else:
finer = False
for_print = False
ax = PlotGWorld.plotResponsibility(fear, FeAL=np.diagonal(fear), for_print=for_print, finer=finer, cbar=cbar,
title='', annot_font_size=12, fmt=fmt)
cbar = ax.collections[0].colorbar # Get the colorbar associated with the heatmap
if cbar: # Check if there is a cbar
# tweak_cbar_ticklabels(cbar=cbar)
nn, _ = fear.shape
if nn <= 4:
scale = 0.6
scale_width = 3
else:
scale = 0.7
scale_width = 1
if for_print:
v_offset = 0.3
else:
v_offset = 0.1
tweak_cbar_ticklabels(cbar=cbar, scale=scale, scale_width=scale_width, v_offset=v_offset)
make_all_axes_gray(ax)