]> rtime.felk.cvut.cz Git - hubacji1/rrts.git/blob - src/rrts.cc
When loading goals, set parent and type
[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         this->log_path_cost_.push_back(cc(this->goals().front()));
48         this->log_path_time_ += 0.1;
49 }
50
51 bool RRTS::should_stop()
52 {
53         // the following counters must be updated, do not comment
54         this->icnt_++;
55         this->elapsed();
56         // current iteration stop conditions
57         if (this->should_finish()) return true;
58         if (this->should_break()) return true;
59         // but continue by default
60         return false;
61 }
62
63 bool RRTS::should_finish()
64 {
65         // decide finish conditions (maybe comment some lines)
66         //if (this->icnt_ > 999) return true;
67         if (this->scnt_ > 2) return true;
68         //if (this->gf()) return true;
69         // but continue by default
70         return false;
71 }
72
73 bool RRTS::should_break()
74 {
75         // decide break conditions (maybe comment some lines)
76         //if (this->scnt_ - this->pcnt_ > 2) return true;
77         // but continue by default
78         return false;
79 }
80
81 bool RRTS::should_continue()
82 {
83         // decide the stop conditions (maybe comment some lines)
84         // it is exact opposite of `should_stop`
85         //if (this->icnt_ > 999) return false;
86         if (this->scnt_ > 10) return false;
87         if (this->gf()) return false;
88         // and reset pause counter if should continue
89         this->pcnt_ = this->scnt_;
90         return true;
91 }
92
93 void RRTS::store_node(RRTNode n)
94 {
95         this->nodes().push_back(n);
96 }
97
98 // RRT procedures
99 std::tuple<bool, unsigned int, unsigned int>
100 RRTS::collide(std::vector<std::tuple<double, double>> &poly)
101 {
102         for (auto &o: this->obstacles())
103                 if (std::get<0>(::collide(poly, o.poly())))
104                         return ::collide(poly, o.poly());
105         return std::make_tuple(false, 0, 0);
106 }
107
108 std::tuple<bool, unsigned int, unsigned int>
109 RRTS::collide_steered_from(RRTNode &f)
110 {
111         auto fbc = BicycleCar();
112         fbc.x(f.x());
113         fbc.y(f.y());
114         fbc.h(f.h());
115         std::vector<std::tuple<double, double>> s;
116         s.push_back(std::make_tuple(fbc.x(), fbc.y()));
117         for (auto &n: this->steered()) {
118                 auto nbc = BicycleCar();
119                 nbc.x(n.x());
120                 nbc.y(n.y());
121                 nbc.h(n.h());
122                 s.push_back(std::make_tuple(nbc.lfx(), nbc.lfy()));
123                 s.push_back(std::make_tuple(nbc.lrx(), nbc.lry()));
124                 s.push_back(std::make_tuple(nbc.rrx(), nbc.rry()));
125                 s.push_back(std::make_tuple(nbc.rfx(), nbc.rfy()));
126         }
127         auto col = this->collide(s);
128         auto strip_from = this->steered().size() - std::get<1>(col) / 4;
129         if (std::get<0>(col) && strip_from > 0) {
130                 while (strip_from-- > 0) {
131                         this->steered().pop_back();
132                 }
133                 return this->collide_steered_from(f);
134         }
135         return col;
136 }
137
138 std::tuple<bool, unsigned int, unsigned int>
139 RRTS::collide_two_nodes(RRTNode &f, RRTNode &t)
140 {
141         auto fbc = BicycleCar();
142         fbc.x(f.x());
143         fbc.y(f.y());
144         fbc.h(f.h());
145         auto tbc = BicycleCar();
146         tbc.x(f.x());
147         tbc.y(f.y());
148         tbc.h(f.h());
149         std::vector<std::tuple<double, double>> p;
150         p.push_back(std::make_tuple(fbc.lfx(), fbc.lfy()));
151         p.push_back(std::make_tuple(fbc.lrx(), fbc.lry()));
152         p.push_back(std::make_tuple(fbc.rrx(), fbc.rry()));
153         p.push_back(std::make_tuple(fbc.rfx(), fbc.rfy()));
154         p.push_back(std::make_tuple(tbc.lfx(), tbc.lfy()));
155         p.push_back(std::make_tuple(tbc.lrx(), tbc.lry()));
156         p.push_back(std::make_tuple(tbc.rrx(), tbc.rry()));
157         p.push_back(std::make_tuple(tbc.rfx(), tbc.rfy()));
158         return this->collide(p);
159 }
160
161 double RRTS::cost_build(RRTNode &f, RRTNode &t)
162 {
163         double cost = 0;
164         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
165         return cost;
166 }
167
168 double RRTS::cost_search(RRTNode &f, RRTNode &t)
169 {
170         double cost = 0;
171         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
172         return cost;
173 }
174
175 void RRTS::sample()
176 {
177         double x = 0;
178         double y = 0;
179         double h = 0;
180         switch (this->sample_dist_type()) {
181         case 1: // uniform
182                 x = this->udx_(this->gen_);
183                 y = this->udy_(this->gen_);
184                 h = this->udh_(this->gen_);
185                 break;
186         case 2: // uniform circle
187         {
188                 // see https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly/50746409#50746409
189                 double R = sqrt(
190                         pow(
191                                 this->nodes().front().x()
192                                 - this->goals().front().x(),
193                                 2
194                         )
195                         + pow(
196                                 this->nodes().front().y()
197                                 - this->goals().front().y(),
198                                 2
199                         )
200                 );
201                 double a = atan2(
202                         this->goals().front().y() - this->nodes().front().y(),
203                         this->goals().front().x() - this->nodes().front().x()
204                 );
205                 double cx = this->goals().front().x() + R/2 * cos(a);
206                 double cy = this->goals().front().y() + R/2 * sin(a);
207                 double r = R * sqrt(this->udx_(this->gen_));
208                 double theta = this->udy_(this->gen_) * 2 * M_PI;
209                 x = cx + r * cos(theta);
210                 y = cy + r * sin(theta);
211                 h = this->udh_(this->gen_);
212         }
213                 break;
214         default: // normal
215                 x = this->ndx_(this->gen_);
216                 y = this->ndy_(this->gen_);
217                 h = this->ndh_(this->gen_);
218         }
219         this->samples().push_back(RRTNode());
220         this->samples().back().x(x);
221         this->samples().back().y(y);
222         this->samples().back().h(h);
223 }
224
225 RRTNode *RRTS::nn(RRTNode &t)
226 {
227         RRTNode *nn = &this->nodes().front();
228         double cost = this->cost_search(*nn, t);
229         for (auto &f: this->nodes()) {
230                 if (this->cost_search(f, t) < cost) {
231                         nn = &f;
232                         cost = this->cost_search(f, t);
233                 }
234         }
235         return nn;
236 }
237
238 std::vector<RRTNode *> RRTS::nv(RRTNode &t)
239 {
240         std::vector<RRTNode *> nv;
241         double cost = std::min(GAMMA(this->nodes().size()), ETA);
242         for (auto &f: this->nodes())
243                 if (this->cost_search(f, t) < cost)
244                         nv.push_back(&f);
245         return nv;
246 }
247
248 int cb_rs_steer(double q[4], void *user_data)
249 {
250         std::vector<RRTNode> *nodes = (std::vector<RRTNode> *) user_data;
251         RRTNode *ln = nullptr;
252         if (nodes->size() > 0)
253                 ln = &nodes->back();
254         nodes->push_back(RRTNode());
255         nodes->back().x(q[0]);
256         nodes->back().y(q[1]);
257         nodes->back().h(q[2]);
258         nodes->back().sp(q[3]);
259         if (nodes->back().sp() == 0)
260                 nodes->back().set_t(RRTNodeType::cusp);
261         else if (ln != nullptr && sgn(ln->sp()) != sgn(nodes->back().sp()))
262                 ln->set_t(RRTNodeType::cusp);
263         return 0;
264 }
265
266 void RRTS::steer(RRTNode &f, RRTNode &t)
267 {
268         this->steered().clear();
269         double q0[] = {f.x(), f.y(), f.h()};
270         double q1[] = {t.x(), t.y(), t.h()};
271         ReedsSheppStateSpace rsss(this->bc.mtr());
272         rsss.sample(q0, q1, 0.5, cb_rs_steer, &this->steered());
273 }
274
275 void RRTS::join_steered(RRTNode *f)
276 {
277         while (this->steered().size() > 0) {
278                 this->store_node(this->steered().front());
279                 RRTNode *t = &this->nodes().back();
280                 t->p(f);
281                 t->c(this->cost_build(*f, *t));
282                 this->steered().erase(this->steered().begin());
283                 f = t;
284         }
285 }
286
287 bool RRTS::goal_found(RRTNode &f)
288 {
289         auto &g = this->goals().front();
290         double cost = this->cost_build(f, g);
291         double edist = sqrt(
292                 pow(f.x() - g.x(), 2)
293                 + pow(f.y() - g.y(), 2)
294         );
295         double adist = std::abs(f.h() - g.h());
296         if (edist < 0.05 && adist < M_PI / 32) {
297                 if (g.p() == nullptr || cc(f) + cost < cc(g)) {
298                         g.p(&f);
299                         g.c(cost);
300                 }
301                 return true;
302         }
303         return false;
304 }
305
306 // RRT* procedures
307 bool RRTS::connect()
308 {
309         RRTNode *t = &this->steered().front();
310         RRTNode *f = this->nn(this->samples().back());
311         double cost = this->cost_search(*f, *t);
312         for (auto n: this->nv(*t)) {
313                 if (
314                         !std::get<0>(this->collide_two_nodes(*n, *t))
315                         && this->cost_search(*n, *t) < cost
316                 ) {
317                         f = n;
318                         cost = this->cost_search(*n, *t);
319                 }
320         }
321         this->store_node(this->steered().front());
322         t = &this->nodes().back();
323         t->p(f);
324         t->c(this->cost_build(*f, *t));
325         t->set_t(RRTNodeType::connected);
326         return true;
327 }
328
329 void RRTS::rewire()
330 {
331         RRTNode *f = &this->nodes().back();
332         for (auto n: this->nv(*f)) {
333                 if (
334                         !std::get<0>(this->collide_two_nodes(*f, *n))
335                         && cc(*f) + this->cost_search(*f, *n) < cc(*n)
336                 ) {
337                         n->p(f);
338                         n->c(this->cost_build(*f, *n));
339                 }
340         }
341 }
342
343 // API
344 void RRTS::init()
345 {
346 }
347
348 void RRTS::deinit()
349 {
350         this->nodes().clear();
351         this->samples().clear();
352         this->steered().clear();
353         this->store_node(RRTNode()); // root
354         this->icnt_ = 0;
355         this->scnt_ = 0;
356         this->pcnt_ = 0;
357         this->gf_ = false;
358 }
359
360 std::vector<RRTNode *> RRTS::path()
361 {
362         std::vector<RRTNode *> path;
363         if (this->goals().size() == 0)
364                 return path;
365         RRTNode *goal = &this->goals().front();
366         if (goal->p() == nullptr)
367                 return path;
368         while (goal != nullptr) {
369                 path.push_back(goal);
370                 goal = goal->p();
371         }
372         std::reverse(path.begin(), path.end());
373         return path;
374 }
375
376 bool RRTS::next()
377 {
378         if (this->icnt_ == 0)
379                 this->tstart_ = std::chrono::high_resolution_clock::now();
380         bool next = true;
381         if (this->scnt_ > this->log_path_time_)
382             this->log_path_cost();
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                 jvo["path_cost_before_opt"] = this->path_cost_before_opt_;
486         }
487         {
488                 if (this->path().size() > 0) {
489                         jvo["cost"] = cc(*this->path().back());
490                         jvo["goal"][0] = this->path().back()->x();
491                         jvo["goal"][1] = this->path().back()->y();
492                         jvo["goal"][2] = this->path().back()->h();
493                 }
494         }
495         {
496                 unsigned int cu = 0;
497                 unsigned int co = 0;
498                 unsigned int pcnt = 0;
499                 for (auto n: this->path()) {
500                         jvo["path"][pcnt][0] = n->x();
501                         jvo["path"][pcnt][1] = n->y();
502                         jvo["path"][pcnt][2] = n->h();
503                         if (n->t(RRTNodeType::cusp))
504                                 cu++;
505                         if (n->t(RRTNodeType::connected))
506                                 co++;
507                         pcnt++;
508                 }
509                 jvo["cusps-in-path"] = cu;
510                 jvo["connecteds-in-path"] = co;
511         }
512         {
513                 unsigned int gcnt = 0;
514                 for (auto g: this->goals()) {
515                         jvo["goals"][gcnt][0] = g.x();
516                         jvo["goals"][gcnt][1] = g.y();
517                         jvo["goals"][gcnt][2] = g.h();
518                         gcnt++;
519                 }
520         }
521         {
522                 unsigned int ocnt = 0;
523                 for (auto o: this->obstacles()) {
524                         unsigned int ccnt = 0;
525                         for (auto c: o.poly()) {
526                                 jvo["obst"][ocnt][ccnt][0] = std::get<0>(c);
527                                 jvo["obst"][ocnt][ccnt][1] = std::get<1>(c);
528                                 ccnt++;
529                         }
530                         ocnt++;
531                 }
532         }
533         {
534                 jvo["nodes"] = (unsigned int) this->nodes().size();
535         }
536         {
537                 unsigned int cnt = 0;
538                 for (auto i: this->log_path_cost_)
539                         jvo["log_path_cost"][cnt++] = i;
540         }
541         //{
542         //        unsigned int ncnt = 0;
543         //        for (auto n: this->nodes()) {
544         //                jvo["nodes_x"][ncnt] = n.x();
545         //                jvo["nodes_y"][ncnt] = n.y();
546         //                //jvo["nodes_h"][ncnt] = n.h();
547         //                ncnt++;
548         //        }
549         //}
550         return jvo;
551 }
552
553 void RRTS::json(Json::Value jvi)
554 {
555         assert(jvi["init"] != Json::nullValue);
556         assert(jvi["goals"] != Json::nullValue);
557         assert(jvi["obst"] != Json::nullValue);
558
559         this->nodes().front().x(jvi["init"][0].asDouble());
560         this->nodes().front().y(jvi["init"][1].asDouble());
561         this->nodes().front().h(jvi["init"][2].asDouble());
562         {
563                 RRTNode tmp_node;
564                 RRTNode* gp = nullptr;
565                 for (auto g: jvi["goals"]) {
566                         tmp_node.x(g[0].asDouble());
567                         tmp_node.y(g[1].asDouble());
568                         tmp_node.h(g[2].asDouble());
569                         this->goals().push_back(tmp_node);
570                         this->goals().back().p(gp);
571                         gp = &this->goals().back();
572                 }
573                 this->goals().front().set_t(RRTNodeType::cusp);
574                 this->goals().back().set_t(RRTNodeType::cusp);
575         }
576         {
577                 Obstacle tmp_obstacle;
578                 for (auto o: jvi["obst"]) {
579                         tmp_obstacle.poly().clear();
580                         for (auto c: o) {
581                                 double tmp_x = c[0].asDouble();
582                                 double tmp_y = c[1].asDouble();
583                                 auto tmp_tuple = std::make_tuple(tmp_x, tmp_y);
584                                 tmp_obstacle.poly().push_back(tmp_tuple);
585                         }
586                         this->obstacles().push_back(tmp_obstacle);
587                 }
588         }
589         {
590                 double edist_init_goal = sqrt(
591                         pow(
592                                 this->nodes().front().x()
593                                 - this->goals().front().x(),
594                                 2
595                         )
596                         + pow(
597                                 this->nodes().front().y()
598                                 - this->goals().front().y(),
599                                 2
600                         )
601                 );
602                 this->set_sample(
603                         this->nodes().front().x(), edist_init_goal,
604                         this->nodes().front().y(), edist_init_goal,
605                         0, 2 * M_PI
606                 );
607         }
608 }
609
610 RRTS::RRTS()
611         : gen_(std::random_device{}())
612 {
613         this->goals().reserve(100);
614         this->nodes().reserve(4000000);
615         this->samples().reserve(1000);
616         this->steered().reserve(20000);
617         this->store_node(RRTNode()); // root
618 }
619
620 double cc(RRTNode &t)
621 {
622         RRTNode *n = &t;
623         double cost = 0;
624         while (n != nullptr) {
625                 cost += n->c();
626                 n = n->p();
627         }
628         return cost;
629 }