]> rtime.felk.cvut.cz Git - hubacji1/rrts.git/blob - src/rrts.cc
Add log path cost method
[hubacji1/rrts.git] / src / rrts.cc
1 #include <algorithm>
2 #include "rrts.h"
3
4 #include "reeds_shepp.h"
5
6 template <typename T> int sgn(T val) {
7         return (T(0) < val) - (val < T(0));
8 }
9
10 RRTNode::RRTNode()
11 {
12 }
13
14 RRTNode::RRTNode(const BicycleCar &bc)
15 {
16     this->x(bc.x());
17     this->y(bc.y());
18     this->h(bc.h());
19     this->sp(bc.sp());
20     this->st(bc.st());
21 }
22
23 bool RRTNode::operator==(const RRTNode& n)
24 {
25         if (this == &n)
26                 return true;
27         return false;
28 }
29
30 Obstacle::Obstacle()
31 {
32 }
33
34 double RRTS::elapsed()
35 {
36         std::chrono::duration<double> dt;
37         dt = std::chrono::duration_cast<std::chrono::duration<double>>(
38                 std::chrono::high_resolution_clock::now()
39                 - this->tstart_
40         );
41         this->scnt_ = dt.count();
42         return this->scnt_;
43 }
44
45 void RRTS::log_path_cost()
46 {
47         if (this->gf())
48                 this->log_path_cost_.push_back(cc(this->goals().front()));
49         else
50                 this->log_path_cost_.push_back(0);
51 }
52
53 bool RRTS::should_stop()
54 {
55         // the following counters must be updated, do not comment
56         this->icnt_++;
57         this->elapsed();
58         // current iteration stop conditions
59         if (this->should_finish()) return true;
60         if (this->should_break()) return true;
61         // but continue by default
62         return false;
63 }
64
65 bool RRTS::should_finish()
66 {
67         // decide finish conditions (maybe comment some lines)
68         //if (this->icnt_ > 999) return true;
69         if (this->scnt_ > 10) return true;
70         if (this->gf()) return true;
71         // but continue by default
72         return false;
73 }
74
75 bool RRTS::should_break()
76 {
77         // decide break conditions (maybe comment some lines)
78         //if (this->scnt_ - this->pcnt_ > 2) return true;
79         // but continue by default
80         return false;
81 }
82
83 bool RRTS::should_continue()
84 {
85         // decide the stop conditions (maybe comment some lines)
86         // it is exact opposite of `should_stop`
87         //if (this->icnt_ > 999) return false;
88         if (this->scnt_ > 10) return false;
89         if (this->gf()) return false;
90         // and reset pause counter if should continue
91         this->pcnt_ = this->scnt_;
92         return true;
93 }
94
95 void RRTS::store_node(RRTNode n)
96 {
97         this->nodes().push_back(n);
98 }
99
100 // RRT procedures
101 std::tuple<bool, unsigned int, unsigned int>
102 RRTS::collide(std::vector<std::tuple<double, double>> &poly)
103 {
104         for (auto &o: this->obstacles())
105                 if (std::get<0>(::collide(poly, o.poly())))
106                         return ::collide(poly, o.poly());
107         return std::make_tuple(false, 0, 0);
108 }
109
110 std::tuple<bool, unsigned int, unsigned int>
111 RRTS::collide_steered_from(RRTNode &f)
112 {
113         auto fbc = BicycleCar();
114         fbc.x(f.x());
115         fbc.y(f.y());
116         fbc.h(f.h());
117         std::vector<std::tuple<double, double>> s;
118         s.push_back(std::make_tuple(fbc.x(), fbc.y()));
119         for (auto &n: this->steered()) {
120                 auto nbc = BicycleCar();
121                 nbc.x(n.x());
122                 nbc.y(n.y());
123                 nbc.h(n.h());
124                 s.push_back(std::make_tuple(nbc.lfx(), nbc.lfy()));
125                 s.push_back(std::make_tuple(nbc.lrx(), nbc.lry()));
126                 s.push_back(std::make_tuple(nbc.rrx(), nbc.rry()));
127                 s.push_back(std::make_tuple(nbc.rfx(), nbc.rfy()));
128         }
129         auto col = this->collide(s);
130         auto strip_from = this->steered().size() - std::get<1>(col) / 4;
131         if (std::get<0>(col) && strip_from > 0) {
132                 while (strip_from-- > 0) {
133                         this->steered().pop_back();
134                 }
135                 return this->collide_steered_from(f);
136         }
137         return col;
138 }
139
140 std::tuple<bool, unsigned int, unsigned int>
141 RRTS::collide_two_nodes(RRTNode &f, RRTNode &t)
142 {
143         auto fbc = BicycleCar();
144         fbc.x(f.x());
145         fbc.y(f.y());
146         fbc.h(f.h());
147         auto tbc = BicycleCar();
148         tbc.x(f.x());
149         tbc.y(f.y());
150         tbc.h(f.h());
151         std::vector<std::tuple<double, double>> p;
152         p.push_back(std::make_tuple(fbc.lfx(), fbc.lfy()));
153         p.push_back(std::make_tuple(fbc.lrx(), fbc.lry()));
154         p.push_back(std::make_tuple(fbc.rrx(), fbc.rry()));
155         p.push_back(std::make_tuple(fbc.rfx(), fbc.rfy()));
156         p.push_back(std::make_tuple(tbc.lfx(), tbc.lfy()));
157         p.push_back(std::make_tuple(tbc.lrx(), tbc.lry()));
158         p.push_back(std::make_tuple(tbc.rrx(), tbc.rry()));
159         p.push_back(std::make_tuple(tbc.rfx(), tbc.rfy()));
160         return this->collide(p);
161 }
162
163 double RRTS::cost_build(RRTNode &f, RRTNode &t)
164 {
165         double cost = 0;
166         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
167         return cost;
168 }
169
170 double RRTS::cost_search(RRTNode &f, RRTNode &t)
171 {
172         double cost = 0;
173         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
174         return cost;
175 }
176
177 void RRTS::sample()
178 {
179         double x = 0;
180         double y = 0;
181         double h = 0;
182         switch (this->sample_dist_type()) {
183         case 1: // uniform
184                 x = this->udx_(this->gen_);
185                 y = this->udy_(this->gen_);
186                 h = this->udh_(this->gen_);
187                 break;
188         case 2: // uniform circle
189         {
190                 // see https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly/50746409#50746409
191                 double R = sqrt(
192                         pow(
193                                 this->nodes().front().x()
194                                 - this->goals().front().x(),
195                                 2
196                         )
197                         + pow(
198                                 this->nodes().front().y()
199                                 - this->goals().front().y(),
200                                 2
201                         )
202                 );
203                 double a = atan2(
204                         this->goals().front().y() - this->nodes().front().y(),
205                         this->goals().front().x() - this->nodes().front().x()
206                 );
207                 double cx = this->goals().front().x() + R/2 * cos(a);
208                 double cy = this->goals().front().y() + R/2 * sin(a);
209                 double r = R * sqrt(this->udx_(this->gen_));
210                 double theta = this->udy_(this->gen_) * 2 * M_PI;
211                 x = cx + r * cos(theta);
212                 y = cy + r * sin(theta);
213                 h = this->udh_(this->gen_);
214         }
215                 break;
216         default: // normal
217                 x = this->ndx_(this->gen_);
218                 y = this->ndy_(this->gen_);
219                 h = this->ndh_(this->gen_);
220         }
221         this->samples().push_back(RRTNode());
222         this->samples().back().x(x);
223         this->samples().back().y(y);
224         this->samples().back().h(h);
225 }
226
227 RRTNode *RRTS::nn(RRTNode &t)
228 {
229         RRTNode *nn = &this->nodes().front();
230         double cost = this->cost_search(*nn, t);
231         for (auto &f: this->nodes()) {
232                 if (this->cost_search(f, t) < cost) {
233                         nn = &f;
234                         cost = this->cost_search(f, t);
235                 }
236         }
237         return nn;
238 }
239
240 std::vector<RRTNode *> RRTS::nv(RRTNode &t)
241 {
242         std::vector<RRTNode *> nv;
243         double cost = std::min(GAMMA(this->nodes().size()), ETA);
244         for (auto &f: this->nodes())
245                 if (this->cost_search(f, t) < cost)
246                         nv.push_back(&f);
247         return nv;
248 }
249
250 int cb_rs_steer(double q[4], void *user_data)
251 {
252         std::vector<RRTNode> *nodes = (std::vector<RRTNode> *) user_data;
253         RRTNode *ln = nullptr;
254         if (nodes->size() > 0)
255                 ln = &nodes->back();
256         nodes->push_back(RRTNode());
257         nodes->back().x(q[0]);
258         nodes->back().y(q[1]);
259         nodes->back().h(q[2]);
260         nodes->back().sp(q[3]);
261         if (nodes->back().sp() == 0)
262                 nodes->back().set_t(RRTNodeType::cusp);
263         else if (ln != nullptr && sgn(ln->sp()) != sgn(nodes->back().sp()))
264                 ln->set_t(RRTNodeType::cusp);
265         return 0;
266 }
267
268 void RRTS::steer(RRTNode &f, RRTNode &t)
269 {
270         this->steered().clear();
271         double q0[] = {f.x(), f.y(), f.h()};
272         double q1[] = {t.x(), t.y(), t.h()};
273         ReedsSheppStateSpace rsss(this->bc.mtr());
274         rsss.sample(q0, q1, 0.5, cb_rs_steer, &this->steered());
275 }
276
277 void RRTS::join_steered(RRTNode *f)
278 {
279         while (this->steered().size() > 0) {
280                 this->store_node(this->steered().front());
281                 RRTNode *t = &this->nodes().back();
282                 t->p(f);
283                 t->c(this->cost_build(*f, *t));
284                 this->steered().erase(this->steered().begin());
285                 f = t;
286         }
287 }
288
289 bool RRTS::goal_found(RRTNode &f)
290 {
291         auto &g = this->goals().front();
292         double cost = this->cost_build(f, g);
293         double edist = sqrt(
294                 pow(f.x() - g.x(), 2)
295                 + pow(f.y() - g.y(), 2)
296         );
297         double adist = std::abs(f.h() - g.h());
298         if (edist < 0.05 && adist < M_PI / 32) {
299                 if (g.p() == nullptr || cc(f) + cost < cc(g)) {
300                         g.p(&f);
301                         g.c(cost);
302                 }
303                 return true;
304         }
305         return false;
306 }
307
308 // RRT* procedures
309 bool RRTS::connect()
310 {
311         RRTNode *t = &this->steered().front();
312         RRTNode *f = this->nn(this->samples().back());
313         double cost = this->cost_search(*f, *t);
314         for (auto n: this->nv(*t)) {
315                 if (
316                         !std::get<0>(this->collide_two_nodes(*n, *t))
317                         && this->cost_search(*n, *t) < cost
318                 ) {
319                         f = n;
320                         cost = this->cost_search(*n, *t);
321                 }
322         }
323         this->store_node(this->steered().front());
324         t = &this->nodes().back();
325         t->p(f);
326         t->c(this->cost_build(*f, *t));
327         t->set_t(RRTNodeType::connected);
328         return true;
329 }
330
331 void RRTS::rewire()
332 {
333         RRTNode *f = &this->nodes().back();
334         for (auto n: this->nv(*f)) {
335                 if (
336                         !std::get<0>(this->collide_two_nodes(*f, *n))
337                         && cc(*f) + this->cost_search(*f, *n) < cc(*n)
338                 ) {
339                         n->p(f);
340                         n->c(this->cost_build(*f, *n));
341                 }
342         }
343 }
344
345 // API
346 void RRTS::init()
347 {
348 }
349
350 void RRTS::deinit()
351 {
352         this->nodes().clear();
353         this->samples().clear();
354         this->steered().clear();
355         this->store_node(RRTNode()); // root
356         this->icnt_ = 0;
357         this->scnt_ = 0;
358         this->pcnt_ = 0;
359         this->gf_ = false;
360 }
361
362 std::vector<RRTNode *> RRTS::path()
363 {
364         std::vector<RRTNode *> path;
365         if (this->goals().size() == 0)
366                 return path;
367         RRTNode *goal = &this->goals().front();
368         if (goal->p() == nullptr)
369                 return path;
370         while (goal != nullptr) {
371                 path.push_back(goal);
372                 goal = goal->p();
373         }
374         std::reverse(path.begin(), path.end());
375         return path;
376 }
377
378 bool RRTS::next()
379 {
380         if (this->icnt_ == 0)
381                 this->tstart_ = std::chrono::high_resolution_clock::now();
382         bool next = true;
383         if (this->should_stop())
384                 return false;
385         if (this->samples().size() == 0) {
386                 this->samples().push_back(RRTNode());
387                 this->samples().back().x(this->goals().front().x());
388                 this->samples().back().y(this->goals().front().y());
389                 this->samples().back().h(this->goals().front().h());
390         } else {
391                 this->sample();
392         }
393         this->steer(
394                 *this->nn(this->samples().back()),
395                 this->samples().back()
396         );
397         if (std::get<0>(this->collide_steered_from(
398                 *this->nn(this->samples().back())
399         )))
400                 return next;
401         if (!this->connect())
402                 return next;
403         this->rewire();
404         unsigned scnt = this->steered().size();
405         this->join_steered(&this->nodes().back());
406         RRTNode *just_added = &this->nodes().back();
407         while (scnt > 0) {
408                 scnt--;
409                 auto &g = this->goals().front();
410                 this->steer(*just_added, g);
411                 if (std::get<0>(this->collide_steered_from(
412                         *just_added
413                 )))
414                         continue;
415                 this->join_steered(just_added);
416                 this->gf(this->goal_found(this->nodes().back()));
417                 just_added = just_added->p();
418         }
419         return next;
420 }
421
422 void RRTS::set_sample_normal(
423         double mx, double dx,
424         double my, double dy,
425         double mh, double dh
426 )
427 {
428         this->ndx_ = std::normal_distribution<double>(mx, dx);
429         this->ndy_ = std::normal_distribution<double>(my, dy);
430         this->ndh_ = std::normal_distribution<double>(mh, dh);
431 }
432 void RRTS::set_sample_uniform(
433         double xmin, double xmax,
434         double ymin, double ymax,
435         double hmin, double hmax
436 )
437 {
438         this->udx_ = std::uniform_real_distribution<double>(xmin,xmax);
439         this->udy_ = std::uniform_real_distribution<double>(ymin,ymax);
440         this->udh_ = std::uniform_real_distribution<double>(hmin,hmax);
441 }
442 void RRTS::set_sample_uniform_circle()
443 {
444         this->udx_ = std::uniform_real_distribution<double>(0, 1);
445         this->udy_ = std::uniform_real_distribution<double>(0, 1);
446         this->udh_ = std::uniform_real_distribution<double>(0, 2 * M_PI);
447 }
448 void RRTS::set_sample(
449         double x1, double x2,
450         double y1, double y2,
451         double h1, double h2
452 )
453 {
454         switch (this->sample_dist_type()) {
455         case 1: // uniform
456                 x1 += this->nodes().front().x();
457                 x2 += this->nodes().front().x();
458                 y1 += this->nodes().front().y();
459                 y2 += this->nodes().front().y();
460                 this->set_sample_uniform(x1, x2, y1, y2, h1, h2);
461                 break;
462         case 2: // uniform circle
463                 this->set_sample_uniform_circle();
464                 break;
465         default: // normal
466                 this->set_sample_normal(x1, x2, y1, y2, h1, h2);
467         }
468 }
469
470 Json::Value RRTS::json()
471 {
472         Json::Value jvo;
473         {
474                 jvo["time"] = this->scnt();
475         }
476         {
477                 jvo["iterations"] = this->icnt();
478         }
479         {
480                 jvo["init"][0] = this->nodes().front().x();
481                 jvo["init"][1] = this->nodes().front().y();
482                 jvo["init"][2] = this->nodes().front().h();
483         }
484         {
485                 if (this->path().size() > 0) {
486                         jvo["cost"] = cc(*this->path().back());
487                         jvo["goal"][0] = this->path().back()->x();
488                         jvo["goal"][1] = this->path().back()->y();
489                         jvo["goal"][2] = this->path().back()->h();
490                 }
491         }
492         {
493                 unsigned int cu = 0;
494                 unsigned int co = 0;
495                 unsigned int pcnt = 0;
496                 for (auto n: this->path()) {
497                         jvo["path"][pcnt][0] = n->x();
498                         jvo["path"][pcnt][1] = n->y();
499                         jvo["path"][pcnt][2] = n->h();
500                         if (n->t(RRTNodeType::cusp))
501                                 cu++;
502                         if (n->t(RRTNodeType::connected))
503                                 co++;
504                         pcnt++;
505                 }
506                 jvo["cusps-in-path"] = cu;
507                 jvo["connecteds-in-path"] = co;
508         }
509         {
510                 unsigned int gcnt = 0;
511                 for (auto g: this->goals()) {
512                         jvo["goals"][gcnt][0] = g.x();
513                         jvo["goals"][gcnt][1] = g.y();
514                         jvo["goals"][gcnt][2] = g.h();
515                         gcnt++;
516                 }
517         }
518         {
519                 unsigned int ocnt = 0;
520                 for (auto o: this->obstacles()) {
521                         unsigned int ccnt = 0;
522                         for (auto c: o.poly()) {
523                                 jvo["obst"][ocnt][ccnt][0] = std::get<0>(c);
524                                 jvo["obst"][ocnt][ccnt][1] = std::get<1>(c);
525                                 ccnt++;
526                         }
527                         ocnt++;
528                 }
529         }
530         {
531                 jvo["nodes"] = (unsigned int) this->nodes().size();
532         }
533         {
534                 unsigned int cnt = 0;
535                 for (auto i: this->log_path_cost_)
536                         jvo["log_path_cost"][cnt++] = i;
537         }
538         //{
539         //        unsigned int ncnt = 0;
540         //        for (auto n: this->nodes()) {
541         //                jvo["nodes_x"][ncnt] = n.x();
542         //                jvo["nodes_y"][ncnt] = n.y();
543         //                //jvo["nodes_h"][ncnt] = n.h();
544         //                ncnt++;
545         //        }
546         //}
547         return jvo;
548 }
549
550 void RRTS::json(Json::Value jvi)
551 {
552         assert(jvi["init"] != Json::nullValue);
553         assert(jvi["goal"] != Json::nullValue);
554         assert(jvi["goals"] != Json::nullValue);
555         assert(jvi["obst"] != Json::nullValue);
556
557         this->nodes().front().x(jvi["init"][0].asDouble());
558         this->nodes().front().y(jvi["init"][1].asDouble());
559         this->nodes().front().h(jvi["init"][2].asDouble());
560         {
561                 RRTNode tmp_node;
562                 tmp_node.x(jvi["goal"][0].asDouble());
563                 tmp_node.y(jvi["goal"][1].asDouble());
564                 tmp_node.h(jvi["goal"][2].asDouble());
565                 this->goals().push_back(tmp_node);
566                 for (auto g: jvi["goals"]) {
567                         tmp_node.x(g[0].asDouble());
568                         tmp_node.y(g[1].asDouble());
569                         tmp_node.h(g[2].asDouble());
570                         this->goals().push_back(tmp_node);
571                 }
572         }
573         {
574                 Obstacle tmp_obstacle;
575                 for (auto o: jvi["obst"]) {
576                         tmp_obstacle.poly().clear();
577                         for (auto c: o) {
578                                 double tmp_x = c[0].asDouble();
579                                 double tmp_y = c[1].asDouble();
580                                 auto tmp_tuple = std::make_tuple(tmp_x, tmp_y);
581                                 tmp_obstacle.poly().push_back(tmp_tuple);
582                         }
583                         this->obstacles().push_back(tmp_obstacle);
584                 }
585         }
586         {
587                 double edist_init_goal = sqrt(
588                         pow(
589                                 this->nodes().front().x()
590                                 - this->goals().front().x(),
591                                 2
592                         )
593                         + pow(
594                                 this->nodes().front().y()
595                                 - this->goals().front().y(),
596                                 2
597                         )
598                 );
599                 this->set_sample(
600                         this->nodes().front().x(), edist_init_goal,
601                         this->nodes().front().y(), edist_init_goal,
602                         0, 2 * M_PI
603                 );
604         }
605 }
606
607 RRTS::RRTS()
608         : gen_(std::random_device{}())
609 {
610         this->goals().reserve(100);
611         this->nodes().reserve(4000000);
612         this->samples().reserve(1000);
613         this->steered().reserve(20000);
614         this->store_node(RRTNode()); // root
615 }
616
617 double cc(RRTNode &t)
618 {
619         RRTNode *n = &t;
620         double cost = 0;
621         while (n != nullptr) {
622                 cost += n->c();
623                 n = n->p();
624         }
625         return cost;
626 }