-
Notifications
You must be signed in to change notification settings - Fork 1
/
hte.cpp
2209 lines (1768 loc) · 86.8 KB
/
hte.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 <csignal>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <assert.h>
#include <stdio.h>
#include <math.h>
#include <chrono>
#include <robot_dart/robot_dart_simu.hpp>
#include <robot_dart/control/pd_control.hpp>
#include <hexa_control.hpp>
#include <limbo/limbo.hpp>
#include <map_elites/binary_map.hpp> // to load in archive_file (behavioural repertoire) from MAPELITES
#include <mcts/uct.hpp>
#include <svg/simple_svg.hpp>
#include <boost/program_options.hpp>
#include <astar/a_star.hpp>
#include <algorithm>
// #ifdef GRAPHIC
// #include <robot_dart/graphics/graphics.hpp>
#include <robot_dart/gui/magnum/graphics.hpp>
#include <robot_dart/gui/magnum/windowless_graphics.hpp>
// #endif
#include <dart/collision/bullet/BulletCollisionDetector.hpp>
#include <dart/constraint/ConstraintSolver.hpp>
#include"hbr_loading.hpp"
#include <hbr/Leg/fit_hexa_leg.hpp>
#include <hbr/Body_Acc/fit_hexa_body_gp.hpp>
#include <hbr/Omnidirectional/fit_mt_me.hpp>
#include <hbr/HBR/quality_diversity_hbr.hpp>
#include <valgrind/callgrind.h>
#ifdef HBR
#define ARCHIVE_SIZE 2
#else
#ifdef LOW_DIM
#define ARCHIVE_SIZE 2
#else
#define ARCHIVE_SIZE 8
#endif
#endif
using namespace limbo ; // for limbo objects and functions dont have to keep typing limbo::
template <typename T> // gaussaion_used in HexaState.move -
inline T gaussian_rand(T m = 0.0, T v = 1.0)
{
static std::random_device rd;
static std::mt19937 gen(rd());
std::normal_distribution<T> gaussian(m, v);
return gaussian(gen);
}// gaussian_rand
// b-a - function that obtains angle difference between the arrival_angle and the desired angle, used to compute the performance/fitness - used in HexaState
double angle_dist(double a, double b)
{
double theta = b - a;
while (theta < -M_PI)
theta += 2 * M_PI;
while (theta > M_PI)
theta -= 2 * M_PI;
return theta;
}// angle_dist
struct Params {
struct uct {
MCTS_DYN_PARAM(double, c);
};
struct spw {
MCTS_DYN_PARAM(double, a);
};
struct cont_outcome {
MCTS_DYN_PARAM(double, b);
};
struct mcts_node {
MCTS_DYN_PARAM(size_t, parallel_roots);
};
struct active_learning {
MCTS_DYN_PARAM(double, k);
MCTS_DYN_PARAM(double, scaling);
};
MCTS_DYN_PARAM(double, goal_x);
MCTS_DYN_PARAM(double, goal_y);
MCTS_DYN_PARAM(double, goal_theta);
MCTS_DYN_PARAM(double, iterations);
MCTS_DYN_PARAM(bool, learning);
MCTS_DYN_PARAM(size_t, collisions);
MCTS_PARAM(double, threshold, 1e-2);
MCTS_PARAM(double, cell_size, 0.5);
MCTS_PARAM(double, robot_radius, 0.25); //hexpod radius maximum value
struct kernel_exp {
BO_PARAM(double, l,0.03);
BO_PARAM(double, sigma_sq, 0.01);
}; //kernel_exp
struct kernel : public defaults::kernel {
BO_PARAM(double, noise, 0.001);
}; // kernel - from new version of limbo
struct archiveparams { // used to extract and store the data from the archive file from MAPELITES
struct elem_archive {
double x, y, cos_theta, sin_theta; //extracts and store behaviroual descriptor and performance
std::vector<double> controller; //to store the controller (motor parameters corresponding to the behaviorual descriptor
}; //elem_archive
struct classcomp {
bool operator()(const std::vector<double>& lhs, const std::vector<double>& rhs) const
{
assert(lhs.size() == ARCHIVE_SIZE && rhs.size() == ARCHIVE_SIZE);
int i = 0;
while (i < (ARCHIVE_SIZE - 1) && std::round(lhs[i] * 1000) == std::round(rhs[i] * 1000)) //lhs[i]==rhs[i])
i++;
return std::round(lhs[i] * 1000) < std::round(rhs[i] * 1000); //lhs[i]<rhs[i];
}
}; //classcomp
struct classcompequal {
bool operator()(const Eigen::VectorXd& lhs, const Eigen::VectorXd& rhs) const
{
assert(lhs.size() == ARCHIVE_SIZE && rhs.size() == ARCHIVE_SIZE);
int i = 0;
while (i < (ARCHIVE_SIZE - 1) && std::round(lhs[i] * 1000) == std::round(rhs[i] * 1000)) //lhs[i]==rhs[i])
i++;
return std::round(lhs[i] * 1000) == std::round(rhs[i] * 1000); //lhs[i]<rhs[i];
}
}; //classcompequal
using archive_t = std::map<std::vector<double>, elem_archive, classcomp>;
static archive_t archive;
}; //archive_params
}; //Params
template <typename Params>
struct MeanArchive {
MeanArchive(size_t dim_out = 4)
{
}
template <typename GP>
Eigen::VectorXd operator()(const Eigen::VectorXd& v, const GP&) const
{
Eigen::VectorXd r(4);
std::vector<double> vv(v.size(), 0.0);
Eigen::VectorXd::Map(&vv[0], v.size()) = v;
typename Params::archiveparams::elem_archive elem = Params::archiveparams::archive[vv];
r << elem.x, elem.y, elem.cos_theta, elem.sin_theta;
return r;
}
}; // MeanArchive
struct SimpleObstacle { // struct for generating obtaining the position of the obstacles from the map
double _x, _y, _radius, _radius_sq;
SimpleObstacle(double x, double y, double r = 0.1) : _x(x), _y(y), _radius(r), _radius_sq(r * r) {}
}; //SimpleObstacle
struct BoxObstacle { // struct for generating obtaining the position of the obstacles from the map
double start_x, start_y, end_x, end_y, _height;
Eigen::Vector3d size(){
Eigen::Vector3d final_size;
final_size << end_x-start_x,end_y-start_y,_height;
return final_size;
}
Eigen::Vector6d pose(){
Eigen::Vector6d final_pose;
//center of box is used to place the box!
final_pose << 0.0,0.0,0.0,(end_x+start_x)/2,(end_y+start_y)/2,0;
return final_pose;
}
double width(){
if(start_x<end_x)
return (end_x-start_x);
else
return (start_x-end_x);
}
double height(){
if(start_y<end_y)
return (end_y-start_y);
else
return (start_y-end_y);
}
double x(){
if(start_x<end_x){
return start_x;
}
return end_x;
}
double y(){
if(start_y<end_y){
return start_y;
}
return end_y;
}
double c_x(){
return (end_x+start_x)/2;
}
double c_y(){
return (end_y+start_y)/2;
}
BoxObstacle(double x1, double y1, double x2, double y2,double height=0.9) : start_x(x1), start_y(y1), end_x(x2), end_y(y2), _height(height) {}
}; //BoxObstacle
using kernel_t = kernel::Exp<Params>; // kernel is under namespace limbo in limbo.hpp - limbo::kernel::Exp
using mean_t = MeanArchive<Params>; // MeanArchive is written above
using GP_t = model::GP<Params, kernel_t, mean_t>; //model is under namespace limbo in limbo.hpp - limbo::model::GP
struct Low_Params{
struct kernel_exp {
BO_PARAM(double, l, 0.1);
BO_PARAM(double, sigma_sq, 0.02);
}; //kernel_exp
struct kernel : public defaults::kernel {
BO_PARAM(double, noise, 0.001);
}; // kernel - from new version of limbo
struct kernel_squared_exp_ard : public defaults::kernel_squared_exp_ard {
};
struct opt_rprop : public defaults::opt_rprop {
};
struct kernel_maternfivehalves : public defaults::kernel_maternfivehalves {
BO_PARAM(double, noise, 0.02);
BO_PARAM(double, sigma_sq, 0.05);
BO_PARAM(double, l, 1.0);
};
};
//Params for the Trial and Error Process between Layers
using kernel_low_t = kernel::MaternFiveHalves<Low_Params>;// kernel is under namespace limbo in limbo.hpp - limbo::kernel::Exp
using mean_low_t = mean::Data<Low_Params>;
using GP_low_t = model::GP<Low_Params, kernel_low_t, mean_low_t>; //model is under namespace limbo in limbo.hpp - limbo::model::GP
bool collides(double x, double y, double r = Params::robot_radius());
namespace global {
//Gaussian Process Definition for Planning with RTE
GP_t gp_model(ARCHIVE_SIZE, 4);
//Gaussian Process Definition for the Trial and Error Process between Layers
GP_low_t gp_low_model(9, 3);
std::shared_ptr<robot_dart::Robot> global_robot, simulated_robot; // simulated_robot is the clone of global_robot used for simulation
Eigen::Vector3d robot_pose;
std::vector<SimpleObstacle> obstacles;
std::vector<BoxObstacle> box_obstacles;
size_t height, width, entity_size, map_size, map_size_x, map_size_y;
svg::Dimensions dimensions;
std::shared_ptr<svg::Document> doc;
size_t target_num;
std::vector<std::string> dofs;
robot_dart::RobotDARTSimu simu(0.001);
// statistics
std::ofstream robot_file, ctrl_file, iter_file, misc_file,dmg_file;
double time_random_search = 0.0;
int n_policies_called = 0,n_random_policies_called=0;
int damaged_leg;
int rep_nr=0;
} //namespace global
// Stat GP - to save/write the gp.dat - used in reach_targets function
void write_gp(std::string filename)
{
std::ofstream ofs;
ofs.open(filename);
typedef typename Params::archiveparams::archive_t::const_iterator archive_it_t;
for (archive_it_t it = Params::archiveparams::archive.begin(); it != Params::archiveparams::archive.end(); it++) {
Eigen::VectorXd desc = Eigen::VectorXd::Map(it->first.data(), it->first.size());
Eigen::VectorXd mu;
double sigma;
std::tie(mu, sigma) = global::gp_model.query(desc);
ofs << desc.transpose() << " "
<< mu.transpose() << " "
<< sigma << std::endl;
}
ofs.close();
} //write-gp
std::shared_ptr<robot_dart::Robot> box(size_t num, double x_pos, double y_pos, double x_dim, double y_dim, double height)
{
// random pose
Eigen::Vector6d pose = Eigen::Vector6d::Random();
// make sure it is above the ground
pose(0) = 0 ;
pose(1) = 0 ;
pose(2) = 0 ;
pose(3) = x_pos ;
pose(4) = y_pos ;
pose(5) = 0 ;
// random size
Eigen::Vector3d size = Eigen::Vector3d::Random().array() * Eigen::Vector3d(0.1, 0.2, 0.1).array() + 0.3;
size(0) = x_dim ;
size(1) = y_dim ;
size(2) = height ;
//red coloured box - create_box function found in robot_dart robot.cpp file
//return robot_dart::Robot::create_box(size, pose, "free", 1., dart::Color::Red(1.0), "box_" + std::to_string(num)); //"free" - the block can be pushed around and can fly
return robot_dart::Robot::create_box(size, pose, "fixed", 1., dart::Color::Red(1.0), "box_" + std::to_string(num)); //"fixed" - fixed at its position. not free to move.
} //box
std::shared_ptr<robot_dart::Robot> sphere(size_t num = 0)
{
// random pose
Eigen::Vector6d pose = Eigen::Vector6d::Random();
// make sure it is above the ground
pose(5) = 1.0;
// random size
Eigen::Vector3d size = Eigen::Vector3d::Random()[0] * Eigen::Vector3d(0.2, 0.2, 0.2).array() + 0.3;
// blue colored sphere - create_ellipsoid function found in robot_dart robot.cpp file
return robot_dart::Robot::create_ellipsoid(size, pose, "free", 1., dart::Color::Blue(1.0), "sphere_" + std::to_string(num));
} // sphere
//collision version for boxes
bool collides(double x, double y,double r)
{
double distance_x = 0,distance_y=0, cDist_sq = 0;
for (size_t i = 0; i < global::box_obstacles.size(); i++) {
distance_x = abs(x - (global::box_obstacles[i].c_x()));
distance_y = abs(y - (global::box_obstacles[i].c_y()));
if (distance_x > (global::box_obstacles[i].width()/2 + r)) { continue; }
if (distance_y > (global::box_obstacles[i].height()/2 + r)) { continue; }
if (distance_x <= (global::box_obstacles[i].width()/2)) { return true; }
if (distance_y <= (global::box_obstacles[i].height()/2)) { return true; }
cDist_sq = std::pow((distance_x - (global::box_obstacles[i].width()/2)),2) + std::pow((distance_y - (global::box_obstacles[i].height()/2)),2);
if(cDist_sq <= (r*r)){
return true;
}
}
return false;
} // collides
bool intersect_segment(double x1, double y1,double x2, double y2, double x3, double y3,double x4, double y4){
double t = (((x1-x3)*(y3-y4))-((y1-y3)*(x3-x4)))/(((x1-x2)*(y3-y4))-((y1-y2)*(x3-x4)));
double u = (((x1-x3)*(y1-y2))-((y1-y3)*(x1-x2)))/(((x1-x2)*(y3-y4))-((y1-y2)*(x3-x4)));
if(u<1 && u>0 && t<1 && t>0){
return true;
}
return false;
}
//collision version for boxes
bool collides_segment(const Eigen::Vector2d& start, const Eigen::Vector2d& end)
{
for (size_t i = 0; i < global::box_obstacles.size(); i++) {
bool l1 = intersect_segment(global::box_obstacles[i].start_x,global::box_obstacles[i].start_y,global::box_obstacles[i].start_x,global::box_obstacles[i].end_y, start(0),start(1), end(0),end(1));
bool l2 = intersect_segment(global::box_obstacles[i].start_x,global::box_obstacles[i].start_y,global::box_obstacles[i].end_x,global::box_obstacles[i].start_y, start(0),start(1), end(0),end(1));
bool l3 = intersect_segment(global::box_obstacles[i].end_x,global::box_obstacles[i].end_y,global::box_obstacles[i].end_x,global::box_obstacles[i].start_y, start(0),start(1), end(0),end(1));
bool l4 = intersect_segment(global::box_obstacles[i].end_x,global::box_obstacles[i].end_y,global::box_obstacles[i].start_x,global::box_obstacles[i].end_y, start(0),start(1), end(0),end(1));
if (l1||l2||l3||l4){
return true;
}
}
return false;
} // collides_box_segment
//collision version for boxes
bool collides(const Eigen::Vector2d& start, const Eigen::Vector2d& end, double r = Params::robot_radius())
{
Eigen::Vector2d dir = end - start;
Eigen::Vector2d perp = Eigen::Vector2d(-dir(1), dir(0));
Eigen::Vector2d A = start + perp * r;
Eigen::Vector2d B = end + perp * r;
Eigen::Vector2d C = end - perp * r;
Eigen::Vector2d D = start - perp * r;
return (collides(start(0), start(1),r) || collides(end(0), end(1),r) || collides_segment(A, B) || collides_segment(B, C) || collides_segment(C, D) || collides_segment(D, A));
} //collides
bool astar_collides(int x, int y, int x_new, int y_new) // used in Default Policy
{
Eigen::Vector2d s(x * Params::cell_size(), y * Params::cell_size());
Eigen::Vector2d t(x_new * Params::cell_size(), y_new * Params::cell_size());
return collides(s, t, Params::robot_radius() * 1.3);//We Multiply the Robot Radius with a Scaling Factor be on the safe side for collisions in A-Star
} //astar_collides
bool check_rotation(robot_dart::RobotDARTSimu* simu){
dart::dynamics::BodyNode* base_link_body_node = simu->robots().back()->body_node("base_link");
Eigen::Matrix3d rot = base_link_body_node->getTransform().linear();
// Then Rotation coordinates
Eigen::Vector3d forward_direction = rot.col(0);
Eigen::Vector3d left_direction = rot.col(1);
Eigen::Vector3d up_direction = rot.col(2);
Eigen::Vector3d u_z{0., 0., 1.};
// u_r and u_theta -> Cylindrical coordinate system
Eigen::Vector3d u_r{forward_direction(0), forward_direction(1), 0.};
u_r = u_r.normalized();
Eigen::Vector3d u_theta = u_z.cross(u_r);
auto abs_pitch_angle = static_cast<float>(
acos(forward_direction.dot(u_z)));
auto abs_roll_angle = static_cast<float>(
acos(u_theta.dot(left_direction)));
auto abs_yaw_angle = static_cast<float>(
acos(u_r.dot(Eigen::Vector3d(1., 0., 0.)))
);
// Get values of angles depending on the direction of the vector
float pitch_angle;
float roll_angle;
float yaw_angle;
if (u_z.dot(up_direction) > 0.) {
pitch_angle = abs_pitch_angle;
} else {
pitch_angle = -1.f * abs_pitch_angle;
}
if (u_theta.dot(up_direction) < 0.) {
roll_angle = abs_roll_angle;
} else {
roll_angle = -1.f * abs_roll_angle;
}
if (u_r.dot(Eigen::Vector3d(0., 1., 0.)) > 0) {
yaw_angle = abs_yaw_angle;
} else {
yaw_angle = -1.f * abs_yaw_angle;
}
if(pitch_angle > M_PI_4 && pitch_angle < 3*M_PI_4){
if(roll_angle > -M_PI_4 && roll_angle < M_PI_4){
return true;
}
else
return false;
}
else
return false;
}
template <typename State, typename Action>
struct DefaultPolicy {
Action operator()(const State* state, bool draw = false)
{
size_t N = 100;
double dx = state->_x - Params::goal_x();
double dy = state->_y - Params::goal_y();
double d = dx * dx + dy * dy;
if (d <= Params::cell_size() * Params::cell_size()) {
Action best_action;
double best_value = std::numeric_limits<double>::max();
for (size_t i = 0; i < N; i++) {
Action act = state->random_action();
auto final = state->move(act, true);
double dx = final._x - Params::goal_x();
double dy = final._y - Params::goal_y();
double val = dx * dx + dy * dy;
if (collides(final._x, final._y))
val = std::numeric_limits<double>::max();
if (best_action._desc.size() == 0 || val < best_value) {
best_value = val;
best_action = act;
}
}
return best_action;
}
astar::AStar<> a_star;
astar::Node ss(std::round(state->_x / Params::cell_size()), std::round(state->_y / Params::cell_size()), global::map_size_x, global::map_size_y);
if (collides(ss._x * Params::cell_size(), ss._y * Params::cell_size()) || ss._x <= 0 || ss._x >= int(global::map_size_x) || ss._y <= 0 || ss._y >= int(global::map_size_y)) {
astar::Node best_root = ss;
bool changed = false;
double val = std::numeric_limits<double>::max();
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0)
continue;
int x_new = ss._x + i;
int y_new = ss._y + j;
double dx = x_new * Params::cell_size() - state->_x;
double dy = y_new * Params::cell_size() - state->_y;
double v = dx * dx + dy * dy;
if (!collides(x_new * Params::cell_size(), y_new * Params::cell_size()) && x_new > 0 && x_new < int(global::map_size_x) && y_new > 0 && y_new < int(global::map_size_y) && v < val) {
best_root._x = x_new;
best_root._y = y_new;
val = v;
changed = true;
}
}
}
if (!changed)
state->random_action();
ss = best_root;
}
astar::Node ee(std::round(Params::goal_x() / Params::cell_size()), std::round(Params::goal_y() / Params::cell_size()), global::map_size_x, global::map_size_y);
auto path = a_star.search(ss, ee, astar_collides, global::map_size_x, global::map_size_y);
if (path.size() < 2) {
// std::cout << "Error: A* path size less than 2: " << path.size() << ". Returning random action!" << std::endl;
return state->random_action();
}
astar::Node best = path[1];
// Find best action
Eigen::Vector2d best_pos(best._x * Params::cell_size(), best._y * Params::cell_size());
Eigen::Vector2d init_vec = Eigen::Vector2d(state->_x, state->_y);
// First check if we have clean path
if (path.size() >= 3 && (best_pos - init_vec).norm() < Params::cell_size()) {
Eigen::Vector2d new_pos(path[2]._x * Params::cell_size(), path[2]._y * Params::cell_size());
if (!collides(init_vec, new_pos, 1.5 * Params::robot_radius())) {
best = path[2];
best_pos = new_pos;
}
}
// We are going to just use the best from sampled actions
// Put best position better in space (to avoid collisions) if we are not in a safer region
if (collides(best_pos(0), best_pos(1), 2.0 * Params::robot_radius())) {
SimpleObstacle closest_obs(0, 0, 0);
double closet_dist = std::numeric_limits<double>::max();
for (auto obs : global::obstacles) {
double dx = best_pos(0) - obs._x;
double dy = best_pos(1) - obs._y;
double v = dx * dx + dy * dy;
if (v < closet_dist) {
closet_dist = v;
closest_obs = obs;
}
}
Eigen::Vector2d dir_to_obs = best_pos - Eigen::Vector2d(closest_obs._x, closest_obs._y);
Eigen::Vector2d new_best = best_pos;
double step = Params::cell_size();
size_t n = 0;
bool b = false;
do {
new_best = best_pos.array() + (n + 1) * step * dir_to_obs.array();
n++;
b = collides(new_best(0), new_best(1), 2.0 * Params::robot_radius());
} while (b && n < 10);
if (n < 10)
best_pos = new_best;
}
Action best_action;
double best_value = std::numeric_limits<double>::max();
std::vector<double> goal_action;
N = 100;
for (size_t i = 0; i < N; i++) {
goal_action = {best_pos(0),best_pos(1)};
//If we want to find the closest next action (deterministic) then this is similar to A-Star without MCTS
// Action act = state->closest_action(goal_action);
Action act = state->random_action();
auto final = state->move(act, true);
double dx = final._x - best_pos(0);
double dy = final._y - best_pos(1);
double val = dx * dx + dy * dy;
if (collides(final._x, final._y))
{
val = std::numeric_limits<double>::max();
}
if (best_action._desc.size()==0 || val < best_value) {
best_value = val;
best_action = act;
}
}
return best_action;
}
};//Default Policy
template <typename Params>
struct HexaAction {
Eigen::VectorXd _desc;
HexaAction() {}
HexaAction(Eigen::VectorXd desc) : _desc(desc) {}
bool operator==(const HexaAction& other) const
{
return (typename Params::archiveparams::classcompequal()(_desc, other._desc));
}
};
template <typename Params>
struct HexaState {
double _x, _y, _theta;
static constexpr double _epsilon = 1e-3;
HexaState()
{
_x = _y = _theta = 0;
}
HexaState(double x, double y, double theta)
{
_x = x;
_y = y;
_theta = theta;
}
bool valid(const HexaAction<Params>& act) const
{
if(act._desc.size()==0)
{
std::cout<<"INVALID DESC"<<std::endl;
return false;
}
return true;
}
HexaAction<Params> next_action() const
{
global::n_policies_called +=1;
return DefaultPolicy<HexaState<Params>, HexaAction<Params>>()(this);
}
//Function returns the action that is closest to the goal direction, useful if we don't want to randomly sample solutions for MCTS
HexaAction<Params> closest_action(std::vector<double> goal) const
{
typedef typename Params::archiveparams::archive_t::const_iterator archive_it_t;
HexaAction<Params> act,best_action;
double best_value = std::numeric_limits<double>::max();
Eigen::VectorXd desc;
for (archive_it_t possible_action =Params::archiveparams::archive.begin() ; possible_action != Params::archiveparams::archive.end(); possible_action++){
desc = Eigen::VectorXd::Map(possible_action->first.data(), possible_action->first.size());
act._desc = desc;
auto final = this->move(act,true);;
double dx = final._x - goal[0];
double dy = final._y - goal[1];
double val = dx * dx + dy * dy;
if (collides(final._x, final._y))
{
val = std::numeric_limits<double>::max();
}
if (best_action._desc.size()==0 || val < best_value) {
best_value = val;
best_action = act;
}
}
return best_action;
}
HexaAction<Params> random_action() const
{
global::n_random_policies_called +=1;
static tools::rgen_int_t rgen(0, Params::archiveparams::archive.size() - 1);
typedef typename Params::archiveparams::archive_t::const_iterator archive_it_t;
HexaAction<Params> act;
double time_running = 0.0;
do {
auto t1 = std::chrono::steady_clock::now();
archive_it_t it = Params::archiveparams::archive.begin();
std::advance(it, rgen.rand());
time_running = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - t1).count();
Eigen::VectorXd desc = Eigen::VectorXd::Map(it->first.data(), it->first.size());
act._desc = desc;
} while (!valid(act));
global::time_random_search += time_running;
return act;
}
HexaState move(const HexaAction<Params>& action, bool no_noise = false) const
{
double x_new, y_new, theta_new;
Eigen::VectorXd mu;
double sigma;
std::tie(mu, sigma) = global::gp_model.query(action._desc);
if (!no_noise) {
mu(0) = std::max(-1.5, std::min(1.5, gaussian_rand(mu(0), sigma)));
mu(1) = std::max(-1.5, std::min(1.5, gaussian_rand(mu(1), sigma)));
mu(2) = std::max(-1.0, std::min(1.0, gaussian_rand(mu(2), sigma)));
mu(3) = std::max(-1.0, std::min(1.0, gaussian_rand(mu(3), sigma)));
}
double theta = std::atan2(mu(3), mu(2));
double c = std::cos(_theta), s = std::sin(_theta);
Eigen::MatrixXd tr(3, 3);
tr << c, -s, _x, s, c, _y, 0, 0, 1;
Eigen::Vector3d tr_pos;
tr_pos << mu(0), mu(1), 1.0;
tr_pos = tr * tr_pos;
x_new = tr_pos(0);
y_new = tr_pos(1);
theta_new = _theta + theta;
while (theta_new < -M_PI)
theta_new += 2 * M_PI;
while (theta_new > M_PI)
theta_new -= 2 * M_PI;
return HexaState(x_new, y_new, theta_new);
}
bool terminal() const
{
// Check if state is outside of bounds
if (_x < 0.0 || _x >= global::map_size_x * Params::cell_size() || _y < 0.0 || _y >= global::map_size_y * Params::cell_size())
{
//std::cout<<"--A--"<<std::endl;
return true;
}
// Check if state is goal
if (goal())
{
//std::cout<<"--B--"<<std::endl;
return true;
}
// Check if state is colliding
if (collides(_x, _y))
{
//std::cout<<"--C--"<<std::endl;
return true;
}
return false;
}
bool goal() const
{
double dx = _x - Params::goal_x();
double dy = _y - Params::goal_y();
double threshold_xy = Params::cell_size() * Params::cell_size() / 4.0;
if ((dx * dx + dy * dy) < threshold_xy)
return true;
return false;
}
bool operator==(const HexaState& other) const
{
double dx = _x - other._x;
double dy = _y - other._y;
double dth = std::abs(angle_dist(other._theta, _theta));
return ((dx * dx + dy * dy) < (Params::cell_size() * Params::cell_size() / 4.0) && dth < 0.3);
}
}; //HexaState
struct RewardFunction {
template <typename State>
double operator()(std::shared_ptr<State> from_state, HexaAction<Params> action, std::shared_ptr<State> to_state)
{
// Check if state is outside of bounds
if (to_state->_x < 0.0 || to_state->_x >= global::map_size_x * Params::cell_size() || to_state->_y < 0.0 || to_state->_y >= global::map_size_y * Params::cell_size())
return -1000.0;
// Return values
if (collides(to_state->_x, to_state->_y) || collides(Eigen::Vector2d(from_state->_x, from_state->_y), Eigen::Vector2d(to_state->_x, to_state->_y)))
return -1000.0;
if (to_state->goal())
return 100.0;
return 0.0;
}
}; // RewardFunction
std::map<std::vector<double>, Params::archiveparams::elem_archive, Params::archiveparams::classcomp> load_archive(std::string archive_name)
{
std::map<std::vector<double>, Params::archiveparams::elem_archive, Params::archiveparams::classcomp> archive;
size_t lastindex = archive_name.find_last_of(".");
std::string extension = archive_name.substr(lastindex + 1);
std::cout << "Loading text file..." << std::endl;
std::ifstream monFlux(archive_name.c_str());
if (monFlux) {
std::string line;
while (std::getline(monFlux, line)) {
std::istringstream iss(line);
std::vector<double> numbers;
double num;
while (iss >> num) {
numbers.push_back(num);
}
int init_i = 0;
if (numbers.size() > 39)
init_i = 1;
Params::archiveparams::elem_archive elem;
std::vector<double> candidate(ARCHIVE_SIZE);
int size_data = 45;//36+8+1
#ifdef HBR
{
size_data = 7;
init_i = 1;
}
#endif
for (int i = 0; i < size_data; i++) {
if(ARCHIVE_SIZE == 8){
double data = numbers[init_i + i];
if (i == 0) {
candidate[i] = data;
elem.x = (data*3)-1.5 ;// The BD score is normalized so we need to put it back into Xreal x,y coordinates
}
if (i == 1) {
candidate[i] = data;
elem.y = (data*3)-1.5 ;// The BD score is normalized so we need to put it back into Xreal x,y coordinates
}
if (i<8){
candidate[i] = data;
}
if (i == 8) {
elem.cos_theta = std::cos(data) ;
elem.sin_theta = std::sin(data) ;
}
if (i >= 9){
elem.controller.push_back(data);
}
if (elem.controller.size() == 36) {
archive[candidate] = elem;
}
}
else{
double data = numbers[init_i + i];
if (i == 0) {
#ifndef HBR
candidate[i] = data;
elem.x = (data*3)-1.5; // The BD score is normalized so we need to put it back into Xreal x,y coordinates
#else
candidate[i] = data;
elem.x = (data*3)-1.5;// The BD score is normalized so we need to put it back into Xreal x,y coordinates
#endif
}
if (i == 1) {
#ifndef HBR
candidate[i] = data;
elem.y = (data*3)-1.5;// The BD score is normalized so we need to put it back into Xreal x,y coordinates
#else
candidate[i] = data;
elem.y = (data*3)-1.5;// The BD score is normalized so we need to put it back into Xreal x,y coordinates
#endif
}
if (i == 2) {
elem.cos_theta = std::cos(data) ;
elem.sin_theta = std::sin(data) ;
}
if (i >= 3){
elem.controller.push_back(data);
}
#ifndef HBR
if (elem.controller.size() == 36) {
archive[candidate] = elem;
}
#else
if (elem.controller.size() == 4) {
archive[candidate] = elem;
}
#endif
}
}
}
}
else {
std::cerr << "ERROR: Could not load the archive." << std::endl;
return archive;
}
std::cout << archive.size() << " elements loaded" << std::endl;
return archive;
}
void execute(const Eigen::VectorXd& desc, double t, bool stat = true)
{
/*This function executes a desired descriptor desc for a given time duration t with a flat repertoire.*/
std::cout<< "Beginning execute function" << std::endl ;
std::vector<double> d(desc.size(), 0.0);
Eigen::VectorXd::Map(d.data(), d.size()) = desc;
std::ofstream ofs;
ofs.open("exp/HTE/visualise_MCTS/execute.dat", std::ios_base::app);
ofs << desc.transpose() << " " << std::endl;
ofs.close();
std::cout<<"EXECUTED DESC: "<<desc.transpose()<<std::endl;
std::vector<double> ctrl = Params::archiveparams::archive[d].controller;
for(double& d:ctrl){
std::cout << d << " " ;
d = round( d * 1000.0 ) / 1000.0;// limite numerical issues
}
std::cout << std::endl ;
double* ptr = &ctrl[0];
Eigen::Map<Eigen::VectorXd> new_ctrl(ptr, ctrl.size());
if (stat) {
// statistics - descriptor
for (int i = 0; i < desc.size(); i++)
global::ctrl_file << desc(i) << " ";
global::ctrl_file << std::endl;
}
static auto init_trans = global::simu.robots().back()->skeleton()->getPositions();
// Run the controller
double ctrl_dt = 0.01;
global::simulated_robot->add_controller(std::make_shared<robot_dart::control::HexaControl>(ctrl_dt, new_ctrl,global::dofs));
std::static_pointer_cast<robot_dart::control::HexaControl>(global::simulated_robot->controllers()[0])->set_h_params(Eigen::VectorXd::Ones(1) * ctrl_dt);
// std::static_pointer_cast<robot_dart::control::HexaControl>(global::simulated_robot->controllers()[0])->set_broken(std::vector<int>(1,4));
global::simu.run(t);
global::simulated_robot->remove_controller(0);
Eigen::Vector3d final_pos;
Eigen::Vector3d final_rot;
double arrival_angle;
double covered_distance;
auto pose = global::simu.robots().back()->skeleton()->getPositions();
Eigen::Matrix3d rot = dart::math::expMapRot({pose[0], pose[1], pose[2]});
Eigen::Matrix3d init_rot = dart::math::expMapRot({init_trans[0], init_trans[1], init_trans[2]});
Eigen::MatrixXd init_homogeneous(4, 4);
init_homogeneous << init_rot(0, 0), init_rot(0, 1), init_rot(0, 2), init_trans[3], init_rot(1, 0), init_rot(1, 1), init_rot(1, 2), init_trans[4], init_rot(2, 0), init_rot(2, 1), init_rot(2, 2), init_trans[5], 0, 0, 0, 1;
Eigen::MatrixXd final_homogeneous(4, 4);
final_homogeneous << rot(0, 0), rot(0, 1), rot(0, 2), pose[3], rot(1, 0), rot(1, 1), rot(1, 2), pose[4], rot(2, 0), rot(2, 1), rot(2, 2), pose[5], 0, 0, 0, 1;
Eigen::Vector4d pos = {init_trans[3], init_trans[4], init_trans[5], 1.0};
pos = init_homogeneous.inverse() * final_homogeneous * pos;
final_pos = pos.head(3);
covered_distance = std::round(final_pos(0) * 100) / 100.0;
// Angle computation
final_rot = dart::math::matrixToEulerXYZ(init_rot.inverse() * rot);
// roll-pitch-yaw
arrival_angle = std::round(final_rot(2) * 100) / 100.0;
std::cout <<"final_pos: " <<"x: "<< final_pos(0) << " y: "<< final_pos(1)<< "->"<< arrival_angle <<std::endl ;
// If the robot tries to fall or collides
size_t n = 0;
while (covered_distance < -10000.0 && n < 10) {
// try to stabilize the robot
global::simulated_robot->skeleton()->setPosition(0, 0.0);
global::simulated_robot->skeleton()->setPosition(1, 0.0);
global::simulated_robot->skeleton()->setPosition(5, 0.2);
global::simulated_robot->skeleton()->setVelocities(Eigen::VectorXd::Zero(global::simulated_robot->skeleton()->getVelocities().size()));
global::simulated_robot->skeleton()->setAccelerations(Eigen::VectorXd::Zero(global::simulated_robot->skeleton()->getAccelerations().size()));
global::simulated_robot->skeleton()->clearExternalForces();
global::simulated_robot->skeleton()->clearInternalForces();
global::simulated_robot->add_controller(std::make_shared<robot_dart::control::HexaControl>(ctrl_dt, Eigen::VectorXd(36).setZero(),global::dofs)); // neutral position controller
std::static_pointer_cast<robot_dart::control::HexaControl>(global::simulated_robot->controllers()[0])->set_h_params(Eigen::VectorXd::Ones(1) * ctrl_dt);
global::simu.run(1.0) ; // global::simu.run(1.0, true, false);
global::simulated_robot->remove_controller(0);
n++;
}