-
Notifications
You must be signed in to change notification settings - Fork 156
/
container.cpp
1309 lines (1112 loc) · 48.4 KB
/
container.cpp
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Bielefeld University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Bielefeld University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Authors: Robert Haschke */
#include <moveit/task_constructor/container_p.h>
#include <moveit/task_constructor/introspection.h>
#include <moveit/task_constructor/merge.h>
#include <moveit/planning_scene/planning_scene.h>
#include <moveit/trajectory_processing/time_optimal_trajectory_generation.h>
#include <rclcpp/logger.hpp>
#include <rclcpp/logging.hpp>
#include <memory>
#include <iostream>
#include <algorithm>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/format.hpp>
#include <functional>
using namespace std::placeholders;
using namespace trajectory_processing;
namespace moveit {
namespace task_constructor {
// for debugging of how children interfaces evolve over time
__attribute__((unused)) // silent unused-function warning
static void
printChildrenInterfaces(const ContainerBasePrivate& container, bool success, const Stage& creator,
std::ostream& os = std::cerr) {
static unsigned int id = 0;
const unsigned int width = 10; // indentation of name
os << std::endl << (success ? '+' : '-') << ' ' << creator.name() << ' ';
if (success)
os << ++id << ' ';
if (const auto conn = dynamic_cast<const ConnectingPrivate*>(creator.pimpl()))
conn->printPendingPairs(os);
os << std::endl;
for (const auto& child : container.children()) {
auto cimpl = child->pimpl();
os << std::setw(width) << std::left << child->name();
if (!cimpl->starts() && !cimpl->ends())
os << "↕ " << std::endl;
if (cimpl->starts())
os << "↓ " << *child->pimpl()->starts() << std::endl;
if (cimpl->starts() && cimpl->ends())
os << std::setw(width) << " ";
if (cimpl->ends())
os << "↑ " << *child->pimpl()->ends() << std::endl;
}
}
ContainerBasePrivate::ContainerBasePrivate(ContainerBase* me, const std::string& name)
: StagePrivate(me, name)
, required_interface_(UNKNOWN)
, pending_backward_(new Interface)
, pending_forward_(new Interface) {}
ContainerBasePrivate& ContainerBasePrivate::operator=(ContainerBasePrivate&& other) {
assert(internal_external_.empty() && other.internal_external_.empty());
// move StagePrivate members
this->StagePrivate::operator=(std::move(other));
// swapping of container members needed to maintain valid pending_* interfaces
// and children (e.g. for TaskPrivate)
required_interface_ = other.required_interface_;
std::swap(pending_backward_, other.pending_backward_);
std::swap(pending_forward_, other.pending_forward_);
std::swap(children_, other.children_);
// redirect all children's parent pointers to the new parent
auto reparent_children = [](ContainerBasePrivate& self) {
for (auto it = self.children_.begin(), end = self.children_.end(); it != end; ++it) {
auto cimpl = (*it)->pimpl();
cimpl->unparent();
cimpl->setParent(static_cast<ContainerBase*>(self.me_));
cimpl->setParentPosition(it);
}
};
reparent_children(*this);
reparent_children(other);
return *this;
}
ContainerBasePrivate::const_iterator ContainerBasePrivate::childByIndex(int index, bool for_insert) const {
if (!for_insert && index < 0)
--index;
const_iterator position = children_.begin();
if (index > 0) {
for (auto end = children_.end(); index > 0 && position != end; --index)
++position;
} else if (++index <= 0) {
container_type::const_reverse_iterator from_end = children_.rbegin();
for (auto end = children_.rend(); index < 0 && from_end != end; ++index)
++from_end;
position = index < 0 ? children_.end() : from_end.base();
}
return position;
}
bool ContainerBasePrivate::traverseStages(const ContainerBase::StageCallback& processor, unsigned int cur_depth,
unsigned int max_depth) const {
if (cur_depth >= max_depth)
return true;
for (auto& stage : children_) {
if (!processor(*stage, cur_depth))
return false;
const ContainerBasePrivate* container = dynamic_cast<const ContainerBasePrivate*>(stage->pimpl());
if (container)
container->traverseStages(processor, cur_depth + 1, max_depth);
}
return true;
}
void ContainerBasePrivate::validateConnectivity() const {
// recursively validate all children and accumulate errors
for (const auto& child : children())
child->pimpl()->validateConnectivity();
}
bool ContainerBasePrivate::canCompute() const {
// call the method of the public interface
return static_cast<ContainerBase*>(me_)->canCompute();
}
void ContainerBasePrivate::compute() {
// call the method of the public interface
static_cast<ContainerBase*>(me_)->compute();
}
template <Interface::Direction dir>
void ContainerBasePrivate::setStatus(const Stage* creator, const InterfaceState* source, const InterfaceState* target,
InterfaceState::Status status) {
if (status != InterfaceState::Status::ENABLED && creator) {
if (const auto* conn = dynamic_cast<const Connecting*>(creator)) {
auto cimpl = conn->pimpl();
// if creator is a Connecting stage and target has enabled opposite states (other than source)
if (cimpl->hasPendingOpposites<dir>(source, target))
return; // don't prune
}
}
if (target->priority().status() == status)
return; // nothing changing
// Skip disabling the state, if there are alternative enabled solutions
if (status != InterfaceState::ENABLED) {
auto solution_is_enabled = [](auto&& solution) {
return state<opposite<dir>()>(*solution)->priority().enabled();
};
const auto& alternatives = trajectories<opposite<dir>()>(*target);
auto alternative_path = std::find_if(alternatives.cbegin(), alternatives.cend(), solution_is_enabled);
if (alternative_path != alternatives.cend())
return;
}
// actually enable/disable the state
const_cast<InterfaceState*>(target)->updateStatus(status);
// if possible (i.e. if target has an external counterpart), escalate setStatus to external interface
if (parent() && trajectories<dir>(*target).empty()) {
// TODO: This was coded with SerialContainer in mind. Not sure, it works for ParallelContainers
auto external{ internalToExternalMap().find(target) };
if (external != internalToExternalMap().end()) { // do we have an external state?
// only escalate if there is no other *enabled* internal state connected to the same external one
// all internal states linked to external
auto internals{ externalToInternalMap().equal_range(external->get<EXTERNAL>()) };
auto is_enabled = [](const auto& ext_int_pair) { return ext_int_pair.second->priority().enabled(); };
auto other_path{ std::find_if(internals.first, internals.second, is_enabled) };
if (other_path == internals.second)
parent()->pimpl()->setStatus<dir>(nullptr, nullptr, external->get<EXTERNAL>(), status);
return;
}
}
// To break symmetry between both ends of a partial solution sequence that gets disabled,
// we mark the first state with ARMED and all other states down the tree with PRUNED.
// This allows us to re-enable the ARMED state, but not the PRUNED states,
// when new states arrive in a Connecting stage.
// For details, https://github.com/ros-planning/moveit_task_constructor/pull/309#issuecomment-974636202
if (status == InterfaceState::Status::ARMED)
status = InterfaceState::Status::PRUNED; // only the first state is marked as ARMED
// traverse solution tree
for (const SolutionBase* successor : trajectories<dir>(*target))
setStatus<dir>(successor->creator(), target, state<dir>(*successor), status);
}
// recursively update state priorities along solution path
template <Interface::Direction dir>
inline void updateStatePrios(const InterfaceState& s, const InterfaceState::Priority& prio) {
InterfaceState::Priority priority(prio, s.priority().status());
if (s.priority() == priority)
return;
const_cast<InterfaceState&>(s).updatePriority(priority);
for (const SolutionBase* successor : trajectories<dir>(s))
updateStatePrios<dir>(*state<dir>(*successor), prio);
}
void ContainerBasePrivate::onNewFailure(const Stage& child, const InterfaceState* from, const InterfaceState* to) {
RCLCPP_DEBUG_STREAM(rclcpp::get_logger("Pruning"), "'" << child.name() << "' generated a failure");
switch (child.pimpl()->interfaceFlags()) {
case GENERATE:
// just ignore: the pair of (new) states isn't known to us anyway
// TODO: If child is a container, from and to might have associated solutions already!
break;
case PROPAGATE_FORWARDS: // mark from as failed (backwards)
setStatus<Interface::BACKWARD>(nullptr, nullptr, from, InterfaceState::Status::PRUNED);
break;
case PROPAGATE_BACKWARDS: // mark to as failed (forwards)
setStatus<Interface::FORWARD>(nullptr, nullptr, to, InterfaceState::Status::PRUNED);
break;
case CONNECT:
setStatus<Interface::BACKWARD>(&child, to, from, InterfaceState::Status::ARMED);
setStatus<Interface::FORWARD>(&child, from, to, InterfaceState::Status::ARMED);
break;
}
// printChildrenInterfaces(*this, false, child);
}
template <Interface::Direction dir>
void ContainerBasePrivate::copyState(Interface::iterator external, const InterfacePtr& target,
Interface::UpdateFlags updated) {
if (updated) {
auto prio = external->priority();
auto internals = externalToInternalMap().equal_range(&*external);
if (updated.testFlag(Interface::Update::STATUS)) { // propagate external status updates to internal copies
for (auto& i = internals.first; i != internals.second; ++i)
setStatus<dir>(nullptr, nullptr, i->second, prio.status());
} else if (updated.testFlag(Interface::Update::PRIORITY)) {
for (auto& i = internals.first; i != internals.second; ++i)
updateStatePrios<opposite<dir>()>(*i->second, prio);
} else
assert(false); // Expecting either STATUS or PRIORITY updates, not both!
return;
}
// create a clone of external state within target interface (child's starts() or ends())
auto internal = states_.insert(states_.end(), InterfaceState(*external));
target->add(*internal);
// and remember the mapping between them
internalToExternalMap().insert(std::make_pair(&*internal, &*external));
}
void ContainerBasePrivate::copyState(Interface::Direction dir, Interface::iterator external, const InterfacePtr& target,
Interface::UpdateFlags updated) {
if (dir == Interface::FORWARD)
copyState<Interface::FORWARD>(external, target, updated);
else
copyState<Interface::BACKWARD>(external, target, updated);
}
void ContainerBasePrivate::liftSolution(const SolutionBasePtr& solution, const InterfaceState* internal_from,
const InterfaceState* internal_to) {
computeCost(*internal_from, *internal_to, *solution);
// map internal to external states
auto find_or_create_external = [this](const InterfaceState* internal, bool& created) -> InterfaceState* {
auto it = internalToExternalMap().find(internal);
if (it != internalToExternalMap().end())
return const_cast<InterfaceState*>(it->second);
InterfaceState* external = &*states_.insert(states_.end(), InterfaceState(*internal));
internalToExternalMap().insert(std::make_pair(internal, external));
created = true;
return external;
};
bool created_from = false;
bool created_to = false;
InterfaceState* external_from = find_or_create_external(internal_from, created_from);
InterfaceState* external_to = find_or_create_external(internal_to, created_to);
if (!storeSolution(solution, external_from, external_to))
return;
// connect solution to start/end state
solution->setStartState(*external_from);
solution->setEndState(*external_to);
// spawn created states in external interfaces
if (created_from)
prevEnds()->add(*external_from);
if (created_to)
nextStarts()->add(*external_to);
newSolution(solution);
}
ContainerBase::ContainerBase(ContainerBasePrivate* impl) : Stage(impl) {}
size_t ContainerBase::numChildren() const {
return pimpl()->children().size();
}
Stage* ContainerBase::findChild(const std::string& name) const {
auto pos = name.find('/');
const std::string first = name.substr(0, pos);
for (const Stage::pointer& child : pimpl()->children())
if (child->name() == first) {
if (pos == std::string::npos)
return child.get();
else if (auto* parent = dynamic_cast<const ContainerBase*>(child.get()))
return parent->findChild(name.substr(pos + 1));
}
return nullptr;
}
Stage* ContainerBase::operator[](int index) const {
auto impl = pimpl();
auto it = impl->childByIndex(index, false);
return it != impl->children().end() ? it->get() : nullptr;
}
bool ContainerBase::traverseChildren(const ContainerBase::StageCallback& processor) const {
return pimpl()->traverseStages(processor, 0, 1);
}
bool ContainerBase::traverseRecursively(const ContainerBase::StageCallback& processor) const {
if (!processor(*this, 0))
return false;
return pimpl()->traverseStages(processor, 1, UINT_MAX);
}
void ContainerBase::add(Stage::pointer&& stage) {
insert(std::move(stage), -1);
}
void ContainerBase::insert(Stage::pointer&& stage, int before) {
if (!stage)
throw std::runtime_error(name() + ": received invalid stage pointer");
StagePrivate* impl = stage->pimpl();
impl->setParent(this);
ContainerBasePrivate::const_iterator where = pimpl()->childByIndex(before, true);
ContainerBasePrivate::iterator it = pimpl()->children_.insert(where, std::move(stage));
impl->setParentPosition(it);
}
Stage::pointer ContainerBasePrivate::remove(ContainerBasePrivate::const_iterator pos) {
if (pos == children_.end())
return Stage::pointer();
(*pos)->pimpl()->unparent();
Stage::pointer result = std::move(*children_.erase(pos, pos)); // stage from non-const iterator to pos
children_.erase(pos); // actually erase stage
return result;
}
Stage::pointer ContainerBase::remove(int pos) {
return pimpl()->remove(pimpl()->childByIndex(pos, false));
}
Stage::pointer ContainerBase::remove(Stage* child) {
auto it = pimpl()->children_.begin(), end = pimpl()->children_.end();
for (; it != end && it->get() != child; ++it)
;
return pimpl()->remove(it);
}
void ContainerBase::clear() {
pimpl()->children_.clear();
}
void ContainerBase::reset() {
auto impl = pimpl();
// recursively reset children
for (auto& child : impl->children())
child->reset();
// clear buffer interfaces
impl->pending_backward_->clear();
impl->pending_forward_->clear();
// ... and state mapping
impl->internalToExternalMap().clear();
// interfaces depend on children which might change
impl->required_interface_ = UNKNOWN;
impl->starts_.reset();
impl->ends_.reset();
Stage::reset();
}
void ContainerBase::init(const moveit::core::RobotModelConstPtr& robot_model) {
auto impl = pimpl();
auto& children = impl->children();
Stage::init(robot_model);
// we need to have some children to do the actual work
if (children.empty())
throw InitStageException(*this, "no children");
// recursively init all children and accumulate errors
InitStageException errors;
for (auto& child : children) {
try {
child->init(robot_model);
} catch (const Property::error& e) {
std::ostringstream oss;
oss << e.what();
pimpl()->composePropertyErrorMsg(e.name(), oss);
errors.push_back(*child, oss.str());
} catch (InitStageException& e) {
errors.append(e);
}
}
if (errors)
throw errors;
}
void ContainerBase::explainFailure(std::ostream& os) const {
for (const auto& stage : pimpl()->children()) {
if (!stage->solutions().empty())
continue; // skip deeper traversal, this stage produced solutions
if (stage->numFailures()) {
os << stage->name() << " (0/" << stage->numFailures() << ")";
stage->explainFailure(os);
os << std::endl;
break;
}
stage->explainFailure(os); // recursively process children
}
}
std::ostream& operator<<(std::ostream& os, const ContainerBase& container) {
ContainerBase::StageCallback processor = [&os](const Stage& stage, unsigned int depth) -> bool {
os << std::string(2 * depth, ' ') << *stage.pimpl() << std::endl;
return true;
};
container.traverseRecursively(processor);
return os;
}
/** Collect all partial solution sequences originating from start into given direction */
template <Interface::Direction dir>
struct SolutionCollector
{
SolutionCollector(size_t max_depth, const SolutionBase& start) : max_depth(max_depth) {
trace.reserve(max_depth);
traverse(start, InterfaceState::Priority(0, 0.0));
assert(trace.empty());
}
void traverse(const SolutionBase& start, const InterfaceState::Priority& prio) {
const InterfaceState::Solutions& next = trajectories<dir>(*state<dir>(start));
if (next.empty()) { // when reaching the end, add the trace to solutions
assert(prio.depth() == trace.size());
assert(prio.depth() <= max_depth);
solutions.emplace_back(std::make_pair(trace, prio));
} else {
for (SolutionBase* successor : next) {
assert(!successor->isFailure()); // We shouldn't have invalid solutions
trace.push_back(successor);
traverse(*successor, prio + InterfaceState::Priority(1, successor->cost()));
trace.pop_back();
}
}
}
using SolutionCostPairs = std::list<std::pair<SolutionSequence::container_type, InterfaceState::Priority>>;
SolutionCostPairs solutions;
const size_t max_depth;
SolutionSequence::container_type trace;
};
void SerialContainer::onNewSolution(const SolutionBase& current) {
RCLCPP_DEBUG_STREAM(rclcpp::get_logger("SerialContainer"), "'" << this->name()
<< "' received solution of child stage '"
<< current.creator()->name() << "'");
// failures should never trigger this callback
assert(!current.isFailure());
auto impl = pimpl();
const Stage* creator = current.creator();
auto& children = impl->children();
// find number of stages before and after creator stage
size_t num_before = 0, num_after = 0;
for (auto it = children.begin(), end = children.end(); it != end; ++it, ++num_before)
if (&(**it) == creator)
break;
assert(num_before < children.size()); // creator should be one of our children
num_after = children.size() - 1 - num_before;
// find all incoming and outgoing solution paths originating from current solution
SolutionCollector<Interface::BACKWARD> incoming(num_before, current);
SolutionCollector<Interface::FORWARD> outgoing(num_after, current);
// collect (and sort) all solutions spanning from start to end of this container
ordered<SolutionSequencePtr> sorted;
for (auto& in : incoming.solutions) {
for (auto& out : outgoing.solutions) {
InterfaceState::Priority prio = in.second + InterfaceState::Priority(1u, current.cost()) + out.second;
assert(prio.enabled());
// found a complete solution path connecting start to end?
if (prio.depth() == children.size()) {
SolutionSequence::container_type solution;
solution.reserve(children.size());
// insert incoming solutions in reverse order
solution.insert(solution.end(), in.first.rbegin(), in.first.rend());
// insert current solution
solution.push_back(¤t);
// insert outgoing solutions in normal order
solution.insert(solution.end(), out.first.begin(), out.first.end());
// store solution in sorted list
sorted.insert(std::make_shared<SolutionSequence>(std::move(solution), prio.cost(), this));
}
if (prio.depth() > 1) {
// update state priorities along the whole partial solution path
updateStatePrios<Interface::BACKWARD>(*current.start(), prio);
updateStatePrios<Interface::FORWARD>(*current.end(), prio);
}
}
}
// printChildrenInterfaces(*this->pimpl(), true, *current.creator());
// finally, store + announce new solutions to external interface
for (const auto& solution : sorted)
impl->liftSolution(solution, solution->internalStart(), solution->internalEnd());
}
SerialContainer::SerialContainer(SerialContainerPrivate* impl) : ContainerBase(impl) {}
SerialContainer::SerialContainer(const std::string& name) : SerialContainer(new SerialContainerPrivate(this, name)) {}
SerialContainerPrivate::SerialContainerPrivate(SerialContainer* me, const std::string& name)
: ContainerBasePrivate(me, name) {}
void SerialContainerPrivate::connect(StagePrivate& stage1, StagePrivate& stage2) {
InterfaceFlags flags1 = stage1.requiredInterface();
InterfaceFlags flags2 = stage2.requiredInterface();
if ((flags1 & WRITES_NEXT_START) && (flags2 & READS_START))
stage1.setNextStarts(stage2.starts());
else if ((flags1 & READS_END) && (flags2 & WRITES_PREV_END))
stage2.setPrevEnds(stage1.ends());
else {
boost::format desc("cannot connect end interface of '%1%' (%2%) to start interface of '%3%' (%4%)");
desc % stage1.name() % flowSymbol<END_IF_MASK>(flags1);
desc % stage2.name() % flowSymbol<START_IF_MASK>(flags2);
throw InitStageException(*me(), desc.str());
}
}
template <unsigned int mask>
void SerialContainerPrivate::validateInterface(const StagePrivate& child, InterfaceFlags required) const {
required = required & mask;
if (required == UNKNOWN)
return; // cannot yet validate
InterfaceFlags child_interface = child.interfaceFlags() & mask;
if (required != child_interface) {
boost::format desc("%1% interface (%3%) of '%2%' does not match mine (%4%)");
desc % (mask == START_IF_MASK ? "start" : "end") % child.name();
desc % flowSymbol<mask>(child_interface) % flowSymbol<mask>(required);
throw InitStageException(*me_, desc.str());
}
}
// called by parent asking for pruning of this' interface
void SerialContainerPrivate::resolveInterface(InterfaceFlags expected) {
// we need to have some children to do the actual work
if (children().empty())
throw InitStageException(*me(), "no children");
if (!(expected & START_IF_MASK))
throw InitStageException(*me(), "unknown start interface");
Stage& first = *children().front();
Stage& last = *children().back();
InitStageException exceptions;
try { // FIRST child
first.pimpl()->resolveInterface(expected & START_IF_MASK);
// connect first child's (start) push interface
setChildsPushBackwardInterface(first.pimpl());
// validate that first child's and this container's start interfaces match
validateInterface<START_IF_MASK>(*first.pimpl(), expected);
// connect first child's (start) pull interface
if (const InterfacePtr& target = first.pimpl()->starts())
starts_ = std::make_shared<Interface>([this, target](Interface::iterator it, Interface::UpdateFlags updated) {
this->copyState<Interface::FORWARD>(it, target, updated);
});
} catch (InitStageException& e) {
exceptions.append(e);
}
// process all children and connect them
for (auto it = ++children().begin(), previous_it = children().begin(); it != children().end(); ++it, ++previous_it) {
try {
StagePrivate* child_impl = (**it).pimpl();
StagePrivate* previous_impl = (**previous_it).pimpl();
child_impl->resolveInterface(invert(previous_impl->requiredInterface()) & START_IF_MASK);
child_impl = (**it).pimpl(); // re-assign as pimpl_ pointer of a Fallback container will change!
connect(*previous_impl, *child_impl);
} catch (InitStageException& e) {
exceptions.append(e);
}
}
try { // connect last child's (end) push interface
setChildsPushForwardInterface(last.pimpl());
// validate that last child's and this container's end interfaces match
validateInterface<END_IF_MASK>(*last.pimpl(), expected);
// connect last child's (end) pull interface
if (const InterfacePtr& target = last.pimpl()->ends())
ends_ = std::make_shared<Interface>([this, target](Interface::iterator it, Interface::UpdateFlags updated) {
this->copyState<Interface::BACKWARD>(it, target, updated);
});
} catch (InitStageException& e) {
exceptions.append(e);
}
required_interface_ = (first.pimpl()->interfaceFlags() & START_IF_MASK) | // clang-format off
(last.pimpl()->interfaceFlags() & END_IF_MASK); // clang-format off
if (exceptions)
throw exceptions;
}
void SerialContainerPrivate::validateConnectivity() const {
ContainerBasePrivate::validateConnectivity();
InterfaceFlags mine = interfaceFlags();
// check that input/output interface of first/last child matches this' resp. interface
validateInterface<START_IF_MASK>(*children().front()->pimpl(), mine);
validateInterface<END_IF_MASK>(*children().back()->pimpl(), mine);
// validate connectivity of children between each other
// ContainerBasePrivate::validateConnectivity() ensures that required push interfaces are present,
// that is, neighbouring stages have a corresponding pull interface.
// Here, it remains to check that - if a child has a pull interface - it's indeed feeded.
for (auto cur = children().begin(), end = children().end(); cur != end; ++cur) {
const StagePrivate* const cur_impl = **cur;
InterfaceFlags required = cur_impl->interfaceFlags();
// get iterators to prev/next stage in sequence
auto prev = cur;
--prev;
auto next = cur;
++next;
// start pull interface fed?
if (cur != children().begin() && // first child has not a previous one
(required & READS_START) && !(*prev)->pimpl()->nextStarts())
throw InitStageException(**cur, "start interface is not fed");
// end pull interface fed?
if (next != end && // last child has not a next one
(required & READS_END) && !(*next)->pimpl()->prevEnds())
throw InitStageException(**cur, "end interface is not fed");
}
}
bool SerialContainer::canCompute() const {
for (const auto& stage : pimpl()->children()) {
if (stage->pimpl()->canCompute())
return true;
}
return false;
}
void SerialContainer::compute() {
for (const auto& stage : pimpl()->children()) {
if (stage->pimpl()->canCompute())
stage->pimpl()->runCompute();
}
}
ParallelContainerBasePrivate::ParallelContainerBasePrivate(ParallelContainerBase* me, const std::string& name)
: ContainerBasePrivate(me, name) {}
void ParallelContainerBasePrivate::resolveInterface(InterfaceFlags expected) {
// we need to have some children to do the actual work
if (children().empty())
throw InitStageException(*me(), "no children");
InitStageException exceptions;
bool first = true;
for (const Stage::pointer& child : children()) {
try {
auto child_impl = child->pimpl();
child_impl->resolveInterface(expected);
validateInterfaces(*child_impl, expected, first);
// initialize push connections of children according to their demands
setChildsPushBackwardInterface(child_impl);
setChildsPushForwardInterface(child_impl);
first = false;
} catch (InitStageException& e) {
exceptions.append(e);
continue;
}
}
if (exceptions)
throw exceptions;
required_interface_ = expected;
initializeExternalInterfaces();
}
void ParallelContainerBasePrivate::initializeExternalInterfaces() {
// States received by the container need to be copied to all children's pull interfaces.
if (requiredInterface() & READS_START)
starts() = std::make_shared<Interface>([this](Interface::iterator external, Interface::UpdateFlags updated) {
this->propagateStateToAllChildren<Interface::FORWARD>(external, updated);
});
if (requiredInterface() & READS_END)
ends() = std::make_shared<Interface>([this](Interface::iterator external, Interface::UpdateFlags updated) {
this->propagateStateToAllChildren<Interface::BACKWARD>(external, updated);
});
}
void ParallelContainerBasePrivate::validateInterfaces(const StagePrivate& child, InterfaceFlags& external,
bool first) const {
const InterfaceFlags child_interface = child.requiredInterface();
bool valid = true;
for (InterfaceFlags mask : { START_IF_MASK, END_IF_MASK }) {
if ((external & mask) == UNKNOWN)
external |= child_interface & mask;
valid = valid & ((external & mask) == (child_interface & mask));
}
if (!valid) {
boost::format desc("interface of '%1%' (%3% %4%) does not match %2% (%5% %6%).");
desc % child.name();
desc % (first ? "external one" : "other children's");
desc % flowSymbol<START_IF_MASK>(child_interface) % flowSymbol<END_IF_MASK>(child_interface);
desc % flowSymbol<START_IF_MASK>(external) % flowSymbol<END_IF_MASK>(external);
throw InitStageException(*me_, desc.str());
}
}
void ParallelContainerBasePrivate::validateConnectivity() const {
InterfaceFlags my_interface = interfaceFlags();
// check that input/output interfaces of all children are handled by my interface
for (const auto& child : children())
validateInterfaces(*child->pimpl(), my_interface);
ContainerBasePrivate::validateConnectivity();
}
template <Interface::Direction dir>
void ParallelContainerBasePrivate::propagateStateToAllChildren(Interface::iterator external, Interface::UpdateFlags updated) {
for (const Stage::pointer& stage : children())
copyState<dir>(external, stage->pimpl()->pullInterface<dir>(), updated);
}
ParallelContainerBase::ParallelContainerBase(ParallelContainerBasePrivate* impl) : ContainerBase(impl) {}
ParallelContainerBase::ParallelContainerBase(const std::string& name)
: ParallelContainerBase(new ParallelContainerBasePrivate(this, name)) {}
void ParallelContainerBase::liftSolution(const SolutionBase& solution, double cost, std::string comment) {
pimpl()->liftSolution(std::make_shared<WrappedSolution>(this, &solution, cost, std::move(comment)),
solution.start(), solution.end());
}
void ParallelContainerBase::spawn(InterfaceState&& state, SubTrajectory&& t) {
pimpl()->StagePrivate::spawn(std::move(state), std::make_shared<SubTrajectory>(std::move(t)));
}
void ParallelContainerBase::sendForward(const InterfaceState& from, InterfaceState&& to, SubTrajectory&& t) {
pimpl()->StagePrivate::sendForward(from, std::move(to), std::make_shared<SubTrajectory>(std::move(t)));
}
void ParallelContainerBase::sendBackward(InterfaceState&& from, const InterfaceState& to, SubTrajectory&& t) {
pimpl()->StagePrivate::sendBackward(std::move(from), to, std::make_shared<SubTrajectory>(std::move(t)));
}
WrapperBasePrivate::WrapperBasePrivate(WrapperBase* me, const std::string& name)
: ParallelContainerBasePrivate(me, name) {}
WrapperBase::WrapperBase(const std::string& name, Stage::pointer&& child)
: WrapperBase(new WrapperBasePrivate(this, name), std::move(child)) {}
WrapperBase::WrapperBase(WrapperBasePrivate* impl, Stage::pointer&& child) : ParallelContainerBase(impl) {
if (child)
WrapperBase::insert(std::move(child));
}
void WrapperBase::insert(Stage::pointer&& stage, int before) {
// restrict num of children to one
if (numChildren() > 0)
throw std::runtime_error(name() + ": Wrapper only allows a single child");
return ParallelContainerBase::insert(std::move(stage), before);
}
Stage* WrapperBase::wrapped() {
return pimpl()->children().empty() ? nullptr : pimpl()->children().front().get();
}
bool WrapperBase::canCompute() const {
return wrapped()->pimpl()->canCompute();
}
void WrapperBase::compute() {
wrapped()->pimpl()->runCompute();
}
bool Alternatives::canCompute() const {
for (const auto& stage : pimpl()->children())
if (stage->pimpl()->canCompute())
return true;
return false;
}
void Alternatives::compute() {
for (const auto& stage : pimpl()->children()) {
stage->pimpl()->runCompute();
}
}
void Alternatives::onNewSolution(const SolutionBase& s) {
liftSolution(s);
}
Fallbacks::Fallbacks(const std::string& name) : Fallbacks(new FallbacksPrivate(this, name)) {}
Fallbacks::Fallbacks(FallbacksPrivate* impl) : ParallelContainerBase(impl) {}
void Fallbacks::reset() {
ParallelContainerBase::reset();
pimpl()->reset();
}
void Fallbacks::init(const moveit::core::RobotModelConstPtr& robot_model) {
ParallelContainerBase::init(robot_model);
pimpl()->reset();
}
void Fallbacks::onNewSolution(const SolutionBase& s) {
pimpl()->onNewSolution(s);
}
inline void Fallbacks::replaceImpl() {
FallbacksPrivate *impl = pimpl();
switch (pimpl()->requiredInterface()) {
case GENERATE:
impl = new FallbacksPrivateGenerator(std::move(*impl));
break;
case PROPAGATE_FORWARDS:
case PROPAGATE_BACKWARDS:
impl = new FallbacksPrivatePropagator(std::move(*impl));
break;
case CONNECT:
// For now, we only support Connecting children
for (const auto& child : impl->children())
if (!dynamic_cast<Connecting*>(child.get()))
throw std::runtime_error("CONNECT-like interface is only supported for Connecting children");
impl = new FallbacksPrivateConnect(std::move(*impl));
break;
}
delete pimpl_;
pimpl_ = impl;
}
FallbacksPrivate::FallbacksPrivate(Fallbacks* me, const std::string& name)
: ParallelContainerBasePrivate(me, name) {}
FallbacksPrivate::FallbacksPrivate(FallbacksPrivate&& other)
: ParallelContainerBasePrivate(static_cast<Fallbacks*>(other.me()), "") {
// move contents of other
this->ParallelContainerBasePrivate::operator=(std::move(other));
}
void FallbacksPrivate::initializeExternalInterfaces() {
// Here we know the final interface of the container (and all its children)
// Thus replace, this pimpl() with a new interface-specific one:
static_cast<Fallbacks*>(me())->replaceImpl();
}
void FallbacksPrivate::onNewSolution(const SolutionBase& s) {
// printChildrenInterfaces(*this, true, *s.creator());
static_cast<Fallbacks*>(me())->liftSolution(s);
}
void FallbacksPrivate::onNewFailure(const Stage& child, const InterfaceState* /*from*/, const InterfaceState* /*to*/) {
// This override is deliberately empty.
// The method prunes solution paths when a child failed to find a valid solution for it,
// but in Fallbacks the next child might still yield a successful solution
// Thus pruning must only occur once the last child is exhausted (inside computePropagate)
// printChildrenInterfaces(*this, false, child);
(void)child;
}
void FallbacksPrivateCommon::reset() {
current_ = children().begin();
}
bool FallbacksPrivateCommon::canCompute() const {
while(current_ != children().end() && // not completely exhausted
!(*current_)->pimpl()->canCompute()) // but current child cannot compute
return const_cast<FallbacksPrivateCommon*>(this)->nextJob(); // advance to next job
// return value: current child is well defined and thus can compute?
return current_ != children().end();
}
void FallbacksPrivateCommon::compute() {
(*current_)->pimpl()->runCompute();
}
inline void FallbacksPrivateCommon::nextChild() {
if (std::next(current_) != children().end())
RCLCPP_DEBUG_STREAM(rclcpp::get_logger("Fallbacks"), "Child '" << (*current_)->name() << "' failed, trying next one.");
++current_; // advance to next child
}
FallbacksPrivateGenerator::FallbacksPrivateGenerator(FallbacksPrivate&& old)
: FallbacksPrivateCommon(std::move(old)) { FallbacksPrivateCommon::reset(); }
bool FallbacksPrivateGenerator::nextJob() {
assert(current_ != children().end() && !(*current_)->pimpl()->canCompute());
// don't advance to next child when we already produced solutions
if (!solutions_.empty()) {
current_ = children().end(); // indicate that we are exhausted
return false;
}
do { nextChild(); }
while (current_ != children().end() && !(*current_)->pimpl()->canCompute());
// return value shall indicate current_->canCompute()
return current_ != children().end();
}
FallbacksPrivatePropagator::FallbacksPrivatePropagator(FallbacksPrivate&& old)
: FallbacksPrivateCommon(std::move(old)) {
switch (requiredInterface()) {
case PROPAGATE_FORWARDS:
dir_ = Interface::FORWARD;
starts() = std::make_shared<Interface>();
break;
case PROPAGATE_BACKWARDS:
dir_ = Interface::BACKWARD;
ends() = std::make_shared<Interface>();
break;
default:
assert(false);
}
FallbacksPrivatePropagator::reset();
}
void FallbacksPrivatePropagator::reset() {
FallbacksPrivateCommon::reset();
job_ = pullInterface(dir_)->end(); // indicate fresh start
job_has_solutions_ = false;
}
void FallbacksPrivatePropagator::onNewSolution(const SolutionBase& s) {
job_has_solutions_ = true;
FallbacksPrivateCommon::onNewSolution(s);
}