]> rtime.felk.cvut.cz Git - hubacji1/rrts.git/blob - src/rrts.cc
Fix json input assert of rrts
[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) : BicycleCar(bc)
15 {
16 }
17
18 Obstacle::Obstacle()
19 {
20 }
21
22 double RRTS::elapsed()
23 {
24         std::chrono::duration<double> dt;
25         dt = std::chrono::duration_cast<std::chrono::duration<double>>(
26                 std::chrono::high_resolution_clock::now()
27                 - this->tstart_
28         );
29         this->scnt_ = dt.count();
30         return this->scnt_;
31 }
32
33 bool RRTS::should_stop()
34 {
35         // the following counters must be updated, do not comment
36         this->icnt_++;
37         this->elapsed();
38         // current iteration stop conditions
39         if (this->should_finish()) return true;
40         if (this->should_break()) return true;
41         // but continue by default
42         return false;
43 }
44
45 bool RRTS::should_finish()
46 {
47         // decide finish conditions (maybe comment some lines)
48         //if (this->icnt_ > 999) return true;
49         if (this->scnt_ > 5) return true;
50         if (this->gf()) return true;
51         // but continue by default
52         return false;
53 }
54
55 bool RRTS::should_break()
56 {
57         // decide break conditions (maybe comment some lines)
58         //if (this->scnt_ - this->pcnt_ > 2) return true;
59         // but continue by default
60         return false;
61 }
62
63 bool RRTS::should_continue()
64 {
65         // decide the stop conditions (maybe comment some lines)
66         // it is exact opposite of `should_stop`
67         //if (this->icnt_ > 999) return false;
68         if (this->scnt_ > 10) return false;
69         if (this->gf()) return false;
70         // and reset pause counter if should continue
71         this->pcnt_ = this->scnt_;
72         return true;
73 }
74
75 void RRTS::store_node(RRTNode n)
76 {
77         this->nodes().push_back(n);
78 }
79
80 // RRT procedures
81 std::tuple<bool, unsigned int, unsigned int>
82 RRTS::collide(std::vector<std::tuple<double, double>> &poly)
83 {
84         for (auto &o: this->obstacles())
85                 if (std::get<0>(::collide(poly, o.poly())))
86                         return ::collide(poly, o.poly());
87         return std::make_tuple(false, 0, 0);
88 }
89
90 std::tuple<bool, unsigned int, unsigned int>
91 RRTS::collide_steered_from(RRTNode &f)
92 {
93         std::vector<std::tuple<double, double>> s;
94         s.push_back(std::make_tuple(f.x(), f.y()));
95         for (auto &n: this->steered()) {
96                 s.push_back(std::make_tuple(n.lfx(), n.lfy()));
97                 s.push_back(std::make_tuple(n.lrx(), n.lry()));
98                 s.push_back(std::make_tuple(n.rrx(), n.rry()));
99                 s.push_back(std::make_tuple(n.rfx(), n.rfy()));
100         }
101         auto col = this->collide(s);
102         auto strip_from = this->steered().size() - std::get<1>(col) / 4;
103         if (std::get<0>(col) && strip_from > 0) {
104                 while (strip_from-- > 0) {
105                         this->steered().pop_back();
106                 }
107                 return this->collide_steered_from(f);
108         }
109         return col;
110 }
111
112 std::tuple<bool, unsigned int, unsigned int>
113 RRTS::collide_two_nodes(RRTNode &f, RRTNode &t)
114 {
115         std::vector<std::tuple<double, double>> p;
116         p.push_back(std::make_tuple(f.lfx(), f.lfy()));
117         p.push_back(std::make_tuple(f.lrx(), f.lry()));
118         p.push_back(std::make_tuple(f.rrx(), f.rry()));
119         p.push_back(std::make_tuple(f.rfx(), f.rfy()));
120         p.push_back(std::make_tuple(t.lfx(), t.lfy()));
121         p.push_back(std::make_tuple(t.lrx(), t.lry()));
122         p.push_back(std::make_tuple(t.rrx(), t.rry()));
123         p.push_back(std::make_tuple(t.rfx(), t.rfy()));
124         return this->collide(p);
125 }
126
127 double RRTS::cost_build(RRTNode &f, RRTNode &t)
128 {
129         double cost = 0;
130         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
131         return cost;
132 }
133
134 double RRTS::cost_search(RRTNode &f, RRTNode &t)
135 {
136         double cost = 0;
137         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
138         return cost;
139 }
140
141 void RRTS::sample()
142 {
143         double x = this->ndx_(this->gen_);
144         double y = this->ndy_(this->gen_);
145         double h = this->ndh_(this->gen_);
146         this->samples().push_back(RRTNode());
147         this->samples().back().x(x);
148         this->samples().back().y(y);
149         this->samples().back().h(h);
150 }
151
152 RRTNode *RRTS::nn(RRTNode &t)
153 {
154         RRTNode *nn = &this->nodes().front();
155         double cost = this->cost_search(*nn, t);
156         for (auto &f: this->nodes()) {
157                 if (this->cost_search(f, t) < cost) {
158                         nn = &f;
159                         cost = this->cost_search(f, t);
160                 }
161         }
162         return nn;
163 }
164
165 std::vector<RRTNode *> RRTS::nv(RRTNode &t)
166 {
167         std::vector<RRTNode *> nv;
168         double cost = std::min(GAMMA(this->nodes().size()), ETA);
169         for (auto &f: this->nodes())
170                 if (this->cost_search(f, t) < cost)
171                         nv.push_back(&f);
172         return nv;
173 }
174
175 int cb_rs_steer(double q[4], void *user_data)
176 {
177         std::vector<RRTNode> *nodes = (std::vector<RRTNode> *) user_data;
178         RRTNode *ln = nullptr;
179         if (nodes->size() > 0)
180                 ln = &nodes->back();
181         nodes->push_back(RRTNode());
182         nodes->back().x(q[0]);
183         nodes->back().y(q[1]);
184         nodes->back().h(q[2]);
185         nodes->back().sp(q[3]);
186         if (nodes->back().sp() == 0)
187                 nodes->back().set_t(RRTNodeType::cusp);
188         else if (ln != nullptr && sgn(ln->sp()) != sgn(nodes->back().sp()))
189                 ln->set_t(RRTNodeType::cusp);
190         return 0;
191 }
192
193 void RRTS::steer(RRTNode &f, RRTNode &t)
194 {
195         this->steered().clear();
196         double q0[] = {f.x(), f.y(), f.h()};
197         double q1[] = {t.x(), t.y(), t.h()};
198         ReedsSheppStateSpace rsss(f.mtr());
199         rsss.sample(q0, q1, 0.5, cb_rs_steer, &this->steered());
200 }
201
202 void RRTS::join_steered(RRTNode *f)
203 {
204         while (this->steered().size() > 0) {
205                 this->store_node(this->steered().front());
206                 RRTNode *t = &this->nodes().back();
207                 t->p(f);
208                 t->c(this->cost_build(*f, *t));
209                 this->steered().erase(this->steered().begin());
210                 f = t;
211         }
212 }
213
214 bool RRTS::goal_found(RRTNode &f)
215 {
216         bool found = false;
217         for (auto &g: this->goals()) {
218                 double cost = this->cost_build(f, g);
219                 double edist = sqrt(
220                         pow(f.x() - g.x(), 2)
221                         + pow(f.y() - g.y(), 2)
222                 );
223                 double adist = std::abs(f.h() - g.h());
224                 if (edist < 0.05 && adist < M_PI / 32) {
225                         found = true;
226                         if (g.p() == nullptr || cc(f) + cost < cc(g)) {
227                                 g.p(&f);
228                                 g.c(cost);
229                         }
230                 }
231         }
232         return found;
233 }
234
235 // RRT* procedures
236 bool RRTS::connect()
237 {
238         RRTNode *t = &this->steered().front();
239         RRTNode *f = this->nn(this->samples().back());
240         double cost = this->cost_search(*f, *t);
241         for (auto n: this->nv(*t)) {
242                 if (
243                         !std::get<0>(this->collide_two_nodes(*n, *t))
244                         && this->cost_search(*n, *t) < cost
245                 ) {
246                         f = n;
247                         cost = this->cost_search(*n, *t);
248                 }
249         }
250         this->store_node(this->steered().front());
251         t = &this->nodes().back();
252         t->p(f);
253         t->c(this->cost_build(*f, *t));
254         t->set_t(RRTNodeType::connected);
255         return true;
256 }
257
258 void RRTS::rewire()
259 {
260         RRTNode *f = &this->nodes().back();
261         for (auto n: this->nv(*f)) {
262                 if (
263                         !std::get<0>(this->collide_two_nodes(*f, *n))
264                         && cc(*f) + this->cost_search(*f, *n) < cc(*n)
265                 ) {
266                         n->p(f);
267                         n->c(this->cost_build(*f, *n));
268                 }
269         }
270 }
271
272 // API
273 void RRTS::init()
274 {
275 }
276
277 void RRTS::deinit()
278 {
279         this->nodes().clear();
280         this->samples().clear();
281         this->steered().clear();
282         this->store_node(RRTNode()); // root
283         this->icnt_ = 0;
284         this->scnt_ = 0;
285         this->pcnt_ = 0;
286         this->gf_ = false;
287 }
288
289 std::vector<RRTNode *> RRTS::path()
290 {
291         std::vector<RRTNode *> path;
292         if (this->goals().size() == 0)
293                 return path;
294         RRTNode *goal = &this->goals().front();
295         for (auto &n: this->goals()) {
296                 if (
297                         n.p() != nullptr
298                         && (n.c() < goal->c() || goal->p() == nullptr)
299                 ) {
300                         goal = &n;
301                 }
302         }
303         if (goal->p() == nullptr)
304                 return path;
305         while (goal != nullptr) {
306                 path.push_back(goal);
307                 goal = goal->p();
308         }
309         std::reverse(path.begin(), path.end());
310         return path;
311 }
312
313 bool RRTS::next()
314 {
315         if (this->icnt_ == 0)
316                 this->tstart_ = std::chrono::high_resolution_clock::now();
317         bool next = true;
318         if (this->should_stop())
319                 return false;
320         this->sample();
321         this->steer(
322                 *this->nn(this->samples().back()),
323                 this->samples().back()
324         );
325         if (std::get<0>(this->collide_steered_from(
326                 *this->nn(this->samples().back())
327         )))
328                 return next;
329         if (!this->connect())
330                 return next;
331         this->rewire();
332         unsigned scnt = this->steered().size();
333         this->steered().erase(this->steered().begin());
334         this->join_steered(&this->nodes().back());
335         RRTNode *just_added = &this->nodes().back();
336         while (scnt > 0) {
337                 scnt--;
338                 for (auto &g: this->goals()) {
339                         this->steer(*just_added, g);
340                         if (std::get<0>(this->collide_steered_from(
341                                 *just_added
342                         )))
343                                 continue;
344                         this->join_steered(just_added);
345                 }
346                 this->gf(this->goal_found(this->nodes().back()));
347                 just_added = just_added->p();
348         }
349         return next;
350 }
351
352 void RRTS::set_sample(
353         double mx, double dx,
354         double my, double dy,
355         double mh, double dh
356 )
357 {
358         this->ndx_ = std::normal_distribution<double>(mx, dx);
359         this->ndy_ = std::normal_distribution<double>(my, dy);
360         this->ndh_ = std::normal_distribution<double>(mh, dh);
361 }
362
363 Json::Value RRTS::json()
364 {
365         Json::Value jvo;
366         {
367                 jvo["time"] = this->scnt();
368         }
369         {
370                 jvo["iterations"] = this->icnt();
371         }
372         {
373                 jvo["init"][0] = this->nodes().front().x();
374                 jvo["init"][1] = this->nodes().front().y();
375                 jvo["init"][2] = this->nodes().front().h();
376         }
377         {
378                 if (this->path().size() > 0) {
379                         jvo["cost"] = cc(*this->path().back());
380                         jvo["goal"][0] = this->path().back()->x();
381                         jvo["goal"][1] = this->path().back()->y();
382                         jvo["goal"][2] = this->path().back()->h();
383                 }
384         }
385         {
386                 unsigned int cu = 0;
387                 unsigned int co = 0;
388                 unsigned int pcnt = 0;
389                 for (auto n: this->path()) {
390                         jvo["path"][pcnt][0] = n->x();
391                         jvo["path"][pcnt][1] = n->y();
392                         jvo["path"][pcnt][2] = n->h();
393                         if (n->t(RRTNodeType::cusp))
394                                 cu++;
395                         if (n->t(RRTNodeType::connected))
396                                 co++;
397                         pcnt++;
398                 }
399                 jvo["cusps-in-path"] = cu;
400                 jvo["connecteds-in-path"] = co;
401         }
402         {
403                 unsigned int gcnt = 0;
404                 for (auto g: this->goals()) {
405                         jvo["goals"][gcnt][0] = g.x();
406                         jvo["goals"][gcnt][1] = g.y();
407                         jvo["goals"][gcnt][2] = g.h();
408                         gcnt++;
409                 }
410         }
411         {
412                 unsigned int ocnt = 0;
413                 for (auto o: this->obstacles()) {
414                         unsigned int ccnt = 0;
415                         for (auto c: o.poly()) {
416                                 jvo["obst"][ocnt][ccnt][0] = std::get<0>(c);
417                                 jvo["obst"][ocnt][ccnt][1] = std::get<1>(c);
418                                 ccnt++;
419                         }
420                         ocnt++;
421                 }
422         }
423         {
424                 jvo["nodes"] = (unsigned int) this->nodes().size();
425         }
426         //{
427         //        unsigned int ncnt = 0;
428         //        for (auto n: this->nodes()) {
429         //                jvo["nodes_x"][ncnt] = n.x();
430         //                jvo["nodes_y"][ncnt] = n.y();
431         //                //jvo["nodes_h"][ncnt] = n.h();
432         //                ncnt++;
433         //        }
434         //}
435         return jvo;
436 }
437
438 void RRTS::json(Json::Value jvi)
439 {
440         assert(jvi["init"] != Json::nullValue);
441         assert(jvi["goal"] != Json::nullValue);
442         assert(jvi["goals"] != Json::nullValue);
443         assert(jvi["obst"] != Json::nullValue);
444
445         this->nodes().front().x(jvi["init"][0].asDouble());
446         this->nodes().front().y(jvi["init"][1].asDouble());
447         this->nodes().front().h(jvi["init"][2].asDouble());
448         {
449                 RRTNode tmp_node;
450                 tmp_node.x(jvi["goal"][0].asDouble());
451                 tmp_node.y(jvi["goal"][1].asDouble());
452                 tmp_node.h(jvi["goal"][2].asDouble());
453                 this->goals().push_back(tmp_node);
454                 for (auto g: jvi["goals"]) {
455                         tmp_node.x(g[0].asDouble());
456                         tmp_node.y(g[1].asDouble());
457                         tmp_node.h(g[2].asDouble());
458                         this->goals().push_back(tmp_node);
459                 }
460         }
461         {
462                 Obstacle tmp_obstacle;
463                 for (auto o: jvi["obst"]) {
464                         tmp_obstacle.poly().clear();
465                         for (auto c: o) {
466                                 double tmp_x = c[0].asDouble();
467                                 double tmp_y = c[1].asDouble();
468                                 auto tmp_tuple = std::make_tuple(tmp_x, tmp_y);
469                                 tmp_obstacle.poly().push_back(tmp_tuple);
470                         }
471                         this->obstacles().push_back(tmp_obstacle);
472                 }
473         }
474         {
475                 double edist_init_goal = sqrt(
476                         pow(
477                                 this->nodes().front().x()
478                                 - this->goals().front().x(),
479                                 2
480                         )
481                         + pow(
482                                 this->nodes().front().y()
483                                 - this->goals().front().y(),
484                                 2
485                         )
486                 );
487                 this->set_sample(
488                         this->nodes().front().x(), edist_init_goal,
489                         this->nodes().front().y(), edist_init_goal,
490                         0, 2 * M_PI
491                 );
492         }
493 }
494
495 RRTS::RRTS()
496         : gen_(std::random_device{}())
497 {
498         this->goals().reserve(100);
499         this->nodes().reserve(4000000);
500         this->samples().reserve(1000);
501         this->steered().reserve(20000);
502         this->store_node(RRTNode()); // root
503 }
504
505 double cc(RRTNode &t)
506 {
507         RRTNode *n = &t;
508         double cost = 0;
509         while (n != nullptr) {
510                 cost += n->c();
511                 n = n->p();
512         }
513         return cost;
514 }