-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathps_solution.py
1597 lines (1406 loc) · 65.3 KB
/
ps_solution.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
import numpy as np
from worlds import Tree, Gridmap, generate_some_worlds, generate_worlds
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import tikzplotlib as tplt
import cloudpickle
import pickle
from drone_params import Drone
import os
import sys
from scipy import integrate
from scipy.interpolate import lagrange
from scipy.interpolate import CubicSpline
class PsSolution:
"""
The PsSolution class is used to evaluate a solution generated by PsControl class.
"""
def __init__(self):
self.n_simpson = 10
self.state = []
self.control = []
self.time = []
self.obstacles = []
self.n_col = []
self.n_seg = 0
self.sampled = False
self.relative_error_max = None
self.relative_deflection = None
self.max_error = None
self.time_error = False
self.time_eq_error = False
self.objective = -1
def new_solution(self, m, drone=None, obs=None, fit='polyfit', n_simpson=10, fix_solution = False):
"""
Generate solution based on data from solved Pyomo model, Drone class with parametes in world obs.
Parameters
----------
m (object): The Pyomo model.
drone (object): The drone class with parameters and dynamics.
obs (object): The world class with parameters in world obs.
fit (str): The type of fitting to use. Default is 'polyfit'.
Supported values are 'polyfit', 'lagrange' and 'spline'.
n_simpson (int): The number of points to use for the Simpson integration. Default is 10.
fix_solution (bool): Whether to fix the solution. !not fully implemented! Default is False.
"""
# set parameters
self.fit = fit
self.n_simpson = int(n_simpson)
self.n_col = m.n_col
self.n_seg = len(self.n_col)
# load drone
if drone is None:
from drone_params import Drone
self.drone = Drone
else:
self.drone = drone
# import drone dynamics for evaluation
self.__eval_dynamics = drone.eval_dynamics
if hasattr(m, 'psm_approx'):
self.psm_approx = m.psm_approx
else:
self.psm_approx = 'chebyshev'
# extract solving time
if hasattr(m, 'presolve_time'):
self.presolve_time = m.presolve_time
self.solve_time = m.solve_time
self.psm_solve_time = self.presolve_time + self.solve_time
else:
self.presolve_time = 0
self.solve_time = 0
self.psm_solve_time = 0
self.objective = m.obj.expr() # extract objective value
# load obstacles
self.obs = obs
if obs is not None and self.obs.n_obstacles is None:
if self.obs.dim == 3:
self.obs.n_obstacles = self.obs.map3d.shape[0]
elif self.obs.dim == 2:
self.obs.n_obstacles = self.obs.map2d.shape[0]
# dimension of optimal control variables
self.nx = m.nx.at(-1)+1
self.nu = m.nu.at(-1)+1
# initialize optimal control variables in collocation points
self.time = np.zeros(m.n_col_sum)
self.state = np.zeros((self.nx, m.n_col_sum))
self.control = np.zeros((self.nu, m.n_col_sum))
# calculate gradual number of collocation points
self.n_col_add = np.zeros(self.n_col.shape[0]+1, dtype=int)
for i, cols in enumerate(self.n_col):
self.n_col_add[i+1] = self.n_col_add[i] + cols
# load time in collocation points from solution and check the time continuity
for i in m.t:
self.time[i] = m.t[i].value
if i > 0:
if self.time[i] < self.time[i-1]:
print(f"[ERROR] Time continuum violation at {i}")
self.time_error = True
elif self.time[i] == self.time[i-1] and i not in self.n_col_add:
print(f"[WARNING] Time continuum equility at {i}")
self.time_eq_error = True
# load state in collocation points
for i in m.x:
self.state[i] = m.x[i].value
# load control in collocation points
for i in m.u:
self.control[i] = m.u[i].value
# build list with start and end time of each segment
self.multiseg_time = []
for i, seg_start in enumerate(self.n_col_add[:-1]):
self.multiseg_time.append(self.time[seg_start:self.n_col_add[i+1]])
if (self.time_error or self.time_eq_error) and fix_solution:
self.fix_solution()
def fix_solution(self):
"""
Fix the solution by checking for errors in collocation points and
fitting the solution to the original number of collocation points.
"""
# copy original solution
time = self.time.copy()
state = self.state.copy()
control = self.control.copy()
n_col = self.n_col.copy()
n_col_old = self.n_col.copy()
n_col_add = self.n_col_add.copy()
n_col_add_old = self.n_col_add.copy()
deleted_segment = []
# search and delete errors
i = 1
len_time = len(time)
while i < len_time:
if (time[i] < time[i-1] or time[i] == time[i-1]) and i not in n_col_add:
# delete wrong point
print(f"Fixing point {i}")
time = np.delete(time, i)
state = np.delete(state, i, axis=1)
control = np.delete(control, i, axis=1)
# find segment number
if n_col_add[0] > i:
seg = 0
else:
seg = np.where(n_col_add <= i)[0][-1]
n_col[seg] = n_col[seg]-1
if n_col[seg] <= 0:
# delete segment without good collocation points
# TODO: test segment deletion:
raise Exception("Whole segment {seg} is wrong.")
# new multiseg_time won't fit to old collocation scheme
deleted_segment.append([seg, n_col[seg], self.multiseg_time[seg][0], self.multiseg_time[seg][-1]])
n_col_old = np.delete(n_col_old, seg)
if seg == 0:
n_col_old[0] = n_col_old[0] + n_col[seg]
else:
n_col_old[seg-1] = n_col_old[seg-1] + n_col[seg]
n_col = np.delete(n_col, seg)
n_col_add = np.delete(n_col_add, seg)
i = i-1
len_time = len_time-1
else:
i = i+1
self.time = time
self.state = state
self.control = control
self.n_col = n_col
# calculate gradual number of collocation points
self.n_col_add = np.zeros(self.n_col.shape[0]+1, dtype=int)
for i, cols in enumerate(self.n_col):
self.n_col_add[i+1] = self.n_col_add[i] + cols
# get t0 and tf for each segment
self.multiseg_time = []
for i, seg_start in enumerate(self.n_col_add[:-1]):
self.multiseg_time.append(self.time[seg_start:self.n_col_add[i+1]])
if self.psm_approx == 'chebyshev':
from chebyshev import cheb_scaled
elif self.psm_approx == 'legendre':
from legendre import legendre_scaled as cheb_scaled
# fit solution to original number of collocation points
new_multiseg_time = []
for i, cols in enumerate(n_col_old):
tt, __, __ = cheb_scaled(cols-1, [self.multiseg_time[i][0],self.multiseg_time[i][-1]])
new_multiseg_time.append(tt)
self.time, self.state, self.control = self.resample_solution(new_multiseg_time)
self.n_col = n_col_old
self.n_col_add = n_col_add_old
self.multiseg_time = new_multiseg_time
self.time_error = False
self.time_eq_error = False
def plot(self, save=False, img_folder="img/", dpi = 600, figsize = (6, 4)):
"""
Plots the collocation points, state and control of the drone over time.
Args:
save (bool): Whether to save the plots as image files or not.
img_folder (str): The folder path where the image files should be saved.
"""
# time vs collocation points
plt.figure(figsize=figsize)
plt.plot(self.time, '.')
plt.xlabel('collocation points [k]')
plt.ylabel('$t$ [s]')
if save:
plt.savefig(img_folder+'time.eps')
plt.savefig(img_folder+'time.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'time.tex')
# position
plt.figure(figsize=figsize)
for i in range(0, 3):
plt.plot(self.time, self.state[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$r$ [m]')
plt.legend(['$r_x$', '$r_y$', '$r_z$'])
if save:
plt.savefig(img_folder+'x_position.eps')
plt.savefig(img_folder+'x_position.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_position.tex')
# speed
plt.figure(figsize=figsize)
for i in range(3, 6):
plt.plot(self.time, self.state[i, :])
plt.xlabel('t[s]')
plt.ylabel('$v$ [m/s]')
plt.legend(['$v_x$', '$v_y$', '$v_z$'])
if save:
plt.savefig(img_folder+'x_velocity.eps')
plt.savefig(img_folder+'x_velocity.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_velocity.tex')
# quaternion
plt.figure(figsize=figsize)
for i in range(6, 10):
plt.plot(self.time, self.state[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$q$')
plt.legend(['$q_w$', '$q_x$', '$q_y$', '$q_z$'])
if save:
plt.savefig(img_folder+'x_quaternion.eps')
plt.savefig(img_folder+'x_quaternion.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_quaternion.tex')
# angular rate
plt.figure(figsize=figsize)
for i in range(10, 13):
plt.plot(self.time, self.state[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$\omega$ [rad/s]')
plt.legend(['$\omega_x$', '$\omega_y$', '$\omega_z$'])
if save:
plt.savefig(img_folder+'x_angular_rate.eps')
plt.savefig(img_folder+'x_angular_rate.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_angular_rate.tex')
# thrust
plt.figure(figsize=figsize)
plt.plot(self.time, self.control[0, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$T$ [N]')
if save:
plt.savefig(img_folder+'u_thrust.eps')
plt.savefig(img_folder+'u_thrust.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'u_thrust.tex')
# control
plt.figure(figsize=figsize)
for i in range(1, 4):
plt.plot(self.time, self.control[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel(r'$\tau$ [N$\cdot$m]')
plt.legend([r'$\tau_x$', r'$\tau_y$', r'$\tau_z$'])
if save:
plt.savefig(img_folder+'u_torque.eps')
plt.savefig(img_folder+'u_torque.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'u_torque.tex')
fig = plt.figure(figsize=figsize)
fig.set_figwidth(8)
fig.set_figheight(8)
if self.obs.dim == 3:
ax = plt.axes(projection="3d")
#plt.title('3D grid map')
ax.scatter3D(self.obs.map3d[:, 0],
self.obs.map3d[:, 1],
self.obs.map3d[:, 2],
marker='s',
linewidths=self.obs.space**2)
ax.set_zlabel("$z$ [m]")
ax.scatter3D(self.drone.x0[0],
self.drone.x0[1],
self.drone.x0[2],
marker='o',
linewidths=self.obs.space,
color='green')
ax.scatter3D(self.drone.xf[0],
self.drone.xf[1],
self.drone.xf[2],
marker='o',
linewidths=self.obs.space,
color='red')
ax.plot3D(self.state[0, :],
self.state[1, :],
self.state[2, :],
color='orange')
else:
ax = plt.axes()
ax.scatter(self.obs.map2d[:, 0],
self.obs.map2d[:, 1],
marker='s',
linewidths=self.obs.space**2, color='blue')
ax.scatter(self.drone.x0[0],
self.drone.x0[1],
marker='o',
linewidths=self.obs.space,
color='green')
ax.scatter(self.drone.xf[0],
self.drone.xf[1],
marker='o',
linewidths=self.obs.space,
color='red')
ax.plot(self.state[0, :],
self.state[1, :],
color='orange')
ax.set_xlabel("$x$ [m]")
ax.set_ylabel("$y$ [m]")
fig.subplots_adjust(left=0, bottom=0, right=1,
top=1, wspace=0, hspace=0)
if save:
fig.savefig(img_folder+'3d_position.eps')
plt.savefig(img_folder+'3d_position.png', dpi=dpi, bbox_inches="tight")
# 3D plots DO NOT WORK in tikzplotlib!!!
plt.show()
def plot_sampled(self, save=False, img_folder="img/", dt=0.01, dpi = 600, figsize = (6,4)):
"""
Plots trajectories resampled according to sampling parameter dt[s].
Args:
save (bool): Whether to save the plots as image files or not.
img_folder (str): The folder path where the image files should be saved.
dt (float): Sampling parameter
Returns:
None
"""
time_array = [np.arange(self.time[0], self.time[-1], dt)]
self.__get_polynomial_solution()
time_sampled, state_sampled, control_sampled = self.resample_solution(
time_array)
time_sampled, state_sampled, control_sampled = time_sampled[
0], state_sampled[0], control_sampled[0]
# time vs collocation points
plt.figure(figsize=figsize)
plt.plot(self.time, '.')
plt.xlabel('collocation points [k]')
plt.ylabel('$t$ [s]')
if save:
plt.savefig(img_folder+'time.eps')
plt.savefig(img_folder+'time.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'time.tex')
# position
plt.figure(figsize=figsize)
for i in range(0, 3):
plt.plot(time_sampled, state_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$r$ [m]')
plt.legend(['$r_x$', '$r_y$', '$r_z$'])
if save:
plt.savefig(img_folder+'x_position.eps')
plt.savefig(img_folder+'x_position.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_position.tex')
# speed
plt.figure(figsize=figsize)
for i in range(3, 6):
plt.plot(time_sampled, state_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$v[m/s]$')
plt.legend(['$v_x$', '$v_y$', '$v_z$'])
if save:
plt.savefig(img_folder+'x_velocity.eps')
plt.savefig(img_folder+'x_velocity.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_velocity.tex')
# quaternion
plt.figure(figsize=figsize)
for i in range(6, 10):
plt.plot(time_sampled, state_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$q$')
plt.legend(['$q_w$', '$q_x$', '$q_y$', '$q_z$'])
if save:
plt.savefig(img_folder+'x_quaternion.eps')
plt.savefig(img_folder+'x_quaternion.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_quaternion.tex')
# angular rate
plt.figure(figsize=figsize)
for i in range(10, 13):
plt.plot(time_sampled, state_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$\omega$ [rad/s]')
plt.legend(['$\omega_x$', '$\omega_y$', '$\omega_z$'])
if save:
plt.savefig(img_folder+'x_angular_rate.eps')
plt.savefig(img_folder+'x_angular_rate.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_angular_rate.tex')
# thrust
plt.figure(figsize=figsize)
plt.plot(time_sampled, control_sampled[0, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$T$ [N]')
if save:
plt.savefig(img_folder+'u_thrust.eps')
plt.savefig(img_folder+'u_thrust.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'u_thrust.tex')
# control
plt.figure(figsize=figsize)
for i in range(1, 4):
plt.plot(time_sampled, control_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel(r'$\tau$ [N$\cdot$m]')
plt.legend([r'$\tau_x$', r'$\tau_y$', r'$\tau_z$'])
if save:
plt.savefig(img_folder+'u_torque.eps')
plt.savefig(img_folder+'u_torque.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'u_torque.tex')
fig = plt.figure(figsize=figsize)
fig.set_figwidth(8)
fig.set_figheight(8)
if self.obs.dim == 3:
ax = plt.axes(projection="3d")
#plt.title('3D grid map')
ax.scatter3D(self.obs.map3d[:, 0],
self.obs.map3d[:, 1],
self.obs.map3d[:, 2],
marker='s',
linewidths=self.obs.space**2)
ax.set_zlabel("$z$ [m]")
ax.scatter3D(self.drone.x0[0],
self.drone.x0[1],
self.drone.x0[2],
marker='o',
linewidths=self.obs.space,
color='green')
ax.scatter3D(self.drone.xf[0],
self.drone.xf[1],
self.drone.xf[2],
marker='o',
linewidths=self.obs.space,
color='red')
ax.plot3D(state_sampled[0, :],
state_sampled[1, :],
state_sampled[2, :],
color='orange')
else:
ax = plt.axes()
ax.scatter(self.obs.map2d[:, 0],
self.obs.map2d[:, 1],
marker='s',
linewidths=self.obs.space**2)
ax.scatter(self.drone.x0[0],
self.drone.x0[1],
marker='o',
linewidths=self.obs.space,
color='green')
ax.scatter(self.drone.xf[0],
self.drone.xf[1],
marker='o',
linewidths=self.obs.space,
color='red')
ax.plot(self.state[0, :],
self.state[1, :],
color='orange')
ax.set_xlabel("$x$ [m]")
ax.set_ylabel("$y$ [m]")
fig.subplots_adjust(left=0, bottom=0, right=1,
top=1, wspace=0, hspace=0)
if save:
fig.savefig(img_folder+'3d_position.eps')
plt.savefig(img_folder+'3d_position.png', dpi=dpi, bbox_inches="tight")
# 3D plots DO NOT WORK in tikzplotlib!!!
plt.show()
def plot_sampled_with_col(self, save=False, img_folder="img/", dt=0.01, dpi = 600, figsize = (6,4)):
"""
Plots trajectories resampled according to sampling parameter dt[s] with collocation points.
Args:
save (bool): Whether to save the plots as image files or not.
img_folder (str): The folder path where the image files should be saved.
dt (float): Sampling parameter
Returns:
None
"""
# Get the default property cycle
prop_cycle = plt.rcParams['axes.prop_cycle']
default_colors = prop_cycle.by_key()['color']
time_array = [np.arange(self.time[0], self.time[-1], dt)]
self.__get_polynomial_solution()
time_sampled, state_sampled, control_sampled = self.resample_solution(
time_array)
time_sampled, state_sampled, control_sampled = time_sampled[
0], state_sampled[0], control_sampled[0]
# time vs collocation points
plt.figure(figsize=figsize)
plt.plot(self.time,np.zeros(len(self.time)), '.')
plt.ylabel('placement of collocation points [k]')
plt.xlabel('$t$ [s]')
if save:
plt.savefig(img_folder+'time.eps')
plt.savefig(img_folder+'time.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'time.tex')
# position
plt.figure(figsize=figsize)
for i in range(0, 3):
plt.plot(time_sampled, state_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$r$ [m]')
plt.legend(['$r_x$', '$r_y$', '$r_z$'])
for i in range(0, 3):
plt.plot(self.time, self.state[i, :],'o', color = default_colors[i])
if save:
plt.savefig(img_folder+'x_position.eps')
plt.savefig(img_folder+'x_position.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_position.tex')
# speed
plt.figure(figsize=figsize)
for i in range(3, 6):
plt.plot(time_sampled, state_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$v$ [m/s]')
plt.legend(['$v_x$', '$v_y$', '$v_z$'])
for i in range(3, 6):
plt.plot(self.time, self.state[i, :],'o', color = default_colors[i-3])
if save:
plt.savefig(img_folder+'x_velocity.eps')
plt.savefig(img_folder+'x_velocity.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_velocity.tex')
# quaternion
plt.figure(figsize=figsize)
for i in range(7, 10):
plt.plot(time_sampled, state_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$q$')
plt.legend(['$q_x$', '$q_y$', '$q_z$'])
for i in range(7, 10):
plt.plot(self.time, self.state[i, :],'o', color = default_colors[i-7])
if save:
plt.savefig(img_folder+'x_quaternion.eps')
plt.savefig(img_folder+'x_quaternion.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_quaternion.tex')
# angular rate
plt.figure(figsize=figsize)
for i in range(10, 13):
plt.plot(time_sampled, state_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$\omega$ [rad/s]')
plt.legend(['$\omega_x$', '$\omega_y$', '$\omega_z$'])
for i in range(10, 13):
plt.plot(self.time, self.state[i, :],'o', color = default_colors[i-10])
if save:
plt.savefig(img_folder+'x_angular_rate.eps')
plt.savefig(img_folder+'x_angular_rate.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'x_angular_rate.tex')
# thrust
plt.figure(figsize=figsize)
plt.plot(time_sampled, control_sampled[0, :])
plt.xlabel('$t$ [s]')
plt.ylabel('$T$ [N]')
plt.plot(self.time, self.control[0, :],'o', color = default_colors[0])
if save:
plt.savefig(img_folder+'u_thrust.eps')
plt.savefig(img_folder+'u_thrust.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'u_thrust.tex')
# control
plt.figure(figsize=figsize)
for i in range(1, 4):
plt.plot(time_sampled, control_sampled[i, :])
plt.xlabel('$t$ [s]')
plt.ylabel(r'$\tau$ [N$\cdot$m]')
plt.legend([r'$\tau_x$', r'$\tau_y$', r'$\tau_z$'])
for i in range(1, 4):
plt.plot(self.time, self.control[i, :],'o', color = default_colors[i-1])
if save:
plt.savefig(img_folder+'u_torque.eps')
plt.savefig(img_folder+'u_torque.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'u_torque.tex')
fig = plt.figure(figsize=(figsize[0],figsize[0]))
if self.obs.dim == 3:
ax = plt.axes(projection="3d")
self.plot_3d_obstacles(ax, self.obs.map3d, self.obs.space*np.sqrt(3)/2+self.drone.safe_radius)
#plt.title('3D grid map')
ax.scatter3D(self.obs.map3d[:, 0],
self.obs.map3d[:, 1],
self.obs.map3d[:, 2],
marker='s',
linewidths=self.obs.space**2)
ax.set_zlabel("$z$ [m]")
ax.scatter3D(self.drone.x0[0],
self.drone.x0[1],
self.drone.x0[2],
marker='o',
linewidths=self.obs.space,
color='green')
ax.scatter3D(self.drone.xf[0],
self.drone.xf[1],
self.drone.xf[2],
marker='o',
linewidths=self.obs.space,
color='red')
ax.plot3D(state_sampled[0, :],
state_sampled[1, :],
state_sampled[2, :],
color='orange')
ax.plot3D(self.state[0, :],
self.state[1, :],
self.state[2, :],
marker='o', linestyle='None', color='orange')
ax.set_box_aspect([1,1,1]) # Equal aspect ratio
# Set the limits of the axes to fit the range of your data
xmin, xmax = np.min(self.obs.map3d[:, 0]), np.max(self.obs.map3d[:, 0])
ymin, ymax = np.min(self.obs.map3d[:, 1]), np.max(self.obs.map3d[:, 1])
zmin, zmax = np.min(self.obs.map3d[:, 2]), np.max(self.obs.map3d[:, 2])
ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])
ax.set_zlim([zmin, zmax])
else:
ax = plt.axes()
# Plot obstacles as circles
for obs_pos in self.obs.map2d:
circle = Circle(obs_pos, self.obs.space*np.sqrt(2)/2+self.drone.safe_radius,
color='blue', fill=False) # Create a circle around the obstacle
ax.add_patch(circle) # Add the circle to the axes
ax.scatter(self.obs.map2d[:, 0],
self.obs.map2d[:, 1],
marker='s',
linewidths=self.obs.space**2)
ax.scatter(self.drone.x0[0],
self.drone.x0[1],
marker='o',
linewidths=self.obs.space,
color='green')
ax.scatter(self.drone.xf[0],
self.drone.xf[1],
marker='o',
linewidths=self.obs.space,
color='red')
ax.plot(state_sampled[0, :],
state_sampled[1, :],
color='orange')
ax.plot(self.state[0, :],
self.state[1, :],
marker='o', linestyle='None', color='orange')
ax.set_xlabel("$x$ [m]")
ax.set_ylabel("$y$ [m]")
# fig.subplots_adjust(left=0, bottom=0, right=1,
# top=1, wspace=0, hspace=0)
if save:
fig.savefig(img_folder+'3d_position.eps')
plt.savefig(img_folder+'3d_position.png', dpi=dpi, bbox_inches="tight")
# 3D plots DO NOT WORK in tikzplotlib!!!
plt.show()
def plot_3d_obstacles(self, ax, centers, radius):
"""
Plots 3D spherical obstacles given centers and radius.
Args:
- ax: Axes3D object to plot on.
- centers: numpy array of shape (N, 3) containing obstacle centers.
- radius: Radius of the spherical obstacles.
"""
u = np.linspace(0, 2 * np.pi, 30)
v = np.linspace(0, np.pi, 30)
x = radius * np.outer(np.cos(u), np.sin(v))
y = radius * np.outer(np.sin(u), np.sin(v))
z = radius * np.outer(np.ones(np.size(u)), np.cos(v))
for center in centers:
ax.plot_surface(x + center[0], y + center[1], z + center[2], color='b', alpha=0.3)
def get_sampled_trajectory(self, dt = 0.01):
"""Get sampled trajectory"""
time_array = [np.arange(self.time[0], self.time[-1], dt)]
self.__get_polynomial_solution()
time_sampled, state_sampled, control_sampled = self.resample_solution(
time_array)
time_sampled, state_sampled, control_sampled = time_sampled[
0], state_sampled[0], control_sampled[0]
return time_sampled, state_sampled, control_sampled
def __get_polynomial(self, y, t, n):
"""Return polynomial of n-th order"""
return np.polynomial.Polynomial.fit(t, y, n-1)
def __get_polynomial_lagrange(self, y, t, n):
"""Return polynomial of n-th order"""
return lagrange(t, y)
def __get_spline(self, y, t, n):
"""Return spline"""
return CubicSpline(t, y, n)
def __get_polynomial_cheby(self, y, t, n):
"""Return chebyshev polynomial of n-th order"""
# TODO: rescaling to <-1,1> needed due to numerical stability
return np.polynomial.chebyshev.Chebyshev.fit(t, y, n-1)
def __get_polynomials(self, y, t, n_col):
"""Return array of polynomials for each segment"""
p = []
n_col_add = np.zeros(n_col.shape[0]+1, dtype=int)
for i, cols in enumerate(n_col):
n_col_add[i+1] = n_col_add[i] + cols
if self.fit == 'cheby':
p.append(self.__get_polynomial_cheby(
y[n_col_add[i]:n_col_add[i+1]], t[n_col_add[i]:n_col_add[i+1]], cols))
elif self.fit == 'lagrange':
p.append(self.__get_polynomial_lagrange(
y[n_col_add[i]:n_col_add[i+1]], t[n_col_add[i]:n_col_add[i+1]], cols))
elif self.fit == 'spline':
p.append(self.__get_spline(
y[n_col_add[i]:n_col_add[i+1]], t[n_col_add[i]:n_col_add[i+1]], cols))
else:
p.append(self.__get_polynomial(
y[n_col_add[i]:n_col_add[i+1]], t[n_col_add[i]:n_col_add[i+1]], cols))
return p
def __get_n_polynomials(self, Y, t, n_col):
"""Returns array of N functions Y[N,t] for each segment """
pY = []
for y in Y:
pY.append(self.__get_polynomials(y, t, n_col))
return pY
def __get_polynomial_solution(self):
"""Calculate polynomial representation of solution"""
if not hasattr(self, 'state_poly'):
self.state_poly = self.__get_n_polynomials(
self.state, self.time, self.n_col)
if not hasattr(self, 'control_poly'):
self.control_poly = self.__get_n_polynomials(
self.control, self.time, self.n_col)
return
def __sample_solution(self):
"""
This function generates a solution sampled on the selected n_simpson points.
It generates time, state, state derivative, and control samples for each segment.
The generated samples are stored as attributes of the class.
"""
# Generate time samples for each segment
t_sample = []
for t in self.multiseg_time:
t_sample_seg = []
for i in range(t.shape[0]-1):
t_sample_seg.append(np.linspace(
t[i], t[i+1], self.n_simpson))
t_sample.append(t_sample_seg)
# Generate state and state derivative samples for each segment
state_sample = []
state_derivative_sample = []
for p_array in self.state_poly:
# go though state elements
state_sample_seg = []
state_derivative_sample_seg = []
for i_seg, p in enumerate(p_array):
# go through segments
for t in t_sample[i_seg]:
# go through collocation points neghborhood
state_sample_seg.append(p(t))
if self.fit == 'spline':
state_derivative_sample_seg.append(p.derivative(1)(t))
else:
state_derivative_sample_seg.append(p.deriv(1)(t))
state_sample.append(state_sample_seg)
state_derivative_sample.append(state_derivative_sample_seg)
# Generate control samples for each segment
control_sample = []
for p_array in self.control_poly:
control_sample_seg = []
for i_seg, p in enumerate(p_array):
for t in t_sample[i_seg]:
control_sample_seg.append(p(t))
control_sample.append(control_sample_seg)
# Save generated samples as attributes of the class
self.__state_sample = state_sample
self.__control_sample = control_sample
self.__t_sample = t_sample
self.__state_derivative_sample = state_derivative_sample
self.sampled = True
def resample_solution(self, new_multiseg_time):
"""
Resamples the solution at the given times.
Args:
new_multiseg_time (list): A list of arrays, where each array contains
the new times for each segment.
Returns:
tuple: A tuple containing:
- time_sample (array): The new time array.
- state_sample (list): A list of arrays, where each array contains the
state samples for each segment.
- control_sample (list): A list of arrays, where each array contains
the control samples for each segment.
"""
if not hasattr('self','state_poly'):
self.__get_polynomial_solution()
time_sample = new_multiseg_time
# Adherence to time continuity
for i in range(len(time_sample[:-1])):
time_sample[i+1][0] = time_sample[i][-1]
# Generate state and state derivative samples for each segment
state_sample = []
control_sample = []
i = 0
for new_seg_time in new_multiseg_time:
n = len(new_seg_time)
state_sample_seg = np.zeros([self.nx, int(n)])
control_sample_seg = np.zeros([self.nu, int(n)])
for j, t_new in enumerate(new_seg_time):
while t_new > self.multiseg_time[i][-1] and i < self.n_seg-1:
# check if time instant is within current segment
i += 1
for k, p in enumerate(self.state_poly):
state_sample_seg[k, j] = p[i](t_new)
for k, p in enumerate(self.control_poly):
control_sample_seg[k, j] = p[i](t_new)
state_sample.append(state_sample_seg)
control_sample.append(control_sample_seg)
return time_sample, state_sample, control_sample
def evaluate_solution(self, n_simpson = 10):
"""
This function evaluates the dynamics error of the solution.
It generates the sample solution using the polynomial solutions
obtained from __get_polynomial_solution() function.
"""
# Set the number of poinst for Simpson's rule
self.n_simpson = n_simpson
self.sampled = False
# Sample the solution
self.__sample_solution()
# Fit solution for state and control as polynomial
self.__get_polynomial_solution()
# Calculate the dynamics error
self.__dynamics_error()
# Calculate the adherence to constraints
self.__constraints_error()
def get_deflection(self):
"""
Calculates the deflection of the local relative error based on the relative error values
stored in `self.relative_error_max`.
Returns a list of deflection values for each segment in `self.relative_error_max`.
"""
# Ensure that the relative error is calculated
if self.relative_error_max is None:
self.get_relative_error()
deflection = []
# Calculate deflection from self.relative_error_max
for relative_error_max_seg in self.relative_error_max:
# Convert the list to a NumPy array
relative_error_max_seg = np.array(relative_error_max_seg)
# Calculate the difference between consecutive local errors
differences = np.diff(relative_error_max_seg)
# Compute the absolute value of the differences to obtain the deflection values
deflection_seg = np.abs(differences)
deflection.append(deflection_seg.tolist())
self.relative_deflection = deflection
return deflection
def plot_deflection(self, figsize=(6,4), save = False, img_folder = 'img/', dpi = 600):
"""
Plots the deflection of the local relative error based on the deflection values
stored in `self.deflection` and the original solution time in `self.time`.
"""
# Ensure that the deflection is calculated
if self.relative_deflection is None:
self.get_deflection()
# Flatten the deflection list and add None between segments to separate them
flat_deflection = []
for i, deflection_seg in enumerate(self.relative_deflection):
flat_deflection.extend(deflection_seg)
if i < len(self.relative_deflection) - 1:
flat_deflection.append(None)
# Flatten the time list and add None between segments to separate them
flat_time = np.delete(self.time, self.n_col_add[1:]-1)
# Plot the deflection values
plt.figure(figsize=figsize)
plt.step(flat_time[:-1], flat_deflection, linestyle='-', where='pre')
plt.xlabel('$t$ [s]')
plt.ylabel('$\Delta\epsilon_{r\max,i}$')
if save:
plt.savefig(img_folder+'error_deflection.eps')
plt.savefig(img_folder+'error_deflection.png', dpi=dpi, bbox_inches="tight")
tplt.save(img_folder+'error_deflection.tex')
plt.show()
def plot_relative_error_max(self, figsize=(6,4), save = False, img_folder = 'img/', dpi = 600):
"""
Plots the maximum relative error based on the values stored in `self.relative_error_max`
and the original solution time in `self.time`.
"""
# Ensure that the relative error is calculated
if self.relative_error_max is None:
self.get_relative_error()
# Flatten the relative_error_max list and add None between segments to separate them
flat_relative_error_max = []
for i, relative_error_max_seg in enumerate(self.relative_error_max):
flat_relative_error_max.extend(relative_error_max_seg)
if i < len(self.relative_error_max) - 1:
flat_relative_error_max.append(self.relative_error_max[i+1][0])
# flat_relative_error_max.append(None)
# pass
# Flatten the time list and add None between segments to separate them
flat_time = self.time.copy()
plt.figure(figsize=figsize)
# Plot the maximum relative error values
plt.step(flat_time[:-1], flat_relative_error_max, linestyle='-', where='pre')
plt.xlabel('$t$ [s]')
plt.ylabel('$\epsilon_{r\max,i}$')
if save: