forked from JustinSi/ROCIN_prototype
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMPC.cpp
1500 lines (1125 loc) · 35.8 KB
/
MPC.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 "MPC.h"
#include "TestHelper.h"
#include <OpenSim/Common/Constant.h>
#include <fstream>
#include <cstring>
using namespace OpenSim;
#define MPC_DEBUG_INFO_VEC_SIZE 8
enum MPCDebugIdx{ CoordErrIdx = 0, VelErrIdx = 1, MuscleEffortIdx = 2, ResEffortIdx = 3,
WeightedCoordErrIdx = 4, WeightedVelErrIdx = 5, WeightedMuscleEffortIdx = 6, WeightedResEffortIdx=7};
// using a FunctionSet to provide the desired trajectory of the observation variables
MPC::MPC(int n_controls, int n_y, int n_samples, double ti, double dt, FunctionSet* r_spline_input, int windowSize)
{
_n_controls = n_controls;
_n_y = n_y;
_initialTime = ti;
_dt = dt;
_n_samples = n_samples;
_finalTime = ti+_dt*(_n_samples-1);
_r_array.resize(_n_samples);
_r_dot_array.resize(_n_samples);
_r_spline = new FunctionSet();
int n_ref_spline_size = r_spline_input->getSize();
for(int i=0;i<n_ref_spline_size;i++)
_r_spline->cloneAndAppend(r_spline_input->get(i));
Constant zeroFunc(0.0);
for(int i=n_ref_spline_size;i<_n_y;i++)
_r_spline->cloneAndAppend(zeroFunc);
Array<double> r_ref_array(0.0,n_y);
Array<double> r_dot_ref_array(0.0,n_y);
double time;
for(int i=0;i<_n_samples;i++)
{
_r_array[i].resize(n_y);
_r_dot_array[i].resize(n_y);
time = _initialTime + _dt* double(i);
_r_spline->evaluate(r_ref_array,0,time);
_r_spline->evaluate(r_dot_ref_array,1,time);
for(int j=0;j<n_y;j++)
{
_r_array[i][j] = r_ref_array[j];
_r_dot_array[i][j] = r_dot_ref_array[j];
}
}
_USE_IMPLICIT = true;
_up_to_date = false;
_penalize_ydot = false;
_penalize_udot = false;
_use_varying_dynamics = false;//true;
_P_is_diag = false;
_Q_is_diag = false;
_Qd_is_diag = false;
_R_is_diag = false;
_Sd_is_diag = false;
_qp_start_index = 0;
_qp_win_size = windowSize; //10
_bound_tracking = 0.03;
_bound_control = 100;
_natural_frequency = 10.0;
_A_array.setSize(_qp_win_size);
_B_array.setSize(_qp_win_size);
_C_array.setSize(_qp_win_size);
_Zinv_array.setSize(_qp_win_size);
_Z2inv_array.setSize(_qp_win_size);
_D_array.setSize(_qp_win_size);
_diag_D_array.setSize(_qp_win_size);
_E_array.setSize(_qp_win_size);
_u_array.resize(n_controls,_qp_win_size);
_u_array.setToZero();
_u.resize(n_controls);
_u.setToZero();
_u_next.resize(n_controls);
_u_next.setToZero();
_qp_u0.resize(n_controls);
_qp_u0.setToZero();
_lowerbounds.resize(n_controls*_qp_win_size);
_lowerbounds.setTo(-SimTK::Infinity);
_upperbounds.resize(n_controls*_qp_win_size);
_upperbounds.setTo(SimTK::Infinity);
_qp.setMPC(this);
_qp.setNumParameters(n_controls*_qp_win_size);
//_opt.setOptimizerSystem(_qp,SimTK::InteriorPoint);
_opt.setOptimizerSystem(_qp,SimTK::CFSQP);
//_opt.setOptimizerSystem(_qp,SimTK::LBFGSB);
_opt.setConvergenceTolerance(1e-4); //1e-3
_opt.setMaxIterations(200); //1000
_opt.setAdvancedBoolOption("warm_start",true);
_opt.setAdvancedRealOption("obj_scaling_factor",1);
_opt.setAdvancedRealOption("nlp_scaling_max_gradient",100);
}
// using an array to provide the desired trajectory of the observation variables
MPC::MPC(int n_controls, int n_y, double ti, double dt, const Array_<Vector>& reference, int windowSize)
{
_n_controls = n_controls;
_n_y = n_y;
_n_muscle_controls = 0;
_n_res_controls = 0;
_initialTime = ti;
_dt = dt;
_n_samples = reference.size();
_r_array.resize(_n_samples);
int size_refvec = reference[0].size();
for(int i=0;i<_n_samples;i++)
{
_r_array[i].resize(_n_y);
_r_array[i].setToZero();
_r_array[i].updBlock(0,0,size_refvec,1) = reference[i];
}
_finalTime = ti+_dt*(_n_samples-1);
//compute _r_dot_array;
_r_dot_array.resize(_n_samples);
_r_spline = NULL;
Storage* rStore = new Storage();
double time;
for(int i=0;i<_n_samples;i++)
{
time = _initialTime +_dt*double(i);
rStore->append(time,_r_array[i]);
}
_r_spline = new GCVSplineSet(5,rStore);
delete rStore;
Array<double> rdot_spline(0.0,_n_y);
for(int i=0;i<_n_samples;i++)
{
time = _initialTime + _dt*double(i);
_r_spline->evaluate(rdot_spline,1,time);
_r_dot_array[i].resize(_n_y);
for(int j=0;j<_n_y;j++)
_r_dot_array[i].set(j,rdot_spline.get(j));
}
//_qp = new MPCQP(this);
_USE_IMPLICIT = true;
_up_to_date = false;
_penalize_ydot = false;
_penalize_udot = false;
_P_is_diag = false;
_Q_is_diag = false;
_Qd_is_diag = false;
_R_is_diag = false;
_Sd_is_diag = false;
_qp_start_index = 0;
_qp_win_size = windowSize; //10
_bound_tracking = 0.03;
_bound_control = 100;
_natural_frequency = 10.0;
_A_array.setSize(_qp_win_size);
_B_array.setSize(_qp_win_size);
_C_array.setSize(_qp_win_size);
_Zinv_array.setSize(_qp_win_size);
_Z2inv_array.setSize(_qp_win_size);
_D_array.setSize(_qp_win_size);
_diag_D_array.setSize(_qp_win_size);
_E_array.setSize(_qp_win_size);
_u_array.resize(n_controls,_qp_win_size);
_u_array.setToZero();
_u.resize(n_controls);
_u.setToZero();
_u_next.resize(n_controls);
_u_next.setToZero();
_qp_u0.resize(n_controls);
_qp_u0.setToZero();
_lowerbounds.resize(n_controls*_qp_win_size);
_lowerbounds.setTo(-SimTK::Infinity);
_upperbounds.resize(n_controls*_qp_win_size);
_upperbounds.setTo(SimTK::Infinity);
_qp.setMPC(this);
_qp.setNumParameters(n_controls*_qp_win_size);
//_opt.setOptimizerSystem(_qp,SimTK::InteriorPoint);
_opt.setOptimizerSystem(_qp,SimTK::CFSQP);
//_opt.setOptimizerSystem(_qp,SimTK::LBFGSB);
_opt.setConvergenceTolerance(1e-4); //1e-3
_opt.setMaxIterations(200); //1000
_opt.setAdvancedBoolOption("warm_start",true);
_opt.setAdvancedRealOption("obj_scaling_factor",1);
_opt.setAdvancedRealOption("nlp_scaling_max_gradient",100);
}
MPC::~MPC()
{
if(_r_spline != NULL)
{
delete _r_spline;
}
}
void MPC::setABCArray(const Array<Matrix>& A_array, const Array<Matrix>& B_array, const Array<Vector>& C_array)
{
for(int i=0;i<A_array.size();i++)
{
if(A_array[i].ncol()!=_n_y || A_array[i].nrow()!=_n_y)
{
std::cout<<"A_array matrix size do not fit into MPC setting!"<<std::endl;
exit(0);
}
if(B_array[i].ncol()!=_n_controls || B_array[i].nrow()!=_n_y)
{
std::cout<<"B_array matrix size do not fit into MPC setting!"<<std::endl;
exit(0);
}
if(C_array[i].size() != _n_y)
{
std::cout<<"C_array vector size do not fit into MPC setting!" <<std::endl;
exit(0);
}
_A_array[i] = A_array[i];
_B_array[i] = B_array[i];
_C_array[i] = C_array[i];
if(_USE_IMPLICIT)
{
Matrix Zi(_A_array[i].nrow(),_A_array[i].ncol());
Zi.setToZero();
Zi.diag().setTo(1.0);
Zi -= _A_array[i]*_dt;
_Zinv_array[i] = Zi.invert();
Matrix Z2i(_A_array[i].nrow(),_A_array[i].ncol());
Z2i.setToZero();
Z2i.diag().setTo(1.0);
Z2i -= _A_array[i]*(_dt*0.5);
_Z2inv_array[i] = Z2i.invert();
}
}
}
void MPC::setABC(const Matrix& A, const Matrix& B, const Vector& C)
{
if(A.ncol()!=_n_y || A.nrow()!=_n_y)
{
std::cout<<"A size do not fit into MPC setting!"<<std::endl;
exit(0);
}
if(B.ncol()!=_n_controls || B.nrow()!=_n_y)
{
std::cout<<"B size do not fit into MPC setting!"<<std::endl;
exit(0);
}
if(C.size() != _n_y)
{
std::cout<<"C size do not fit into MPC setting!" <<std::endl;
exit(0);
}
_A=A;
_B=B;
_C=C;
if(_USE_IMPLICIT)
{
Matrix Z(_A.nrow(),_A.ncol());
Z.setToZero();
Z.diag().setTo(1.0);
Z -= _A*_dt;
_Zinv = Z.invert();
}
}
void MPC::setDandE(const Matrix& D, const Vector&E)
{
if(D.ncol() != _n_controls || D.nrow() != E.size())
{
std::cout<<"D and Esize do not fit into MPC setting!"<<std::endl;
exit(0);
}
_D = D;
_E = E;
_D_is_diag = false;
}
void MPC::setDiagDandE(const Vector& D, const Vector& E)
{
if(D.size() != _n_controls || D.size() != E.size())
{
std::cout<<"D and Esize do not fit into MPC setting!"<<std::endl;
exit(0);
}
_diag_D = D;
_E = E;
_D_is_diag = true;
}
void MPC::setDandEArray(const Array<Matrix>& D_array, const Array<Vector>& E_array)
{
for(int i=0;i<D_array.size();i++)
{
if(D_array[i].ncol() != _n_controls || D_array[i].nrow() != E_array[i].size())
{
std::cout<<"D and Esize do not fit into MPC setting!"<<std::endl;
exit(0);
}
_D_array[i] = D_array[i];
_E_array[i] = E_array[i];
}
_D_is_diag = false;
}
void MPC::setDiagDandEAarray(const Array<Vector>& D_array, const Array<Vector>& E_array)
{
for(int i=0;i<D_array.size();i++)
{
if(D_array[i].size() != _n_controls || D_array[i].size() != E_array[i].size())
{
std::cout<<"D and Esize do not fit into MPC setting!"<<std::endl;
exit(0);
}
_diag_D_array[i] = D_array[i];
_E_array[i] = E_array[i];
}
_D_is_diag = true;
}
Vector MPC::DLeftMultiply(const Vector& e) const
{
if(_D_is_diag)
return _diag_D.elementwiseMultiply(e);
else
return _D*e;
}
Vector MPC::DiLeftMultiply(int i, const Vector& e) const
{
if(_D_is_diag)
return _diag_D_array[i].elementwiseMultiply(e);
else
return _D_array[i]*e;
}
Vector MPC::DTransposeLeftMultiply(const Vector& e) const
{
if(_D_is_diag)
return _diag_D.elementwiseMultiply(e);
else
return _D.transpose()*e;
}
Vector MPC::DiTransposeLeftMultiply(int i, const Vector& e) const
{
if(_D_is_diag)
return _diag_D_array[i].elementwiseMultiply(e);
else
return _D_array[i].transpose()*e;
}
Vector MPC::PLeftMultiply(const Vector& e) const
{
if(_P_is_diag)
return _diag_P.elementwiseMultiply(e);
else
return _P*e;
}
Vector MPC::QLeftMultiply(const Vector& e) const
{
if(_Q_is_diag)
return _diag_Q.elementwiseMultiply(e);
else
return _Q*e;
}
Vector MPC::RLeftMultiply(const Vector& e) const
{
if(_R_is_diag)
return _diag_R.elementwiseMultiply(e);
else
return _R*e;
}
Vector MPC::QdLeftMultiply(const Vector& e) const
{
if(_Qd_is_diag)
return _diag_Qd.elementwiseMultiply(e);
else
return _Qd*e;
}
Vector MPC::SdLeftMultiply(const Vector& e) const
{
if(_Sd_is_diag)
return _diag_Sd.elementwiseMultiply(e);
else
return _Sd*e;
}
// test function to see whether the provided gradient functions are correct (compare them with numerical gradients)
void MPC::testMPC()
{
int n_u = _n_controls;
int n_y = _n_y;
int n_vars = n_u*_qp_win_size;
Vector u(n_vars);
//u.setToZero();
//u.setTo(10.0);
for(int i=0;i<n_vars;i++)
u.setTo(double(i)*0.1);
//u.setTo(sin(double(i)*0.1));
//u.setTo(0.0);
double delta = 0.000001;
Vector du(n_vars);
// test object and gradient
Vector gradient_analytic(n_vars);
Vector gradient_numeric(n_vars);
//numeric gradient
double f=0.0,f_new =0.0;
_qp.objectiveFunc(u,true,f);
_qp.gradientFunc(u,true,gradient_analytic);
for(int i=0;i<n_vars;i++)
{
du.setToZero();
du(i) = delta;
_qp.objectiveFunc(u+du,true,f_new);
double df = f_new-f;
gradient_numeric(i) = df/delta;
}
Matrix gradient_comparison(n_vars,3);
gradient_comparison.updCol(0) = gradient_analytic;
gradient_comparison.updCol(1) = gradient_numeric;
gradient_comparison.updCol(2) = (gradient_analytic-gradient_numeric).elementwiseDivide(gradient_analytic);
PrintMatrix(gradient_comparison,"gradient_comparison",std::cout);
//std::cout<<"gradient_ankle_r: "<<gradient_analytic.get(13)<<" gradient_ankle_l: "<<gradient_analytic.get(22)<<std::endl;
//PrintVector(gradient_analytic-gradient_numeric,"gradient_difference",std::cout);
//test constraint and jacobian
/* int n_c = 0;
n_c = n_y;//6*_qp_win_size;
Matrix Jacob_analytic(n_c,n_vars);
Matrix Jacob_numeric(n_c,n_vars);
Vector c(n_c),c_new(n_c);
_qp.constraintFunc(u,true,c);
_qp.constraintJacobian(u,true,Jacob_analytic);
for(int i=0;i<n_vars;i++)
{
du.setToZero();
du(i) = delta;
_qp.constraintFunc(u+du,true,c_new);
Jacob_numeric.updCol(i) = (c_new-c)/delta;
}
Matrix Jacob_diff = Jacob_analytic - Jacob_numeric;
Matrix Jacob_diff_normalize = Jacob_diff.elementwiseDivide(Jacob_analytic);
PrintMatrix(Jacob_diff,"Jacob_diff",std::cout);
PrintMatrix(Jacob_diff_normalize,"Jacob_diff_normalize",std::cout);
*/
}
int MPC::getTimeIndex(SimTK::Real t)
{
int k= round((t-_initialTime)/_dt);
if(k<0)
k=0;
if(k>=_n_samples)
k=_n_samples-1;
return k;
}
bool MPC::isUpToDate(double t)
{
int cur_k = getTimeIndex(t);
if(cur_k > _qp_start_index)
return false;
return true;
}
// this is the core function that solves MPC problem
std::vector<SimTK::Real> MPC::precomputeU(double t, const Vector& initY, bool return_debug_info)
{
std::vector<SimTK::Real> debug_info;
int n_u = 0;
if(_B_array.size()>0)
n_u = _B_array[0].ncol();
else
n_u = _B.ncol();
int n_y = initY.size();
int cur_k = getTimeIndex(t);
if(cur_k > _qp_start_index)
_up_to_date = false;
_qp_y0 = initY;
_qp_start_index = cur_k;
if(_qp_win_size>_n_samples-1-cur_k)
_qp_win_size = _n_samples-1-cur_k;
if(_qp_win_size<1)
{
_up_to_date = true;
return debug_info;
}
//using PD law to update Ydot reference
if(_penalize_ydot)
updateYdotRef(initY);
int n_para = n_u*_qp_win_size;
_qp.setNumParameters(n_para);
_qp.setNumEqualityConstraints(0);
_qp.setNumInequalityConstraints(0);
_qp.setParameterLimits(_lowerbounds.block(0,0,n_para,1).getAsVector(),_upperbounds.block(0,0,n_para,1).getAsVector());
Vector result_u(n_para);
result_u.setTo(0.0);
for(int i=0;i<_qp_win_size;i++)
{
result_u.updBlock(n_u*i,0,n_u,1) = _u_array.col(i);
}
SimTK::Real f = 0.0;
try{
f = _opt.optimize(result_u);
}
catch(const std::exception& ex)
{
std::cout<<ex.what()<<std::endl;
}
std::cout<<"t = "<<t<<std::endl;
std::cout<<"optimization error: "<<f<<std::endl;
if (return_debug_info)
{
debug_info.resize(MPC_DEBUG_INFO_VEC_SIZE);
SimTK::Real f_debug;
_qp.getObjectiveFuncDebugInfo(result_u, f_debug, debug_info);
}
for(int i=0;i<_qp_win_size;i++)
{
_u_array.updCol(i) = result_u.block(n_u*i,0,n_u,1).getAsVector();
}
_u = _u_array.col(0);
if(_qp_win_size>1)
_u_next = _u_array.col(1);
else
_u_next = _u;
_qp_u0 = _u;
_up_to_date = true;
return debug_info;
}
// update the YdotRef (in our case, it is mainly used to update the desired acceleration by PD rule)
void MPC::updateYdotRef(const Vector& curY)
{
//critical damping, natural frequency
double omega = _natural_frequency;
//std::cout<<"omega = "<<omega<<std::endl;
double Ks = omega*omega, Kd = 2.0*omega;
int n_y = curY.size();
int n_coords = n_y/2;
Matrix acc_exp(n_coords,1);
Matrix vel_exp(n_coords,1);
Array<double> rdot_spline;
Array<double> rddot_spline;
int k_ydot = 0;
int k_cur = 0;
double time = 0.0;
Vector pErr_init, vErr_init;
Vector A, B;
for(int i=0;i<_qp_win_size;i++)
{
k_cur = _qp_start_index+i;
if(_USE_IMPLICIT)
k_ydot = k_cur+1;
else
k_ydot = k_cur;
time = _initialTime + _dt*double(k_cur+1);
_r_spline->evaluate(rdot_spline,1,time);
for(int j=0;j<n_coords;j++)
{
vel_exp.set(j,0,rdot_spline.get(j));
acc_exp.set(j,0,rdot_spline.get(j+n_coords));
}
if(i==0)
{
pErr_init = (_r_array[k_cur].block(0,0,n_coords,1)-curY.block(0,0,n_coords,1)).getAsVector();
vErr_init = (_r_array[k_cur].block(n_coords,0,n_coords,1)-curY.block(n_coords,0,n_coords,1)).getAsVector();
A = pErr_init;
B = vErr_init+pErr_init*omega;
}
double t_damp = _dt*i;
double exp_damp = exp(-omega*t_damp);
Vector pErr = (A+B*t_damp)*exp_damp;
Vector vErr = (B*(1.0-omega*t_damp)-A*omega)*exp_damp;
_r_dot_array[k_ydot].updBlock(0,0,n_coords,1) = vel_exp+Ks*pErr;
_r_dot_array[k_ydot].updBlock(n_coords,0,n_coords,1) = acc_exp+Ks*pErr+Kd*vErr;
}
}
MPCQP::MPCQP(MPC* mpc)
{
_mpc = mpc;
}
// override the objective function
int MPCQP::objectiveFunc( const Vector& coefficients, bool new_coefficients, SimTK::Real& f ) const
{
std::vector<SimTK::Real> debug_info = {};
if(_mpc->_USE_IMPLICIT)
{
if(_mpc->_use_varying_dynamics)
return objectiveFunc_varying_dynamics_implicit(coefficients, new_coefficients, f, debug_info);
else
return objectiveFunc_const_dynamics_implicit(coefficients, new_coefficients, f, debug_info);
}
else
{
if(_mpc->_use_varying_dynamics)
return objectiveFunc_varying_dynamics_explicit(coefficients, new_coefficients, f, debug_info);
else
return objectiveFunc_const_dynamics_explicit(coefficients, new_coefficients, f, debug_info);
}
}
int MPCQP::getObjectiveFuncDebugInfo(const Vector& coefficients, SimTK::Real& f, std::vector<SimTK::Real>& debug_info) const
{
if (_mpc->_USE_IMPLICIT)
{
if (_mpc->_use_varying_dynamics)
return objectiveFunc_varying_dynamics_implicit(coefficients, true, f, debug_info);
else
return objectiveFunc_const_dynamics_implicit(coefficients, true, f, debug_info);
}
else
{
if (_mpc->_use_varying_dynamics)
return objectiveFunc_varying_dynamics_explicit(coefficients, true, f, debug_info);
else
return objectiveFunc_const_dynamics_explicit(coefficients, true, f, debug_info);
}
}
// override the gradient of the objective function
int MPCQP::gradientFunc( const Vector& coefficients, bool new_coefficients, Vector &gradient ) const
{
if(_mpc->_USE_IMPLICIT)
{
if(_mpc->_use_varying_dynamics)
return gradientFunc_varying_dynamics_implicit(coefficients,new_coefficients,gradient);
else
return gradientFunc_const_dynamics_implicit(coefficients,new_coefficients,gradient);
}
else
{
if(_mpc->_use_varying_dynamics)
return gradientFunc_varying_dynamics_explicit(coefficients,new_coefficients,gradient);
else
return gradientFunc_const_dynamics_explicit(coefficients,new_coefficients,gradient);
}
}
// using varying dynamics (instead of constant dynamics) and explicit formulation
int MPCQP::objectiveFunc_varying_dynamics_explicit(const Vector& coefficients, bool new_coefficients, SimTK::Real& f, std::vector<SimTK::Real>& debug_info) const
{
if (debug_info.size() != 0 && debug_info.size() != MPC_DEBUG_INFO_VEC_SIZE)
throw std::invalid_argument("debug_info doesn't have proper size!");
f = 0.0;
Vector y = _mpc->_qp_y0;
Vector u_pre = _mpc->_qp_u0;
int n_y = y.size();
int n_u = _mpc->_B_array[0].ncol();
int k_y = 0;
for(int i=0;i<_mpc->_qp_win_size;i++)
{
int k_u = _mpc->_qp_start_index+i;
k_y = k_u+1;
Vector u(n_u);
u = coefficients.block(i*n_u,0,n_u,1).getAsVector();
Vector ydot = _mpc->_A_array[i]*y+_mpc->_B_array[i]*u+_mpc->_C_array[i];
y += ydot*_mpc->_dt;
Vector e = y-_mpc->_r_array[k_y];
if(_mpc->_penalize_ydot)
{
Vector e_ydot = ydot - _mpc->_r_dot_array[k_u];
f += e_ydot.elementwiseMultiply(_mpc->QdLeftMultiply(e_ydot)).sum();
}
f += e.elementwiseMultiply(_mpc->QLeftMultiply(e)).sum();
Vector z = _mpc->DiLeftMultiply(i,u)+_mpc->_E_array[i];
f += z.elementwiseMultiply(_mpc->RLeftMultiply(z)).sum();
if(_mpc->_penalize_udot)
{
Vector udot = (u-u_pre)/_mpc->_dt;
f += udot.elementwiseMultiply(_mpc->SdLeftMultiply(udot)).sum();
u_pre = u;
}
}
Vector e = y-_mpc->_r_array[k_y];
f += e.elementwiseMultiply(_mpc->PLeftMultiply(e)).sum();
return 0;
}
int MPCQP::gradientFunc_varying_dynamics_explicit(const Vector& coefficients, bool new_coefficients, Vector &gradient ) const
{
gradient.setToZero();
Vector y = _mpc->_qp_y0;
Vector u_pre = _mpc->_qp_u0;
int n_y = y.size();
int n_u = _mpc->_B_array[0].ncol();
int k_y = 0;
Matrix dydu(n_y,n_u);
dydu.setToZero();
Matrix dydotdu(n_y,n_u);
dydotdu.setToZero();
Matrix eye(n_y,n_y);
eye.setToZero();
eye.diag().setTo(1.0);
for(int i=0;i<_mpc->_qp_win_size;i++)
{
int k_u = _mpc->_qp_start_index+i;
k_y = k_u+1;
Vector u(n_u);
u = coefficients.block(i*n_u,0,n_u,1).getAsVector();
Vector ydot = _mpc->_A_array[i]*y+_mpc->_B_array[i]*u+_mpc->_C_array[i];
y += ydot*_mpc->_dt;
Vector e_ydot = ydot - _mpc->_r_dot_array[k_u];
Vector e_y = y - _mpc->_r_array[k_y];
for(int j=i;j>=0;j--)
{
if(j==i)
{
dydotdu = _mpc->_B_array[i];
dydu = dydotdu*_mpc->_dt;
}
else
{
//dydotdu = _mpc->_B_array[j]*
dydotdu = _mpc->_B_array[j]*_mpc->_dt;
for(int k=j+1;k<i;k++)
dydotdu = (eye+_mpc->_A_array[k]*_mpc->_dt)*dydotdu;
dydu = (eye+_mpc->_A_array[i]*_mpc->_dt)*dydotdu;
dydotdu = _mpc->_A_array[i]*dydotdu;
}
gradient.updBlock(j*n_u,0,n_u,1) += 2.0*dydu.transpose()*_mpc->QLeftMultiply(e_y);
if(_mpc->_penalize_ydot)
gradient.updBlock(j*n_u,0,n_u,1) += 2.0*dydotdu.transpose()*_mpc->QdLeftMultiply(e_ydot);
if(i==_mpc->_qp_win_size-1)
gradient.updBlock(j*n_u,0,n_u,1) += 2.0*dydu.transpose()*_mpc->PLeftMultiply(e_y)/_mpc->_dt;
}
Vector z = _mpc->DiLeftMultiply(i,u)+_mpc->_E_array[i];
gradient.updBlock(i*n_u,0,n_u,1) += _mpc->DiTransposeLeftMultiply(i,2.0*_mpc->RLeftMultiply(z));
if(_mpc->_penalize_udot)
{
Vector udot = (u-u_pre)/_mpc->_dt;
Vector temp = 2.0*_mpc->SdLeftMultiply(udot)/_mpc->_dt;
if(i==0)
gradient.updBlock(i*n_u,0,n_u,1) += temp;
else
{
gradient.updBlock(i*n_u,0,n_u,1) += temp;
gradient.updBlock((i-1)*n_u,0,n_u,1) -= temp;
}
u_pre = u;
}
}
return 0;
}
// using varying dynamics and implicit formulation
int MPCQP::objectiveFunc_varying_dynamics_implicit(const Vector& coefficients, bool new_coefficients, SimTK::Real& f, std::vector<SimTK::Real>& debug_info) const
{
if (debug_info.size() != 0 && debug_info.size() != MPC_DEBUG_INFO_VEC_SIZE)
throw std::invalid_argument("debug_info doesn't have proper size!");
bool get_debug_info = (debug_info.size() > 0);
if (get_debug_info)
{
debug_info.assign(MPC_DEBUG_INFO_VEC_SIZE, 0.0);
if (_mpc->_n_muscle_controls + _mpc->_n_res_controls != _mpc->_n_controls)
throw std::runtime_error("The number of muscle control for MPC hasn't been set properly!");
}
f = 0.0;
Vector y = _mpc->_qp_y0;
Vector u_pre = _mpc->_qp_u0;
int n_y = y.size();
int n_u = _mpc->_B.ncol();
int k_y = 0;
for(int i=0;i<_mpc->_qp_win_size;i++)
{
int k_u = _mpc->_qp_start_index+i;
k_y = k_u+1;
Vector u(n_u);
u = coefficients.block(i*n_u,0,n_u,1).getAsVector();
Vector tmp_BuPlusC = _mpc->_B_array[i]*u+_mpc->_C_array[i];
//y = _mpc->_Zinv_array[i]*(y+_mpc->_B_array[i]*_mpc->_dt*u+_mpc->_C_array[i]*_mpc->_dt);
y = _mpc->_Zinv_array[i]*(y+tmp_BuPlusC*_mpc->_dt);
//Vector ydot = _mpc->_A_array[i]*y+_mpc->_B_array[i]*u+_mpc->_C_array[i];
Vector ydot = _mpc->_A_array[i]*y+tmp_BuPlusC;
Vector e = y-_mpc->_r_array[k_y];
if(_mpc->_penalize_ydot)
{
Vector e_ydot = ydot - _mpc->_r_dot_array[k_y];
f += e_ydot.elementwiseMultiply(_mpc->QdLeftMultiply(e_ydot)).sum();
}
f += e.elementwiseMultiply(_mpc->QLeftMultiply(e)).sum();
Vector z = _mpc->DiLeftMultiply(i,u)+_mpc->_E_array[i];
f += z.elementwiseMultiply(_mpc->RLeftMultiply(z)).sum();
if (get_debug_info)
{
Vector e_coord = e;
Vector e_vel = e;
int n_coord = n_y / 2;
e_coord.updBlock(n_coord, 0, n_coord, 1).setToZero();
e_vel.updBlock(0, 0, n_coord, 1).setToZero();
Matrix unit_mat(n_coord, n_coord);
unit_mat.setToZero();
for (int j = 0; j < n_coord; ++j)
{