forked from zhzhang0225/sampling_based_planners
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplanner.cpp
More file actions
executable file
·1188 lines (999 loc) · 38.5 KB
/
Copy pathplanner.cpp
File metadata and controls
executable file
·1188 lines (999 loc) · 38.5 KB
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
/*=================================================================
*
* planner.c
*
*=================================================================*/
#include <math.h>
#include "mex.h"
#include <random>
#include <iostream>
#include <math.h>
#include <vector>
#include <assert.h>
#include <time.h>
#include <stack>
#include <queue>
#include <unordered_map>
#include "rrt_tree.h"
#include "prm_graph.h"
/* Input Arguments */
#define MAP_IN prhs[0]
#define ARMSTART_IN prhs[1]
#define ARMGOAL_IN prhs[2]
#define PLANNER_ID_IN prhs[3]
/* Planner Ids */
#define RRT 0
#define RRTCONNECT 1
#define RRTSTAR 2
#define PRM 3
/* Output Arguments */
#define PLAN_OUT plhs[0]
#define PLANLENGTH_OUT plhs[1]
#define GETMAPINDEX(X, Y, XSIZE, YSIZE) (Y*XSIZE + X)
#if !defined(MAX)
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#endif
#if !defined(MIN)
#define MIN(A, B) ((A) < (B) ? (A) : (B))
#endif
#define PI 3.141592654
//the length of each link in the arm (should be the same as the one used in runtest.m)
#define LINKLENGTH_CELLS 10
typedef struct {
int X1, Y1;
int X2, Y2;
int Increment;
int UsingYIndex;
int DeltaX, DeltaY;
int DTerm;
int IncrE, IncrNE;
int XIndex, YIndex;
int Flipped;
} bresenham_param_t;
void ContXY2Cell(double x, double y, short unsigned int* pX, short unsigned int *pY, int x_size, int y_size)
{
double cellsize = 1.0;
//take the nearest cell
*pX = (int)(x/(double)(cellsize));
if( x < 0) *pX = 0;
if( *pX >= x_size) *pX = x_size-1;
*pY = (int)(y/(double)(cellsize));
if( y < 0) *pY = 0;
if( *pY >= y_size) *pY = y_size-1;
}
void get_bresenham_parameters(int p1x, int p1y, int p2x, int p2y, bresenham_param_t *params)
{
params->UsingYIndex = 0;
if (fabs((double)(p2y-p1y)/(double)(p2x-p1x)) > 1)
(params->UsingYIndex)++;
if (params->UsingYIndex)
{
params->Y1=p1x;
params->X1=p1y;
params->Y2=p2x;
params->X2=p2y;
}
else
{
params->X1=p1x;
params->Y1=p1y;
params->X2=p2x;
params->Y2=p2y;
}
if ((p2x - p1x) * (p2y - p1y) < 0)
{
params->Flipped = 1;
params->Y1 = -params->Y1;
params->Y2 = -params->Y2;
}
else
params->Flipped = 0;
if (params->X2 > params->X1)
params->Increment = 1;
else
params->Increment = -1;
params->DeltaX=params->X2-params->X1;
params->DeltaY=params->Y2-params->Y1;
params->IncrE=2*params->DeltaY*params->Increment;
params->IncrNE=2*(params->DeltaY-params->DeltaX)*params->Increment;
params->DTerm=(2*params->DeltaY-params->DeltaX)*params->Increment;
params->XIndex = params->X1;
params->YIndex = params->Y1;
}
void get_current_point(bresenham_param_t *params, int *x, int *y)
{
if (params->UsingYIndex)
{
*y = params->XIndex;
*x = params->YIndex;
if (params->Flipped)
*x = -*x;
}
else
{
*x = params->XIndex;
*y = params->YIndex;
if (params->Flipped)
*y = -*y;
}
}
int get_next_point(bresenham_param_t *params)
{
if (params->XIndex == params->X2)
{
return 0;
}
params->XIndex += params->Increment;
if (params->DTerm < 0 || (params->Increment < 0 && params->DTerm <= 0))
params->DTerm += params->IncrE;
else
{
params->DTerm += params->IncrNE;
params->YIndex += params->Increment;
}
return 1;
}
int IsValidLineSegment(double x0, double y0, double x1, double y1, double* map,
int x_size,
int y_size)
{
bresenham_param_t params;
int nX, nY;
short unsigned int nX0, nY0, nX1, nY1;
//printf("checking link <%f %f> to <%f %f>\n", x0,y0,x1,y1);
//make sure the line segment is inside the environment
if(x0 < 0 || x0 >= x_size ||
x1 < 0 || x1 >= x_size ||
y0 < 0 || y0 >= y_size ||
y1 < 0 || y1 >= y_size)
return 0;
ContXY2Cell(x0, y0, &nX0, &nY0, x_size, y_size);
ContXY2Cell(x1, y1, &nX1, &nY1, x_size, y_size);
//printf("checking link <%d %d> to <%d %d>\n", nX0,nY0,nX1,nY1);
//iterate through the points on the segment
get_bresenham_parameters(nX0, nY0, nX1, nY1, ¶ms);
do {
get_current_point(¶ms, &nX, &nY);
if(map[GETMAPINDEX(nX,nY,x_size,y_size)] == 1)
return 0;
} while (get_next_point(¶ms));
return 1;
}
int IsValidArmConfiguration(double* angles, int numofDOFs, double* map,
int x_size, int y_size)
{
double x0,y0,x1,y1;
int i;
//iterate through all the links starting with the base
x1 = ((double)x_size)/2.0;
y1 = 0;
for(i = 0; i < numofDOFs; i++)
{
//compute the corresponding line segment
x0 = x1;
y0 = y1;
x1 = x0 + LINKLENGTH_CELLS*cos(2*PI-angles[i]);
y1 = y0 - LINKLENGTH_CELLS*sin(2*PI-angles[i]);
//check the validity of the corresponding line segment
if(!IsValidLineSegment(x0,y0,x1,y1,map,x_size,y_size))
return 0;
}
return 1;
}
void incrementToJointAngles(int num_of_dof, double step_size, double** curr_ptr, std::vector<double>& goal)
{
for (int i = 0; i < num_of_dof; i++) {
double temp_dist = goal[i] - (*curr_ptr)[i];
if (temp_dist > 0.0) {
if (temp_dist < PI) (*curr_ptr)[i] += step_size;
// remember to wrap the angle between 0 and 2pi
else (*curr_ptr)[i] = (((*curr_ptr)[i] - step_size) > 0.0) ? ((*curr_ptr)[i] - step_size)
: (2*PI + (*curr_ptr)[i] - step_size);
}
else {
if (temp_dist > -PI) (*curr_ptr)[i] -= step_size;
// remember to wrap the angle between 0 and 2pi
else (*curr_ptr)[i] = (((*curr_ptr)[i] + step_size) < 2*PI) ? ((*curr_ptr)[i] + step_size)
: ((*curr_ptr)[i] + step_size - 2*PI);
}
//assert((*curr_ptr)[i] > 0.0 && (*curr_ptr)[i] < 2*PI);
}
return;
}
static void planner(
double* map,
int x_size,
int y_size,
double* armstart_anglesV_rad,
double* armgoal_anglesV_rad,
int numofDOFs,
double*** plan,
int* planlength)
{
//no plan by default
*plan = NULL;
*planlength = 0;
//for now just do straight interpolation between start and goal checking for the validity of samples
double distance = 0;
int i,j;
for (j = 0; j < numofDOFs; j++){
if(distance < fabs(armstart_anglesV_rad[j] - armgoal_anglesV_rad[j]))
distance = fabs(armstart_anglesV_rad[j] - armgoal_anglesV_rad[j]);
}
int numofsamples = (int)(distance/(PI/20));
if(numofsamples < 2){
printf("the arm is already at the goal\n");
return;
}
*plan = (double**) malloc(numofsamples*sizeof(double*));
int firstinvalidconf = 1;
for (i = 0; i < numofsamples; i++){
(*plan)[i] = (double*) malloc(numofDOFs*sizeof(double));
for(j = 0; j < numofDOFs; j++){
(*plan)[i][j] = armstart_anglesV_rad[j] + ((double)(i)/(numofsamples-1))*(armgoal_anglesV_rad[j] - armstart_anglesV_rad[j]);
}
if(!IsValidArmConfiguration((*plan)[i], numofDOFs, map, x_size, y_size) && firstinvalidconf)
{
firstinvalidconf = 1;
printf("ERROR: Invalid arm configuration!!!\n");
}
}
*planlength = numofsamples;
return;
}
double calculateCost(std::vector<double>& config1, std::vector<double>& config2)
{
// calcualte L1 cost between two configurations
assert(config1.size() == config2.size());
double total_cost = 0.0;
for (int i = 0; i < config1.size(); i++) {
total_cost += (fabs(config1[i]-config2[i])>PI) ? (2*PI-fabs(config1[i]-config2[i])) : fabs(config1[i]-config2[i]);
}
return total_cost;
}
static void plannerRRT(double* map,
int x_size,
int y_size,
double* armstart_anglesV_rad,
double* armgoal_anglesV_rad,
int numofDOFs,
double*** plan,
int* planlength)
{
if (!IsValidArmConfiguration(armstart_anglesV_rad, numofDOFs, map, x_size, y_size) ||
!IsValidArmConfiguration(armgoal_anglesV_rad, numofDOFs, map, x_size, y_size)) {
std::cout << "START or GOAL is in collision. Aborted!" << std::endl;
return;
}
std::uniform_real_distribution<double> goal_bias_generation(0.0, 1.0);
std::uniform_real_distribution<double> joint_ang_generation(0.0, 2*PI);
std::random_device rd;
std::default_random_engine generator(rd());
int epsilon = 60; //epsilon here specifies max. num of steps for each iteration
double step_size = PI/90;
int num_vertices = 0;
// Create tree object
RRTTree tree(numofDOFs);
// Add initial pose as vertex
std::vector<double> start_config(armstart_anglesV_rad, armstart_anglesV_rad+numofDOFs);
tree.addVertex(start_config);
tree.setVertexCost(tree.getNodeID()-1, 0.0);
num_vertices++;
// Create while loop until goal configuration is reached
bool goal_reached = false;
while (!goal_reached) {
// Initialize new/ sampled configuration
std::vector<double> new_config(numofDOFs);
// Introduce goal bias here
double bias = goal_bias_generation(generator);
if (bias > 0.80) {
// Set new_config to goal configuration
copy(armgoal_anglesV_rad, armgoal_anglesV_rad+numofDOFs, new_config.begin());
}
else {
// Sample new arm configuration
//new_config[0] = joint_ang_generation(generator)/2;
for (int i = 0; i < numofDOFs; i++)
new_config[i] = joint_ang_generation(generator);
}
// Find nearest neighbor
int nn_index = tree.getNearestVertex(new_config);
std::vector<double> nn_config = tree.getNodeConfig(nn_index);
if (bias < 0.80 && tree.calculateDistance(new_config, nn_config) < 0.10) continue;
// Attempt to extend to new sample
bool extend = true;
double* temp_config = &nn_config[0];
double* backup_config = (double*) malloc(numofDOFs*sizeof(double));
int step_count = 0;
while (extend) {
// save configuration before increment
copy(temp_config, temp_config+numofDOFs, backup_config);
// increment on each joint angle
incrementToJointAngles(numofDOFs, step_size, &temp_config, new_config);
// check collision
if (!IsValidArmConfiguration(temp_config, numofDOFs, map, x_size, y_size)) {
copy(backup_config, backup_config+numofDOFs, temp_config);
extend = false;
break;
}
step_count++;
if (step_count > epsilon) extend = false;
//vector<double> temp_config_vec(temp_config, temp_config+numofDOFs);
//else if (tree.calculateDistance(temp_config_vec, new_config) < 0.1) extend = false;
}
free(backup_config);
if (step_count > 0) {
// Update ACUTUAL new configuration
copy(temp_config, temp_config+numofDOFs, new_config.begin());
// Add new_config to the tree
tree.addVertex(new_config);
tree.addEdge(nn_index, tree.getNodeID()-1);
// Set cost for the new vertex
nn_config = tree.getNodeConfig(nn_index);
double cost_new = tree.getVertexCost(nn_index) + calculateCost(nn_config, new_config);
tree.setVertexCost(tree.getNodeID()-1, cost_new);
num_vertices++;
if (num_vertices % 1000 == 0) std::cout << "Num of Vertices: " << num_vertices << std::endl;
double dist_to_goal = 0.0;
for (int i = 0; i < numofDOFs; i++) {
double joint_dist = fabs(new_config[i] - armgoal_anglesV_rad[i]);
dist_to_goal += (joint_dist > PI) ? (2*PI-joint_dist) : joint_dist;
}
if (dist_to_goal < 0.1) goal_reached = true;
}
if (num_vertices > 50000) {
std::cout << "Aborted due to timeout ... Please re-plan" << std::endl;
break;
}
}
if (num_vertices <= 50000) {
std::cout << "generating the plan" << std::endl;
//back-track the path and return the plan
std::vector<int> plan_ids = tree.returnPlan();
int path_length = plan_ids.size();
*plan = (double**) malloc(path_length*sizeof(double*));
for (int i = 0; i < path_length; i++) {
(*plan)[i] = (double*) malloc(numofDOFs*sizeof(double));
std::vector<double> config = tree.getNodeConfig(plan_ids[path_length-i-1]);
//(*plan)[i] = &config[0]; is WRONG
// for(int j = 0; j < numofDOFs; j++) std::cout << config[j] << " ";
// std::cout << std::endl;
copy(config.begin(), config.end(), (*plan)[i]);
}
std::cout << "Cost to goal: " << tree.getVertexCost(tree.getNodeID()-1) << std::endl;
std::cout << "Number of vertices: " << num_vertices << std::endl;
*planlength = path_length;
}
return;
}
static void plannerRRTConnect(double* map,
int x_size,
int y_size,
double* armstart_anglesV_rad,
double* armgoal_anglesV_rad,
int numofDOFs,
double*** plan,
int* planlength)
{
if (!IsValidArmConfiguration(armstart_anglesV_rad, numofDOFs, map, x_size, y_size) ||
!IsValidArmConfiguration(armgoal_anglesV_rad, numofDOFs, map, x_size, y_size)) {
std::cout << "START or GOAL is in collision. Aborted!" << std::endl;
return;
}
// Generate sampling tool
std::uniform_real_distribution<double> goal_bias_generation(0.0, 1.0);
std::uniform_real_distribution<double> joint_ang_generation(0.0, 2*PI);
std::random_device rd;
std::default_random_engine generator(rd());
int epsilon = 30; //epsilon here specifies max. num of steps for each iteration
double step_size = PI/180;
int num_vertices = 0;
// Create tree objects
RRTTree tree_s(numofDOFs);
RRTTree tree_g(numofDOFs);
// Add initial pose as vertex
std::vector<double> start_config(armstart_anglesV_rad, armstart_anglesV_rad+numofDOFs);
std::vector<double> goal_config(armgoal_anglesV_rad, armgoal_anglesV_rad+numofDOFs);
tree_s.addVertex(start_config);
tree_g.addVertex(goal_config);
num_vertices += 2;
// Initialize new / sampled configurations
std::vector<double> new_config(numofDOFs);
std::vector<double> rand_config(numofDOFs);
// Initialize vector to store nearest neighbor's configuration
std::vector<double> nn_config(numofDOFs);
int nn_index = -1;
// Create while loop until the two trees are connected
bool connected = false;
int num_iterations = 0;
while (!connected) {
// if (num_iterations % 2 == 0)->Extend tree_s to q_rand; Extend tree_g to q_new
// if (num_iterations % 2 == 1)->Extend tree_g to q_rand; Extend tree_s to q_new
// Introduce goal bias here
double bias = goal_bias_generation(generator);
if (bias > 0.90) {
// Set rand_config to goal configuration
if (num_iterations % 2 == 0)
copy(armgoal_anglesV_rad, armgoal_anglesV_rad+numofDOFs, rand_config.begin());
else
copy(armstart_anglesV_rad, armstart_anglesV_rad+numofDOFs, rand_config.begin());
}
else {
// Sample new arm configuration
for (int i = 0; i < numofDOFs; i++)
rand_config[i] = joint_ang_generation(generator);
}
// Find nearest neighbor
if (num_iterations % 2 == 0) {
nn_index = tree_s.getNearestVertex(rand_config);
nn_config = tree_s.getNodeConfig(nn_index);
} else {
nn_index = tree_g.getNearestVertex(rand_config);
nn_config = tree_g.getNodeConfig(nn_index);
}
// Ignore sample that is too close to existing vertices
if (bias < 0.90 && tree_s.calculateDistance(rand_config, nn_config) < 0.20) continue;
// Attempt to extend to new sample
bool extend = true;
double* temp_config = &nn_config[0];
double* backup_config = (double*) malloc(numofDOFs*sizeof(double));
int step_count = 0;
while (extend) {
// save configuration before increment
copy(temp_config, temp_config+numofDOFs, backup_config);
// increment on each joint angle
incrementToJointAngles(numofDOFs, step_size, &temp_config, rand_config);
// check collision
if (!IsValidArmConfiguration(temp_config, numofDOFs, map, x_size, y_size)) {
copy(backup_config, backup_config+numofDOFs, temp_config);
break;
}
step_count++;
if (step_count > epsilon) extend = false;
}
// If not trapped...
if (step_count > 0) {
// Update ACUTUAL new configuration
copy(temp_config, temp_config+numofDOFs, new_config.begin());
if (num_iterations % 2 == 0) {
// Add new_config to the tree
tree_s.addVertex(new_config);
tree_s.addEdge(nn_index, tree_s.getNodeID()-1);
// Find nearest neighbor of new_config from tree_g
nn_index = tree_g.getNearestVertex(new_config);
nn_config = tree_g.getNodeConfig(nn_index);
} else {
// Add new_config to the tree
tree_g.addVertex(new_config);
tree_g.addEdge(nn_index, tree_g.getNodeID()-1);
// Find nearest neighbor of new_config from tree_s
nn_index = tree_s.getNearestVertex(new_config);
nn_config = tree_s.getNodeConfig(nn_index);
}
num_vertices++;
if (num_vertices % 100 == 0) std::cout << "Num of Vertices: " << num_vertices << std::endl;
// Attempt to extend to new sample
// Reset parameters
extend = true;
temp_config = &nn_config[0];
step_count = 0;
while (extend) {
// save configuration before increment
copy(temp_config, temp_config+numofDOFs, backup_config);
// increment on each joint angle
incrementToJointAngles(numofDOFs, step_size, &temp_config, new_config);
step_count++;
if (step_count > epsilon) extend = false;
// check collision
if (!IsValidArmConfiguration(temp_config, numofDOFs, map, x_size, y_size)) {
copy(backup_config, backup_config+numofDOFs, temp_config);
extend = false;
}
// check if two trees are connected
double dist_to_new = 0.0;
for (int i = 0; i < numofDOFs; i++) {
double joint_dist = fabs(new_config[i] - temp_config[i]);
dist_to_new += (joint_dist > PI) ? (2*PI-joint_dist) : joint_dist;
}
if (dist_to_new < 0.1) {
connected = true;
extend = false;
}
}
if (step_count > 0) {
// Update ACUTUAL new configuration
if (!connected) copy(temp_config, temp_config+numofDOFs, new_config.begin());
// Add new_config to the tree
if (num_iterations % 2 == 0) {
tree_g.addVertex(new_config);
tree_g.addEdge(nn_index, tree_g.getNodeID()-1);
} else {
tree_s.addVertex(new_config);
tree_s.addEdge(nn_index, tree_s.getNodeID()-1);
}
num_vertices++;
if (num_vertices % 100 == 0) std::cout << "Num of Vertices: " << num_vertices << std::endl;
}
}
// remember to free backup pointer
free(backup_config);
num_iterations++;
}
std::cout << "generating the plan" << std::endl;
//back-track the path and return the plan
std::vector<int> plan1_ids;
std::vector<int> plan2_ids;
if (num_iterations % 2 == 0) {
plan1_ids = tree_s.returnPlan(nn_index);
plan2_ids = tree_g.returnPlan();
} else {
plan1_ids = tree_s.returnPlan();
plan2_ids = tree_g.returnPlan(nn_index);
}
int path_length = plan1_ids.size() + plan2_ids.size();
double total_cost = 0.0;
std::vector<double> config;
std::vector<double> prev_config;
*plan = (double**) malloc(path_length*sizeof(double*));
for (int i = 0; i < plan1_ids.size(); i++) {
(*plan)[i] = (double*) malloc(numofDOFs*sizeof(double));
config = tree_s.getNodeConfig(plan1_ids[plan1_ids.size()-i-1]);
copy(config.begin(), config.end(), (*plan)[i]);
if (i > 0) total_cost += calculateCost(prev_config, config);
prev_config = config;
}
prev_config = tree_g.getNodeConfig(plan1_ids[0]);
for (int i = 0; i < plan2_ids.size(); i++) {
(*plan)[i+plan1_ids.size()] = (double*) malloc(numofDOFs*sizeof(double));
config = tree_g.getNodeConfig(plan2_ids[i]);
copy(config.begin(), config.end(), (*plan)[i+plan1_ids.size()]);
total_cost += calculateCost(prev_config, config);
prev_config = config;
}
std::cout << "Cost to goal: " << total_cost << std::endl;
std::cout << "Number of vertices: " << num_vertices << std::endl;
*planlength = path_length;
return;
}
bool isPathValid(std::vector<double> new_config, std::vector<double>& neighbor_config,
int numofDOFs, double* map, int x_size, int y_size)
{
double distance = 0;
for (int i = 0; i < numofDOFs; i++){
if(distance < fabs(new_config[i] - neighbor_config[i]))
distance = fabs(new_config[i] - neighbor_config[i]);
}
int numofsamples = (int)(distance/(PI/90));
if (numofsamples < 2) return true;
double* temp_config = &new_config[0];
for (int i = 0; i < numofsamples; i++) {
for (int i = 0; i < numofDOFs; i++) {
temp_config[i] += (neighbor_config[i] - new_config[i])/(double)numofsamples;
}
if (!IsValidArmConfiguration(temp_config, numofDOFs, map, x_size, y_size)) return false;
}
return true;
}
static void plannerRRTStar(double* map,
int x_size,
int y_size,
double* armstart_anglesV_rad,
double* armgoal_anglesV_rad,
int numofDOFs,
double*** plan,
int* planlength)
{
if (!IsValidArmConfiguration(armstart_anglesV_rad, numofDOFs, map, x_size, y_size) ||
!IsValidArmConfiguration(armgoal_anglesV_rad, numofDOFs, map, x_size, y_size)) {
std::cout << "START or GOAL is in collision. Aborted!" << std::endl;
return;
}
std::uniform_real_distribution<double> goal_bias_generation(0.0, 1.0);
std::uniform_real_distribution<double> joint_ang_generation(0.0, 2*PI);
std::random_device rd;
std::default_random_engine generator(rd());
int epsilon = 60; //epsilon here specifies max. num of steps for each iteration
double step_size = PI/90;
int num_vertices = 0;
// Create tree object
RRTTree tree(numofDOFs);
// Add initial pose as vertex
std::vector<double> start_config(armstart_anglesV_rad, armstart_anglesV_rad+numofDOFs);
tree.addVertex(start_config);
tree.setVertexCost(tree.getNodeID()-1, 0.0);
num_vertices++;
// Create while loop until goal configuration is reached
bool goal_reached = false;
while (!goal_reached) {
// Initialize new/ sampled configuration
std::vector<double> new_config(numofDOFs);
// Introduce goal bias here
double bias = goal_bias_generation(generator);
if (bias > 0.80) {
// Set new_config to goal configuration
copy(armgoal_anglesV_rad, armgoal_anglesV_rad+numofDOFs, new_config.begin());
}
else {
// Sample new arm configuration
for (int i = 0; i < numofDOFs; i++)
new_config[i] = joint_ang_generation(generator);
}
// Find nearest neighbor
int nn_index = tree.getNearestVertex(new_config);
std::vector<double> nn_config = tree.getNodeConfig(nn_index);
if (bias < 0.80 && tree.calculateDistance(new_config, nn_config) < 0.1) continue;
// Attempt to extend to new sample
bool extend = true;
double* temp_config = &nn_config[0];
double* backup_config = (double*) malloc(numofDOFs*sizeof(double));
int step_count = 0;
while (extend) {
// save configuration before increment
copy(temp_config, temp_config+numofDOFs, backup_config);
// increment on each joint angle
incrementToJointAngles(numofDOFs, step_size, &temp_config, new_config);
// check collision
if (!IsValidArmConfiguration(temp_config, numofDOFs, map, x_size, y_size)) {
copy(backup_config, backup_config+numofDOFs, temp_config);
extend = false;
}
else {
step_count++;
if (step_count > epsilon) extend = false;
}
}
free(backup_config);
if (step_count > 0) {
// Update ACUTUAL new configuration
copy(temp_config, temp_config+numofDOFs, new_config.begin());
// Add new_config to the tree
tree.addVertex(new_config);
num_vertices++;
if (num_vertices % 1000 == 0) std::cout << "Num of Vertices: " << num_vertices << std::endl;
// Add cost of new vertex
nn_config = tree.getNodeConfig(nn_index);
double cost_new = tree.getVertexCost(nn_index) + calculateCost(nn_config, new_config);
tree.setVertexCost(tree.getNodeID()-1, cost_new);
// Find all neighbors within certain distance from new_config
double radius = 1.6*pow(log(num_vertices)/num_vertices, 1/numofDOFs); //epsilon * step_size;
std::vector<int> near_neighbors = tree.getNearVertices(nn_index, radius);
//if (num_vertices % 1000 == 0) std::cout << "Num of near neighbors: " << near_neighbors.size() << std::endl;
// Try to find best parent for new config
// (Is there better path to get ot new vertex from existing neighbors)
std::vector<double> neighbor_config;
int min_neighbor_id = nn_index;
// record indices of valid neighbors of new config (i.e. collision-free)
std::vector<int> valid_neighbor_id;
for (int i = 0; i < near_neighbors.size(); i++) {
neighbor_config = tree.getNodeConfig(near_neighbors[i]);
if (isPathValid(new_config, neighbor_config, numofDOFs, map, x_size, y_size)) {
double cost_temp = tree.getVertexCost(near_neighbors[i]) + calculateCost(new_config, neighbor_config);
if (cost_temp + 0.1 < cost_new) {
// record index of x_min
min_neighbor_id = near_neighbors[i];
// update cost of new vertex
cost_new = cost_temp;
tree.setVertexCost(tree.getNodeID()-1, cost_new);
}
valid_neighbor_id.push_back(near_neighbors[i]);
}
}
// Add edge for new vertex now
tree.addEdge(min_neighbor_id, tree.getNodeID()-1);
// Try to update cost of each vertex
// (Is there better path (through new vertex) to some existing neighbor w/lower cost)
for (int i = 0; i < valid_neighbor_id.size(); i++) {
if (valid_neighbor_id[i] != min_neighbor_id) {
neighbor_config = tree.getNodeConfig(valid_neighbor_id[i]);
double cost_temp = cost_new + calculateCost(new_config, neighbor_config);
// In case cost(near) > cost(new) + cost(new,near)
// If so, disconnect existing node and its parent AND add new edges
if (cost_temp + 0.1 < tree.getVertexCost(valid_neighbor_id[i])) {
// update neighbor's cost
tree.setVertexCost(valid_neighbor_id[i], cost_temp);
// remove connection (edge) between the neighbor and its parent
tree.removeEdge(valid_neighbor_id[i]);
// add connection (edge) between the neighbor and new vertex
tree.addEdge(tree.getNodeID()-1, valid_neighbor_id[i]);
}
}
}
// Check whether we reach the goal
double dist_to_goal = 0.0;
for (int i = 0; i < numofDOFs; i++) {
double joint_dist = fabs(new_config[i] - armgoal_anglesV_rad[i]);
dist_to_goal += (joint_dist > PI) ? (2*PI-joint_dist) : joint_dist;
}
if (dist_to_goal < 0.1) goal_reached = true;
}
if (num_vertices > 50000) {
std::cout << "Aborted due to timeout ... Please re-plan" << std::endl;
break;
}
}
if (num_vertices <= 50000) {
std::cout << "generating the plan" << std::endl;
//back-track the path and return the plan
std::vector<int> plan_ids = tree.returnPlan();
int path_length = plan_ids.size();
*plan = (double**) malloc(path_length*sizeof(double*));
for (int i = 0; i < path_length; i++) {
(*plan)[i] = (double*) malloc(numofDOFs*sizeof(double));
std::vector<double> config = tree.getNodeConfig(plan_ids[path_length-i-1]);
copy(config.begin(), config.end(), (*plan)[i]);
}
std::cout << "Cost to goal: " << tree.getVertexCost(tree.getNodeID()-1) << std::endl;
std::cout << "Number of vertices: " << num_vertices << std::endl;
*planlength = path_length;
}
return;
}
static void plannerPRM(double* map,
int x_size,
int y_size,
double* armstart_anglesV_rad,
double* armgoal_anglesV_rad,
int numofDOFs,
double*** plan,
int* planlength)
{
/********************Building Roadmap************************/
std::uniform_real_distribution<double> joint_ang_generation(0.0, 2*PI);
std::random_device rd;
std::default_random_engine generator(rd());
// Create graph object
PRMGraph graph(numofDOFs);
// K specifies number of neighbors we try to connect with new vertex
int K = 10;
int num_vertices = 0;
bool extend = true;
double* new_config = (double*) malloc(numofDOFs*sizeof(double));
while (extend) {
// Random sampling for new vertex/configuration
for (int i = 0; i < numofDOFs; i++) new_config[i] = joint_ang_generation(generator);
// Check if new vertex/configuration is valid (collision-free)
if (IsValidArmConfiguration(new_config, numofDOFs, map, x_size, y_size)) {
// Add new vertex to graph
std::vector<double> new_vertex(5,0.0);
copy(new_config, new_config+numofDOFs, new_vertex.begin());
graph.addVertex(new_vertex);
num_vertices++;
if (num_vertices > 100) {
// Find neighbors of new vertex in the graph
std::vector<int> knn_id = graph.findKNN(new_vertex, K);
// Check if the path from new vertex to the neighbor is valid (collision-free)
std::vector<double> neighbor_vertex;
for (int i = 0; i < knn_id.size(); i++) {
neighbor_vertex = graph.getNodeConfig(knn_id[i]);
// If valid, add edge between new vertex and the neighbor in the graph
if (isPathValid(new_vertex, neighbor_vertex, numofDOFs, map, x_size, y_size))
graph.addEdge(knn_id[i], graph.getCurrentNodeID()-1);
}
}
}
//if (num_vertices%100 == 0) std::cout << num_vertices << std::endl;
if (num_vertices >= 5000) extend = false;
}
free(new_config);
std::cout << "Roadmap construction is completed. Searching for path now." << std::endl;
/********************Searching Path*************************/
std::vector<double> start_config(armstart_anglesV_rad, armstart_anglesV_rad + numofDOFs);
std::vector<double> goal_config(armgoal_anglesV_rad, armgoal_anglesV_rad + numofDOFs);
int start_on_graph_id = graph.getNearestVertex(start_config);
int goal_on_graph_id = graph.getNearestVertex(goal_config);
std::vector<double> start_on_graph = graph.getNodeConfig(start_on_graph_id);
std::vector<double> goal_on_graph = graph.getNodeConfig(goal_on_graph_id);
if (!isPathValid(start_config, start_on_graph, numofDOFs, map, x_size, y_size)) {
std::cout << "Cannot connect START to the graph...Please re-plan." << std::endl;
return;
}
if (!isPathValid(goal_config, goal_on_graph, numofDOFs, map, x_size, y_size)) {
std::cout << "Cannot connect GOAL to the graph...Please re-plan." << std::endl;
return;
}
// Perform Depth-First Search
/********************************************************************
std::stack<int> DFS_stack;
DFS_stack.push(start_on_graph_id);
bool goal_reached = false;
if (start_on_graph_id == goal_on_graph_id) goal_reached = true;
// Create dictionary with key = node_id (visited) and value = parent_id
std::unordered_map<int, int> node_info;
int curr_id;
while (!goal_reached && !DFS_stack.empty()) {
// Get the vertex at the top of stack
curr_id = DFS_stack.top();
DFS_stack.pop();
vector<int> curr_neighbors = graph.getNeighborsID(curr_id);
// Add neighbors to the stack
for (int i = 0; i < curr_neighbors.size(); i++) {
if (curr_neighbors[i] == goal_on_graph_id) {
node_info[goal_on_graph_id] = curr_id;
goal_reached = true;
break;
}
else if (node_info.find(curr_neighbors[i]) == node_info.end()) {
node_info[curr_neighbors[i]] = curr_id;
DFS_stack.push(curr_neighbors[i]);
}
}
}
********************************************************************/
// Perform Breath-First Search
std::queue<int> BFS_queue;
BFS_queue.push(start_on_graph_id);
bool goal_reached = false;
if (start_on_graph_id == goal_on_graph_id) goal_reached = true;
// Create dictionary with key = node_id (visited) and value = parent_id
std::unordered_map<int, int> node_info;
int curr_id;
while (!goal_reached && !BFS_queue.empty()) {
// Get the vertex at the top of stack
curr_id = BFS_queue.front();
BFS_queue.pop();
vector<int> curr_neighbors = graph.getNeighborsID(curr_id);
// Add neighbors to the stack
for (int i = 0; i < curr_neighbors.size(); i++) {
if (curr_neighbors[i] == goal_on_graph_id) {
node_info[goal_on_graph_id] = curr_id;
goal_reached = true;
break;
}
else if (node_info.find(curr_neighbors[i]) == node_info.end()) {
node_info[curr_neighbors[i]] = curr_id;
BFS_queue.push(curr_neighbors[i]);
}
}