-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplanner.cpp
More file actions
418 lines (355 loc) · 11 KB
/
planner.cpp
File metadata and controls
418 lines (355 loc) · 11 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
/*=================================================================
*
* planner.c
*
*=================================================================*/
#include <math.h>
#include <random>
#include <vector>
#include <array>
#include <algorithm>
#include <chrono>
#include <tuple>
#include <string>
#include <stdexcept>
#include <regex> // For regex and split logic
#include <iostream> // cout, endl
#include <fstream> // For reading/writing files
#include <assert.h>
#include "kataArmPlanner.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
#define LINKLENGTH_CELLS 10
// Some potentially helpful imports
using std::vector;
using std::array;
using std::string;
using std::runtime_error;
using std::tuple;
using std::make_tuple;
using std::tie;
using std::cout;
using std::endl;
/// @brief
/// @param filepath
/// @return map, x_size, y_size
tuple<double*, int, int> loadMap(string filepath) {
std::FILE *f = fopen(filepath.c_str(), "r");
if (f) {
}
else {
printf("Opening file failed! \n");
throw runtime_error("Opening map file failed!");
}
int height, width;
if (fscanf(f, "height %d\nwidth %d\n", &height, &width) != 2) {
throw runtime_error("Invalid loadMap parsing map metadata");
}
////// Go through file and add to m_occupancy
double* map = new double[height*width];
double cx, cy, cz;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
char c;
do {
if (fscanf(f, "%c", &c) != 1) {
throw runtime_error("Invalid parsing individual map data");
}
} while (isspace(c));
if (!(c == '0')) {
map[y+x*width] = 1; // Note transposed from visual
} else {
map[y+x*width] = 0;
}
}
}
fclose(f);
return make_tuple(map, width, height);
}
// Splits string based on deliminator
vector<string> split(const string& str, const string& delim) {
// https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c/64886763#64886763
const std::regex ws_re(delim);
return { std::sregex_token_iterator(str.begin(), str.end(), ws_re, -1), std::sregex_token_iterator() };
}
double* doubleArrayFromString(string str) {
vector<string> vals = split(str, ",");
double* ans = new double[vals.size()];
for (int i = 0; i < vals.size(); ++i) {
ans[i] = std::stod(vals[i]);
}
return ans;
}
bool equalDoubleArrays(double* v1, double *v2, int size) {
for (int i = 0; i < size; ++i) {
if (abs(v1[i]-v2[i]) > 1e-3) {
cout << endl;
return false;
}
}
return true;
}
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;
}
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,
int whichPlanner=0 //defaulting to RRT
)
{
auto start = std::chrono::high_resolution_clock::now();
//no plan by default
*plan = NULL;
*planlength = 0;
std::vector<arm_state*> plan_vec;
// plan_vec.push_back(new arm_state()); // populated by the planner.
if(1 == whichPlanner)
{
rrt_connect rrt_conn = rrt_connect(map, x_size,y_size,armstart_anglesV_rad,armgoal_anglesV_rad,numofDOFs,plan, planlength);
rrt_conn.run_rrt_connect_planner();
plan_vec = rrt_conn.get_plan();
}
else if (2 == whichPlanner)
{
rrt_star rrt_str = rrt_star(map, x_size,y_size,armstart_anglesV_rad,armgoal_anglesV_rad,numofDOFs,plan, planlength);
rrt_str.build_rrt();
plan_vec = rrt_str.get_plan();
}
else if (3 == whichPlanner)
{
prm prm_planner = prm(map, x_size,y_size,armstart_anglesV_rad,armgoal_anglesV_rad,numofDOFs,plan, planlength);
prm_planner.build_roadmap();
prm_planner.generate_plan();
plan_vec = prm_planner.get_path();
}
else //default to RRT (also case 0)
{
rrt rrt_planner = rrt(map, x_size,y_size,armstart_anglesV_rad,armgoal_anglesV_rad,numofDOFs,plan, planlength);
rrt_planner.build_rrt();
plan_vec = rrt_planner.get_plan();
}
//populates final plan parameters in final format
*planlength = plan_vec.size();
*plan = (double**) malloc(plan_vec.size()*sizeof(double*));
for (int i = 0; i < plan_vec.size(); i++)
{
(*plan)[i] = (double*) malloc(numofDOFs*sizeof(double));
for(int j = 0; j < numofDOFs; j++)
{
(*plan)[i][j] = plan_vec[i]->get_angle(j);
}
}
auto finish = std::chrono::high_resolution_clock::now();
auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);
std::cout << "Done. (" << double(microseconds.count())/double(1000000) << " seconds)" << std::endl;
return;
}
/** Your final solution will be graded by an grading script which will
* send the default 6 arguments:
* map, numOfDOFs, commaSeparatedStartPos, commaSeparatedGoalPos,
* whichPlanner, outputFilePath
* An example run after compiling and getting the planner.out executable
* >> ./planner.out map1.txt 5 1.57,0.78,1.57,0.78,1.57 0.392,2.35,3.14,2.82,4.71 0 output.txt
* See the hw handout for full information.
* If you modify this for testing (e.g. to try out different hyper-parameters),
* make sure it can run with the original 6 commands.
* Programs that do not will automatically get a 0.
* */
int main(int argc, char** argv) {
double* map;
int x_size, y_size;
tie(map, x_size, y_size) = loadMap(argv[1]);
const int numOfDOFs = std::stoi(argv[2]);
double* startPos = doubleArrayFromString(argv[3]);
double* goalPos = doubleArrayFromString(argv[4]);
int whichPlanner = std::stoi(argv[5]);
string outputFile = argv[6];
if(!IsValidArmConfiguration(startPos, numOfDOFs, map, x_size, y_size)||
!IsValidArmConfiguration(goalPos, numOfDOFs, map, x_size, y_size)) {
throw runtime_error("Invalid start or goal configuration!\n");
}
///////////////////////////////////////
//// Feel free to modify anything below. Be careful modifying anything above.
double** plan = NULL;
int planlength = 0;
planner(map, x_size, y_size, startPos, goalPos, numOfDOFs, &plan, &planlength, whichPlanner);
//// Feel free to modify anything above.
//// If you modify something below, please change it back afterwards as my
//// grading script will not work and you will recieve a 0.
///////////////////////////////////////
// Your solution's path should start with startPos and end with goalPos
if (!equalDoubleArrays(plan[0], startPos, numOfDOFs) ||
!equalDoubleArrays(plan[planlength-1], goalPos, numOfDOFs)) {
throw std::runtime_error("Start or goal position not matching");
}
/** Saves the solution to output file
* Do not modify the output log file output format as it is required for visualization
* and for grading.
*/
std::ofstream m_log_fstream;
m_log_fstream.open(outputFile, std::ios::trunc); // Creates new or replaces existing file
if (!m_log_fstream.is_open()) {
throw std::runtime_error("Cannot open file");
}
m_log_fstream << argv[1] << endl; // Write out map name first
/// Then write out all the joint angles in the plan sequentially
for (int i = 0; i < planlength; ++i) {
for (int k = 0; k < numOfDOFs; ++k) {
m_log_fstream << plan[i][k] << ",";
}
m_log_fstream << endl;
}
}