-
Notifications
You must be signed in to change notification settings - Fork 26
/
EngineMultiRobot.cc
4242 lines (3744 loc) · 184 KB
/
EngineMultiRobot.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 <cmath>
#include <ctime>
#include <unordered_set>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <streambuf>
#include "pinocchio/parsers/urdf.hpp"
#include "pinocchio/spatial/inertia.hpp" // `pinocchio::Inertia`
#include "pinocchio/spatial/force.hpp" // `pinocchio::Force`
#include "pinocchio/spatial/se3.hpp" // `pinocchio::SE3`
#include "pinocchio/spatial/explog.hpp" // `pinocchio::exp6`, `pinocchio::log6`
#include "pinocchio/spatial/explog-quaternion.hpp" // `pinocchio::quaternion::log3`
#include "pinocchio/multibody/visitor.hpp" // `pinocchio::fusion::JointUnaryVisitorBase`
#include "pinocchio/multibody/joint/joint-model-base.hpp" // `pinocchio::JointModelBase`
#include "pinocchio/algorithm/center-of-mass.hpp" // `pinocchio::getComFromCrba`
#include "pinocchio/algorithm/frames.hpp" // `pinocchio::getFrameVelocity`
#include "pinocchio/algorithm/jacobian.hpp" // `pinocchio::getJointJacobian`
#include "pinocchio/algorithm/energy.hpp" // `pinocchio::computePotentialEnergy`
#include "pinocchio/algorithm/joint-configuration.hpp" // `pinocchio::normalize`
#include "pinocchio/algorithm/geometry.hpp" // `pinocchio::computeCollisions`
#include "pinocchio/serialization/model.hpp" // `pinocchio::ModelTpl<T>.serialize`
#include "H5Cpp.h"
#include "json/json.h"
#include "jiminy/core/io/FileDevice.h"
#include "jiminy/core/telemetry/TelemetryData.h"
#include "jiminy/core/telemetry/TelemetryRecorder.h"
#include "jiminy/core/robot/PinocchioOverloadAlgorithms.h"
#include "jiminy/core/robot/AbstractMotor.h"
#include "jiminy/core/robot/AbstractSensor.h"
#include "jiminy/core/constraints/AbstractConstraint.h"
#include "jiminy/core/constraints/JointConstraint.h"
#include "jiminy/core/constraints/FixedFrameConstraint.h"
#include "jiminy/core/robot/Robot.h"
#include "jiminy/core/control/AbstractController.h"
#include "jiminy/core/control/ControllerFunctor.h"
#include "jiminy/core/solver/ConstraintSolvers.h"
#include "jiminy/core/stepper/AbstractStepper.h"
#include "jiminy/core/stepper/EulerExplicitStepper.h"
#include "jiminy/core/stepper/RungeKuttaDOPRIStepper.h"
#include "jiminy/core/stepper/RungeKutta4Stepper.h"
#include "jiminy/core/engine/EngineMultiRobot.h"
#include "jiminy/core/utilities/Pinocchio.h"
#include "jiminy/core/utilities/Random.h"
#include "jiminy/core/utilities/Json.h"
#include "jiminy/core/utilities/Helpers.h"
#include "jiminy/core/Constants.h"
namespace jiminy
{
EngineMultiRobot::EngineMultiRobot(void):
engineOptions_(nullptr),
systems_(),
isTelemetryConfigured_(false),
isSimulationRunning_(false),
engineOptionsHolder_(),
timer_(std::make_unique<Timer>()),
contactModel_(contactModel_t::NONE),
telemetrySender_(),
telemetryData_(nullptr),
telemetryRecorder_(nullptr),
stepper_(),
stepperUpdatePeriod_(INF),
stepperState_(),
systemsDataHolder_(),
forcesCoupling_(),
fPrev_(),
aPrev_(),
logData_(nullptr)
{
// Initialize the configuration options to the default.
setOptions(getDefaultEngineOptions());
// Initialize the global telemetry data holder
telemetryData_ = std::make_shared<TelemetryData>();
telemetryData_->reset();
// Initialize the global telemetry recorder
telemetryRecorder_ = std::make_unique<TelemetryRecorder>();
// Initialize the engine-specific telemetry sender
telemetrySender_.configureObject(telemetryData_, ENGINE_TELEMETRY_NAMESPACE);
}
EngineMultiRobot::~EngineMultiRobot(void) = default; // Cannot be default in the header since some types are incomplete at this point
hresult_t EngineMultiRobot::addSystem(std::string const & systemName,
std::shared_ptr<Robot> robot,
std::shared_ptr<AbstractController> controller,
callbackFunctor_t callbackFct)
{
// Make sure that no simulation is running
if (isSimulationRunning_)
{
PRINT_ERROR("A simulation is already running. Stop it before adding a new system.");
return hresult_t::ERROR_GENERIC;
}
if (!robot)
{
PRINT_ERROR("Robot unspecified.");
return hresult_t::ERROR_INIT_FAILED;
}
if (!robot->getIsInitialized())
{
PRINT_ERROR("Robot not initialized.");
return hresult_t::ERROR_INIT_FAILED;
}
if (!controller)
{
PRINT_ERROR("Controller unspecified.");
return hresult_t::ERROR_INIT_FAILED;
}
if (!controller->getIsInitialized())
{
PRINT_ERROR("Controller not initialized.");
return hresult_t::ERROR_INIT_FAILED;
}
auto robot_controller = controller->robot_.lock();
if (!robot_controller)
{
PRINT_ERROR("Controller's robot expired or unset.");
return hresult_t::ERROR_INIT_FAILED;
}
if (robot != robot_controller)
{
PRINT_ERROR("Controller not initialized for specified robot.");
return hresult_t::ERROR_INIT_FAILED;
}
// TODO: Check that the callback function is working as expected
systems_.emplace_back(systemName,
robot,
controller,
std::move(callbackFct));
systemsDataHolder_.resize(systems_.size());
return hresult_t::SUCCESS;
}
hresult_t EngineMultiRobot::addSystem(std::string const & systemName,
std::shared_ptr<Robot> robot,
callbackFunctor_t callbackFct)
{
if (!robot)
{
PRINT_ERROR("Robot unspecified.");
return hresult_t::ERROR_INIT_FAILED;
}
if (!robot->getIsInitialized())
{
PRINT_ERROR("Robot not initialized.");
return hresult_t::ERROR_INIT_FAILED;
}
auto systemIt = std::find_if(systems_.begin(), systems_.end(),
[&systemName](auto const & sys)
{
return (sys.name == systemName);
});
if (systemIt != systems_.end())
{
PRINT_ERROR("A system with this name has already been added to the engine.");
return hresult_t::ERROR_BAD_INPUT;
}
// Create and initialize a controller doing nothing
auto bypassFunctor = [](float64_t const & /* t */,
vectorN_t const & /* q */,
vectorN_t const & /* v */,
sensorsDataMap_t const & /* sensorsData */,
vectorN_t & /* out */) {};
auto controller = std::make_shared<ControllerFunctor<
decltype(bypassFunctor), decltype(bypassFunctor)> >(bypassFunctor, bypassFunctor);
controller->initialize(robot);
return addSystem(systemName, robot, controller, std::move(callbackFct));
}
hresult_t EngineMultiRobot::removeSystem(std::string const & systemName)
{
hresult_t returnCode = hresult_t::SUCCESS;
// Make sure that no simulation is running
if (isSimulationRunning_)
{
PRINT_ERROR("A simulation is already running. Stop it before removing a system.");
returnCode = hresult_t::ERROR_GENERIC;
}
if (returnCode == hresult_t::SUCCESS)
{
/* Remove every coupling forces involving the system.
Note that it is already checking that the system exists. */
returnCode = removeForcesCoupling(systemName);
}
if (returnCode == hresult_t::SUCCESS)
{
// Get the system index
int32_t systemIdx;
getSystemIdx(systemName, systemIdx); // It cannot fail at this point
// Update the systems' indices for the remaining coupling forces
for (auto & force : forcesCoupling_)
{
if (force.systemIdx1 > systemIdx)
{
force.systemIdx1--;
}
if (force.systemIdx2 > systemIdx)
{
force.systemIdx2--;
}
}
// Remove the system from the list
systems_.erase(systems_.begin() + systemIdx);
systemsDataHolder_.erase(systemsDataHolder_.begin() + systemIdx);
}
return returnCode;
}
hresult_t EngineMultiRobot::setController(std::string const & systemName,
std::shared_ptr<AbstractController> controller)
{
hresult_t returnCode = hresult_t::SUCCESS;
// Make sure that no simulation is running
if (isSimulationRunning_)
{
PRINT_ERROR("A simulation is already running. Stop it before setting a new controller for a system.");
returnCode = hresult_t::ERROR_GENERIC;
}
// Make sure that the controller is initialized
if (returnCode == hresult_t::SUCCESS)
{
if (!controller->getIsInitialized())
{
PRINT_ERROR("Controller not initialized.");
returnCode = hresult_t::ERROR_INIT_FAILED;
}
}
auto robot_controller = controller->robot_.lock();
if (returnCode == hresult_t::SUCCESS)
{
if (!robot_controller)
{
PRINT_ERROR("Controller's robot expired or unset.");
returnCode = hresult_t::ERROR_INIT_FAILED;
}
}
// Make sure that the system for which to set the controller exists
systemHolder_t * system;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getSystem(systemName, system);
}
if (returnCode == hresult_t::SUCCESS)
{
if (system->robot != robot_controller)
{
PRINT_ERROR("Controller not initialized for robot associated with specified system.");
returnCode = hresult_t::ERROR_INIT_FAILED;
}
}
// Set the controller
if (returnCode == hresult_t::SUCCESS)
{
system->controller = controller;
}
return returnCode;
}
hresult_t EngineMultiRobot::registerForceCoupling(std::string const & systemName1,
std::string const & systemName2,
std::string const & frameName1,
std::string const & frameName2,
forceCouplingFunctor_t forceFct)
{
hresult_t returnCode = hresult_t::SUCCESS;
// Make sure that no simulation is running
if (isSimulationRunning_)
{
PRINT_ERROR("A simulation is already running. Stop it before adding coupling forces.");
returnCode = hresult_t::ERROR_GENERIC;
}
int32_t systemIdx1;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getSystemIdx(systemName1, systemIdx1);
}
int32_t systemIdx2;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getSystemIdx(systemName2, systemIdx2);
}
frameIndex_t frameIdx1;
if (returnCode == hresult_t::SUCCESS)
{
systemHolder_t const & system = systems_[systemIdx1];
returnCode = getFrameIdx(system.robot->pncModel_, frameName1, frameIdx1);
}
frameIndex_t frameIdx2;
if (returnCode == hresult_t::SUCCESS)
{
systemHolder_t const & system = systems_[systemIdx2];
returnCode = getFrameIdx(system.robot->pncModel_, frameName2, frameIdx2);
}
if (returnCode == hresult_t::SUCCESS)
{
forcesCoupling_.emplace_back(systemName1,
systemIdx1,
systemName2,
systemIdx2,
frameName1,
frameIdx1,
frameName2,
frameIdx2,
std::move(forceFct));
}
return returnCode;
}
hresult_t EngineMultiRobot::registerViscoElasticForceCoupling(std::string const & systemName1,
std::string const & systemName2,
std::string const & frameName1,
std::string const & frameName2,
vectorN_t const & stiffness,
vectorN_t const & damping)
{
hresult_t returnCode = hresult_t::SUCCESS;
systemHolder_t * system1;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getSystem(systemName1, system1);
}
frameIndex_t frameIdx1;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getFrameIdx(system1->robot->pncModel_, frameName1, frameIdx1);
}
systemHolder_t * system2;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getSystem(systemName2, system2);
}
frameIndex_t frameIdx2;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getFrameIdx(system2->robot->pncModel_, frameName2, frameIdx2);
}
if (stiffness.size() != 6 || damping.size() != 6)
{
PRINT_ERROR("'stiffness' and 'damping' must have size 6.");
returnCode = hresult_t::ERROR_GENERIC;
}
if (returnCode == hresult_t::SUCCESS)
{
auto forceFct = [=] (
float64_t const & /*t*/,
vectorN_t const & /*q_1*/,
vectorN_t const & /*v_1*/,
vectorN_t const & /*q_2*/,
vectorN_t const & /*v_2*/) mutable -> pinocchio::Force
{
/* One must keep track of system pointers and frames indices internally
and update them at reset since the systems may have changed between
simulations. Note that `isSimulationRunning_` is false when called
for the first time in `start` method before locking the robot, so it
is the right time to update those proxies. */
if (!isSimulationRunning_)
{
getSystem(systemName1, system1);
getFrameIdx(system1->robot->pncModel_, frameName1, frameIdx1);
getSystem(systemName2, system2);
getFrameIdx(system2->robot->pncModel_, frameName2, frameIdx2);
}
// Get the frames positions and velocities in world
pinocchio::SE3 const & oMf1 = system1->robot->pncData_.oMf[frameIdx1];
pinocchio::SE3 const & oMf2 = system2->robot->pncData_.oMf[frameIdx2];
pinocchio::Motion const oVf1 = getFrameVelocity(system1->robot->pncModel_,
system1->robot->pncData_,
frameIdx1,
pinocchio::LOCAL_WORLD_ALIGNED);
pinocchio::Motion const oVf2 = getFrameVelocity(system2->robot ->pncModel_,
system2->robot->pncData_,
frameIdx2,
pinocchio::LOCAL_WORLD_ALIGNED);
/* Compute the force coupling them.
Note that the application point is the "middle" between frames to
get "symmetric" forces on both frame. */
pinocchio::Motion const pos12 = pinocchio::log6(oMf1.actInv(oMf2));
pinocchio::SE3 const oMf12 = pinocchio::exp6(0.5 * pos12);
pinocchio::SE3 const oRf1 = pinocchio::SE3(oMf1.rotation(), vector3_t::Zero());
vector6_t const vel12 = (oVf2 - oVf1).toVector();
return oRf1.act(oMf12.actInv(pinocchio::Force((
stiffness.array() * pos12.toVector().array() +
damping.array() * vel12.array()).matrix())));
};
returnCode = registerForceCoupling(
systemName1, systemName2, frameName1, frameName2, forceFct);
}
return returnCode;
}
hresult_t EngineMultiRobot::registerViscoElasticForceCoupling(std::string const & systemName,
std::string const & frameName1,
std::string const & frameName2,
vectorN_t const & stiffness,
vectorN_t const & damping)
{
return registerViscoElasticForceCoupling(
systemName, systemName, frameName1, frameName2, stiffness, damping);
}
hresult_t EngineMultiRobot::registerViscoElasticDirectionalForceCoupling(std::string const & systemName1,
std::string const & systemName2,
std::string const & frameName1,
std::string const & frameName2,
float64_t const & stiffness,
float64_t const & damping)
{
hresult_t returnCode = hresult_t::SUCCESS;
systemHolder_t * system1;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getSystem(systemName1, system1);
}
frameIndex_t frameIdx1;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getFrameIdx(system1->robot->pncModel_, frameName1, frameIdx1);
}
systemHolder_t * system2;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getSystem(systemName2, system2);
}
frameIndex_t frameIdx2;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getFrameIdx(system2->robot->pncModel_, frameName2, frameIdx2);
}
if (returnCode == hresult_t::SUCCESS)
{
auto forceFct = [=] (
float64_t const & /*t*/,
vectorN_t const & /*q_1*/,
vectorN_t const & /*v_1*/,
vectorN_t const & /*q_2*/,
vectorN_t const & /*v_2*/) mutable -> pinocchio::Force
{
/* One must keep track of system pointers and frames indices internally
and update them at reset since the systems may have changed between
simulations. Note that `isSimulationRunning_` is false when called
for the first time in `start` method before locking the robot, so it
is the right time to update those proxies. */
if (!isSimulationRunning_)
{
getSystem(systemName1, system1);
getFrameIdx(system1->robot->pncModel_, frameName1, frameIdx1);
getSystem(systemName2, system2);
getFrameIdx(system2->robot->pncModel_, frameName2, frameIdx2);
}
// Get the frames positions and velocities in world
pinocchio::SE3 const & oMf1 = system1->robot->pncData_.oMf[frameIdx1];
pinocchio::SE3 const & oMf2 = system2->robot->pncData_.oMf[frameIdx2];
pinocchio::Motion const oVf1 = getFrameVelocity(system1->robot->pncModel_,
system1->robot->pncData_,
frameIdx1,
pinocchio::LOCAL_WORLD_ALIGNED);
pinocchio::Motion const oVf2 = getFrameVelocity(system2->robot ->pncModel_,
system2->robot->pncData_,
frameIdx2,
pinocchio::LOCAL_WORLD_ALIGNED);
// Compute the linear force coupling them
vector3_t const dir12 = oMf2.translation() - oMf1.translation();
if ((dir12.array().abs() > EPS).any())
{
auto vel12 = oVf2.linear() - oVf1.linear();
auto vel12Proj = vel12.dot(dir12) / dir12.squaredNorm() * dir12;
return pinocchio::Force(
stiffness * dir12 + damping * vel12Proj, vector3_t::Zero());
}
return pinocchio::Force::Zero();
};
returnCode = registerForceCoupling(
systemName1, systemName2, frameName1, frameName2, forceFct);
}
return returnCode;
}
hresult_t EngineMultiRobot::registerViscoElasticDirectionalForceCoupling(std::string const & systemName,
std::string const & frameName1,
std::string const & frameName2,
float64_t const & stiffness,
float64_t const & damping)
{
return registerViscoElasticDirectionalForceCoupling(
systemName, systemName, frameName1, frameName2, stiffness, damping);
}
hresult_t EngineMultiRobot::removeForcesCoupling(std::string const & systemName1,
std::string const & systemName2)
{
hresult_t returnCode = hresult_t::SUCCESS;
// Make sure that no simulation is running
if (isSimulationRunning_)
{
PRINT_ERROR("A simulation is already running. Stop it before removing coupling forces.");
returnCode = hresult_t::ERROR_GENERIC;
}
systemHolder_t * system1;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getSystem(systemName1, system1);
}
if (returnCode == hresult_t::SUCCESS)
{
systemHolder_t * system2;
returnCode = getSystem(systemName2, system2);
}
if (returnCode == hresult_t::SUCCESS)
{
forcesCoupling_.erase(
std::remove_if(forcesCoupling_.begin(), forcesCoupling_.end(),
[&systemName1, &systemName2](auto const & force)
{
return (force.systemName1 == systemName1 &&
force.systemName2 == systemName2);
}),
forcesCoupling_.end()
);
}
return returnCode;
}
hresult_t EngineMultiRobot::removeForcesCoupling(std::string const & systemName)
{
hresult_t returnCode = hresult_t::SUCCESS;
// Make sure that no simulation is running
if (isSimulationRunning_)
{
PRINT_ERROR("A simulation is already running. Stop it before removing coupling forces.");
returnCode = hresult_t::ERROR_GENERIC;
}
systemHolder_t * system;
if (returnCode == hresult_t::SUCCESS)
{
returnCode = getSystem(systemName, system);
}
if (returnCode == hresult_t::SUCCESS)
{
forcesCoupling_.erase(
std::remove_if(forcesCoupling_.begin(), forcesCoupling_.end(),
[&systemName](auto const & force)
{
return (force.systemName1 == systemName ||
force.systemName2 == systemName);
}),
forcesCoupling_.end()
);
}
return returnCode;
}
hresult_t EngineMultiRobot::removeForcesCoupling(void)
{
hresult_t returnCode = hresult_t::SUCCESS;
// Make sure that no simulation is running
if (isSimulationRunning_)
{
PRINT_ERROR("A simulation is already running. Stop it before removing coupling forces.");
returnCode = hresult_t::ERROR_GENERIC;
}
forcesCoupling_.clear();
return returnCode;
}
forceCouplingRegister_t const & EngineMultiRobot::getForcesCoupling(void) const
{
return forcesCoupling_;
}
hresult_t EngineMultiRobot::removeAllForces(void)
{
hresult_t returnCode = hresult_t::SUCCESS;
returnCode = removeForcesCoupling();
if (returnCode == hresult_t::SUCCESS)
{
returnCode = removeForcesImpulse();
}
if (returnCode == hresult_t::SUCCESS)
{
returnCode = removeForcesProfile();
}
return returnCode;
}
hresult_t EngineMultiRobot::configureTelemetry(void)
{
hresult_t returnCode = hresult_t::SUCCESS;
if (systems_.empty())
{
PRINT_ERROR("No system added to the engine.");
returnCode = hresult_t::ERROR_INIT_FAILED;
}
if (!isTelemetryConfigured_)
{
auto systemIt = systems_.begin();
auto systemDataIt = systemsDataHolder_.begin();
for ( ; systemIt != systems_.end(); ++systemIt, ++systemDataIt)
{
// Generate the log fieldnames
systemDataIt->positionFieldnames =
addCircumfix(systemIt->robot->getPositionFieldnames(),
systemIt->name, "", TELEMETRY_FIELDNAME_DELIMITER);
systemDataIt->velocityFieldnames =
addCircumfix(systemIt->robot->getVelocityFieldnames(),
systemIt->name, "", TELEMETRY_FIELDNAME_DELIMITER);
systemDataIt->accelerationFieldnames =
addCircumfix(systemIt->robot->getAccelerationFieldnames(),
systemIt->name, "", TELEMETRY_FIELDNAME_DELIMITER);
systemDataIt->forceExternalFieldnames =
addCircumfix(systemIt->robot->getForceExternalFieldnames(),
systemIt->name, "", TELEMETRY_FIELDNAME_DELIMITER);
systemDataIt->commandFieldnames =
addCircumfix(systemIt->robot->getCommandFieldnames(),
systemIt->name, "", TELEMETRY_FIELDNAME_DELIMITER);
systemDataIt->motorEffortFieldnames =
addCircumfix(systemIt->robot->getMotorEffortFieldnames(),
systemIt->name, "", TELEMETRY_FIELDNAME_DELIMITER);
systemDataIt->energyFieldname =
addCircumfix("energy",
systemIt->name, "", TELEMETRY_FIELDNAME_DELIMITER);
// Register variables to the telemetry senders
if (returnCode == hresult_t::SUCCESS)
{
if (engineOptions_->telemetry.enableConfiguration)
{
returnCode = telemetrySender_.registerVariable(
systemDataIt->positionFieldnames,
systemDataIt->state.q);
}
}
if (returnCode == hresult_t::SUCCESS)
{
if (engineOptions_->telemetry.enableVelocity)
{
returnCode = telemetrySender_.registerVariable(
systemDataIt->velocityFieldnames,
systemDataIt->state.v);
}
}
if (returnCode == hresult_t::SUCCESS)
{
if (engineOptions_->telemetry.enableAcceleration)
{
returnCode = telemetrySender_.registerVariable(
systemDataIt->accelerationFieldnames,
systemDataIt->state.a);
}
}
if (engineOptions_->telemetry.enableForceExternal)
{
for (std::size_t i = 1; i < systemDataIt->state.fExternal.size(); ++i)
{
auto const & fext = systemDataIt->state.fExternal[i].toVector();
for (uint8_t j = 0; j < 6U; ++j)
{
returnCode = telemetrySender_.registerVariable(
systemDataIt->forceExternalFieldnames[(i - 1) * 6U + j],
fext[j]);
}
}
}
if (returnCode == hresult_t::SUCCESS)
{
if (engineOptions_->telemetry.enableCommand)
{
returnCode = telemetrySender_.registerVariable(
systemDataIt->commandFieldnames,
systemDataIt->state.command);
}
}
if (returnCode == hresult_t::SUCCESS)
{
if (engineOptions_->telemetry.enableMotorEffort)
{
returnCode = telemetrySender_.registerVariable(
systemDataIt->motorEffortFieldnames,
systemDataIt->state.uMotor);
}
}
if (returnCode == hresult_t::SUCCESS)
{
if (engineOptions_->telemetry.enableEnergy)
{
returnCode = telemetrySender_.registerVariable(
systemDataIt->energyFieldname, 0.0);
}
}
if (returnCode == hresult_t::SUCCESS)
{
returnCode = systemIt->controller->configureTelemetry(
telemetryData_, systemIt->name);
}
if (returnCode == hresult_t::SUCCESS)
{
returnCode = systemIt->robot->configureTelemetry(
telemetryData_, systemIt->name);
}
}
}
if (returnCode == hresult_t::SUCCESS)
{
isTelemetryConfigured_ = true;
}
return returnCode;
}
void EngineMultiRobot::updateTelemetry(void)
{
auto systemIt = systems_.begin();
auto systemDataIt = systemsDataHolder_.begin();
for ( ; systemIt != systems_.end(); ++systemIt, ++systemDataIt)
{
// Compute the total energy of the system
float64_t energy = pinocchio_overload::computeKineticEnergy(
systemIt->robot->pncModel_,
systemIt->robot->pncData_,
systemDataIt->state.q,
systemDataIt->state.v);
energy += pinocchio::computePotentialEnergy(
systemIt->robot->pncModel_,
systemIt->robot->pncData_);
// Update telemetry values
if (engineOptions_->telemetry.enableConfiguration)
{
telemetrySender_.updateValue(systemDataIt->positionFieldnames,
systemDataIt->state.q);
}
if (engineOptions_->telemetry.enableVelocity)
{
telemetrySender_.updateValue(systemDataIt->velocityFieldnames,
systemDataIt->state.v);
}
if (engineOptions_->telemetry.enableAcceleration)
{
telemetrySender_.updateValue(systemDataIt->accelerationFieldnames,
systemDataIt->state.a);
}
if (engineOptions_->telemetry.enableForceExternal)
{
for (std::size_t i = 1; i < systemDataIt->state.fExternal.size(); ++i)
{
auto const & fext = systemDataIt->state.fExternal[i].toVector();
for (uint8_t j = 0; j < 6U; ++j)
{
telemetrySender_.updateValue(
systemDataIt->forceExternalFieldnames[(i - 1) * 6U + j],
fext[j]);
}
}
}
if (engineOptions_->telemetry.enableCommand)
{
telemetrySender_.updateValue(systemDataIt->commandFieldnames,
systemDataIt->state.command);
}
if (engineOptions_->telemetry.enableMotorEffort)
{
telemetrySender_.updateValue(systemDataIt->motorEffortFieldnames,
systemDataIt->state.uMotor);
}
if (engineOptions_->telemetry.enableEnergy)
{
telemetrySender_.updateValue(systemDataIt->energyFieldname, energy);
}
systemIt->controller->updateTelemetry();
systemIt->robot->updateTelemetry();
}
// Flush the telemetry internal state
telemetryRecorder_->flushDataSnapshot(stepperState_.t);
}
void EngineMultiRobot::reset(bool_t const & resetRandomNumbers,
bool_t const & removeAllForce)
{
// Make sure the simulation is properly stopped
if (isSimulationRunning_)
{
stop();
}
// Clear log data buffer
logData_ = nullptr;
// Reset the dynamic force register if requested
if (removeAllForce)
{
for (auto & systemData : systemsDataHolder_)
{
systemData.forcesImpulse.clear();
systemData.forcesImpulseBreaks.clear();
systemData.forcesImpulseActive.clear();
systemData.forcesProfile.clear();
}
stepperUpdatePeriod_ = std::get<1>(isGcdIncluded(
engineOptions_->stepper.sensorsUpdatePeriod,
engineOptions_->stepper.controllerUpdatePeriod));
}
// Reset the random number generators
if (resetRandomNumbers)
{
resetRandomGenerators(engineOptions_->stepper.randomSeed);
}
// Reset the internal state of the robot and controller
for (auto & system : systems_)
{
system.robot->reset();
system.controller->reset();
}
// Clear system state buffers, since the robot kinematic may change
for (auto & systemData : systemsDataHolder_)
{
systemData.state.clear();
systemData.statePrev.clear();
}
isTelemetryConfigured_ = false;
}
void computeExtraTerms(systemHolder_t & system,
systemDataHolder_t const & /* systemData */)
{
/// This method is optimized to avoid redundant computations.
/// See `pinocchio::computeAllTerms` for reference:
///
/// Based on https://github.com/stack-of-tasks/pinocchio/blob/a1df23c2f183d84febdc2099e5fbfdbd1fc8018b/src/algorithm/compute-all-terms.hxx
///
/// Copyright (c) 2014-2020, CNRS
/// Copyright (c) 2018-2020, INRIA
pinocchio::Model const & model = system.robot->pncModel_;
pinocchio::Data & data = system.robot->pncData_;
/* Update manually the subtree (apparent) inertia, since it is only
computed by crba, which is doing more computation than necessary.
It will be used here for computing the centroidal kinematics, and
used later for joint bounds dynamics. Note that, by doing all the
computations here instead of 'computeForwardKinematics', we are
doing the assumption that it is varying slowly enough to consider
it constant during one integration step. */
if (!system.robot->hasConstraints())
{
for (int32_t i = 1; i < model.njoints; ++i)
{
data.Ycrb[i] = model.inertias[i];
}
for (int32_t i = model.njoints - 1; i > 0; --i)
{
jointIndex_t const & jointIdx = model.joints[i].id();
jointIndex_t const & parentIdx = model.parents[jointIdx];
if (parentIdx > 0)
{
data.Ycrb[parentIdx] += data.liMi[jointIdx].act(data.Ycrb[jointIdx]);
}
}
}
/* Neither 'aba' nor 'forwardDynamics' are computing simultaneously the actual
joint accelerations, joint forces and body forces, so it must be done separately:
- 1st step: computing the accelerations based on ForwardKinematic algorithm
- 2nd step: computing the forces based on rnea algorithm */
pinocchio_overload::forwardKinematicsAcceleration(model, data, data.ddq);
// Compute the spatial momenta and the sum of external forces acting on each body
data.h[0].setZero();
data.f[0].setZero();
for (int32_t i = 1; i < model.njoints; ++i)
{
data.h[i] = model.inertias[i] * data.v[i];
data.f[i] = model.inertias[i] * data.a[i] + data.v[i].cross(data.h[i]);
}
for (int32_t i = model.njoints - 1; i > 0; --i)
{
jointIndex_t const & parentIdx = model.parents[i];
data.h[parentIdx] += data.liMi[i].act(data.h[i]);
data.f[parentIdx] += data.liMi[i].act(data.f[i]);
}
/* Now that `data.Ycrb` and `data.h` are available, one can get directly
the position and velocity of the center of mass of each subtrees. */
for (int32_t i = 0; i < model.njoints; ++i)
{
data.com[i] = data.Ycrb[i].lever();
data.vcom[i].noalias() = data.h[i].linear() / data.mass[i];
}
data.com[0] = data.liMi[1].act(data.com[1]);
data.vcom[0].noalias() = data.h[0].linear() / data.mass[0];
// Compute centrodial dynamics and its derivative
data.hg = data.h[0];
data.hg.angular() += data.hg.linear().cross(data.com[0]);
data.dhg = data.f[0];
data.dhg.angular() += data.dhg.linear().cross(data.com[0]);
}
void computeAllExtraTerms(std::vector<systemHolder_t> & systems,
vector_aligned_t<systemDataHolder_t> const & systemsDataHolder)
{
auto systemIt = systems.begin();
auto systemDataIt = systemsDataHolder.begin();
for ( ; systemIt != systems.end(); ++systemIt, ++systemDataIt)
{
computeExtraTerms(*systemIt, *systemDataIt);
}
}
void syncAccelerationsAndForces(systemHolder_t const & system,
forceVector_t & f,
motionVector_t & a)
{
for (int32_t i = 0; i < system.robot->pncModel_.njoints; ++i)
{
f[i] = system.robot->pncData_.f[i];
a[i] = system.robot->pncData_.a[i];
}
}