-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
BSpline.cpp
1768 lines (1385 loc) · 60.2 KB
/
BSpline.cpp
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 <sparse_block_matrix/sparse_block_matrix.h>
#include <sparse_block_matrix/linear_solver_cholmod.h>
#include <bsplines/BSpline.hpp>
#include <sm/assert_macros.hpp>
#include <Eigen/Cholesky>
#include <Eigen/LU>
#include <Eigen/QR>
//#include <asrl/string_routines.hpp>
// boost::tie()
#include <boost/tuple/tuple.hpp>
#include <Eigen/SVD>
namespace bsplines {
BSpline::BSpline(int splineOrder)
: splineOrder_(splineOrder)
{
SM_ASSERT_GE(Exception, splineOrder_, 2, "The B-spline order must be greater than or equal to 2");
}
BSpline::~BSpline()
{
}
int BSpline::splineOrder() const
{
return splineOrder_;
}
int BSpline::polynomialDegree() const
{
return splineOrder_ - 1;
}
void BSpline::setKnotsAndCoefficients(const std::vector<double> & knots, const Eigen::MatrixXd & coefficients)
{
//std::cout << "setting " << knots.size() << " knots\n";
// This will throw an exception if it is an invalid knot sequence.
verifyKnotSequence(knots);
// Check if the number of coefficients matches the number of knots.
SM_ASSERT_EQ(Exception,
numCoefficientsRequired(numValidTimeSegments(knots.size())),
coefficients.cols(),
"A B-spline of order " << splineOrder_ << " requires " << numCoefficientsRequired(numValidTimeSegments(knots.size()))
<< " coefficients for the " << numValidTimeSegments(knots.size())
<< " time segments defined by " << knots.size() << " knots");
//std::cout << "Setting coefficients: " << coefficients << std::endl;
knots_ = knots;
coefficients_ = coefficients;
initializeBasisMatrices();
}
void BSpline::initializeBasisMatrices()
{
basisMatrices_.resize(numValidTimeSegments());
for(unsigned i = 0; i < basisMatrices_.size(); i++)
{
basisMatrices_[i] = M(splineOrder_,i + splineOrder_ - 1);
// std::cout << "M[" << i << "]:\n" << basisMatrices_[i] << std::endl;
}
}
Eigen::MatrixXd BSpline::M(int k, int i)
{
SM_ASSERT_GE_DBG(Exception, k, 1, "The parameter k must be greater than or equal to 1");
SM_ASSERT_GE_DBG(Exception, i, 0, "The parameter i must be greater than or equal to 0");
SM_ASSERT_LT_DBG(Exception, i, (int)knots_.size(), "The parameter i must be less than the number of time segments");
if(k == 1)
{
// The base-case for recursion.
Eigen::MatrixXd M(1,1);
M(0,0) = 1;
return M;
}
else
{
Eigen::MatrixXd M_km1 = M(k-1,i);
// The recursive equation for M
// M_k = [ M_km1 ] A + [ 0^T ] B
// [ 0^T ] [ M_km1 ]
// ------- -------
// =: M1 =: M2
//
// = M1 A + M2 B
Eigen::MatrixXd M1 = Eigen::MatrixXd::Zero(M_km1.rows() + 1, M_km1.cols());
Eigen::MatrixXd M2 = Eigen::MatrixXd::Zero(M_km1.rows() + 1, M_km1.cols());
M1.topRightCorner(M_km1.rows(),M_km1.cols()) = M_km1;
M2.bottomRightCorner(M_km1.rows(),M_km1.cols()) = M_km1;
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(k-1, k);
for(int idx = 0; idx < A.rows(); idx++)
{
int j = i - k + 2 + idx;
double d0 = d_0(k, i, j);
A(idx, idx ) = 1.0 - d0;
A(idx, idx+1) = d0;
}
Eigen::MatrixXd B = Eigen::MatrixXd::Zero(k-1, k);
for(int idx = 0; idx < B.rows(); idx++)
{
int j = i - k + 2 + idx;
double d1 = d_1(k, i, j);
B(idx, idx ) = -d1;
B(idx, idx+1) = d1;
}
Eigen::MatrixXd M_k;
return M_k = M1 * A + M2 * B;
}
}
double BSpline::d_0(int k, int i, int j)
{
SM_ASSERT_GE_LT_DBG(Exception,j+k-1,0,(int)knots_.size(), "Index out of range with k=" << k << ", i=" << i << ", and j=" << j);
SM_ASSERT_GE_LT_DBG(Exception,j,0,(int)knots_.size(), "Index out of range with k=" << k << ", i=" << i << ", and j=" << j);
SM_ASSERT_GE_LT_DBG(Exception,i,0,(int)knots_.size(), "Index out of range with k=" << k << ", i=" << i << ", and j=" << j);
double denom = knots_[j+k-1] - knots_[j];
if(denom <= 0.0)
return 0.0;
double numerator = knots_[i] - knots_[j];
return numerator/denom;
}
double BSpline::d_1(int k, int i, int j)
{
SM_ASSERT_GE_LT_DBG(Exception,j+k-1,0,(int)knots_.size(), "Index out of range with k=" << k << ", i=" << i << ", and j=" << j);
SM_ASSERT_GE_LT_DBG(Exception,i+1,0,(int)knots_.size(), "Index out of range with k=" << k << ", i=" << i << ", and j=" << j);
SM_ASSERT_GE_LT_DBG(Exception,i,0,(int)knots_.size(), "Index out of range with k=" << k << ", i=" << i << ", and j=" << j);
double denom = knots_[j+k-1] - knots_[j];
if(denom <= 0.0)
return 0.0;
double numerator = knots_[i+1] - knots_[i];
return numerator/denom;
}
void BSpline::setKnotVectorAndCoefficients(const Eigen::VectorXd & knots, const Eigen::MatrixXd & coefficients)
{
//std::cout << "setting knots of size " << knots.size() << std::endl;//": " << knots.transpose() << std::endl;
std::vector<double> k(knots.size());
for(unsigned i = 0; i < k.size(); i++)
k[i] = knots(i);
setKnotsAndCoefficients(k, coefficients);
}
const std::vector<double> BSpline::knots() const
{
return knots_;
}
Eigen::VectorXd BSpline::knotVector() const
{
Eigen::VectorXd k(knots_.size());
for(unsigned i = 0; i < knots_.size(); i++)
k(i) = knots_[i];
return k;
}
const Eigen::MatrixXd & BSpline::coefficients() const
{
return coefficients_;
}
void BSpline::verifyKnotSequence(const std::vector<double> & knots)
{
SM_ASSERT_GE(Exception, (int)knots.size(), minimumKnotsRequired(),
"The sequence does not contain enough knots to define an active time sequence "
<< "for a B-spline of order " << splineOrder_ << ". At least " << minimumKnotsRequired()
<< " knots are required");
for(unsigned i = 1; i < knots_.size(); i++)
{
SM_ASSERT_LE(Exception, knots[i-1], knots[i],
"The knot sequence must be nondecreasing. Knot " << i
<< " was not greater than or equal to knot " << (i-1));
}
}
int BSpline::numValidTimeSegments(int numKnots) const
{
int nv = numKnots - 2*splineOrder_ + 1;
return std::max(nv,0);
}
int BSpline::numValidTimeSegments() const
{
return numValidTimeSegments(knots_.size());
}
int BSpline::minimumKnotsRequired() const
{
return numKnotsRequired(1);
}
int BSpline::numCoefficientsRequired(int numTimeSegments) const
{
return numTimeSegments + splineOrder_ - 1;
}
int BSpline::numKnotsRequired(int numTimeSegments) const
{
return numCoefficientsRequired(numTimeSegments) + splineOrder_;
}
double BSpline::t_min() const
{
SM_ASSERT_GE(Exception, (int)knots_.size(), minimumKnotsRequired(), "The B-spline is not well initialized");
return knots_[splineOrder_ - 1];
}
double BSpline::t_max() const
{
SM_ASSERT_GE(Exception, (int)knots_.size(), minimumKnotsRequired(), "The B-spline is not well initialized");
return knots_[knots_.size() - splineOrder_];
}
std::pair<double,int> BSpline::computeTIndex(double t) const
{
SM_ASSERT_GE(Exception, t, t_min(), "The time is out of range by " << (t - t_min()));
//// HACK - avoids numerical problems on initialisation
if ( fabs(t_max() - t) < 1e-10 )
t = t_max();
//// \HACK
SM_ASSERT_LE(Exception, t, t_max(), "The time is out of range by " << (t_max() - t));
std::vector<double>::const_iterator i;
if(t == t_max())
{
// This is a special case to allow us to evaluate the spline at the boundary of the
// interval. This is not stricly correct but it will be useful when we start doing
// estimation and defining knots at our measurement times.
i = knots_.end() - splineOrder_;
}
else
{
i = std::upper_bound(knots_.begin(), knots_.end(), t);
}
SM_ASSERT_TRUE_DBG(Exception, i != knots_.end(), "Something very bad has happened in computeTIndex(" << t << ")");
// Returns the index of the knot segment this time lies on and the width of this knot segment.
return std::make_pair(*i - *(i-1),(i - knots_.begin()) - 1);
}
std::pair<double,int> BSpline::computeUAndTIndex(double t) const
{
std::pair<double,int> ui = computeTIndex(t);
int index = ui.second;
double denom = ui.first;
if(denom <= 0.0)
{
// The case of duplicate knots.
//std::cout << "Duplicate knots\n";
return std::make_pair(0, index);
}
else
{
// std::cout << "u:" << t << ", " << knots_[index] << ", " << denom << " idx:" << index;
double u = (t - knots_[index])/denom;
return std::make_pair(u, index);
}
}
int dmul(int i, int derivativeOrder)
{
if(derivativeOrder == 0)
return 1;
else if(derivativeOrder == 1)
return i;
else
return i * dmul(i-1,derivativeOrder-1) ;
}
Eigen::VectorXd BSpline::computeU(double uval, int segmentIndex, int derivativeOrder) const
{
Eigen::VectorXd u = Eigen::VectorXd::Zero(splineOrder_);
double delta_t = knots_[segmentIndex+1] - knots_[segmentIndex];
double multiplier = 0.0;
if(delta_t > 0.0)
multiplier = 1.0/pow(delta_t, derivativeOrder);
double uu = 1.0;
for(int i = derivativeOrder; i < splineOrder_; i++)
{
u(i) = multiplier * uu * dmul(i,derivativeOrder) ;
uu = uu * uval;
}
// std::cout << "u:" << std::endl;
// std::cout << u << std::endl;
return u;
}
Eigen::VectorXd BSpline::eval(double t) const
{
return evalD(t,0);
}
const Eigen::MatrixXd & BSpline::basisMatrixFromKnotIndex(int knotIndex) const
{
return basisMatrices_[basisMatrixIndexFromStartingKnotIndex(knotIndex)];
}
Eigen::VectorXd BSpline::evalD(double t, int derivativeOrder) const
{
SM_ASSERT_GE(Exception, derivativeOrder, 0, "To integrate, use the integral function");
// Returns the normalized u value and the lower-bound time index.
std::pair<double,int> ui = computeUAndTIndex(t);
Eigen::VectorXd u = computeU(ui.first, ui.second, derivativeOrder);
int bidx = ui.second - splineOrder_ + 1;
// Evaluate the spline (or derivative) in matrix form.
//
// [c_0 c_1 c_2 c_3] * B^T * u
// spline coefficients
Eigen::VectorXd rv = coefficients_.block(0,bidx,coefficients_.rows(),splineOrder_) * basisMatrices_[bidx].transpose() * u;
return rv;
}
Eigen::VectorXd BSpline::evalDAndJacobian(double t, int derivativeOrder, Eigen::MatrixXd * Jacobian, Eigen::VectorXi * coefficientIndices) const
{
SM_ASSERT_GE(Exception, derivativeOrder, 0, "To integrate, use the integral function");
// Returns the normalized u value and the lower-bound time index.
std::pair<double,int> ui = computeUAndTIndex(t);
Eigen::VectorXd u = computeU(ui.first, ui.second, derivativeOrder);
int bidx = ui.second - splineOrder_ + 1;
// Evaluate the spline (or derivative) in matrix form.
//
// [c_0 c_1 c_2 c_3] * B^T * u
// spline coefficients
// The spline value
Eigen::VectorXd Bt_u = basisMatrices_[bidx].transpose() * u;
Eigen::VectorXd v = coefficients_.block(0,bidx,coefficients_.rows(),splineOrder_) * Bt_u;
if(Jacobian)
{
// The Jacobian
Jacobian->resize(coefficients_.rows(), Bt_u.size() * coefficients_.rows());
Eigen::MatrixXd one = Eigen::MatrixXd::Identity(coefficients_.rows(), coefficients_.rows());
for(int i = 0; i < Bt_u.size(); i++)
{
Jacobian->block(0, i*coefficients_.rows(), coefficients_.rows(), coefficients_.rows()) = one * Bt_u[i];
}
}
if(coefficientIndices)
{
int D = coefficients_.rows();
*coefficientIndices = Eigen::VectorXi::LinSpaced(splineOrder_*D,bidx*D,(bidx + splineOrder_)*D - 1);
}
return v;
}
std::pair<Eigen::VectorXd, Eigen::MatrixXd> BSpline::evalDAndJacobian(double t, int derivativeOrder) const
{
std::pair<Eigen::VectorXd, Eigen::MatrixXd> rv;
rv.first = evalDAndJacobian(t, derivativeOrder, &rv.second, NULL);
return rv;
}
Eigen::MatrixXd BSpline::localBasisMatrix(double t, int derivativeOrder) const
{
return Phi(t,derivativeOrder);
}
Eigen::MatrixXd BSpline::localCoefficientMatrix(double t) const
{
std::pair<double,int> ui = computeTIndex(t);
int bidx = ui.second - splineOrder_ + 1;
return coefficients_.block(0,bidx,coefficients_.rows(),splineOrder_);
}
Eigen::VectorXd BSpline::localCoefficientVector(double t) const
{
std::pair<double,int> ui = computeTIndex(t);
int bidx = ui.second - splineOrder_ + 1;
Eigen::VectorXd c(splineOrder_ * coefficients_.rows());
for(int i = 0; i < splineOrder_; i++)
{
c.segment(i*coefficients_.rows(), coefficients_.rows()) = coefficients_.col(i + bidx);
}
return c;
}
Eigen::VectorXd BSpline::segmentCoefficientVector(int segmentIdx) const {
SM_ASSERT_GE_LT(std::runtime_error, segmentIdx, 0, numValidTimeSegments(), "segment index out of bounds");
int bidx = segmentIdx;
Eigen::VectorXd c(splineOrder_ * coefficients_.rows());
for(int i = 0; i < splineOrder_; i++) {
c.segment(i*coefficients_.rows(), coefficients_.rows()) = coefficients_.col(i + bidx);
}
return c;
}
Eigen::VectorXi BSpline::localCoefficientVectorIndices(double t) const
{
std::pair<double,int> ui = computeTIndex(t);
int bidx = ui.second - splineOrder_ + 1;
int D = coefficients_.rows();
return Eigen::VectorXi::LinSpaced(splineOrder_*D,bidx*D,(bidx + splineOrder_)*D - 1);
}
Eigen::VectorXi BSpline::segmentCoefficientVectorIndices(int segmentIdx) const {
SM_ASSERT_GE_LT(std::runtime_error, segmentIdx, 0, numValidTimeSegments(), "segment index out of bounds");
int bidx = segmentIdx;
int D = coefficients_.rows();
return Eigen::VectorXi::LinSpaced(splineOrder_*D,bidx*D,(bidx + splineOrder_)*D - 1);
}
Eigen::VectorXi BSpline::localVvCoefficientVectorIndices(double t) const
{
std::pair<double,int> ui = computeTIndex(t);
int bidx = ui.second - splineOrder_ + 1;
return Eigen::VectorXi::LinSpaced(splineOrder_,bidx,(bidx + splineOrder_) - 1);
}
Eigen::VectorXi BSpline::segmentVvCoefficientVectorIndices(int segmentIdx) const {
SM_ASSERT_GE_LT(std::runtime_error, segmentIdx, 0, numValidTimeSegments(), "segment index out of bounds");
int bidx = segmentIdx;
return Eigen::VectorXi::LinSpaced(splineOrder_,bidx,(bidx + splineOrder_) - 1);
}
Eigen::MatrixXd BSpline::Phi(double t, int derivativeOrder) const
{
SM_ASSERT_GE(Exception, derivativeOrder, 0, "To integrate, use the integral function");
std::pair<double,int> ui = computeUAndTIndex(t);
// std::cout << " ui:" << ui.first << " " << t << std::endl;
Eigen::VectorXd u = computeU(ui.first, ui.second, derivativeOrder);
// std::cout << "u:" << std::endl;
// std::cout << u << std::endl << std::endl;
int bidx = ui.second - splineOrder_ + 1;
// std::cout << "Spline order: " << splineOrder_ << std::endl;
// std::cout << "t: " << t_min() << " <= " << t << " <= " << t_max() << std::endl;
// std::cout << "bidx: " << bidx << std::endl;
// std::cout << "number of basis matrices: " << basisMatrices_.size() << std::endl;
// std::cout << "basis matrix:\n" << basisMatrices_[bidx] << std::endl;
// std::cout << "u:\n" << u << std::endl;
u = basisMatrices_[bidx].transpose() * u;
// std::cout << "u:" << std::endl;
// std::cout << u << std::endl;
Eigen::MatrixXd Phi = Eigen::MatrixXd::Zero(coefficients_.rows(),splineOrder_*coefficients_.rows());
Eigen::MatrixXd one = Eigen::MatrixXd::Identity(Phi.rows(), Phi.rows());
for(int i = 0; i < splineOrder_; i++)
{
Phi.block(0,Phi.rows()*i,Phi.rows(),Phi.rows()) = one * u(i);
}
return Phi;
}
void BSpline::setCoefficientVector(const Eigen::VectorXd & c)
{
SM_ASSERT_EQ(Exception,c.size(),coefficients_.rows() * coefficients_.cols(), "The coefficient vector is the wrong size. The vector must contain all vector-valued coefficients stacked up into one column.");
for(int i = 0; i < coefficients_.cols(); i++)
{
coefficients_.col(i) = c.segment(i * coefficients_.rows(),coefficients_.rows());
}
}
Eigen::VectorXd BSpline::coefficientVector()
{
Eigen::VectorXd c(coefficients_.rows() * coefficients_.cols());
for(int i = 0; i < coefficients_.cols(); i++)
{
c.segment(i * coefficients_.rows(),coefficients_.rows()) = coefficients_.col(i);
}
return c;
}
void BSpline::setCoefficientMatrix(const Eigen::MatrixXd & coefficients)
{
SM_ASSERT_EQ(Exception,coefficients_.rows(), coefficients.rows(), "The new coefficient matrix must match the size of the existing coefficient matrix");
SM_ASSERT_EQ(Exception,coefficients_.cols(), coefficients.cols(), "The new coefficient matrix must match the size of the existing coefficient matrix");
coefficients_ = coefficients;
}
const Eigen::MatrixXd & BSpline::basisMatrix(int i) const
{
SM_ASSERT_GE_LT(Exception,i, 0, numValidTimeSegments(), "index out of range");
return basisMatrices_[i];
}
std::pair<double,double> BSpline::timeInterval() const
{
return std::make_pair(t_min(), t_max());
}
std::pair<double,double> BSpline::timeInterval(int i) const
{
SM_ASSERT_GE(Exception, (int)knots_.size(), minimumKnotsRequired(), "The B-spline is not well initialized");
SM_ASSERT_GE_LT(Exception, i, 0, numValidTimeSegments(), "index out of range");
return std::make_pair(knots_[splineOrder_ + i - 1],knots_[splineOrder_ + i]);
}
void BSpline::initSpline(double t_0, double t_1, const Eigen::VectorXd & p_0, const Eigen::VectorXd & p_1)
{
SM_ASSERT_EQ(Exception,p_0.size(), p_1.size(), "The coefficient vectors should be the same size");
SM_ASSERT_GT(Exception,t_1, t_0, "Time must be increasing from t_0 to t_1");
// Initialize the spline so that it interpolates the two points and moves between them with a constant velocity.
// How many knots are required for one time segment?
int K = numKnotsRequired(1);
// How many coefficients are required for one time segment?
int C = numCoefficientsRequired(1);
// What is the vector coefficient dimension
int D = p_0.size();
// Initialize a uniform knot sequence
double dt = t_1 - t_0;
std::vector<double> knots(K);
for(int i = 0; i < K; i++)
{
knots[i] = t_0 + (i - splineOrder_ + 1) * dt;
}
// Set the knots and zero the coefficients
setKnotsAndCoefficients(knots, Eigen::MatrixXd::Zero(D,C));
// Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.
int coefficientDim = C * D;
// We always need an even number of constraints.
int constraintsRequired = C + (C & 0x1);
int constraintSize = constraintsRequired * D;
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(constraintSize, coefficientDim);
Eigen::VectorXd b = Eigen::VectorXd::Zero(constraintSize);
// Add the position constraints.
int brow = 0;
int bcol = 0;
A.block(brow,bcol,D,coefficientDim) = Phi(t_min(),0);
b.segment(brow,D) = p_0;
brow += D;
A.block(brow,bcol,D,coefficientDim) = Phi(t_max(),0);
b.segment(brow,D) = p_1;
brow += D;
if(splineOrder_ > 2)
{
// At the very minimum we have to add velocity constraints.
Eigen::VectorXd v = (p_1 - p_0)/dt;
A.block(brow,bcol,D,coefficientDim) = Phi(t_min(),1);
b.segment(brow,D) = v;
brow += D;
A.block(brow,bcol,D,coefficientDim) = Phi(t_max(),1);
b.segment(brow,D) = v;
brow += D;
if(splineOrder_ > 4)
{
// Now we add the constraint that all higher-order derivatives are zero.
int derivativeOrder = 2;
Eigen::VectorXd z = Eigen::VectorXd::Zero(D);
while(brow < A.rows())
{
A.block(brow,bcol,D,coefficientDim) = Phi(t_min(),derivativeOrder);
b.segment(brow,D) = z;
brow += D;
A.block(brow,bcol,D,coefficientDim) = Phi(t_max(),derivativeOrder);
b.segment(brow,D) = z;
brow += D;
++derivativeOrder;
}
}
}
// Now we solve the Ax=b system
if(A.rows() != A.cols())
{
// The system is over constrained. This happens for odd ordered splines.
b = (A.transpose() * b).eval();
A = (A.transpose() * A).eval();
}
// Solve for the coefficient vector.
Eigen::VectorXd c = A.householderQr().solve(b);
// ldlt doesn't work for this problem. It may be because the ldlt decomposition
// requires the matrix to be positive or negative semidefinite
// http://eigen.tuxfamily.org/dox-devel/TutorialLinearAlgebra.html#TutorialLinAlgRankRevealing
// which may imply that it is symmetric. Our A matrix is only symmetric in the over-constrained case.
//Eigen::VectorXd c = A.ldlt().solve(b);
setCoefficientVector(c);
}
void BSpline::addCurveSegment(double t, const Eigen::VectorXd & p_1)
{
SM_ASSERT_GT(Exception, t, t_max(), "The new time must be past the end of the last valid segment");
SM_ASSERT_EQ(Exception, p_1.size(), coefficients_.rows(), "Invalid coefficient vector size");
// Get the final valid time interval.
int NT = numValidTimeSegments();
std::pair<double, double> interval_km1 = timeInterval(NT-1);
Eigen::VectorXd p_0;
// Store the position of the spline at the end of the interval.
// We will use these as constraints as we don't want them to change.
p_0 = eval(interval_km1.second);
// Retool the knot vector.
double du;
int km1;
boost::tie(du,km1) = computeTIndex(interval_km1.first);
// leave knots km1 and k alone but retool the other knots.
double dt = t - knots_[km1 + 1];
double kt = t;
// add another knot.
std::vector<double> knots(knots_);
knots.push_back(0.0);
// space the further knots uniformly.
for(unsigned k = km1 + 2; k < knots.size(); k++)
{
knots[k] = kt;
kt += dt;
}
// Tack on an new, uninitialized coefficient column.
Eigen::MatrixXd c(coefficients_.rows(), coefficients_.cols() + 1);
c.topLeftCorner(coefficients_.rows(), coefficients_.cols()) = coefficients_;
setKnotsAndCoefficients(knots,c);
// Now, regardless of the order of the spline, we should only have to add a single knot and coefficient vector.
// In this case, we should solve for the last two coefficient vectors (i.e., the new one and the one before the
// new one).
// Get the time interval of the new time segment.
double t_0, t_1;
boost::tie(t_0,t_1) = timeInterval(NT);
// what is the coefficient dimension?
int D = coefficients_.rows();
// How many vector-valued coefficients are required? In this case, 2. We will leave the others fixed.
int C = 2;
// Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.
int coefficientDim = C * D;
// We always need an even number of constraints.
int constraintsRequired = 2;
int constraintSize = constraintsRequired * D;
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(constraintSize, coefficientDim);
Eigen::VectorXd b = Eigen::VectorXd::Zero(constraintSize); // Build the A matrix.
int phiBlockColumnOffset = D * std::max(0,(splineOrder_ - 2));
Eigen::VectorXd fixedCoefficients = localCoefficientVector(t_0).segment(0,phiBlockColumnOffset);
// Add the position constraints.
int brow = 0;
int bcol = 0;
Eigen::MatrixXd P;
P = Phi(t_0,0);
A.block(brow,bcol,D,coefficientDim) = P.block(0,phiBlockColumnOffset, D, coefficientDim);
b.segment(brow,D) = p_0 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;
brow += D;
P = Phi(t_1,0);
A.block(brow,bcol,D,coefficientDim) = P.block(0,phiBlockColumnOffset, D, coefficientDim);
b.segment(brow,D) = p_1 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;;
brow += D;
// Add regularization constraints (keep the coefficients small)
//A.block(brow,bcol,coefficientDim,coefficientDim) = 1e-4 * Eigen::MatrixXd::Identity(coefficientDim, coefficientDim);
//b.segment(brow,coefficientDim) = Eigen::VectorXd::Zero(coefficientDim);
//brow += coefficientDim;
// Now we solve the Ax=b system
if(A.rows() != A.cols())
{
// The system is over constrained. This happens for odd ordered splines.
b = (A.transpose() * b).eval();
A = (A.transpose() * A).eval();
}
Eigen::VectorXd cstar = A.householderQr().solve(b);
coefficients_.col(coefficients_.cols() - 2) = cstar.head(D);
coefficients_.col(coefficients_.cols() - 1) = cstar.tail(D);
}
void BSpline::removeCurveSegment()
{
if(knots_.size() > 0 && coefficients_.cols() > 0)
{
knots_.erase(knots_.begin());
coefficients_ = coefficients_.block(0,1,coefficients_.rows(),coefficients_.cols() - 1).eval();
}
}
void BSpline::setLocalCoefficientVector(double t, const Eigen::VectorXd & c)
{
SM_ASSERT_EQ(Exception, c.size(), splineOrder_ * coefficients_.rows(), "The local coefficient vector is the wrong size");
std::pair<double,int> ui = computeTIndex(t);
int bidx = ui.second - splineOrder_ + 1;
for(int i = 0; i < splineOrder_; i++)
{
coefficients_.col(i + bidx) = c.segment(i*coefficients_.rows(), coefficients_.rows());
}
}
void BSpline::initSpline2(const Eigen::VectorXd & times, const Eigen::MatrixXd & interpolationPoints, int numSegments, double lambda)
{
SM_ASSERT_EQ(Exception,times.size(), interpolationPoints.cols(), "The number of times and the number of interpolation points must be equal");
SM_ASSERT_GE(Exception,times.size(),2, "There must be at least two times");
SM_ASSERT_GE(Exception,numSegments,1, "There must be at least one time segment");
for(int i = 1; i < times.size(); i++)
{
SM_ASSERT_LE(Exception, times[i-1], times[i],
"The time sequence must be nondecreasing. time " << i
<< " was not greater than or equal to time " << (i-1));
}
// Initialize the spline so that it interpolates the N points
// How many knots are required for one time segment?
int K = numKnotsRequired(numSegments);
// How many coefficients are required for one time segment?
int C = numCoefficientsRequired(numSegments);
// What is the vector coefficient dimension
int D = interpolationPoints.rows();
// Initialize a uniform knot sequence
double dt = (times[times.size() - 1] - times[0]) / numSegments;
std::vector<double> knots(K);
for(int i = 0; i < K; i++)
{
knots[i] = times[0] + (i - splineOrder_ + 1) * dt;
}
// Set the knots and zero the coefficients
setKnotsAndCoefficients(knots, Eigen::MatrixXd::Zero(D,C));
// Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.
int coefficientDim = C * D;
int numConstraints = (knots.size() - 2 * splineOrder_ + 2) + interpolationPoints.cols();
int constraintSize = numConstraints * D;
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(constraintSize, coefficientDim);
Eigen::VectorXd b = Eigen::VectorXd::Zero(constraintSize);
int brow = 0;
//int bcol = 0;
// Now add the regularization constraint.
//A.block(brow,bcol,coefficientDim,coefficientDim) = 1e-1* Eigen::MatrixXd::Identity(coefficientDim, coefficientDim);
//b.segment(brow,coefficientDim) = Eigen::VectorXd::Zero(coefficientDim);
//brow += coefficientDim;
for(int i = splineOrder_ - 1; i < (int)knots.size() - splineOrder_ + 1; i++)
{
Eigen::VectorXi coeffIndices = localCoefficientVectorIndices(knots[i]);
A.block(brow,coeffIndices[0],D,coeffIndices.size()) = lambda * Phi(knots[i],2);
b.segment(brow,D) = Eigen::VectorXd::Zero(D);
brow += D;
}
// Add the position constraints.
for(int i = 0; i < interpolationPoints.cols(); i++)
{
Eigen::VectorXi coeffIndices = localCoefficientVectorIndices(times[i]);
A.block(brow,coeffIndices[0],D,coeffIndices.size()) = Phi(times[i],0);
b.segment(brow,D) = interpolationPoints.col(i);
brow += D;
}
// Now we solve the Ax=b system
//if(A.rows() != A.cols())
// {
// The system is over constrained. This happens for odd ordered splines.
b = (A.transpose() * b).eval();
A = (A.transpose() * A).eval();
// }
// Solve for the coefficient vector.
Eigen::VectorXd c = A.ldlt().solve(b);
// ldlt doesn't work for this problem. It may be because the ldlt decomposition
// requires the matrix to be positive or negative semidefinite
// http://eigen.tuxfamily.org/dox-devel/TutorialLinearAlgebra.html#TutorialLinAlgRankRevealing
// which may imply that it is symmetric. Our A matrix is only symmetric in the over-constrained case.
// Eigen::VectorXd c = A.ldlt().solve(b);
setCoefficientVector(c);
}
void BSpline::initSplineSparseKnots(const Eigen::VectorXd ×, const Eigen::MatrixXd &interpolationPoints, const Eigen::VectorXd knots, double lambda)
{
SM_ASSERT_EQ(Exception,times.size(), interpolationPoints.cols(), "The number of times and the number of interpolation points must be equal");
SM_ASSERT_GE(Exception,times.size(),2, "There must be at least two times");
for(int i = 1; i < times.size(); i++)
{
SM_ASSERT_LE(Exception, times[i-1], times[i],
"The time sequence must be nondecreasing. time " << i
<< " was not greater than or equal to time " << (i-1));
}
int K = knots.size();
// How many coefficients are required for one time segment?
int C = numCoefficientsRequired(knots.size() - 2*(splineOrder_ - 1)-1);
// What is the vector coefficient dimension
int D = interpolationPoints.rows();
// Set the knots and zero the coefficients
std::vector<double> knotsVector(K);
for(int i = 0; i < K; i++)
{
knotsVector[i] = knots(i);
}
setKnotsAndCoefficients(knotsVector, Eigen::MatrixXd::Zero(D,C));
// define the structure:
std::vector<int> rows;
std::vector<int> cols;
for (int i = 1; i <= interpolationPoints.cols(); i++)
rows.push_back(i*D);
for(int i = 1; i <= C; i++)
cols.push_back(i*D);
std::vector<int> bcols(1);
bcols[0] = 1;
sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> A(rows,cols, true);
sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> b(rows,bcols, true);
int brow = 0;
// try to fill the matrix:
for(int i = 0; i < interpolationPoints.cols(); i++) {
Eigen::VectorXi coeffIndices = localCoefficientVectorIndices(times[i]);
const bool allocateBlock = true;
// get Phi
Eigen::MatrixXd P = Phi(times[i],0); // Dx(n*D)
// the n'th order spline needs n column blocks (n*D columns)
for(int j = 0; j < splineOrder_; j++) {
Eigen::MatrixXd & Ai = *A.block(brow/D,coeffIndices[0]/D+j,allocateBlock );
Ai= P.block(0,j*D,D,D);
}
Eigen::MatrixXd & bi = *b.block(brow/D,0,allocateBlock );
bi = interpolationPoints.col(i);
brow += D;
}
//Eigen::MatrixXd Ad = A.toDense();
sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> At(cols,rows, true);
sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> * Atp = &At;
A.transpose(Atp);
// A'b
sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Ab(cols,bcols, true);
sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> * Abp = &Ab;
Atp->multiply(Abp, &b);
// A'A
sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> AtA(cols,cols, true);
sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> * AtAp = &AtA;
Atp->multiply(AtAp, &A);
// Add the motion constraint.
Eigen::VectorXd W = Eigen::VectorXd::Constant(D,lambda);
// make this conditional on the order of the spline:
sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Q(cols,cols,true);
if (splineOrder_ == 2)
curveQuadraticIntegralDiagSparse(W, 1).cloneInto(Q);
else
curveQuadraticIntegralDiagSparse(W, 2).cloneInto(Q);
// A'A + Q
Q.add(AtAp);
// solve:
sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd> solver;
solver.init();
Eigen::VectorXd c(AtAp->rows());
c.setZero();
Eigen::VectorXd b_dense = Abp->toDense();
bool result = solver.solve(*AtAp,&c[0],&b_dense[0]);
if(!result) {
c.setZero();
// fallback => use nonsparse solver:
std::cout << "Fallback to Dense Solver" << std::endl;
Eigen::MatrixXd Adense = AtAp->toDense();
c = Adense.ldlt().solve(b_dense);
}
// std::cout << "b\nA=" << A << "\n b=" << b << "\n";
// Solve for the coefficient vector.
// Eigen::VectorXd c = A.ldlt().solve(b);
setCoefficientVector(c);
}
void BSpline::initSplineSparse(const Eigen::VectorXd & times, const Eigen::MatrixXd & interpolationPoints, int numSegments, double lambda)
{
SM_ASSERT_EQ(Exception,times.size(), interpolationPoints.cols(), "The number of times and the number of interpolation points must be equal");
SM_ASSERT_GE(Exception,times.size(),2, "There must be at least two times");
SM_ASSERT_GE(Exception,numSegments,1, "There must be at least one time segment");
for(int i = 1; i < times.size(); i++)
{
SM_ASSERT_LE(Exception, times[i-1], times[i],
"The time sequence must be nondecreasing. time " << i
<< " was not greater than or equal to time " << (i-1));
}
// How many knots are required for one time segment?
int K = numKnotsRequired(numSegments);
// How many coefficients are required for one time segment?
int C = numCoefficientsRequired(numSegments);
// What is the vector coefficient dimension
int D = interpolationPoints.rows();
// Initialize a uniform knot sequence
double dt = (times[times.size() - 1] - times[0]) / numSegments;
std::vector<double> knots(K);
for(int i = 0; i < K; i++)
{
knots[i] = times[0] + (i - splineOrder_ + 1) * dt;
}
// Set the knots and zero the coefficients
setKnotsAndCoefficients(knots, Eigen::MatrixXd::Zero(D,C));
// define the structure:
std::vector<int> rows;
std::vector<int> cols;
for (int i = 1; i <= interpolationPoints.cols(); i++)