forked from caslabuiowa/OptimalBezierTrajectoryGeneration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbezier.py
1868 lines (1517 loc) · 57.2 KB
/
bezier.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 25 10:20:47 2019
Note that all sources titled "Paper Reference: ..." refer to the paper
"Bernstein Polynomial Toolkit for Trajectory Generation in Multiple Autonomous
Vehicle Missions" written by Calvin Kielas-Jensen and Venanzio Cichella.
@author: ckielasjensen
"""
from collections import defaultdict
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from numba import njit, jit
import numpy as np
from scipy.special import binom
#from gjk.gjk import gjkNew
#from gjk import gjkNew
#TODO:
# Implement curve using Bernstein basis instead of de cast
# Precompute function to be called before optimizer
# Min dist 3D
# JIT ahead of time compiling
# Priorities:
# 1. GJK for 3D
# 2. Speed
# 3.
class BezierParams:
"""Parent class used for storing Bezier parameters
:param cpts: Control points used to define the Bezier curve. The degree of
the Bezier curve is equal to the number of columns -1. The dimension of
the curve is equal to the number of rows.
:type cpts: numpy.ndarray or None
:param tau: Values at which to evaluate the Bezier curve.
:type tau: numpy.ndarray or None
:param t0: Initial time of the Bezier curve trajectory.
:type t0: float
:param tf: Final time of the Bezier curve trajectory.
:type tf: float
"""
splitCache = defaultdict(dict)
elevationMatrixCache = defaultdict(dict)
productMatrixCache = defaultdict(dict)
diffMatrixCache = defaultdict(dict)
bezCoefCache = dict()
def __init__(self, cpts=None, tau=None, t0=0.0, tf=1.0):
self._curve = None
if cpts is not None:
if cpts.ndim == 1:
self._cpts = np.atleast_2d(cpts)
self._dim = 1
self._deg = cpts.size - 1
else:
self._cpts = cpts
self._dim = self._cpts.shape[0]
self._deg = self._cpts.shape[1] - 1
else:
self._dim = None
self._deg = None
if tau is not None:
self._t0 = tau[0]
self._tf = tau[-1]
else:
self._t0 = float(t0)
self._tf = float(tf)
self._tau = tau
@property
def cpts(self):
return self._cpts
@cpts.setter
def cpts(self, value):
self._curve = None
if (isinstance(value, np.ndarray) and
value.ndim == 2 and
value.dtype == 'float64'):
newCpts = value
else:
newCpts = np.array(value, ndmin=2, dtype=float)
self._dim = newCpts.shape[0]
self._deg = newCpts.shape[1] - 1
self._cpts = newCpts
@property
def deg(self):
return self._deg
@property
def degree(self):
return self._deg
@property
def dim(self):
return self._dim
@property
def dimension(self):
return self._dim
@property
def t0(self):
return self._t0
@t0.setter
def t0(self, value):
self._t0 = float(value)
self._tau = None
@property
def tf(self):
return self._tf
@tf.setter
def tf(self, value):
self._tf = float(value)
self._tau = None
@property
def tau(self):
if self._tau is None:
self._tau = np.linspace(self._t0, self._tf, 1001)
elif not isinstance(self._tau, np.ndarray):
self._tau = np.array(self._tau)
return self._tau
@tau.setter
def tau(self, val):
self._curve = None
self._t0 = val[0]
self._tf = val[-1]
self._tau = np.array(val)
class Bezier(BezierParams):
"""Bezier curve for trajectory generation
Allows the user to construct a Bezier curve of arbitrary dimension and
degree.
:param cpts: Control points used to define the Bezier curve. The degree of
the Bezier curve is equal to the number of columns -1. The dimension of
the curve is equal to the number of rows.
:type cpts: numpy.ndarray or None
:param t0: Initial time of the Bezier curve trajectory.
:type t0: float
:param tf: Final time of the Bezier curve trajectory.
:type tf: float
"""
def __init__(self, cpts=None, t0=0.0, tf=1.0, tau=None):
super().__init__(cpts=cpts, tau=tau, t0=t0, tf=tf)
def __add__(self, curve):
return self.add(curve)
def __sub__(self, curve):
return self.sub(curve)
def __mul__(self, curve):
return self.mul(curve)
def __truediv__(self, curve):
return self.div(curve)
def __pow__(self, power):
pass
def __repr__(self):
return 'Bezier({}, {}, {}, {})'.format(self.cpts, self.tau, self.t0,
self.tf)
def __call__(self, t):
"""Calling the object returns the values of the curve at the t values
Note that unlike the curve property, this will NOT cache the computed
values. This is meant to be a convenience function to quickly peek at
the values of the curve.
:param t: Single value or numpy array of values at which to compute the
curve.
:type t: float or numpy.ndarray
"""
tau = np.atleast_1d(t)
curve = np.empty((self.dim, tau.size))
for i, pts in enumerate(self.cpts):
curve[i] = deCasteljauCurve(pts, tau, self.t0, self.tf)
return curve
@property
def x(self):
"""Convenience function to return only the X dimension of the curve
Returns a Bezier object whose control points are the 0th row of the
original object's control points.
"""
return Bezier(self.cpts[0], t0=self.t0, tf=self.tf)
@property
def y(self):
"""Convenience function to return only the Y dimension of the curve
Returns a Bezier object whose control points are the 1st row of the
original object's control points. If the original object is less than
2 dimensions, this returns None.
"""
if self.dim > 1:
return Bezier(self.cpts[1], t0=self.t0, tf=self.tf)
else:
return None
@property
def z(self):
"""Convenience function to return only the Z dimension of the curve
Returns a Bezier object whose control points are the 2nd row of the
original object's control points. If the original object is less than
3 dimensions, this returns None.
"""
if self.dim > 2:
return Bezier(self.cpts[2], t0=self.t0, tf=self.tf)
else:
return None
@property
def curve(self):
"""Returns the curve computed at each value of Tau.
This function will use the De Casteljau algorithm to find the value of
the curve at each value found within Tau \in [t0, tf]. Note that by
default Tau is computed by np.linspace(t0, tf, 1001). This function
will also cache the curve for future use to avoid computing the curve
multiple times.
The computation of the curve uses the De Casteljau algorithm rather
than the definition of Bernstein polynomials due to roundoff errors for
high order curves. While Bernstein polynomials exhibit numerical
stability, Python will not properly handle values to the power of large
numbers.
"""
if self._curve is None:
self._curve = np.zeros([self.dim, len(self.tau)])
for i, pts in enumerate(self.cpts):
self._curve[i] = deCasteljauCurve(pts, self.tau, self.t0,
self.tf)
return self._curve
def copy(self):
"""Creates an exact, deep copy of the current Bezier object
:return: Deep copy of Bezier object
:rtype: Bezier
"""
return Bezier(self.cpts, self.t0, self.tf)
def plot(self, axisHandle=None, showCpts=True, **kwargs):
"""Plots the Bezier curve in 1D or 2D
Note: Currently only supports plotting in 1D or 2D.
:param axisHandle: Handle to the figure axis. If it is None, a new
figure will be plotted.
:type axisHandle: matplotlib.axes._subplots.AxesSubplot or None
:param showCpts: Flag that decides whether to show the control points
in the plot. Default is True.
:type showCpts: bool
:param **kwargs: Keyword arguments passed into the plot command. Note
that the arguments are only passed into the plot command that
plots the curve and not the command that plots the control points.
:type **kwargs: dict
:return: Axis object where the curve was plotted.
:rtype: matplotlib.axes._subplots.AxesSubplot
"""
if axisHandle is None:
fig, ax = plt.subplots()
else:
ax = axisHandle
cpts = np.asarray(self.cpts)
if self.dim == 1:
ax.plot(self.tau, self.curve[0], **kwargs)
if showCpts:
ax.plot(np.linspace(self.t0, self.tf, self.deg+1),
self.cpts.squeeze(), '.--')
elif self.dim == 2 or (self.cpts[2, :] == 0).all():
ax.plot(self.curve[0], self.curve[1], **kwargs)
if showCpts:
ax.plot(cpts[0], cpts[1], '.--')
else:
# Check whether ax is 3D
if not hasattr(ax, 'get_zlim'):
parent = ax.get_figure()
ax.remove()
ax = parent.add_subplot(111, projection='3d')
ax.plot(self.curve[0], self.curve[1], self.curve[2], **kwargs)
if showCpts:
ax.plot(self.cpts[0], self.cpts[1], self.cpts[2], '.--')
return ax
def add(self, other):
"""Adds two Bezier curves
This function will automatically check to make sure that the initial
and final times are aligned.
Paper Reference: Property 7: Arithmetic Operations
:param other: Other Bezier curve to be added
:type other: Bezier
:return: Sum of the two Bezier curves, or None if their times do not
overlap.
:rtype: Bezier
"""
if self.t0 == other.t0 and self.tf == other.tf:
cpts = self.cpts + other.cpts
t0 = self.t0
tf = self.tf
else:
c1, c2 = _temporalAlignment(self, other)
cpts = c1.cpts + c2.cpts
t0 = c1.t0
tf = c1.tf
if t0 >= tf:
return None
else:
return Bezier(cpts, t0=t0, tf=tf)
def sub(self, other):
"""Subtracts two Bezier curves
This function will automatically check to make sure that the initial
and final times are aligned.
Paper Reference: Property 7: Arithmetic Operations
:param other: Bezier curve to subtract from the original
:type other: Bezier
:return: Original curve - Other curve, or None if their times do not
overlap.
:rtype: Bezier
"""
if self.t0 == other.t0 and self.tf == other.tf:
cpts = self.cpts - other.cpts
t0 = self.t0
tf = self.tf
else:
c1, c2 = _temporalAlignment(self, other)
cpts = c1.cpts - c2.cpts
t0 = c1.t0
tf = c1.tf
if t0 >= tf:
return None
else:
return Bezier(cpts, t0=t0, tf=tf)
def mul(self, multiplicand):
"""Computes the product of two Bezier curves.
Paper Reference: Property 7: Arithmetic Operations
Source: Section 5.1 of "The Bernstein Polynomial Basis: A Centennial
Retrospective" by Farouki.
:param multiplicand: Multiplicand
:type multiplicand: Bezier
:return: Product of the two curve
:rtype: Bezier
"""
if not isinstance(multiplicand, Bezier):
msg = 'The multiplicand must be a {} object, not a {}'.format(
Bezier, type(multiplicand))
raise TypeError(msg)
dim = self.dim
if multiplicand.dim != dim:
msg = ('The dimension of both Bezier curves must be the same.\n'
'The first dimension is {} and the second is {}'.format(
dim, multiplicand.dim))
raise ValueError(msg)
a = np.array(self.cpts, ndmin=2)
b = np.array(multiplicand.cpts, ndmin=2)
m = self.deg
n = multiplicand.deg
c = np.empty((dim, m+n+1))
try:
coefMat = Bezier.productMatrixCache[m][n]
except KeyError:
coefMat = bezProductCoefficients(m, n)
Bezier.productMatrixCache[m][n] = coefMat
for d in range(dim):
c[d] = multiplyBezCurves(a[d], b[d], coefMat)
# This code uses Farouki's method for multiplication but does not simplify
# the problem using matrices.
# for d in range(dim):
# for k in np.arange(0, m+n+1):
# summation = 0
# for j in np.arange(max(0, k-n), min(m, k)+1):
# summation += binom(m, j) \
# * binom(n, k-j) \
# * a[d, j] \
# * b[d, k-j]
# c[d, k] = summation / binom(m+n, k)
newCurve = self.copy()
newCurve.cpts = c
return newCurve
def div(self, denominator):
"""Divides one Bezier curve by another.
The division of two Bezier curves results in a rational Bezier curve.
Paper Reference: Property 7: Arithmetic Operations
:param denominator: Denominator of the division
:type denominator: Bezier
:return: Rational Bezier curve representing the division of the two
curves.
:rtype: RationalBezier
"""
if not isinstance(denominator, Bezier):
msg = ('The denominator must be a Bezier object, not a {}. '
'Or the module has been reloaded.').format(
type(denominator))
raise TypeError(msg)
cpts = np.empty((self.dim, self.deg+1))
for i in range(self.dim):
for j in range(self.deg+1):
if self.cpts[i, j] == 0:
cpts[i, j] = 0
elif denominator.cpts[i, j] == 0:
cpts[i, j] = np.inf
else:
cpts[i, j] = self.cpts[i, j] / denominator.cpts[i, j]
weights = denominator.cpts
return RationalBezier(cpts.astype(np.float64),
weights.astype(np.float64),
tau=self.tau, tf=self.tf)
def elev(self, R=1):
"""Elevates the degree of the Bezier curve
Elevates the degree of the Bezier curve by R (default is 1) and returns
a new, higher degree Bezier object.
:param R: Number of degrees to elevate the curve
:type R: int
:return: Elevated Bezier curve
:rtype: Bezier
"""
try:
elevMat = Bezier.elevationMatrixCache[self.deg][R]
except KeyError:
elevMat = elevMatrix(self.deg, R)
Bezier.elevationMatrixCache[self.deg][R] = elevMat
elevPts = []
for cpts in self.cpts:
elevPts.append(np.dot(cpts, elevMat))
elevPts = np.vstack(elevPts)
curveElev = self.copy()
curveElev.cpts = elevPts
return curveElev
def diff(self):
"""Calculates the derivative of the Bezier curve
Note that this does not affect the object. Instead it returns the
derivative.
:return: Derivative of the Bezier curve
:rtype: Bezier
"""
try:
Dm = Bezier.diffMatrixCache[self.deg][self.tf-self.t0]
except KeyError:
Dm = diffMatrix(self.deg, self.tf-self.t0)
Bezier.diffMatrixCache[self.deg][self.tf-self.t0] = Dm
cptsDot = []
for i in range(self.dim):
cptsDot.append(np.dot(self.cpts[i, :], Dm))
curveDot = self.copy()
curveDot.cpts = cptsDot
return curveDot.elev()
def integrate(self):
"""Calculates the area under the curve in each dimension
:return: Area under the curve in each dimension.
:rtype: numpy.ndarray
"""
areas = np.empty(self.dim)
for d in range(self.dim):
areas[d] = self.tf * sum(self.cpts[d]) / (self.deg+1)
return areas
def split(self, tDiv):
"""Splits the curve into two curves at point tDiv
Note that the two returned curves will have the SAME tf value as the
original curve. This may result in slightly unexpected behavior for a
1D curve when plotting since both slices of the original curve will
also be plotted on [0, tf]. The behavior should work as expected when
plotting in 2D though.
Paper Reference: Property 5: The de Casteljau Algorithm
:param tDiv: Point at which to split the curve
:type tDiv: float
:return: Tuple of curves. One before the split point and one after.
:rtype: tuple(Bezier, Bezier)
"""
c1 = self.copy()
c2 = self.copy()
cpts1 = []
cpts2 = []
if np.isnan(tDiv):
print('[!] Warning, tDiv is {}, changing to 0.'.format(tDiv))
tDiv = 0
for d in range(self.dim):
left, right = deCasteljauSplit(self.cpts[d, :], tDiv - self.t0,
self.tf - self.t0)
cpts1.append(left)
cpts2.append(right[::-1])
c1.cpts = cpts1
c1.t0 = self.t0
c1.tf = tDiv
c2.cpts = cpts2
c2.t0 = tDiv
c2.tf = self.tf
return c1, c2
# def min(self, dim=0, tol=1e-6, maxIter=1000):
# """Returns the minimum value of the Bezier curve in a single dimension
#
# Finds the minimum value of the Bezier curve. This is done by first
# checking the first and last control points since the first and last
# point lie on the curve. If the first or last control point is not the
# minimum value, the curve is split at the lowest control point. The new
# minimum value is then defined as the lowest control point of the two
# new curves. This continues until the difference between the new minimum
# and old minimum values is within the desired tolerance.
#
# :param dim: Which dimension to return the minimum of.
# :type dim: int
# :param tol: Tolerance of the minimum value.
# :type tol: float
# :param maxIter: Maximum number of iterations to search for the minimum.
# :type maxIter: int
# :return: Minimum value of the Bezier curve. None if maximum iterations
# is met.
# :rtype: float or None
# """
# minVal = min(self.cpts[dim, :])
# tol = np.abs(tol*np.mean(self.cpts))
#
# if self.cpts[dim, 0] == minVal:
# return self.cpts[dim, 0]
#
# elif self.cpts[dim, -1] == minVal:
# return self.cpts[dim, -1]
#
# else:
# lastMin = np.inf
# newCurve = self.copy()
# for _ in range(maxIter):
# splitPoint = (np.argmin(newCurve.cpts[dim, :])
# / (newCurve.deg+1.0))
# c1, c2 = newCurve.split(splitPoint)
#
# min1 = min(c1.cpts[dim, :])
# min2 = min(c2.cpts[dim, :])
#
# if min1 < min2:
# newCurve = c1
# newMin = min1
#
# else:
# newCurve = c2
# newMin = min2
#
# if np.abs(newMin-lastMin) < tol:
# return newMin
# else:
# lastMin = newMin
#
# print('Maximum number of iterations met')
# return None
def min(self, dim=0, globMin=-np.inf, tol=1e-6):
"""Returns the minimum value of the Bezier curve in a single dimension
Finds the minimum value of the Bezier curve. This is done by first
checking the first and last control points since the first and last
point lie on the curve. If the first or last control point is not the
minimum value, the curve is split at the lowest control point. The new
minimum value is then defined as the lowest control point of the two
new curves. This continues until the difference between the new minimum
and old minimum values is within the desired tolerance.
:param dim: Which dimension to return the minimum of.
:type dim: int
:param tol: Tolerance of the minimum value.
:type tol: float
:param maxIter: Maximum number of iterations to search for the minimum.
:type maxIter: int
:return: Minimum value of the Bezier curve. None if maximum iterations
is met.
:rtype: float or None
"""
minIdx = np.argmin(self.cpts[dim, :])
newMin = min(self.cpts[dim, :])
error = np.abs(globMin-newMin)
if error < tol:
return newMin
elif minIdx != 0 and minIdx != self.deg:
splitPoint = minIdx / self.deg
c1, c2 = self.split(splitPoint)
c1min = c1.min(dim=dim, globMin=newMin, tol=tol)
c2min = c2.min(dim=dim, globMin=newMin, tol=tol)
newMin = min((c1min, c2min))
return newMin
# def max4(self, dim=0, tol=1e-6, maxIter=1000):
# """Returns the maximum value of the Bezier curve in a single dimension
#
# Finds the maximum value of the Bezier curve. This is done by first
# checking the first and last control points since the first and last
# point lie on the curve. If the first or last control point is not the
# maximum value, the curve is split at the highest control point. The new
# maximum value is then defined as the highest control point of the two
# new curves. This continues until the difference between the new maximum
# and old maximum values is within the desired tolerance.
#
# :param dim: Which dimension to return the maximum of.
# :type dim: int
# :param tol: Tolerance of the maximum value.
# :type tol: float
# :param maxIter: Maximum number of iterations to search for the minimum.
# :type maxIter: int
# :return: Maximum value of the Bezier curve. None if maximum iterations
# is met.
# :rtype: float or None
# """
# maxVal = max(self.cpts[dim, :])
#
# if self.cpts[dim, 0] == maxVal:
# return self.cpts[dim, 0]
#
# elif self.cpts[dim, -1] == maxVal:
# return self.cpts[dim, -1]
#
# else:
# lastMax = np.inf
# newCurve = self.copy()
# for _ in range(maxIter):
# splitPoint = (np.argmax(newCurve.cpts[dim, :])
# / (newCurve.deg+1.0))
# c1, c2 = newCurve.split(splitPoint)
#
# max1 = max(c1.cpts[dim, :])
# max2 = max(c2.cpts[dim, :])
#
# if max1 > max2:
# newCurve = c1
# newMax = max1
#
# else:
# newCurve = c2
# newMax = max2
#
# if np.abs(newMax-lastMax)/newMax < tol:
# return newMax
# else:
# lastMax = newMax
#
# print('Maximum number of iterations met')
# return None
# TODO:
# Change error to be absolute not normalized (look @ paper)
def max(self, dim=0, globMax=np.inf, tol=1e-6): # , maxIter=1000):
"""Returns the maximum value of the Bezier curve in a single dimension
Finds the maximum value of the Bezier curve. This is done by first
checking the first and last control points since the first and last
point lie on the curve. If the first or last control point is not the
maximum value, the curve is split at the highest control point. The new
maximum value is then defined as the highest control point of the two
new curves. This continues until the difference between the new maximum
and old maximum values is within the desired tolerance.
:param dim: Which dimension to return the maximum of.
:type dim: int
:param tol: Tolerance of the maximum value.
:type tol: float
:param maxIter: Maximum number of iterations to search for the minimum.
:type maxIter: int
:return: Maximum value of the Bezier curve. None if maximum iterations
is met.
:rtype: float or None
"""
maxIdx = np.argmax(self.cpts[dim, :])
newMax = max(self.cpts[dim, :])
error = np.abs(globMax-newMax)
if error < tol:
return newMax
elif maxIdx != 0 and maxIdx != self.deg:
splitPoint = maxIdx / self.deg
c1, c2 = self.split(splitPoint)
c1max = c1.max(dim=dim, globMax=newMax, tol=tol)
c2max = c2.max(dim=dim, globMax=newMax, tol=tol)
newMax = max((c1max, c2max))
return newMax
# def max3(self, dim=0, tol=1e-3, maxIter=1000):
# maxIdx = np.argmax(self.cpts[dim, :])
# oldMax = max(self.cpts[dim, :])
#
# oldCurve = self.copy()
#
# if maxIdx == 0 or maxIdx == self.deg:
# newMax = oldMax
# else:
# for _ in range(maxIter):
# newCurve = oldCurve.elev(oldCurve.deg+10)
# newMax = max(newCurve.cpts[dim, :])
#
# error = np.abs(newMax-oldMax) / newMax
#
# if error < tol:
# break
#
# oldMax = newMax
# oldCurve = newCurve.copy()
#
# return newMax
#
# def min2(self, dim=0, tol=1e-6, maxIter=1000):
# """Uses scipy's fminbound to find the minimum value of the Bezier curve
#
# This method is slower than min because it does not exploit the useful
# properties of a Bezier curve.
#
# :param dim: Which dimension to return the minimum of.
# :type dim: int
# :param tol: Tolerance of the minimum value.
# :type tol: float
# :param maxIter: Maximum number of iterations to search for the minimum.
# :type maxIter: int
# :return: Minimum value of the Bezier curve. None if maximum iterations
# is met.
# :rtype: float or None
# """
# def fun(x): return bezierCurve(self.cpts[dim, :], x, tf=self._tf)
# _, minVal, status, _ = scipy.optimize.fminbound(fun,
# x1=0,
# x2=1,
# xtol=tol,
# maxfun=maxIter,
# full_output=True,
# disp=1)
# return minVal[0] if status == 0 else None
#
# def max2(self, dim=0, tol=1e-6, maxIter=1000):
# """Uses scipy's fminbound to find the maximum value of the Bezier curve
#
# This method is slower than max because it does not exploit the useful
# properties of a Bezier curve.
#
# :param dim: Which dimension to return the minimum of.
# :type dim: int
# :param tol: Tolerance of the minimum value.
# :type tol: float
# :param maxIter: Maximum number of iterations to search for the minimum.
# :type maxIter: int
# :return: Maximum value of the Bezier curve. None if maximum iterations
# is met.
# :rtype: float or None
# """
# def fun(x): return -bezierCurve(self.cpts[dim, :], x, tf=self._tf)
# _, maxVal, status, _ = scipy.optimize.fminbound(fun,
# x1=0,
# x2=1,
# xtol=tol,
# maxfun=maxIter,
# full_output=True,
# disp=1)
# return -maxVal[0] if status == 0 else None
def minDist(self, otherCurve):
"""
"""
# if self.dim != 2 or otherCurve.dim != 2:
# err = ('Both curves must be 2D only, not {} and {}.'
# ).format(self.dim, otherCurve.dim)
# raise ValueError(err)
if (self.dim < 2 or self.dim > 3 or
otherCurve.dim < 2 or otherCurve.dim > 3):
err = ('Both curves must be either 2D or 3D, not {}D and {}D.'
).format(self.dim, otherCurve.dim)
raise ValueError(err)
return _minDist(self, otherCurve)
def minDist2Poly(self, poly):
"""
"""
return _minDist2Poly(self, poly)
def collCheck(self, otherCurve):
"""
"""
return _collCheckBez2Bez(self, otherCurve)
def collCheck2Poly(self, poly):
"""
"""
return _collCheckBez2Poly(self, poly)
def normSquare(self):
"""Calculates the norm squared of the Bezier curve
Returns a Bezier object for the norm squared result of the current
Bezier curve.
:return: Norm squared of the Bezier curve
:rtype: Bezier
"""
try:
prodM = Bezier.productMatrixCache[self.deg][self.deg]
except KeyError:
prodM = prodMatrix(self.deg).T
Bezier.productMatrixCache[self.deg][self.deg] = prodM
normCpts = _normSquare(self.cpts, 1, self.dim, prodM.T)/2
newCurve = self.copy()
newCurve.cpts = normCpts
return newCurve
# return Bezier(_normSquare(self.cpts, 1, self.dim, prodM.T),
# tau=self.tau, tf=self.tf)
class RationalBezier(BezierParams):
"""Rational Bezier curve for trajectory generation
"""
def __init__(self, cpts=None, weights=None, tau=None, tf=1.0):
super().__init__(cpts=cpts, tau=tau, tf=tf)
self._weights = np.array(weights, ndmin=2)
def _temporalAlignment(c1, c2):
"""Returns two curves that are temporally aligned (i.e. same t0 and tf)
:param c1: First curve to be aligned
:type c1: Bezier
:param c2: Second curve to be aligned
:type c2: Bezier
:return: Two curves whose control points are defined for the intersection
of time of c1 and c2. (i.e. t0 = max(c1.t0, c2.t0),
tf = min(c1.tf, c2.tf))
:rtype: (Bezier, Bezier)
"""
newC1 = c1.copy()
newC2 = c2.copy()
if c1.t0 < c2.t0:
t0 = c2.t0
_, newC1 = newC1.split(t0)
elif c1.t0 > c2.t0:
t0 = c1.t0
_, newC2 = newC2.split(t0)
else:
t0 = c1.t0
if c1.tf < c2.tf:
tf = c1.tf
newC2, _ = newC2.split(tf)
elif c1.tf > c2.tf:
tf = c2.tf
newC1, _ = newC1.split(tf)
else:
tf = c1.tf
newC1.t0 = t0
newC2.t0 = t0
newC1.tf = tf
newC2.tf = tf
return newC1, newC2
@njit(cache=True)
def deCasteljauCurve(cpts, tau, t0=0.0, tf=1.0):
"""Returns a Bezier curve using the de Casteljau algorithm
Uses the de Casteljau algorithm to generate the Bezier curve defined by
the provided control points. Note that the datatypes are important due to
the nature of the numba library.
Paper Reference: Property 5: The de Casteljau Algorithm
:param cpts: Control points defining the 1D Bezier curve.
:type cpts: numpy.ndarray(dtype=numpy.float64)
:param tau: Values at which to evaluate Bezier curve.
:type tau: numpy.ndarray(dtype=numpy.float64)
:param t0: Initial time of the curve. Default is 0.0.
:type t0: float
:param tf: Final time of the curve. Default is 1.0.
:type tf: float
:return: Numpy array of length tau of the Bezier curve evaluated at each
value of tau.
:rtype: numpy.ndarray(dtype=numpy.float64)
"""
T = (tau - t0) / (tf - t0)
curveLen = T.size
curve = np.empty(curveLen)
curveIdx = 0
for t in T:
newCpts = cpts.copy()
while newCpts.size > 1:
cptsTemp = np.empty(newCpts.size-1)
for i in range(cptsTemp.size):
cptsTemp[i] = (1-t)*newCpts[i] + t*newCpts[i+1]
newCpts = cptsTemp.copy()
curve[curveIdx] = newCpts[0]
curveIdx += 1
return curve
@njit(cache=True)
def deCasteljauSplit(cpts, tDiv, tf=1.0):
"""Uses the de Casteljau algorithm to split the curve at tDiv
This function is similar to the de Casteljau curve function but instead of
drawing a curve, it returns two sets of control points which define the
curve to the left and to the right of the split point, tDiv.
Paper Reference: Property 5: The de Casteljau Algorithm
:param cpts: Control points defining the 1D Bezier curve.
:type cpts: numpy.ndarray(dtype=numpy.float64)
:param tDiv: Point at which to divide the curve.
:type tDiv: float
:param tf: Final tau value for the 1D curve. Default is 1.0. Note that the
Bezier curve is defined on the range of [0, tf].