-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathROCINForceController.cpp
2496 lines (1792 loc) · 65.5 KB
/
ROCINForceController.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 "ROCINForceController.h"
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/ForceSet.h>
#include <OpenSim/Simulation/SimbodyEngine/Body.h>
#include <OpenSim/Simulation/Model/Marker.h>
#include <OpenSim/Simulation/Model/MarkerSet.h>
#include <OpenSim/Simulation/Model/BodySet.h>
#include "SimTKmath.h"
#include <SimTKcommon/internal/Serialize.h>
#include <OpenSim/Common/GCVSplineSet.h>
#include <OpenSim/Common/Signal.h>
#include <OpenSim/Simulation/SimbodyEngine/CoordinateCouplerConstraint.h>
#include <OpenSim/Simulation/Model/HuntCrossleyForce.h>
#include <OpenSim/Simulation/Model/ContactGeometrySet.h>
#include <OpenSim/Simulation/Model/ContactSphere.h>
#include <OpenSim/Simulation/Model/AbstractTool.h>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Simulation/Model/Force.h>
#include <OpenSim/Actuators/CoordinateActuator.h>
#include <OpenSim/Simulation/Model/CoordinateSet.h>
#include <OpenSim/Common/RootSolver.h>
#include <OpenSim/Simulation/Model/ControllerSet.h>
#include <OpenSim/Simulation/Control/Controller.h>
#include <OpenSim/Simulation/Control/ControlConstant.h>
#include <OpenSim/Simulation/Control/ControlLinear.h>
#include <OpenSim/Common/FunctionSet.h>
#include <OpenSim/Simulation/osimSimulationDLL.h>
#include "SimTKsimbody.h"
#include "SimTKcommon/internal/SubsystemGuts.h"
#include "SimTKcommon/internal/SystemGuts.h"
#include <OpenSim/Simulation/Model/ActivationFiberLengthMuscle.h>
#include <OpenSim/Actuators/Thelen2003Muscle.h>
#include "TestHelper.h"
#include "ControllerHelper.h"
#include "VirtualActuatorSet.h"
#include "StateInitializer.h"
#include <time.h>
using SimTK::Matrix;
using SimTK::Vector;
using SimTK::Vec3;
using namespace OpenSim;
#define VERBOSE_PRINT 0
class ROCINControlEventHandler : public SimTK::PeriodicEventHandler {
public:
ROCINControlEventHandler(ROCINForceController* controller) :
PeriodicEventHandler(SimTK::Stage::Time), _controller(controller) {}
// the event is calling doControlPrecomputation periodically
void handleEvent (SimTK::State& s, SimTK::Real accuracy, bool& terminate) const {
terminate = false;
_controller->doControlPrecomputation(s);
_controller->setTargetTime(s.getTime()+_controller->getTargetDT());
}
SimTK::Real getNextEventTime(const SimTK::State& s, bool includeCurrent) const
{
if(_controller->getCheckTargetTime())
return _controller->getTargetTime();
else
return std::numeric_limits<SimTK::Real>::infinity();
}
ROCINForceController* _controller;
};
void ROCINForceController::initController(const Model& aModel, const std::string& dataFileName, bool track_coords, double lookahead_window, int lookahead_number)
{
_track_coords = track_coords;
_lookahead_window = lookahead_window;
_lookahead_number = lookahead_number;
setNull();
_numNonMuscleActuators = 0;
int n_u = aModel.getNumSpeeds();
_mapping_nonMuscleActuators.resize(n_u,_numNonMuscleActuators);
_mapping_nonMuscleActuators.setToZero();
_checkTargetTime = false;
if(_track_coords)
{
_coordData = new Storage(dataFileName);
//TODO: make numCoord auto select only level q;
if(aModel.getNumSpeeds() != aModel.getNumCoordinates())
{
std::cout<<"The number of speeds and the number of coordinates are not equal, does not support this case at this point!!"<<std::endl;
exit(1);
}
_numCoords = aModel.getNumSpeeds();
}
else
{
std::cout << "Current implementation does not support tracking marker positions!" << std::endl;
exit(1);
}
}
ROCINForceController::ROCINForceController(const Model& aModel, const std::string& dataFileName, bool track_coords, double lookahead_window, int lookahead_number)
{
initController(aModel,dataFileName,track_coords,lookahead_window,lookahead_number);
}
void ROCINForceController::doControlPrecomputation(const SimTK::State& s)
{
doPrecomputation_Varying_Dynamics(s);
}
ROCINForceController::~ROCINForceController()
{
if(_mpcSolver != NULL)
delete _mpcSolver;
if(_markerData != NULL)
delete _markerData;
if(_coordData != NULL)
delete _coordData;
if(_externalLoads != NULL)
delete _externalLoads;
if(_momentArmSolver != NULL)
delete _momentArmSolver;
if(_qSet != NULL)
delete _qSet;
if(_uSet != NULL)
delete _uSet;
if(_uDotSet != NULL)
delete _uDotSet;
if(_internalIntegrator != NULL)
delete _internalIntegrator;
if(_internalManager != NULL)
delete _internalManager;
// if(_internalController != NULL)
// delete _internalController;
if(_internalModel != NULL)
delete _internalModel;
}
void ROCINForceController::setNull()
{
_n_q=0;
_n_u=0;
_numMuscles=0;
_numMarkers=0;
_coord_tracking_penalty = 50.0;
_speed_tracking_penalty = 50.0;
_activation_penalty = 1.0;
_PD_penalty = 0.01;
_lowpass_freq = -1.0;
_use_taylor_expansion = false;
_markerData = NULL;
_mpcSolver = NULL;
_coordData = NULL;
_markerData = NULL;
_qSet = NULL;
_uSet = NULL;
_uDotSet = NULL;
_externalLoads = NULL;
_momentArmSolver = NULL;
_internalModel = NULL;
_internalIntegrator = NULL;
_internalManager = NULL;
_internalController = NULL;
_internalSys = NULL;
_internalSubsys = NULL;
}
void ROCINForceController::evalModelCoordTrackingErrs(const Model& aModel, const std::string& coordFileName1, const std::string& coordFileName2, const std::string& outFileName)
{
Storage* refCoordData = new Storage(coordFileName1);
Storage* cmpCoordData = new Storage(coordFileName2);
if(refCoordData->isInDegrees())
aModel.getSimbodyEngine().convertDegreesToRadians(*refCoordData);
if(cmpCoordData->isInDegrees())
aModel.getSimbodyEngine().convertDegreesToRadians(*cmpCoordData);
std::ofstream fout(outFileName);
if(!fout.is_open())
{
std::cout<<"Fail to open file "<<outFileName.c_str()<<" to write!!!"<<std::endl;
exit(1);
}
int n_samples_cmp = cmpCoordData->getSize();
int numCoords_ref = refCoordData->getColumnLabels().size()-1;
//write the header
fout<<"CoordErrors"<<std::endl;
fout<<"version=1"<<std::endl;
fout<<"nRows="<<n_samples_cmp<<std::endl;
fout<<"nColumns="<<1+numCoords_ref<<std::endl;
fout<<"inDegrees=no"<<std::endl;
fout<<"endheader"<<std::endl;
const Array<std::string>& strs_labels = refCoordData->getColumnLabels();
const Array<std::string>& strs_labels_cmp = cmpCoordData->getColumnLabels();
int numCoords_cmp = strs_labels_cmp.size()-1;
Array<int> corresponding_indices_in_cmp(-1,numCoords_ref);
for(int i=1;i<=numCoords_ref;i++)
{
for(int j=1;j<=numCoords_cmp;j++)
{
if(strs_labels[i] == strs_labels_cmp[j])
{
corresponding_indices_in_cmp[i-1] = j-1;
break;
}
}
}
fout<<"time";
for(int i=1;i<=numCoords_ref;i++)
fout<<" "<<strs_labels.get(i).c_str();
fout<<std::endl;
SimTK::Real t;
SimTK::Vector q(numCoords_cmp);
SimTK::Vector q_ref(numCoords_ref);
Vector err_q(numCoords_ref);
for(int i=0;i<n_samples_cmp;i++)
{
cmpCoordData->getTime(i,t);
cmpCoordData->getData(i,numCoords_cmp,q);
refCoordData->getDataAtTime(t,numCoords_ref,q_ref);
for(int j=0;j<numCoords_ref;j++)
{
if(corresponding_indices_in_cmp[j]<0)
err_q[j] = 0;
else
err_q[j] = q[corresponding_indices_in_cmp[j]]-q_ref[j];
}
fout<<t;
for(int j=0;j<numCoords_ref;j++)
fout<<" "<<err_q[j];
fout<<std::endl;
}
fout.close();
delete refCoordData;
delete cmpCoordData;
}
void ROCINForceController::evalCoordTrackingErrs(const std::string& coordFileName1, const std::string& coordFileName2, const std::string& outFileName)
{
evalModelCoordTrackingErrs(getModel(),coordFileName1,coordFileName2,outFileName);
}
void ROCINForceController::initMPCSolver(int numExtraObservations)
{
// number of observations
int n_y = _numCoords*2+numExtraObservations;
// number of control variables
int n_controls = _numMuscles+_numNonMuscleActuators;
double initTime, finalTime;
Array_<Vector> y_reference;
const SimTK::State& initState = getModel().getWorkingState();
int n_samples = 0;
{
// get the trajectories of the joint angles and joint velocities
if(_coordData->isInDegrees())
getModel().getSimbodyEngine().convertDegreesToRadians(*_coordData);
initTime = _coordData->getFirstTime();
finalTime = _coordData->getLastTime();
n_samples = floor((finalTime-initTime)/_lookahead_window)+1;
Storage _coordDataPad = *_coordData;
_coordDataPad.pad(60);
if(_lowpass_freq>0.0)
_coordDataPad.lowpassFIR(50,_lowpass_freq);
// form the complete storage
Storage* qStore = NULL;
Storage* uStore = NULL;
getModel().getSimbodyEngine().formCompleteStorages(initState,_coordDataPad,qStore,uStore);
if(qStore->isInDegrees())
{
getModel().getSimbodyEngine().convertDegreesToRadians(*qStore);
getModel().getSimbodyEngine().convertDegreesToRadians(*uStore);
}
_qSet = new GCVSplineSet(5,qStore);
_uSet = new GCVSplineSet(5,uStore);
Storage* dudtStore = _uSet->constructStorage(1);
_uDotSet = new GCVSplineSet(5,dudtStore);
//_qSet->print("test_qSet_ROCIN.xml");
delete qStore;
delete uStore;
delete dudtStore;
FunctionSet * yRefSet = new FunctionSet();
for(int i=0;i<_qSet->getSize();i++)
yRefSet->cloneAndAppend(_qSet->get(i));
for(int i=0;i<_uSet->getSize();i++)
yRefSet->cloneAndAppend(_uSet->get(i));
// construct the MPC solver
_mpcSolver = new MPC(n_controls,n_y,n_samples,initTime,_lookahead_window,yRefSet,_lookahead_number);
}
// initialize the variables
_actuator_forces.setSize(n_controls);
_actuator_controls.setSize(n_controls);
_actuator_controls_new.setSize(n_controls);
for(int i=0;i<n_controls;i++)
{
_actuator_controls.set(i,0.0); //set to be 0.01
_actuator_controls_new.set(i,0.0);
}
_gen_forces_array.setSize(_lookahead_number);
_actuator_forces_array.setSize(_lookahead_number);
for(int i=0;i<_lookahead_number;i++)
{
_actuator_forces_array[i].resize(n_controls);
_actuator_forces_array[i].setToZero();
_gen_forces_array[i].resize(_n_u);
_gen_forces_array[i].setToZero();
}
_muscle_min_control_array.resize(_numMuscles);
_muscle_max_control_array.resize(_numMuscles);
int idx_musc=0;
for(int i=0;i<_numMuscles+_numNonMuscleActuators;i++)
{
Actuator& act = getModel().getActuators().get(i);
PathActuator* m = dynamic_cast<PathActuator*>(&act);
if(m!=NULL)
{
_muscle_min_control_array[idx_musc] = m->getMinControl();
_muscle_max_control_array[idx_musc] = m->getMaxControl();
idx_musc++;
}
}
setTargetDT(_lookahead_window);
// set the lower and upper bounds for the control variables
_control_lowerbounds.resize(n_controls*_lookahead_number);
_control_upperbounds.resize(n_controls*_lookahead_number);
if(_numMuscles>0)
{
for(int i=0;i<_lookahead_number;i++)
{
_control_lowerbounds.updBlock(i*n_controls,0,_numMuscles,1) = _muscle_min_control_array;
_control_upperbounds.updBlock(i*n_controls,0,_numMuscles,1) = _muscle_max_control_array;
}
}
if(_numNonMuscleActuators>0)
{
for(int i=0;i<_lookahead_number;i++)
{
_control_lowerbounds.updBlock(i*n_controls+_numMuscles,0,_numNonMuscleActuators,1) = _virtual_actuator_min_control_array; //200 for running //-40 for standing
_control_upperbounds.updBlock(i*n_controls+_numMuscles,0,_numNonMuscleActuators,1) = _virtual_actuator_max_control_array; //30
}
}
_mpcSolver->setLowerBounds(_control_lowerbounds);
_mpcSolver->setUpperBounds(_control_upperbounds);
// initialize the matrix coefficients for the dynamics equation: y_dot = A*y + B*u+ C (y = x in our case)
// these matrix values are not really used since we will assign them again in the doControlPrecomputation
Matrix A(n_y,n_y);
Matrix B(n_y,n_controls);
Vector C(n_y);
A.setToZero();
A.diag().setTo(1.0);
B.setToZero();
B.diag().setTo(1.0);
C.setToZero();
//C.setTo(0.3);
Array<Matrix> A_array;
Array<Matrix> B_array;
Array<Vector> C_array;
A_array.setSize(_lookahead_number);
B_array.setSize(_lookahead_number);
C_array.setSize(_lookahead_number);
for(int i=0;i<_lookahead_number;i++)
{
A_array[i] = A;
B_array[i] = B;
C_array[i] = C;
}
_mpcSolver->setABCArray(A_array,B_array,C_array);
_mpcSolver->setABC(A,B,C);
// D and E, one item in the objective function is (D*u+E)^T*R*(D*u+E)
Matrix D(n_controls,n_controls);
Vector E(n_controls);
D.setToZero();
D.diag().setTo(1.0);
E.setToZero();
Array<Vector> D_array;
Array<Vector> E_array;
D_array.setSize(_lookahead_number);
E_array.setSize(_lookahead_number);
for(int i=0;i<_lookahead_number;i++)
{
D_array[i] = D.diag();
E_array[i] = E;
}
_mpcSolver->setDiagDandEAarray(D_array,E_array);
_mpcSolver->setDiagDandE(D.diag(),E);
// currently we don't penalize the terminal time error
Matrix P(n_y,n_y);
P.setToZero();
// penalty matrix, objective function item: (y-\hat y)^T * Q* (y- \hat y)
Matrix Q(n_y,n_y);
Q.setToZero();
int n_tracking = n_y - numExtraObservations;
//Q.updBlock(0,0,n_tracking,n_tracking).diag().setTo(_tracking_penalty); //5.0e1
Q.updBlock(0,0,n_tracking/2,n_tracking/2).diag().setTo(_coord_tracking_penalty); //5.0e1
Q.updBlock(n_tracking/2,n_tracking/2,n_tracking/2,n_tracking/2).diag().setTo(_speed_tracking_penalty);
Matrix R(n_controls,n_controls);
R.setToZero();
R.updBlock(0,0,_numMuscles,_numMuscles).diag().setTo(_activation_penalty);
if(_numNonMuscleActuators>0)
{
for(int i=0;i<_numNonMuscleActuators;i++)
R.set(_numMuscles+i,_numMuscles+i,_virtual_actuator_weight_array[i]);
}
// objective function time: (\dot y - \hat\dot y)^T * Qd * (\dot y - \hat\dot y)
Matrix Qd(n_y,n_y);
Qd.setToZero();
Qd.updBlock(n_y/2,n_y/2,n_y/2,n_y/2).diag().setTo(_PD_penalty); //1.0e-3
// objective function time: \dot u^T * Sd * \dot u
Matrix Sd(n_controls,n_controls);
Sd.setToZero();
// do not track the coordinates or speeds that are constrained
{
const Array<std::string>& labelArray = _coordData->getColumnLabels();
_CoordsSelection.resize(_numCoords,_n_u);
_CoordsSelection.setToZero();
for(int i=0;i<_numCoords;i++)
{
int idx_coord = i;
//if(getModel().getCoordinateSet()[idx_coord].getDefaultLocked() || getModel().getCoordinateSet()[idx_coord].getDefaultIsPrescribed())
if(getModel().getCoordinateSet()[idx_coord].isConstrained(initState))
{
P.set(i,i,0.0);
P.set(_numCoords+i,_numCoords+i,0.0);
Q.set(i,i,0.0);
Q.set(_numCoords+i,_numCoords+i,0.0);
Qd.set(i,i,0.0);
Qd.set(_numCoords+i,_numCoords+i,0.0);
}
else
{
_CoordsSelection.set(i,idx_coord,1.0);
}
}
}
if(_numNonMuscleActuators>0)
{
for(int i=0;i<_numNonMuscleActuators;i++)
{
for(int j=0;j<_n_u;j++)
{
if(_mapping_nonMuscleActuators.get(j,i)>0)
{
if(getModel().getCoordinateSet().get(j).isConstrained(initState))
//if(getModel().getCoordinateSet()[j].getDefaultLocked() || getModel().getCoordinateSet()[j].getDefaultIsPrescribed())
{
R.set(_numMuscles+i,_numMuscles+i,0.0);
Sd.set(_numMuscles+i,_numMuscles+i,0.0);
_mapping_nonMuscleActuators.set(j,i,0.0);
}
break;
}
}
}
}
_mpcSolver->setDiagPQR(P.diag(),Q.diag(),R.diag());
_mpcSolver->setDiagQd(Qd.diag());
_mpcSolver->setDiagSd(Sd.diag());
}
void ROCINForceController::connectToModel(Model& model)
{
// setUpInternalModel(model);
Super::connectToModel(model);
setNumControls(getActuatorSet().getSize());
_n_u = getModel().getNumSpeeds();
_n_q = getModel().getNumCoordinates();
// check coupled coordinates
const ForceSet& forceSet = getModel().getForceSet();
_numMuscles = 0;
for(int i=0;i<forceSet.getSize();i++)
{
PathActuator* m = dynamic_cast<PathActuator*>(&forceSet.get(i));
if(m!=NULL)
_numMuscles++;
}
}
void ROCINForceController::addEventHandlerToSystem()
{
ROCINControlEventHandler* ROCINHandler = new ROCINControlEventHandler(this);
getModel().updMultibodySystem().updDefaultSubsystem().addEventHandler(ROCINHandler);
}
void ROCINForceController::computeOptimalInitialState(SimTK::State& initState, double tiReal)
{
// solve an optimization problem that minimize the joint acceleration error and muscle activations
_internalSubsys->assignTimeAndQU(tiReal,initState);
_internalModel->getMultibodySystem().realize(initState,SimTK::Stage::Velocity);
if(initState.getZ().size()==0)
return;
StateInitializer stateInitializer(_internalModel,_internalController,initState);
Array<double> UDotRef;
if(_uSet != NULL)
_uSet->evaluate(UDotRef,1,tiReal);
else
_qSet->evaluate(UDotRef,2,tiReal);
Vector UDotRef_vec(_n_u);
for(int i=0;i<_n_u;i++)
UDotRef_vec[i] = UDotRef[i];
int nActs = getActuatorSet().getSize();
Vector w_actuator_forces(nActs), lower_bd_forces(nActs), upper_bd_forces(nActs);
Vector maxIsoForces(_numMuscles);
Vector acts_min(_numMuscles),acts_max(_numMuscles);
Vector lm_min(_numMuscles), lm_max(_numMuscles);
acts_min.setTo(0.02);
acts_max.setTo(1.0);
int idx_musc = 0;
for(int i=0;i<nActs;i++)
{
Actuator& act = getActuatorSet().get(i);
Muscle* musc = dynamic_cast<Muscle*>(&act);
if(musc != NULL)
{
double h = musc->getOptimalFiberLength()*sin(musc->getPennationAngleAtOptimalFiberLength());
double lmt = musc->getLength(initState);
double lst = musc->getTendonSlackLength();
lm_min[idx_musc] = h;
lm_max[idx_musc] = sqrt(h*h+(lmt-lst)*(lmt-lst));
maxIsoForces[idx_musc] = musc->getMaxIsometricForce();
w_actuator_forces[idx_musc] = 1.0;//1.0/(musc->getMaxIsometricForce()*musc->getMaxIsometricForce());
idx_musc++;
}
}
for(int i=0;i<_numNonMuscleActuators;i++)
w_actuator_forces[_numMuscles+i] = _virtual_actuator_weight_array[i];
lower_bd_forces.updBlock(0,0,_numMuscles,1).setTo(0.0);
Vector maxMuscleForces(_numMuscles);
evaluateMuscleForceBasedOnFiberLength(*_internalModel,initState,NULL,lm_min,maxMuscleForces);
upper_bd_forces.updBlock(0,0,_numMuscles,1) = maxMuscleForces.elementwiseDivide(maxIsoForces);
lower_bd_forces.updBlock(_numMuscles,0,_numNonMuscleActuators,1) = _virtual_actuator_min_control_array;
upper_bd_forces.updBlock(_numMuscles,0,_numNonMuscleActuators,1) = _virtual_actuator_max_control_array;
Vector optForces(_numMuscles+_numNonMuscleActuators);
optForces.updBlock(0,0,_numMuscles,1) = maxIsoForces;
optForces.updBlock(_numMuscles,0,_numNonMuscleActuators,1).setTo(1.0);
Matrix A_mbs;
Vector B_mbs;
computeMBSDynamicsNumerically(initState,A_mbs,B_mbs);
stateInitializer.setUDotRef(UDotRef_vec);
stateInitializer.setActuatorForceWeights(w_actuator_forces);
stateInitializer.setAccWeights(1.0e3);
stateInitializer.setActuatorForceBounds(lower_bd_forces,upper_bd_forces);
stateInitializer.setActivationBounds(acts_min,acts_max);
stateInitializer.setFiberLengthBounds(lm_min,lm_max);
stateInitializer.setMBSDynamicsAndOptForces(A_mbs,B_mbs,optForces);
initState = stateInitializer.getOptimizedInitState();
PrintVector(initState.getZ(),"initState.Z",std::cout);
}
SimTK::State& ROCINForceController::initSystem(Model& aModel)
{
setCheckTargetTime(true);
aModel.buildSystem();
addEventHandlerToSystem();
SimTK::State& initState = aModel.initializeState();
initMPCSolver(0);//_numMuscles
//initialize control Set
int nActs = getActuatorSet().getSize();
for(int i=0;i<nActs;i++)
{
Actuator& act = getActuatorSet().get(i);
ControlLinear* control = new ControlLinear();
control->setName(act.getName()+".excitation");
{
control->setUseSteps(true);
}
_controlSet.adoptAndAppend(control);
}
_internalSubsys->setCoordinateTrajectories(_qSet);
_internalSubsys->setSpeedTrajectories(_uSet);
_momentArmSolver = new MomentArmSolver(aModel);
return initState;
}
SimTK::State& ROCINForceController::setInitStateFromFile(Model& aModel, const std::string& aStateFileName)
{
SimTK::State& initState = initSystem(aModel);
Storage tmp(aStateFileName);
Storage* stateStorage = new Storage();
aModel.formStateStorage(tmp, *stateStorage);
const Array<std::string>& strs_labels = stateStorage->getColumnLabels();
int n_states = strs_labels.size()-1;
Vector initStateVector(n_states);
double initTime;
stateStorage->getTime(0,initTime);
stateStorage->getData(0,n_states,initStateVector);
for(int i=1;i<=n_states;i++)
aModel.setStateVariable(initState,strs_labels[i],initStateVector[i-1]);
initState.updTime() = initTime;
delete stateStorage;
aModel.getMultibodySystem().realize(initState,SimTK::Stage::Velocity);
return initState;
}
SimTK::State& ROCINForceController::setInitState(Model& aModel, double tiReal)
{
SimTK::State& initState = initSystem(aModel);
computeOptimalInitialState(initState,tiReal);
return initState;
}
// using forward difference method to compute the partial derivatives
void ROCINForceController::computeGeneralizedForceDynamicsPartialsFwdDiff(const SimTK::State& s, const Vector& genForces, Matrix& dUDotdQ, Matrix& dUDotdU)
{
dUDotdQ.resize(_n_u,_n_q);
dUDotdU.resize(_n_u,_n_u);
SimTK::State s_cpy = s;
const SimTK::SimbodyMatterSubsystem& smss = getModel().getMatterSubsystem();
const SimTK::MultibodySystem& mbs = getModel().getMultibodySystem();
const Set<Actuator>& fSet = getActuatorSet();
int nf = fSet.getSize();
for(int i=0;i<nf;i++)
{
ScalarActuator& act = (ScalarActuator&)fSet.get(i);
act.overrideActuation(s_cpy, true);
act.setOverrideActuation(s_cpy, 0.0);
}
mbs.realize(s_cpy,SimTK::Stage::Dynamics);
const SimTK::Vector_<SimTK::SpatialVec>& bodyForces = mbs.getRigidBodyForces(s_cpy,SimTK::Stage::Dynamics);
SimTK::Vector_<SimTK::SpatialVec> bodyAccs;
Vector uDot_0(_n_u);
smss.calcAcceleration(s_cpy,genForces,bodyForces,uDot_0,bodyAccs);
Vector uDot(_n_u);
const Vector& q_s = s.getQ();
const Vector& u_s = s.getU();
double delta = 1e-6;
for(int i=0;i<_n_q;i++)
{
s_cpy.updQ()[i] = q_s[i]+delta;
mbs.realize(s_cpy,SimTK::Stage::Dynamics);
smss.calcAcceleration(s_cpy,genForces,bodyForces,uDot,bodyAccs);
dUDotdQ.updCol(i) = (uDot-uDot_0)/delta;
s_cpy.updQ()[i] = q_s[i];
}
for(int i=0;i<_n_u;i++)
{
s_cpy.updU()[i] = u_s[i]+delta;
mbs.realize(s_cpy,SimTK::Stage::Dynamics);
smss.calcAcceleration(s_cpy,genForces,bodyForces,uDot,bodyAccs);
dUDotdU.updCol(i) = (uDot-uDot_0)/delta;
s_cpy.updU()[i] = u_s[i];
}
}
void ROCINForceController::computeDynamicsPartialsFwdDiff(const SimTK::State& s, const Vector& actuatorForces,Matrix& dUDotdQ, Matrix& dUDotdU)
{
SimTK::State s_cpy = s;
const SimTK::SimbodyMatterSubsystem& smss = getModel().getMatterSubsystem();
const SimTK::MultibodySystem& mbs = getModel().getMultibodySystem();
const Set<Actuator>& fSet = getActuatorSet();
int nf = fSet.getSize();
for(int i=0;i<nf;i++)
{
ScalarActuator& act = (ScalarActuator&)fSet.get(i);
act.overrideActuation(s_cpy, true);
act.setOverrideActuation(s_cpy, actuatorForces[i]);
}
mbs.realize(s_cpy,SimTK::Stage::Acceleration);
Vector udot_s = s_cpy.getUDot();
const Vector& q_s = s.getQ();
const Vector& u_s = s.getU();
double delta = 1e-6;
int n_q = q_s.size();
int n_u = u_s.size();
dUDotdQ.resize(n_u,n_q);
dUDotdU.resize(n_u,n_u);
for(int i=0;i<n_q;i++)
{
s_cpy.updQ()[i] = q_s[i]+delta;
mbs.realize(s_cpy,SimTK::Stage::Acceleration);
dUDotdQ.updCol(i) = (s_cpy.getUDot()-udot_s)/delta;
s_cpy.updQ()[i] = q_s[i];
}
for(int i=0;i<n_u;i++)
{
s_cpy.updU()[i] = u_s[i]+delta;
mbs.realize(s_cpy,SimTK::Stage::Acceleration);
dUDotdU.updCol(i) = (s_cpy.getUDot()-udot_s)/delta;
s_cpy.updU()[i] = u_s[i];
}
}
// use central difference methods to compute the partial derivatives
void ROCINForceController::computeGeneralizedForceDynamicsPartialsCentralDiff(const SimTK::State& s, const Vector& genForces, Matrix& dUDotdQ, Matrix& dUDotdU)
{
dUDotdQ.resize(_n_u,_n_q);
dUDotdU.resize(_n_u,_n_u);
SimTK::State s_cpy = s;
const SimTK::SimbodyMatterSubsystem& smss = getModel().getMatterSubsystem();
const SimTK::MultibodySystem& mbs = getModel().getMultibodySystem();
const Set<Actuator>& fSet = getActuatorSet();
int nf = fSet.getSize();
for(int i=0;i<nf;i++)
{
ScalarActuator& act = (ScalarActuator&)fSet.get(i);
act.overrideActuation(s_cpy, true);
act.setOverrideActuation(s_cpy, 0.0);
}
mbs.realize(s_cpy,SimTK::Stage::Dynamics);
const SimTK::Vector_<SimTK::SpatialVec>& bodyForces = mbs.getRigidBodyForces(s_cpy,SimTK::Stage::Dynamics);
SimTK::Vector_<SimTK::SpatialVec> bodyAccs;
const Vector& q_s = s.getQ();
const Vector& u_s = s.getU();
double delta = 1e-5;
Vector udot_plus(_n_u), udot_minus(_n_u);
for(int i=0;i<_n_q;i++)
{
s_cpy.updQ()[i] = q_s[i]+delta;
mbs.realize(s_cpy,SimTK::Stage::Dynamics);
smss.calcAcceleration(s_cpy,genForces,bodyForces,udot_plus,bodyAccs);
s_cpy.updQ()[i] = q_s[i]-delta;
mbs.realize(s_cpy,SimTK::Stage::Dynamics);
smss.calcAcceleration(s_cpy,genForces,bodyForces,udot_minus,bodyAccs);
dUDotdQ.updCol(i) = (udot_plus-udot_minus)/(2.0*delta);
s_cpy.updQ()[i] = q_s[i];
}
for(int i=0;i<_n_u;i++)
{
s_cpy.updU()[i] = u_s[i]+delta;
mbs.realize(s_cpy,SimTK::Stage::Dynamics);
smss.calcAcceleration(s_cpy,genForces,bodyForces,udot_plus,bodyAccs);
s_cpy.updU()[i] = u_s[i]-delta;
mbs.realize(s_cpy,SimTK::Stage::Dynamics);
smss.calcAcceleration(s_cpy,genForces,bodyForces,udot_minus,bodyAccs);
dUDotdU.updCol(i) = (udot_plus-udot_minus)/(2.0*delta);
s_cpy.updU()[i] = u_s[i];
}
}
void ROCINForceController::computeDynamicsPartialsCentralDiff(const SimTK::State& s, const Vector& actuatorForces,Matrix& dUDotdQ, Matrix& dUDotdU)
{
SimTK::State s_cpy = s;
const SimTK::SimbodyMatterSubsystem& smss = getModel().getMatterSubsystem();
const SimTK::MultibodySystem& mbs = getModel().getMultibodySystem();
const Set<Actuator>& fSet = getActuatorSet();
int nf = fSet.getSize();
for(int i=0;i<nf;i++)
{
ScalarActuator& act = (ScalarActuator&)fSet.get(i);
act.overrideActuation(s_cpy, true);
act.setOverrideActuation(s_cpy, actuatorForces[i]);
}
const Vector& q_s = s.getQ();
const Vector& u_s = s.getU();
int n_q = q_s.size();
int n_u = u_s.size();