-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
piecewise_polynomial.cc
1299 lines (1154 loc) · 46.8 KB
/
piecewise_polynomial.cc
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
#include "drake/common/trajectories/piecewise_polynomial.h"
#include <algorithm>
#include <memory>
#include <utility>
#include <Eigen/SparseCore>
#include <Eigen/SparseLU>
#include <fmt/format.h>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_throw.h"
#include "drake/common/unused.h"
#include "drake/math/matrix_util.h"
using Eigen::VectorXd;
using std::abs;
using std::clamp;
using std::max;
using std::runtime_error;
using std::vector;
namespace drake {
namespace trajectories {
using math::EigenToStdVector;
template <typename T>
PiecewisePolynomial<T>::PiecewisePolynomial(
const std::vector<PolynomialMatrix>& polynomials,
const std::vector<T>& breaks)
: PiecewiseTrajectory<T>(breaks), polynomials_(polynomials) {
DRAKE_ASSERT(breaks.size() == (polynomials.size() + 1));
for (int i = 1; i < this->get_number_of_segments(); i++) {
if (polynomials[i].rows() != polynomials[0].rows())
throw std::runtime_error(
"The polynomial matrix for each segment must have the same number of "
"rows.");
if (polynomials[i].cols() != polynomials[0].cols())
throw std::runtime_error(
"The polynomial matrix for each segment must have the same number of "
"columns.");
}
}
template <typename T>
PiecewisePolynomial<T>::PiecewisePolynomial(
const std::vector<Polynomial<T>>& polynomials, const std::vector<T>& breaks)
: PiecewiseTrajectory<T>(breaks) {
DRAKE_ASSERT(breaks.size() == (polynomials.size() + 1));
for (size_t i = 0; i < polynomials.size(); i++) {
PolynomialMatrix matrix(1, 1);
matrix(0, 0) = polynomials[i];
polynomials_.push_back(matrix);
}
}
template <typename T>
std::unique_ptr<Trajectory<T>> PiecewisePolynomial<T>::Clone() const {
return std::make_unique<PiecewisePolynomial<T>>(*this);
}
template <typename T>
std::tuple<std::vector<double>, std::vector<MatrixX<VectorXd>>>
PiecewisePolynomial<T>::GetSerialized() const {
if constexpr (!std::is_same_v<T, double>) {
DRAKE_UNREACHABLE();
} else {
std::vector<MatrixX<VectorXd>> polynomials(polynomials_.size());
// Copy the polynomials_'s coefficients into polynomials.
int max_degree = 0;
for (int i = 0; i < static_cast<int>(polynomials.size()); ++i) {
const MatrixX<Polynomial<double>>& ith_in = polynomials_[i];
MatrixX<VectorXd>& ith_out = polynomials[i];
ith_out.resize(ith_in.rows(), ith_in.cols());
for (int j = 0; j < ith_in.rows(); ++j) {
for (int k = 0; k < ith_in.cols(); ++k) {
ith_out(j, k) = ith_in(j, k).GetCoefficients();
max_degree = std::max(max_degree, ith_in(j, k).GetDegree());
}
}
}
// Always output a square ndarray with shape=(npoly, nrow, ncol, ncoeff).
for (int i = 0; i < static_cast<int>(polynomials.size()); ++i) {
MatrixX<VectorXd>& ith_out = polynomials[i];
for (int j = 0; j < ith_out.rows(); ++j) {
for (int k = 0; k < ith_out.cols(); ++k) {
const int old_size = ith_out(j, k).size();
ith_out(j, k).conservativeResize(max_degree + 1);
for (int z = old_size; z < max_degree + 1; ++z) {
ith_out(j, k)(z) = 0.0;
}
}
}
}
return std::make_tuple(this->breaks(), std::move(polynomials));
}
}
template <typename T>
void PiecewisePolynomial<T>::SetSerialized(
const std::vector<double>& breaks,
const std::vector<MatrixX<VectorXd>>& polynomials) {
if constexpr (!std::is_same_v<T, double>) {
unused(breaks, polynomials);
DRAKE_UNREACHABLE();
} else {
if (breaks.empty() && polynomials.empty()) {
*this = PiecewisePolynomial<double>();
return;
}
if (breaks.size() != polynomials.size() + 1) {
throw std::logic_error(fmt::format(
"PiecewisePolynomial deserialization must provide "
"len(breaks) == len(polynomials) + 1, but had len(breaks) == {} and "
"len(polynomials) == {}",
breaks.size(), polynomials.size()));
}
for (int n = 1; n < static_cast<int>(polynomials.size()); ++n) {
if ((polynomials[n].rows() != polynomials[0].rows()) ||
(polynomials[n].cols() != polynomials[0].cols())) {
throw std::logic_error(fmt::format(
"PiecewisePolynomial deserialization must provide consistently "
"sized polynomial matrices, but polynomials[{}] had shape ({}, {}) "
"yet all prior polynomials had shape ({}, {})",
n, polynomials[n].rows(), polynomials[n].cols(),
polynomials[0].rows(), polynomials[0].cols()));
}
}
this->get_mutable_breaks() = breaks;
polynomials_.resize(polynomials.size());
for (int i = 0; i < static_cast<int>(polynomials.size()); ++i) {
const MatrixX<VectorXd>& ith_in = polynomials[i];
MatrixX<Polynomial<double>>& ith_out = polynomials_[i];
ith_out.resize(ith_in.rows(), ith_in.cols());
for (int j = 0; j < ith_in.rows(); ++j) {
for (int k = 0; k < ith_in.cols(); ++k) {
ith_out(j, k) = Polynomial<double>(ith_in(j, k));
}
}
}
}
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::derivative(
int derivative_order) const {
DRAKE_DEMAND(derivative_order >= 0);
PiecewisePolynomial ret = *this;
if (derivative_order == 0) {
return ret;
}
for (auto it = ret.polynomials_.begin(); it != ret.polynomials_.end(); ++it) {
PolynomialMatrix& matrix = *it;
for (Eigen::Index row = 0; row < rows(); row++) {
for (Eigen::Index col = 0; col < cols(); col++) {
matrix(row, col) = matrix(row, col).Derivative(derivative_order);
}
}
}
return ret;
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::integral(
const T& value_at_start_time) const {
MatrixX<T> matrix_value_at_start_time =
MatrixX<T>::Constant(rows(), cols(), value_at_start_time);
return integral(matrix_value_at_start_time);
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::integral(
const Eigen::Ref<MatrixX<T>>& value_at_start_time) const {
PiecewisePolynomial ret = *this;
for (int segment_index = 0; segment_index < this->get_number_of_segments();
segment_index++) {
PolynomialMatrix& matrix = ret.polynomials_[segment_index];
for (Eigen::Index row = 0; row < rows(); row++) {
for (Eigen::Index col = 0; col < cols(); col++) {
if (segment_index == 0) {
matrix(row, col) =
matrix(row, col).Integral(value_at_start_time(row, col));
} else {
matrix(row, col) =
matrix(row, col).Integral(ret.EvaluateSegmentAbsoluteTime(
segment_index - 1, this->start_time(segment_index), row,
col));
}
}
}
}
return ret;
}
template <typename T>
T PiecewisePolynomial<T>::scalarValue(const T& t, Eigen::Index row,
Eigen::Index col) const {
int segment_index = this->get_segment_index(t);
return EvaluateSegmentAbsoluteTime(segment_index, t, row, col);
}
template <typename T>
MatrixX<T> PiecewisePolynomial<T>::DoEvalDerivative(
const T& t, int derivative_order) const {
const int segment_index = this->get_segment_index(t);
const T time = clamp(t, this->start_time(), this->end_time());
Eigen::Matrix<T, PolynomialMatrix::RowsAtCompileTime,
PolynomialMatrix::ColsAtCompileTime>
ret(rows(), cols());
for (Eigen::Index row = 0; row < rows(); row++) {
for (Eigen::Index col = 0; col < cols(); col++) {
ret(row, col) = EvaluateSegmentAbsoluteTime(segment_index, time, row, col,
derivative_order);
}
}
return ret;
}
template <typename T>
const typename PiecewisePolynomial<T>::PolynomialMatrix&
PiecewisePolynomial<T>::getPolynomialMatrix(int segment_index) const {
return polynomials_[segment_index];
}
template <typename T>
const Polynomial<T>& PiecewisePolynomial<T>::getPolynomial(
int segment_index, Eigen::Index row, Eigen::Index col) const {
this->segment_number_range_check(segment_index);
return polynomials_[segment_index](row, col);
}
template <typename T>
int PiecewisePolynomial<T>::getSegmentPolynomialDegree(int segment_index,
Eigen::Index row,
Eigen::Index col) const {
this->segment_number_range_check(segment_index);
return polynomials_[segment_index](row, col).GetDegree();
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator+=(
const PiecewisePolynomial<T>& other) {
if (!this->SegmentTimesEqual(other))
throw runtime_error(
"Addition not yet implemented when segment times are not equal");
for (size_t i = 0; i < polynomials_.size(); i++)
polynomials_[i] += other.polynomials_[i];
return *this;
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator-=(
const PiecewisePolynomial<T>& other) {
if (!this->SegmentTimesEqual(other))
throw runtime_error(
"Subtraction not yet implemented when segment times are not equal");
for (size_t i = 0; i < polynomials_.size(); i++)
polynomials_[i] -= other.polynomials_[i];
return *this;
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator*=(
const PiecewisePolynomial<T>& other) {
if (!this->SegmentTimesEqual(other))
throw runtime_error(
"Multiplication not yet implemented when segment times are not equal");
for (size_t i = 0; i < polynomials_.size(); i++) {
polynomials_[i] *= other.polynomials_[i];
}
return *this;
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator+=(
const MatrixX<T>& offset) {
for (size_t i = 0; i < polynomials_.size(); i++)
polynomials_[i] += offset.template cast<Polynomial<T>>();
return *this;
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator-=(
const MatrixX<T>& offset) {
for (size_t i = 0; i < polynomials_.size(); i++)
polynomials_[i] -= offset.template cast<Polynomial<T>>();
return *this;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator+(
const PiecewisePolynomial<T>& other) const {
PiecewisePolynomial<T> ret = *this;
ret += other;
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator-(
const PiecewisePolynomial<T>& other) const {
PiecewisePolynomial<T> ret = *this;
ret -= other;
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator-() const {
PiecewisePolynomial<T> ret = *this;
for (size_t i = 0; i < polynomials_.size(); i++) {
ret.polynomials_[i] = -polynomials_[i];
}
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator*(
const PiecewisePolynomial<T>& other) const {
PiecewisePolynomial<T> ret = *this;
ret *= other;
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator+(
const MatrixX<T>& offset) const {
PiecewisePolynomial<T> ret = *this;
ret += offset;
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator-(
const MatrixX<T>& offset) const {
PiecewisePolynomial<T> ret = *this;
ret -= offset;
return ret;
}
template <typename T>
bool PiecewisePolynomial<T>::isApprox(const PiecewisePolynomial<T>& other,
double tol,
const ToleranceType& tol_type) const {
if (rows() != other.rows() || cols() != other.cols()) return false;
if (!this->SegmentTimesEqual(other, tol)) return false;
for (int segment_index = 0; segment_index < this->get_number_of_segments();
segment_index++) {
const PolynomialMatrix& matrix = polynomials_[segment_index];
const PolynomialMatrix& other_matrix = other.polynomials_[segment_index];
for (Eigen::Index row = 0; row < rows(); row++) {
for (Eigen::Index col = 0; col < cols(); col++) {
if (!matrix(row, col).CoefficientsAlmostEqual(other_matrix(row, col),
tol, tol_type)) {
return false;
}
}
}
}
return true;
}
template <typename T>
void PiecewisePolynomial<T>::ConcatenateInTime(
const PiecewisePolynomial<T>& other) {
if (!empty()) {
// Performs basic sanity checks.
DRAKE_THROW_UNLESS(this->rows() == other.rows());
DRAKE_THROW_UNLESS(this->cols() == other.cols());
const T time_offset = other.start_time() - this->end_time();
// Absolute tolerance is scaled along with the time scale.
const T absolute_tolerance = max(abs(this->end_time()), 1.0) *
std::numeric_limits<double>::epsilon();
DRAKE_THROW_UNLESS(abs(time_offset) < absolute_tolerance);
// Gets instance breaks.
std::vector<T>& breaks = this->get_mutable_breaks();
// Drops first break to avoid duplication.
breaks.pop_back();
// Concatenates other breaks, while shifting them appropriately
// for both trajectories to be time-aligned.
for (const T& other_break : other.breaks()) {
breaks.push_back(other_break - time_offset);
}
// Concatenates other polynomials.
polynomials_.insert(polynomials_.end(), other.polynomials_.begin(),
other.polynomials_.end());
} else {
std::vector<T>& breaks = this->get_mutable_breaks();
breaks = other.breaks();
polynomials_ = other.polynomials_;
}
}
template <typename T>
void PiecewisePolynomial<T>::AppendCubicHermiteSegment(
const T& time, const Eigen::Ref<const MatrixX<T>>& sample,
const Eigen::Ref<const MatrixX<T>>& sample_dot) {
DRAKE_DEMAND(!empty());
DRAKE_DEMAND(time > this->end_time());
DRAKE_DEMAND(sample.rows() == rows());
DRAKE_DEMAND(sample.cols() == cols());
DRAKE_DEMAND(sample_dot.rows() == rows());
DRAKE_DEMAND(sample_dot.cols() == cols());
const int segment_index = polynomials_.size() - 1;
const T dt = time - this->end_time();
PolynomialMatrix matrix(rows(), cols());
for (int row = 0; row < rows(); ++row) {
for (int col = 0; col < cols(); ++col) {
const T start = EvaluateSegmentAbsoluteTime(segment_index,
this->end_time(), row, col);
const int derivative_order = 1;
const T start_dot = EvaluateSegmentAbsoluteTime(
segment_index, this->end_time(), row, col, derivative_order);
Vector4<T> coeffs = ComputeCubicSplineCoeffs(
dt, start, sample(row, col), start_dot, sample_dot(row, col));
matrix(row, col) = Polynomial<T>(coeffs);
}
}
polynomials_.push_back(std::move(matrix));
this->get_mutable_breaks().push_back(time);
}
template <typename T>
void PiecewisePolynomial<T>::AppendFirstOrderSegment(
const T& time, const Eigen::Ref<const MatrixX<T>>& sample) {
DRAKE_DEMAND(!empty());
DRAKE_DEMAND(time > this->end_time());
DRAKE_DEMAND(sample.rows() == rows());
DRAKE_DEMAND(sample.cols() == cols());
const int segment_index = polynomials_.size() - 1;
const T dt = time - this->end_time();
PolynomialMatrix matrix(rows(), cols());
for (int row = 0; row < rows(); ++row) {
for (int col = 0; col < cols(); ++col) {
const T start = EvaluateSegmentAbsoluteTime(segment_index,
this->end_time(), row, col);
matrix(row, col) = Polynomial<T>(
Eigen::Matrix<T, 2, 1>(start, (sample(row, col) - start) / dt));
}
}
polynomials_.push_back(std::move(matrix));
this->get_mutable_breaks().push_back(time);
}
template <typename T>
void PiecewisePolynomial<T>::RemoveFinalSegment() {
DRAKE_DEMAND(!empty());
polynomials_.pop_back();
this->get_mutable_breaks().pop_back();
}
template <typename T>
void PiecewisePolynomial<T>::ReverseTime() {
using std::pow;
const std::vector<T>& b = this->breaks();
// Update the coefficients.
for (int i = 0; i < this->get_number_of_segments(); i++) {
PolynomialMatrix& matrix = polynomials_[i];
const T h = b[i + 1] - b[i];
for (int row = 0; row < rows(); row++) {
for (int col = 0; col < cols(); col++) {
const int d = matrix(row, col).GetDegree();
if (d == 0) continue;
// Must shift this segment by h, because it will now be evaluated
// relative to breaks[i+1] instead of breaks[i], via p_after(t) =
// p_before(t+h). But we can perform the time-reversal at the same
// time, using the variant p_after(t) = p_before(h-t).
const auto& vars = matrix(row, col).GetVariables();
DRAKE_ASSERT(vars.size() == 1);
const typename Polynomial<T>::VarType& t = *vars.begin();
matrix(row, col) =
matrix(row, col).Substitute(t, h - Polynomial<T>(1.0, t));
}
}
}
// Reverse the order of the breaks and polynomials.
std::vector<T>& breaks = this->get_mutable_breaks();
std::reverse(breaks.begin(), breaks.end());
std::reverse(polynomials_.begin(), polynomials_.end());
// Update the breaks.
for (auto it = breaks.begin(); it != breaks.end(); ++it) {
*it *= -1.0;
}
}
template <typename T>
void PiecewisePolynomial<T>::ScaleTime(const T& scale) {
using std::pow;
DRAKE_DEMAND(scale > 0.0);
// Update the coefficients.
for (int i = 0; i < this->get_number_of_segments(); i++) {
PolynomialMatrix& matrix = polynomials_[i];
for (int row = 0; row < rows(); row++) {
for (int col = 0; col < cols(); col++) {
const int d = matrix(row, col).GetDegree();
if (d == 0) continue;
VectorX<T> coeffs = matrix(row, col).GetCoefficients();
for (int p = 1; p < d + 1; p++) {
coeffs(p) /= pow(scale, p);
}
matrix(row, col) = Polynomial<T>(coeffs);
}
}
}
// Update the breaks.
std::vector<T>& breaks = this->get_mutable_breaks();
for (auto it = breaks.begin(); it != breaks.end(); ++it) {
*it *= scale;
}
}
template <typename T>
void PiecewisePolynomial<T>::shiftRight(const T& offset) {
std::vector<T>& breaks = this->get_mutable_breaks();
for (auto it = breaks.begin(); it != breaks.end(); ++it) {
*it += offset;
}
}
template <typename T>
void PiecewisePolynomial<T>::setPolynomialMatrixBlock(
const typename PiecewisePolynomial<T>::PolynomialMatrix& replacement,
int segment_number, Eigen::Index row_start, Eigen::Index col_start) {
this->segment_number_range_check(segment_number);
polynomials_[segment_number].block(row_start, col_start, replacement.rows(),
replacement.cols()) = replacement;
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::slice(int start_segment_index,
int num_segments) const {
this->segment_number_range_check(start_segment_index);
this->segment_number_range_check(start_segment_index + num_segments - 1);
auto breaks_start_it = this->breaks().begin() + start_segment_index;
auto breaks_slice = vector<T>(
breaks_start_it,
breaks_start_it + num_segments +
1); // + 1 because there's one more segment times than segments.
auto polynomials_start_it = polynomials_.begin() + start_segment_index;
auto polynomials_slice = vector<PolynomialMatrix>(
polynomials_start_it, polynomials_start_it + num_segments);
return PiecewisePolynomial<T>(polynomials_slice, breaks_slice);
}
template <typename T>
T PiecewisePolynomial<T>::EvaluateSegmentAbsoluteTime(
int segment_index, const T& t, Eigen::Index row, Eigen::Index col,
int derivative_order) const {
DRAKE_DEMAND(static_cast<int>(polynomials_.size()) > segment_index);
return polynomials_[segment_index](row, col).EvaluateUnivariate(
t - this->start_time(segment_index), derivative_order);
}
template <typename T>
Eigen::Index PiecewisePolynomial<T>::rows() const {
if (polynomials_.size() > 0) {
return polynomials_[0].rows();
} else {
throw std::runtime_error(
"PiecewisePolynomial has no segments. Number of rows is undefined.");
}
}
template <typename T>
Eigen::Index PiecewisePolynomial<T>::cols() const {
if (polynomials_.size() > 0) {
return polynomials_[0].cols();
} else {
throw std::runtime_error(
"PiecewisePolynomial has no segments. Number of columns is undefined.");
}
}
template <typename T>
void PiecewisePolynomial<T>::Reshape(int rows, int cols) {
DRAKE_DEMAND(rows * cols == this->rows() * this->cols());
for (auto& p : polynomials_) {
// Accordining to the Eigen documentation, data is preserved when the total
// number of elements does not change.
p.resize(rows, cols);
}
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::Transpose() const {
std::vector<PolynomialMatrix> transposed;
std::transform(polynomials_.begin(), polynomials_.end(),
std::back_inserter(transposed),
[](const PolynomialMatrix& matrix) {
return matrix.transpose();
});
return PiecewisePolynomial<T>(transposed, this->breaks());
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::Block(int start_row,
int start_col,
int block_rows,
int block_cols) const {
DRAKE_DEMAND(start_row >= 0 && start_row < rows());
DRAKE_DEMAND(start_col >= 0 && start_col < cols());
DRAKE_DEMAND(block_rows >= 0 && start_row + block_rows <= rows());
DRAKE_DEMAND(block_cols >= 0 && start_col + block_cols <= cols());
std::vector<PolynomialMatrix> block_polynomials;
std::transform(polynomials_.begin(), polynomials_.end(),
std::back_inserter(block_polynomials),
[start_row, start_col, block_rows,
block_cols](const PolynomialMatrix& matrix) {
return matrix.block(start_row, start_col, block_rows,
block_cols);
});
return PiecewisePolynomial<T>(block_polynomials, this->breaks());
}
// Static generators for splines.
// Throws std::runtime_error if these conditions are true:
// `breaks` and `samples` have different length,
// `samples` have inconsistent dimensions,
// any `samples` have either 0 rows or 0 cols,
// `breaks` is not strictly increasing by at least kEpsilonTime per break,
// `breaks` has length smaller than `min_length`.
template <typename T>
void PiecewisePolynomial<T>::CheckSplineGenerationInputValidityOrThrow(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
int min_length) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
if (times.size() != Y.size()) {
throw std::runtime_error(fmt::format(
"Number of break points {} does not match number of samples {}.",
times.size(), Y.size()));
}
if (static_cast<int>(times.size()) < min_length) {
throw std::runtime_error(fmt::format(
"{} samples is not enough samples (this method requires at least {}).",
times.size(), min_length));
}
Eigen::Index rows = Y.front().rows();
Eigen::Index cols = Y.front().cols();
if (rows < 1 || cols < 1) {
throw std::runtime_error("Knots need to be non-empty.");
}
for (const auto& y : Y) {
if (y.rows() != rows || y.cols() != cols) {
throw std::runtime_error("Knots have inconsistent dimensions.");
}
}
for (size_t i = 0; i < times.size() - 1; i++) {
if (times[i + 1] <= times[i]) {
throw std::runtime_error("Times must be in increasing order.");
}
if (times[i + 1] - times[i] < PiecewiseTrajectory<T>::kEpsilonTime) {
throw std::runtime_error(
fmt::format("Times must be at least {} apart.",
PiecewiseTrajectory<T>::kEpsilonTime));
}
}
}
// Makes a piecewise constant polynomial.
// The value for each segment is set to the value at the beginning of each
// segment.
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::ZeroOrderHold(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples) {
CheckSplineGenerationInputValidityOrThrow(breaks, samples, 2);
std::vector<PolynomialMatrix> polys;
polys.reserve(breaks.size() - 1);
// For each of the breaks, creates a PolynomialMatrix which can contain joint
// positions.
for (int i = 0; i < static_cast<int>(breaks.size()) - 1; ++i) {
PolynomialMatrix poly_matrix(samples[0].rows(), samples[0].cols());
for (int j = 0; j < samples[i].rows(); ++j) {
for (int k = 0; k < samples[i].cols(); ++k) {
poly_matrix(j, k) =
Polynomial<T>(Eigen::Matrix<T, 1, 1>(samples[i](j, k)));
}
}
polys.push_back(poly_matrix);
}
return PiecewisePolynomial<T>(polys, breaks);
}
// Makes a piecewise linear polynomial.
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::FirstOrderHold(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples) {
CheckSplineGenerationInputValidityOrThrow(breaks, samples, 2);
std::vector<PolynomialMatrix> polys;
polys.reserve(breaks.size() - 1);
// For each of the breaks, creates a PolynomialMatrix which can contain joint
// positions.
for (int i = 0; i < static_cast<int>(breaks.size()) - 1; ++i) {
PolynomialMatrix poly_matrix(samples[0].rows(), samples[0].cols());
for (int j = 0; j < samples[i].rows(); ++j) {
for (int k = 0; k < samples[i].cols(); ++k) {
poly_matrix(j, k) = Polynomial<T>(Eigen::Matrix<T, 2, 1>(
samples[i](j, k), (samples[i + 1](j, k) - samples[i](j, k)) /
(breaks[i + 1] - breaks[i])));
}
}
polys.push_back(poly_matrix);
}
return PiecewisePolynomial<T>(polys, breaks);
}
template <typename T>
static int sign(T val, T tol) {
if (val < -tol)
return -1;
else if (val > tol)
return 1;
return 0;
}
namespace {
// Computes the first derivative for either the starting or the end sample
// point. This is an internal helpful function for pchip.
// The first derivative is computed using a non-centered, shape-preserving
// three-point formulae.
// See equation (2.10) in the following reference for more details.
// http://www.mi.sanu.ac.rs/~gvm/radovi/mon.pdf
template <typename T>
MatrixX<T> ComputePchipEndSlope(const T& dt0, const T& dt1,
const MatrixX<T>& slope0,
const MatrixX<T>& slope1) {
const T kSlopeEpsilon = 1e-10;
MatrixX<T> deriv = ((2.0 * dt0 + dt1) * slope0 - dt0 * slope1) / (dt0 + dt1);
for (int i = 0; i < deriv.rows(); ++i) {
for (int j = 0; j < deriv.cols(); ++j) {
if (sign(deriv(i, j), kSlopeEpsilon) !=
sign(slope0(i, j), kSlopeEpsilon)) {
deriv(i, j) = 0.;
} else if (sign(slope0(i, j), kSlopeEpsilon) !=
sign(slope1(i, j), kSlopeEpsilon) &&
abs(deriv(i, j)) > abs(3. * slope0(i, j))) {
deriv(i, j) = 3. * slope0(i, j);
}
}
}
return deriv;
}
} // namespace
// Makes a cubic piecewise polynomial.
// It first computes the first derivatives at each break, and solves for each
// segment's coefficients using the derivatives and samples.
// The derivatives are computed using a weighted harmonic mean for internal
// points, and ComputePchipEndSlope is used for computing the end points'
// derivatives.
// See pg 9 in http://home.uchicago.edu/~sctchoi/courses/cs138/interp.pdf for
// more details.
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::CubicShapePreserving(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
bool zero_end_point_derivatives) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
if (zero_end_point_derivatives) {
CheckSplineGenerationInputValidityOrThrow(times, Y, 2);
} else {
CheckSplineGenerationInputValidityOrThrow(times, Y, 3);
}
int N = static_cast<int>(times.size());
int rows = Y.front().rows();
int cols = Y.front().cols();
std::vector<PolynomialMatrix> polynomials(N - 1);
std::vector<MatrixX<T>> slope(N - 1);
std::vector<T> dt(N - 1);
std::vector<MatrixX<T>> Ydot(N, MatrixX<T>::Zero(rows, cols));
Eigen::Matrix<T, 4, 1> coeffs;
// Computes the end slopes.
MatrixX<T> Ydot_start = MatrixX<T>::Zero(rows, cols);
MatrixX<T> Ydot_end = MatrixX<T>::Zero(rows, cols);
if (!zero_end_point_derivatives) {
Ydot_start =
ComputePchipEndSlope<T>(times[1] - times[0], times[2] - times[1],
(Y[1] - Y[0]) / (times[1] - times[0]),
(Y[2] - Y[1]) / (times[2] - times[1]));
Ydot_end = ComputePchipEndSlope<T>(
times[N - 1] - times[N - 2], times[N - 2] - times[N - 3],
(Y[N - 1] - Y[N - 2]) / (times[N - 1] - times[N - 2]),
(Y[N - 2] - Y[N - 3]) / (times[N - 2] - times[N - 3]));
}
for (int t = 0; t < N - 1; ++t) {
dt[t] = times[t + 1] - times[t];
slope[t] = (Y[t + 1] - Y[t]) / dt[t];
polynomials[t].resize(Y[t].rows(), Y[t].cols());
}
for (int j = 0; j < rows; ++j) {
for (int k = 0; k < cols; ++k) {
// Computes Ydot.
for (size_t t = 0; t < dt.size() - 1; ++t) {
// sample[t+1] is local extrema.
if (slope[t](j, k) * slope[t + 1](j, k) <= 0) {
Ydot[t + 1](j, k) = 0;
} else {
// Computed with using weighted harmonic mean.
T common = dt[t] + dt[t + 1];
Ydot[t + 1](j, k) = 3 * common /
((common + dt[t + 1]) / slope[t](j, k) +
(common + dt[t]) / slope[t + 1](j, k));
}
}
// Fixes end point slopes.
Ydot[0](j, k) = Ydot_start(j, k);
Ydot[N - 1](j, k) = Ydot_end(j, k);
// Computes coeffs given Y and Ydot at the end points for each segment.
for (int t = 0; t < N - 1; ++t) {
coeffs = ComputeCubicSplineCoeffs(dt[t], Y[t](j, k), Y[t + 1](j, k),
Ydot[t](j, k), Ydot[t + 1](j, k));
polynomials[t](j, k) = Polynomial<T>(coeffs);
}
}
}
return PiecewisePolynomial<T>(polynomials, times);
}
// Makes a cubic piecewise polynomial using the given samples and their
// derivatives at each break.
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::CubicHermite(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
const std::vector<MatrixX<T>>& samples_dot) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
const std::vector<MatrixX<T>>& Ydot = samples_dot;
CheckSplineGenerationInputValidityOrThrow(times, Y, 2);
int N = static_cast<int>(times.size());
int rows = Y.front().rows();
int cols = Y.front().cols();
if (times.size() != Ydot.size()) {
throw std::runtime_error("Y and Ydot have different length.");
}
for (int t = 0; t < N; ++t) {
if (rows != Ydot[t].rows() || cols != Ydot[t].cols()) {
throw std::runtime_error("Y and Ydot dimension mismatch.");
}
}
std::vector<PolynomialMatrix> polynomials(N - 1);
for (int t = 0; t < N - 1; ++t) {
polynomials[t].resize(Y[t].rows(), Y[t].cols());
const T dt = times[t + 1] - times[t];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
Eigen::Matrix<T, 4, 1> coeffs = ComputeCubicSplineCoeffs(
dt, Y[t](i, j), Y[t + 1](i, j), Ydot[t](i, j), Ydot[t + 1](i, j));
polynomials[t](i, j) = Polynomial<T>(coeffs);
}
}
}
return PiecewisePolynomial<T>(polynomials, times);
}
// Sets up the linear system for solving for the cubic piecewise polynomial
// coefficients.
// See the header file for more information.
template <typename T>
int PiecewisePolynomial<T>::SetupCubicSplineInteriorCoeffsLinearSystem(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
int row, int col, std::vector<Eigen::Triplet<T>>* triplet_list,
VectorX<T>* b) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
int N = static_cast<int>(times.size());
DRAKE_DEMAND(triplet_list != nullptr);
DRAKE_DEMAND(b != nullptr);
DRAKE_DEMAND(b->rows() == 3 * (N - 1));
int row_idx = 0;
std::vector<Eigen::Triplet<T>>& triplet_ref = *triplet_list;
VectorX<T>& bref = *b;
for (int i = 0; i < N - 1; ++i) {
const T dt = times[i + 1] - times[i];
// y_i(x_{i+1}) = y_{i+1}(x_{i}) =>
// Y[i] + a1i*(x_{i+1} - x_i) + a2i(x_{i+1} - x_i)^2 + a3i(x_{i+1} -
// x_i)^3 = Y[i+1]
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 0, dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 1, dt * dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 2, dt * dt * dt));
bref(row_idx++) = Y[i + 1](row, col) - Y[i](row, col);
// y_i'(x_{i+1}) = y_{i+1}'(x_{i}) =>
// a1i + 2*a2i(x_{i+1} - x_i) + 3*a3i(x_{i+1} - x_i)^2 = a1{i+1}
if (i != N - 2) {
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 0, 1));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 1, 2 * dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 2, 3 * dt * dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx++, 3 * (i + 1), -1));
}
if (i != N - 2) {
// y_i''(x_{i+1}) = y_{i+1}''(x_{i}) =>
// 2*a2i + 6*a3i(x_{i+1} - x_i) = 2*a2{i+1}
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 1, 2));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 2, 6 * dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx++, 3 * (i + 1) + 1, -2));
}
}
DRAKE_DEMAND(row_idx == 3 * (N - 1) - 2);
return row_idx;
}
// Makes a cubic piecewise polynomial.
// Internal sample points have continuous values, first and second derivatives,
// and first derivatives at both end points are set to `sample_dot_at_start`
// and `sample_dot_at_end`.
template <typename T>
PiecewisePolynomial<T>
PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
const MatrixX<T>& sample_dot_at_start,
const MatrixX<T>& sample_dot_at_end) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
const MatrixX<T>& Ydot_start = sample_dot_at_start;
const MatrixX<T>& Ydot_end = sample_dot_at_end;
CheckSplineGenerationInputValidityOrThrow(times, Y, 2);
int N = static_cast<int>(times.size());
int rows = Y.front().rows();
int cols = Y.front().cols();
if (Ydot_start.rows() != rows || Ydot_start.cols() != cols) {
throw std::runtime_error("Ydot_start and Y dimension mismatch");
}
if (Ydot_end.rows() != rows || Ydot_end.cols() != cols) {
throw std::runtime_error("Ydot_end and Y dimension mismatch");
}
std::vector<PolynomialMatrix> polynomials(N - 1);
for (int i = 0; i < N - 1; ++i) {
polynomials[i].resize(rows, cols);
}
Eigen::SparseMatrix<T> A(3 * (N - 1), 3 * (N - 1));
VectorX<T> b(3 * (N - 1));
VectorX<T> solution;
VectorX<T> coeffs(4);
Eigen::SparseLU<Eigen::SparseMatrix<T>> solver;
b.setZero();
// Sets up a linear equation to solve for the coefficients.
for (int j = 0; j < rows; ++j) {
for (int k = 0; k < cols; ++k) {
std::vector<Eigen::Triplet<T>> triplet_list;
// 10 coefficients are needed for the constraints that ensure continuity
// between adjacent segments: 3 for position, 4 for velocity, 3 for
// acceleration. The additional coefficients consist of: 3 for final
// position constraint, 1 for initial velocity constraint & 3 for final
// velocity constraint.
triplet_list.reserve(10 * (N - 2) + 7);
int row_idx = SetupCubicSplineInteriorCoeffsLinearSystem(
times, Y, j, k, &triplet_list, &b);