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