forked from justinhj/astar-algorithm-cpp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAStarPython.cpp
More file actions
606 lines (484 loc) · 21.1 KB
/
AStarPython.cpp
File metadata and controls
606 lines (484 loc) · 21.1 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
#include <iostream>
#include <vector>
#include <tuple>
#include <stdio.h>
#include <math.h>
#include "stlastar.h"
#include "MapSearchNode.h"
#include "MapInfo.h"
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "get_combination.h"
#include "find_path.h"
#include "smooth_path.h"
#include <chrono>
#include "ThreadPool.h"
#include <future>
#include <tbb/parallel_for.h>
#include <tbb/task_arena.h>
/*
FindPathOneByOne: Find all the collision-free paths consecutively, i.e. the paths from a0~t0, t0~t1, t1~t2, ...
Input:
agent_position: 1D integer array [x, y] for the agent position
targets_position: 1D integer array [x0,y0, x1,y1, x2,y2, ...] for the targets positions
world_map: 1D integer array for the map, flattened by a 2D array map; 0 for no obstacles, 255 for obstacles
mapSizeX: integer for the width of the map
mapSizeY: integer for the height of the map
Output:
path: 2D integer array for all the index paths, [[idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], [idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], ...]
distance: 1D float array for all the distances of the paths
*/
inline std::tuple<std::vector<std::vector<int>>, std::vector<float>> FindPathOneByOne(
const std::vector<int> &agent_position,
const std::vector<int> &targets_position,
const std::vector<int> &world_map,
const int &map_width,
const int &map_height)
{
std::vector<std::vector<int>> path_many;
std::vector<float> distances_many;
int start[2];
int goal[2];
struct MapInfo Map;
Map.world_map = world_map;
Map.map_width = map_width;
Map.map_height = map_height;
if (targets_position.size() > 0) {
// start is agent_position, goal is the first two elements of targets_position, doing the search
goal[0] = targets_position[0];
goal[1] = targets_position[1];
auto [path, distance] = find_path(agent_position.data(), goal, Map);
path_many.push_back(path);
distances_many.push_back(distance);
// Regenerate the neighbors for next run
for (size_t idx = 2; idx < targets_position.size(); idx = idx + 2) {
goal[0] = targets_position[idx];
goal[1] = targets_position[idx+1];
start[0] = targets_position[idx-2];
start[1] = targets_position[idx-1];
// start is the previous target, goal is the current target, doing the search
auto [path, distance] = find_path(start, goal, Map);
path_many.push_back(path);
distances_many.push_back(distance);
}
}
// if targets_position is empty, return empty arrays
return {path_many, distances_many};
}
/*
FindPathAllTBB: The Intel TBB version of FindPathAll: Find all the collision-free paths from every element to another element in start+targets.
targets_position potentially contains a large number of targets.
Input:
agent_position: 1D integer vector [x, y] for the agent position
targets_position: 1D integer vector [x0,y0, x1,y1, x2,y2, ...] for the targets positions
world_map: 1D integer vector for the map, flattened by a 2D vector map; 0 for no obstacles, 255 for obstacles
mapSizeX: integer for the width of the map
mapSizeY: integer for the height of the map
Output:
path: 2D integer vector for all the index paths, [[idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], [idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], ...]
distance: 1D float vector for all the distances of the paths
*/
inline std::tuple<std::vector<std::vector<int>>, std::vector<float>> FindPathAllTBB(
const std::vector<int> agent_position,
const std::vector<int> targets_position,
const std::vector<int> &world_map,
int &map_width,
int &map_height)
{
// release GIL for true parallelism
pybind11::gil_scoped_release release;
struct MapInfo Map;
Map.world_map = world_map;
Map.map_width = map_width;
Map.map_height = map_height;
int num_targets = targets_position.size()/2;
std::vector<int> start_goal_pair = get_combination(num_targets+1, 2);
size_t n_pairs = start_goal_pair.size() / 2;
std::vector<std::vector<int>> path_all(n_pairs);
std::vector<float> distance_all(n_pairs);
// NOTE: for Intel CPUs, e.g., Intel® Core™ i7-13700
// there are 8 Performance-cores and 8 Efficient-cores.
// So the total number of threads is 2*8 + 8 = 24, which is
// what arena(tbb::task_arena::automatic) does. (using arena.max_concurrency() = 24)
// But I found out that when n_pairs is large, on the order of 5k+,
// only using performance threads is faster.
// That means we may need to manually set num_threads as 2*8 = 16.
// TBB arena: use all cores
// tbb::task_arena arena(tbb::task_arena::automatic);
tbb::task_arena arena(16);
// std::cout << "num_threads (tbb::task_arena::automatic): " << arena.max_concurrency() << std::endl;
// parallelly executed
arena.execute([&] {
tbb::parallel_for(size_t(0), n_pairs, [&](size_t k) {
size_t idx = 2 * k;
int start_idx = start_goal_pair[idx];
int goal_idx = start_goal_pair[idx + 1];
int start[2], goal[2];
if (start_idx != 0) {
start[0] = targets_position[2 * (start_idx - 1)];
start[1] = targets_position[2 * (start_idx - 1) + 1];
} else {
start[0] = agent_position[0];
start[1] = agent_position[1];
}
if (goal_idx != 0) {
goal[0] = targets_position[2 * (goal_idx - 1)];
goal[1] = targets_position[2 * (goal_idx - 1) + 1];
} else {
goal[0] = agent_position[0];
goal[1] = agent_position[1];
}
auto [path_this, distance] = find_path(start, goal, Map);
// each parallel task writes into its own index
path_all[k] = std::move(path_this);
distance_all[k] = distance;
});
});
return {path_all, distance_all};
}
/*
FindPathAllMT: The multi-threading version of FindPathAll: Find all the collision-free paths from every element to another element in start+targets.
targets_position potentially contains a large number of targets.
Input:
agent_position: 1D integer vector [x, y] for the agent position
targets_position: 1D integer vector [x0,y0, x1,y1, x2,y2, ...] for the targets positions
world_map: 1D integer vector for the map, flattened by a 2D vector map; 0 for no obstacles, 255 for obstacles
mapSizeX: integer for the width of the map
mapSizeY: integer for the height of the map
Output:
path: 2D integer vector for all the index paths, [[idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], [idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], ...]
distance: 1D float vector for all the distances of the paths
*/
inline std::tuple<std::vector<std::vector<int>>, std::vector<float>> FindPathAllMT(
const std::vector<int> agent_position,
const std::vector<int> targets_position,
const std::vector<int> &world_map,
int &map_width,
int &map_height)
{
// release GIL for true parallelism
pybind11::gil_scoped_release release;
struct MapInfo Map;
Map.world_map = world_map;
Map.map_width = map_width;
Map.map_height = map_height;
int num_targets = targets_position.size()/2;
std::vector<int> start_goal_pair = get_combination(num_targets+1, 2);
size_t n_pairs = start_goal_pair.size() / 2;
std::vector<std::vector<int>> path_all(n_pairs);
std::vector<float> distance_all(n_pairs);
// choose number of threads
// NOTE: for Intel CPUs, e.g., Intel® Core™ i7-13700
// there are 8 Performance-cores and 8 Efficient-cores.
// So the total number of threads is 2*8 + 8 = 24, which is
// what std::thread::hardware_concurrency() returns.
// But I found out that when n_pairs is large, on the order of 5k+,
// only using performance threads is faster.
// That means we may need to manually set num_threads as 2*8 = 16.
// size_t num_threads = std::thread::hardware_concurrency();
size_t num_threads = 16;
// std::cout << "num_threads: " << num_threads << std::endl;
if (num_threads == 0) num_threads = 4;
ThreadPool pool(num_threads);
std::vector<std::future<void>> futures;
futures.reserve(n_pairs);
// parallel: submit tasks
for (size_t k = 0; k < n_pairs; ++k)
{
futures.emplace_back(pool.enqueue([&, k] {
size_t idx = 2 * k;
int start_idx = start_goal_pair[idx];
int goal_idx = start_goal_pair[idx + 1];
int start[2], goal[2];
if (start_idx != 0) {
start[0] = targets_position[2 * (start_idx - 1)];
start[1] = targets_position[2 * (start_idx - 1) + 1];
} else {
start[0] = agent_position[0];
start[1] = agent_position[1];
}
if (goal_idx != 0) {
goal[0] = targets_position[2 * (goal_idx - 1)];
goal[1] = targets_position[2 * (goal_idx - 1) + 1];
} else {
goal[0] = agent_position[0];
goal[1] = agent_position[1];
}
auto [path_this, distance] = find_path(start, goal, Map);
path_all[k] = std::move(path_this);
distance_all[k] = distance;
}));
}
// Wait for all tasks
for (auto &f : futures) f.get();
return {path_all, distance_all};
}
/*
FindPathAllMP: The openMP version of FindPathAll: Find all the collision-free paths from every element to another element in start+targets.
targets_position potentially contains a large number of targets.
Input:
agent_position: 1D integer vector [x, y] for the agent position
targets_position: 1D integer vector [x0,y0, x1,y1, x2,y2, ...] for the targets positions
world_map: 1D integer vector for the map, flattened by a 2D vector map; 0 for no obstacles, 255 for obstacles
mapSizeX: integer for the width of the map
mapSizeY: integer for the height of the map
Output:
path: 2D integer vector for all the index paths, [[idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], [idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], ...]
distance: 1D float vector for all the distances of the paths
*/
inline std::tuple<std::vector<std::vector<int>>, std::vector<float>> FindPathAllMP(
const std::vector<int> agent_position,
const std::vector<int> targets_position,
const std::vector<int> &world_map,
int &map_width,
int &map_height)
{
// release GIL for true parallelism
pybind11::gil_scoped_release release;
struct MapInfo Map;
Map.world_map = world_map;
Map.map_width = map_width;
Map.map_height = map_height;
int num_targets = targets_position.size()/2;
std::vector<int> start_goal_pair = get_combination(num_targets+1, 2);
size_t n_pairs = start_goal_pair.size() / 2;
std::vector<std::vector<int>> path_all(n_pairs);
std::vector<float> distance_all(n_pairs);
#pragma omp parallel for schedule(dynamic)
for (size_t idx = 0; idx < n_pairs; idx++)
{
int start_idx = start_goal_pair[2*idx];
int goal_idx = start_goal_pair[2*idx+1];
int start[2];
int goal[2];
if (start_idx != 0)
{
start[0] = targets_position[2*(start_idx-1)];
start[1] = targets_position[2*(start_idx-1)+1];
}
else
{
start[0] = agent_position[0];
start[1] = agent_position[1];
}
if (goal_idx != 0)
{
goal[0] = targets_position[2*(goal_idx-1)];
goal[1] = targets_position[2*(goal_idx-1)+1];
}
else
{
goal[0] = agent_position[0];
goal[1] = agent_position[1];
}
auto [path_this, distance] = find_path(start, goal, Map);
path_all[idx] = std::move(path_this);
distance_all[idx] = distance;
}
return {path_all, distance_all};
}
/*
FindPathAll: Find all the collision-free paths from every element to another element in start+targets.
Input:
agent_position: 1D integer vector [x, y] for the agent position
targets_position: 1D integer vector [x0,y0, x1,y1, x2,y2, ...] for the targets positions
world_map: 1D integer vector for the map, flattened by a 2D vector map; 0 for no obstacles, 255 for obstacles
mapSizeX: integer for the width of the map
mapSizeY: integer for the height of the map
Output:
path: 2D integer vector for all the index paths, [[idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], [idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], ...]
distance: 1D float vector for all the distances of the paths
*/
inline std::tuple<std::vector<std::vector<int>>, std::vector<float>> FindPathAll(
const std::vector<int> agent_position,
const std::vector<int> targets_position,
const std::vector<int> &world_map,
int &map_width,
int &map_height)
{
struct MapInfo Map;
Map.world_map = world_map;
Map.map_width = map_width;
Map.map_height = map_height;
int num_targets = targets_position.size()/2;
std::vector<int> start_goal_pair = get_combination(num_targets+1, 2);
std::vector<std::vector<int>> path_all;
std::vector<float> distance_all;
int start[2];
int goal[2];
for (unsigned long idx = 0; idx < start_goal_pair.size(); idx = idx + 2)
{
int start_idx = start_goal_pair[idx];
int goal_idx = start_goal_pair[idx+1];
if (start_idx != 0)
{
start[0] = targets_position[2*(start_idx-1)];
start[1] = targets_position[2*(start_idx-1)+1];
}
else
{
start[0] = agent_position[0];
start[1] = agent_position[1];
}
if (goal_idx != 0)
{
goal[0] = targets_position[2*(goal_idx-1)];
goal[1] = targets_position[2*(goal_idx-1)+1];
}
else
{
goal[0] = agent_position[0];
goal[1] = agent_position[1];
}
auto [path_this, distance] = find_path(start, goal, Map);
path_all.push_back(path_this);
distance_all.push_back(distance);
}
return {path_all, distance_all};
}
/*
FindPath: Find a collision-free path from a start to a target.
Input:
startPoint: 1D integer array [x, y] for the start position
endPoint: 1D integer array [x, y] for the goal position
world_map: 1D integer array for the map, flattened by a 2D array map; 0 for no obstacles, 255 for obstacles
mapSizeX: integer for the width of the map
mapSizeY: integer for the height of the map
Output:
path: 1D integer array for the index path from startPoint to endPoint, [idx_x_0,idx_y_0, idx_x_1,idx_y_1, idx_x_2,idx_y_2, ...]
distance: float for the total distance of the path
*/
inline std::tuple<std::vector<int>, float> FindPath(
const std::vector<int> &start,
const std::vector<int> &end,
const std::vector<int> &world_map,
const int &map_width,
const int &map_height)
{
// std::cout << "STL A* Search implementation\n(C)2001 Justin Heyes-Jones\n";
// Our sample problem defines the world as a 2d array representing a terrain
// Each element contains an integer from 0 to 5 which indicates the cost
// of travel across the terrain. Zero means the least possible difficulty
// in travelling (think ice rink if you can skate) whilst 5 represents the
// most difficult. 255 indicates that we cannot pass.
// Create an instance of the search class...
struct MapInfo Map;
Map.world_map = world_map;
Map.map_width = map_width;
Map.map_height = map_height;
auto [path, distance] = find_path(start.data(), end.data(), Map);
return {path, distance};
}
inline std::tuple<std::vector<int>, std::vector<int>, int, float> FindPath_test(
const std::vector<int> &start,
const std::vector<int> &end,
const std::vector<int> &world_map,
int &map_width,
int &map_height)
{
// std::cout << "STL A* Search implementation\n(C)2001 Justin Heyes-Jones\n";
// Our sample problem defines the world as a 2d array representing a terrain
// Each element contains an integer from 0 to 5 which indicates the cost
// of travel across the terrain. Zero means the least possible difficulty
// in travelling (think ice rink if you can skate) whilst 5 represents the
// most difficult. 255 indicates that we cannot pass.
// Create an instance of the search class...
struct MapInfo Map;
Map.world_map = world_map;
Map.map_width = map_width;
Map.map_height = map_height;
AStarSearch<MapSearchNode> astarsearch;
unsigned int SearchCount = 0;
const unsigned int NumSearches = 1;
// full path
std::vector<int> path_full;
// a short path only contains path corners
std::vector<int> path_short;
// how many steps used
int steps = 0;
while(SearchCount < NumSearches)
{
// MapSearchNode nodeStart;
MapSearchNode nodeStart = MapSearchNode(start[0], start[1], Map);
MapSearchNode nodeEnd(end[0], end[1], Map);
// Set Start and goal states
astarsearch.SetStartAndGoalStates( nodeStart, nodeEnd );
unsigned int SearchState;
unsigned int SearchSteps = 0;
do
{
SearchState = astarsearch.SearchStep();
SearchSteps++;
}
while( SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SEARCHING );
if( SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SUCCEEDED )
{
// std::cout << "Search found goal state\n";
MapSearchNode *node = astarsearch.GetSolutionStart();
steps = 0;
// node->PrintNodeInfo();
path_full.push_back(node->x);
path_full.push_back(node->y);
while (true)
{
node = astarsearch.GetSolutionNext();
if ( !node )
{
break;
}
// node->PrintNodeInfo();
path_full.push_back(node->x);
path_full.push_back(node->y);
steps ++;
/*
Let's say there are 3 steps, x0, x1, x2. To verify whether x1 is a corner for the path.
If the coordinates of x0 and x1 at least have 1 component same, and the coordinates of
x0 and x2 don't have any components same, then x1 is a corner.
Always append the second path point to path_full.
When steps >= 2 (starting from the third point), append the point if it's a corner.
*/
if ((((path_full[2*steps-4]==path_full[2*steps-2]) || (path_full[2*steps-3]==path_full[2*steps-1])) &&
((path_full[2*steps-4]!=node->x) && (path_full[2*steps-3]!=node->y)) && (steps>=2)) || (steps < 2))
{
path_short.push_back(path_full[2*steps-2]);
path_short.push_back(path_full[2*steps-1]);
}
}
// the last two elements
// This works for both steps>2 and steps <=2
path_short.push_back(path_full[path_full.size()-2]);
path_short.push_back(path_full[path_full.size()-1]);
// std::cout << "Solution steps " << steps << endl;
// Once you're done with the solution you can free the nodes up
astarsearch.FreeSolutionNodes();
}
else if( SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_FAILED )
{
std::cout << "Search terminated. Did not find goal state\n";
}
// Display the number of loops the search went through
// std::cout << "SearchSteps : " << SearchSteps << "\n";
SearchCount ++;
astarsearch.EnsureMemoryFreed();
}
// auto t_start = std::chrono::high_resolution_clock::now();
std::vector<int> path_output = smooth_path(path_short, Map);
// auto t_stop = std::chrono::high_resolution_clock::now();
// auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t_stop - t_start);
// std::cout << "smooth path time [microseconds]: " << duration.count() << std::endl;
float distance = 0.0;
for (size_t idx = 0; idx < path_output.size()/2 - 1; idx++) {
distance += std::sqrt(std::pow(path_output[2*idx]-path_output[2*(idx+1)], 2) + std::pow(path_output[2*idx+1]-path_output[2*(idx+1)+1], 2));
}
return {path_short, path_output, steps, distance};
}
inline PYBIND11_MODULE(AStarPython, module) {
module.doc() = "Python wrapper of AStar c++ implementation";
module.def("FindPath", &FindPath, "Find a collision-free path");
module.def("FindPathAll", &FindPathAll, "Find all the collision-free paths between every two nodes");
module.def("FindPathAllMP", &FindPathAllMP, "openMP version: Find all the collision-free paths between every two nodes");
module.def("FindPathAllMT", &FindPathAllMT, "Multi-threading version: Find all the collision-free paths between every two nodes");
module.def("FindPathAllTBB", &FindPathAllTBB, "Intel TBB version: Find all the collision-free paths between every two nodes");
module.def("FindPathOneByOne", &FindPathOneByOne, "Find all the collision-free paths consecutively");
module.def("FindPath_test", &FindPath_test, "Find a collision-free path (TEST VERSION)");
}