Task.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of ArmarX.
3  *
4  * Copyright (C) 2011-2017, High Performance Humanoid Technologies (H2T), Karlsruhe Institute of Technology (KIT), all rights reserved.
5  *
6  * ArmarX is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  *
10  * ArmarX is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  *
18  * @package ArmarX
19  * @author Mirko Waechter( mirko.waechter at kit dot edu)
20  * @date 2017
21  * @copyright http://www.gnu.org/licenses/gpl-2.0.txt
22  * GNU General Public License
23  */
24 #include "Task.h"
25 
26 #include "../../util/CollisionCheckUtil.h"
27 #include "../../util/Metrics.h"
28 
29 #include <MotionPlanning/Planner/BiRrt.h>
30 #include <MotionPlanning/CSpace/CSpacePath.h>
33 #include <MotionPlanning/PostProcessing/ShortcutProcessor.h>
34 
35 #include <SimoxUtility/algorithm/string/string_tools.h>
36 
37 namespace armarx::birrt
38 {
39 
40  Task::Task(const CSpaceBasePtr& cspace, const VectorXf& startCfg, const VectorXf& goalCfg, const std::string& taskName, Ice::Long maximalPlanningTimeInSeconds, float dcdStep)
41  {
42  this->cspace = cspace->clone();
43  this->startCfg = startCfg;
44  this->goalCfg = goalCfg;
45  this->dcdStep = dcdStep;
46  this->maximalPlanningTimeInSeconds = maximalPlanningTimeInSeconds;
47  this->taskName = taskName;
48 
49  if (startCfg.size() != goalCfg.size() || startCfg.size() != static_cast<std::size_t>(this->cspace->getDimensionality()))
50  {
51  throw std::invalid_argument {"start and goal have to be the size of the cspace's dimensionality"};
52  }
53  }
54 
55  void Task::abortTask(const::Ice::Current&)
56  {
57  }
58 
59  Path Task::getPath(const::Ice::Current&) const
60  {
61  std::lock_guard<std::mutex> lock {mtx};
62  return solution;
63  }
64 
65  void Task::run(const RemoteObjectNodePrxList&, const::Ice::Current&)
66  {
67 
68  auto failureOutput = [this]
69  {
70  SimoxCSpacePtr origCSpace = getOriginalCSpace();
71  ARMARX_CHECK_EXPRESSION(origCSpace);
72 
73  std::stringstream ss;
74  for (auto set : origCSpace->getCD().getSceneObjectSets())
75  {
76  if (origCSpace->getCD().isInCollision(set))
77  {
78  std::string name = set->getName();
79  Ice::StringSeq names;
80  if (name.empty())
81  {
83  for (auto e : set->getSceneObjects())
84  {
85  names.push_back(e->getName());
86  }
87  }
88  else
89  {
90  names.push_back(name);
91  }
92 
93  ss << "scene object set consisting of " << simox::alg::join(names, ", ") << " is in collision\n";
94  }
95  }
96  return ss.str();
97  };
98 
99 
100  setTaskStatus(TaskStatus::ePlanning);
101  ARMARX_CHECK_EXPRESSION(cspace);
102  //check trivial cases
103  cspace->initCollisionTest();
104 
105  const auto startIsCollisionFree = cspace->isCollisionFree(std::pair<const Ice::Float*, const Ice::Float*> {startCfg.data(), startCfg.data() + startCfg.size()});
106  if (!startIsCollisionFree)
107  {
108  ARMARX_WARNING << "BiRRT failed trivially: start config is in collision: " << startCfg << " Collisions:\n" << failureOutput();
109 
110  setTaskStatus(TaskStatus::ePlanningFailed);
111  return;
112  }
113  const auto goalIscollisionFree = cspace->isCollisionFree(std::pair<const Ice::Float*, const Ice::Float*> { goalCfg.data(), goalCfg.data() + goalCfg.size()});
114  if (!goalIscollisionFree)
115  {
116  ARMARX_WARNING << "BiRRT failed trivially: goal config is in collision" << goalCfg << " Collisions:\n" << failureOutput();
117  setTaskStatus(TaskStatus::ePlanningFailed);
118  return;
119  }
120 
121  SimoxCSpacePtr origCSpace = getOriginalCSpace();
122  ARMARX_CHECK_EXPRESSION(origCSpace);
123  ARMARX_INFO << "RobotConfig: " << origCSpace->getAgentSceneObj()->getConfig()->getRobotNodeJointValueMap();
124  Saba::CSpaceSampledPtr sampledcSpace = getOriginalCSpace()->createSimoxCSpace();
125  ARMARX_CHECK_EXPRESSION(sampledcSpace);
126  IceUtil::Time start = IceUtil::Time::now();
128  {
129  ARMARX_INFO << "BiRRT took : " << (IceUtil::Time::now() - start).toMilliSecondsDouble() << " ms";
130  };
131 
132  ScaledCSpacePtr scaledCSpace = ScaledCSpacePtr::dynamicCast(cspace);
133  if (scaledCSpace)
134  {
135  ARMARX_VERBOSE << "unscaling configs " << VAROUT(startCfg) << VAROUT(goalCfg);
136  scaledCSpace->unscaleConfig(startCfg);
137  scaledCSpace->unscaleConfig(goalCfg);
138  sampledcSpace->setMetricWeights(Eigen::Map<Eigen::VectorXf>(scaledCSpace->getScalingFactors().data(), scaledCSpace->getScalingFactors().size()));
139  ARMARX_VERBOSE << "unscaled configs " << VAROUT(startCfg) << VAROUT(goalCfg);
140  }
141 
142  const auto distStartEnd = euclideanDistance(startCfg.begin(), startCfg.end(), goalCfg.begin());
143 
144  if (distStartEnd <= dcdStep)
145  {
146  setTaskStatus(TaskStatus::eDone);
147  solution.nodes.emplace_back(startCfg);
148  solution.nodes.emplace_back(goalCfg);
149  return;
150  }
151 
152 
153 
154  Saba::Rrt::RrtMethod mode;
155  mode = Saba::Rrt::eExtend;
156  ARMARX_CHECK_EXPRESSION(cspace);
157  ARMARX_INFO << "CSpace type : " << cspace->ice_id();
158 
159 
160  ARMARX_INFO << "Created simox cspace";
161  // float samplingSize = 0.04f;
162  // sampledcSpace->setSamplingSize(samplingSize);
163  sampledcSpace->setSamplingSizeDCD(dcdStep);
164  ARMARX_INFO << "SamplingSizeDCD: " << sampledcSpace->getSamplingSizeDCD();
165  Saba::BiRrtPtr rrt(new Saba::BiRrt(sampledcSpace,
166  mode/*, mode2, samplingSize*/));
167 
168 
169  rrt->setStart(Eigen::Map<Eigen::ArrayXf>(startCfg.data(), startCfg.size()));
170  rrt->setGoal(Eigen::Map<Eigen::ArrayXf>(goalCfg.data(), goalCfg.size()));
171 
172  bool planningSucceeded = rrt->plan();
173  if (planningSucceeded)
174  {
175  ARMARX_VERBOSE << "BiRRT succeeded! ";
176  Saba::CSpacePathPtr tmpSolution = rrt->getSolution();
177  ARMARX_INFO << "waypoints: " << tmpSolution->getPoints().size();
178 
179 
180  TIMING_START(ShortCutter);
181  ARMARX_INFO << "Shortcutting!";
182  Saba::ShortcutProcessor shortcutter(tmpSolution, sampledcSpace);
183  tmpSolution = shortcutter.shortenSolutionRandom(100, 200);
184  ARMARX_INFO << "Shortcutting resulted into " << tmpSolution->getPoints().size();
185  TIMING_END(ShortCutter);
186  for (auto& vec : tmpSolution->getPoints())
187  {
188  this->solution.nodes.push_back(VectorXf {vec.data(), vec.data() + vec.rows()});
189  }
190  ARMARX_VERBOSE << VAROUT(solution.nodes);
191  if (scaledCSpace)
192  {
193  scaledCSpace->scalePath(solution);
194  }
195  // auto from = *solution.nodes.begin();
196  // int i = 1;
197  // for (auto& to : solution.nodes)
198  // {
199  // bool collisionFree = dcdIsPathCollisionFree(
200  // from, to, dcdStep,
201  // [this](const VectorXf & cfg)
202  // {
203  // return cspace->isCollisionFree({cfg.data(), cfg.data() + cfg.size()});
204  // },
205  // false
206  // );
207  // if (!collisionFree)
208  // {
209  // ARMARX_ERROR << "Collision in path at node: " << i << " Collisions:\n" << failureOutput();
210  // setTaskStatus(TaskStatus::ePlanningFailed);
211  // return;
212  // }
213  // from = to;
214  // i++;
215  // }
216 
217  setTaskStatus(TaskStatus::eDone);
218  return;
219  }
220 
221  else
222  {
223  setTaskStatus(TaskStatus::ePlanningFailed);
224  return;
225  }
226  }
227 
229  {
230  SimoxCSpacePtr origCSpace;
231  if (cspace->ice_isA(CSpaceAdaptorBase::ice_staticId()))
232  {
233  origCSpace = SimoxCSpacePtr::dynamicCast(CSpaceAdaptorBasePtr::dynamicCast(cspace)->getOriginalCSpace());
234 
235  // sampledcSpace = ScaledCSpacePtr::dynamicCast(cspace)->getOriginal()->createSimoxCSpace();
236  }
237  else
238  {
239  origCSpace = SimoxCSpacePtr::dynamicCast(cspace);
240  }
241  return origCSpace;
242  }
243 
244 
245 }
ARMARX_VERBOSE
#define ARMARX_VERBOSE
Definition: Logging.h:180
TIMING_START
#define TIMING_START(name)
Definition: TimeUtil.h:280
TIMING_END
#define TIMING_END(name)
Definition: TimeUtil.h:296
OnScopeExit.h
ScaledCSpace.h
ARMARX_ON_SCOPE_EXIT
#define ARMARX_ON_SCOPE_EXIT
Executes given code when the enclosing scope is left.
Definition: OnScopeExit.h:112
armarx::birrt::Task::getPath
Path getPath(const ::Ice::Current &) const override
Definition: Task.cpp:59
armarx::birrt::Task::abortTask
void abortTask(const ::Ice::Current &) override
Definition: Task.cpp:55
IceInternal::Handle< SimoxCSpace >
armarx::birrt::Task::Task
Task()=default
armarx::birrt::Task::run
void run(const RemoteObjectNodePrxList &, const ::Ice::Current &) override
Definition: Task.cpp:65
armarx::birrt::Task::mtx
std::mutex mtx
Definition: Task.h:61
armarx::birrt::Task::solution
Path solution
Definition: Task.h:62
Task.h
armarx::VariantType::Long
const VariantTypeId Long
Definition: Variant.h:917
armarx::armem::Time
armarx::core::time::DateTime Time
Definition: forward_declarations.h:13
armarx::birrt
Definition: Task.cpp:37
armarx::euclideanDistance
float euclideanDistance(IteratorType1 first1, IteratorType1 last1, IteratorType2 first2)
Returns the euclidean distance.
Definition: Metrics.h:94
ARMARX_CHECK_EXPRESSION
#define ARMARX_CHECK_EXPRESSION(expression)
This macro evaluates the expression and if it turns out to be false it will throw an ExpressionExcept...
Definition: ExpressionException.h:73
armarx::viz::data::ElementFlags::names
const simox::meta::IntEnumNames names
Definition: json_elements.cpp:14
ARMARX_INFO
#define ARMARX_INFO
Definition: Logging.h:174
VAROUT
#define VAROUT(x)
Definition: StringHelpers.h:182
set
set(LIBS ArmarXCoreInterfaces ${CMAKE_THREAD_LIBS_INIT} ${dl_LIBRARIES} ${rt_LIBRARIES} ${QT_LIBRARIES} ${Boost_LIBRARIES} BoostAssertionHandler ArmarXCPPUtility SimoxUtility) set(LIB_FILES ArmarXManager.cpp ArmarXMultipleObjectsScheduler.cpp ArmarXObjectScheduler.cpp ManagedIceObject.cpp ManagedIceObjectPlugin.cpp Component.cpp ComponentPlugin.cpp IceGridAdmin.cpp ArmarXObjectObserver.cpp IceManager.cpp PackagePath.cpp RemoteReferenceCount.cpp logging/LoggingUtil.cpp logging/Logging.cpp logging/LogSender.cpp logging/ArmarXLogBuf.cpp system/ArmarXDataPath.cpp system/DynamicLibrary.cpp system/ProcessWatcher.cpp system/FactoryCollectionBase.cpp system/cmake/CMakePackageFinder.cpp system/cmake/CMakePackageFinderCache.cpp system/cmake/ArmarXPackageToolInterface.cpp system/RemoteObjectNode.cpp services/sharedmemory/HardwareId.cpp services/tasks/RunningTask.cpp services/tasks/ThreadList.cpp services/tasks/ThreadPool.cpp services/profiler/Profiler.cpp services/profiler/FileLoggingStrategy.cpp services/profiler/IceLoggingStrategy.cpp application/Application.cpp application/ApplicationOptions.cpp application/ApplicationProcessFacet.cpp application/ApplicationNetworkStats.cpp application/properties/PropertyUser.cpp application/properties/Property.cpp application/properties/PropertyDefinition.cpp application/properties/PropertyDefinitionContainer.cpp application/properties/PropertyDefinitionHelpFormatter.cpp application/properties/PropertyDefinitionConfigFormatter.cpp application/properties/PropertyDefinitionBriefHelpFormatter.cpp application/properties/PropertyDefinitionXmlFormatter.cpp application/properties/PropertyDefinitionDoxygenFormatter.cpp application/properties/PropertyDefinitionDoxygenComponentPagesFormatter.cpp application/properties/PropertyDefinitionContainerBriefHelpFormatter.cpp application/properties/IceProperties.cpp exceptions/Exception.cpp exceptions/local/UnexpectedEnumValueException.cpp util/FileSystemPathBuilder.cpp util/StringHelpers.cpp util/IceReportSkipper.cpp util/Throttler.cpp util/distributed/AMDCallbackCollection.cpp util/distributed/RemoteHandle/ClientSideRemoteHandleControlBlock.cpp util/distributed/RemoteHandle/RemoteHandle.cpp util/distributed/RemoteHandle/RemoteHandleControlBlock.cpp time/ice_conversions.cpp time/json_conversions.cpp time/CallbackWaitLock.cpp time/Clock.cpp time/ClockType.cpp time/ClockTypeNames.cpp time/CycleUtil.cpp time/DateTime.cpp time/Duration.cpp time/Frequency.cpp time/LocalTimeServer.cpp time/Metronome.cpp time/ScopedStopWatch.cpp time/StopWatch.cpp time/Timer.cpp time/TimeKeeper.cpp time/TimeUtil.cpp csv/CsvWriter.cpp csv/CsvReader.cpp eigen/conversions.cpp eigen/ice_conversions.cpp) set(LIB_HEADERS ArmarXManager.h ArmarXDummyManager.h ArmarXMultipleObjectsScheduler.h ArmarXObjectObserver.h ArmarXObjectScheduler.h ArmarXFwd.h Component.h ComponentPlugin.h ComponentFactories.h CoreObjectFactories.h IceGridAdmin.h IceManager.h IceManagerImpl.h json_conversions.h ManagedIceObject.h ManagedIceObjectPlugin.h ManagedIceObjectImpl.h ManagedIceObjectDependency.h ManagedIceObjectRegistryInterface.h PackagePath.h RemoteReferenceCount.h system/ImportExport.h system/ImportExportComponent.h system/AbstractFactoryMethod.h system/FactoryCollectionBase.h system/Synchronization.h system/ArmarXDataPath.h system/DynamicLibrary.h system/ProcessWatcher.h system/ConditionSynchronization.h system/cmake/CMakePackageFinder.h system/cmake/CMakePackageFinderCache.h system/cmake/FindPackageX.cmake system/cmake/ArmarXPackageToolInterface.h system/RemoteObjectNode.h logging/LoggingUtil.h logging/LogSender.h logging/Logging.h logging/ArmarXLogBuf.h logging/SpamFilterData.h services/tasks/RunningTask.h services/tasks/PeriodicTask.h services/tasks/ThreadList.h services/tasks/TaskUtil.h services/tasks/ThreadPool.h services/sharedmemory/SharedMemoryProvider.h services/sharedmemory/SharedMemoryConsumer.h services/sharedmemory/IceSharedMemoryProvider.h services/sharedmemory/IceSharedMemoryConsumer.h services/sharedmemory/HardwareIdentifierProvider.h services/sharedmemory/HardwareId.h services/sharedmemory/exceptions/SharedMemoryExceptions.h services/profiler/Profiler.h services/profiler/LoggingStrategy.h services/profiler/FileLoggingStrategy.h services/profiler/IceLoggingStrategy.h application/Application.h application/ApplicationOptions.h application/ApplicationProcessFacet.h application/ApplicationNetworkStats.h application/properties/forward_declarations.h application/properties/Properties.h application/properties/Property.h application/properties/PluginEigen.h application/properties/PluginEnumNames.h application/properties/PluginCfgStruct.h application/properties/PluginAll.h application/properties/PropertyUser.h application/properties/PropertyDefinition.h application/properties/PropertyDefinition.hpp application/properties/PropertyDefinitionInterface.h application/properties/PropertyDefinitionContainer.h application/properties/PropertyDefinitionFormatter.h application/properties/PropertyDefinitionContainerFormatter.h application/properties/PropertyDefinitionConfigFormatter.h application/properties/PropertyDefinitionHelpFormatter.h application/properties/PropertyDefinitionBriefHelpFormatter.h application/properties/PropertyDefinitionXmlFormatter.h application/properties/PropertyDefinitionDoxygenFormatter.h application/properties/PropertyDefinitionDoxygenComponentPagesFormatter.h application/properties/PropertyDefinitionContainerBriefHelpFormatter.h application/properties/ProxyPropertyDefinition.h application/properties/IceProperties.h exceptions/Exception.h exceptions/LocalException.h exceptions/local/DynamicLibraryException.h exceptions/local/ExpressionException.h exceptions/local/FileIOException.h exceptions/local/InvalidPropertyValueException.h exceptions/local/MissingRequiredPropertyException.h exceptions/local/PropertyInheritanceCycleException.h exceptions/local/ProxyNotInitializedException.h exceptions/local/UnexpectedEnumValueException.h exceptions/local/UnmappedValueException.h exceptions/local/ValueRangeExceededException.h exceptions/user/NotImplementedYetException.h rapidxml/rapidxml.hpp rapidxml/rapidxml_print.hpp rapidxml/rapidxml_iterators.hpp rapidxml/rapidxml_utils.hpp rapidxml/wrapper/RapidXmlReader.h rapidxml/wrapper/RapidXmlWriter.h rapidxml/wrapper/DefaultRapidXmlReader.h rapidxml/wrapper/MultiNodeRapidXMLReader.h util/IceBlobToObject.h util/ObjectToIceBlob.h util/FileSystemPathBuilder.h util/FiniteStateMachine.h util/StringHelpers.h util/StringHelperTemplates.h util/algorithm.h util/OnScopeExit.h util/Predicates.h util/Preprocessor.h util/PropagateConst.h util/Registrar.h util/TemplateMetaProgramming.h util/TripleBuffer.h util/IceReportSkipper.h util/Throttler.h util/distributed/AMDCallbackCollection.h util/distributed/RemoteHandle/ClientSideRemoteHandleControlBlock.h util/distributed/RemoteHandle/RemoteHandle.h util/distributed/RemoteHandle/RemoteHandleControlBlock.h util/SimpleStatemachine.h time.h time_minimal.h time/forward_declarations.h time/ice_conversions.h time/json_conversions.h time/CallbackWaitLock.h time/Clock.h time/ClockType.h time/ClockTypeNames.h time/CycleUtil.h time/DateTime.h time/Duration.h time/Frequency.h time/LocalTimeServer.h time/Metronome.h time/ScopedStopWatch.h time/StopWatch.h time/Timer.h time/TimeUtil.h time/TimeKeeper.h csv/CsvWriter.h csv/CsvReader.h eigen/conversions.h eigen/ice_conversions.h ice_conversions.h ice_conversions/ice_conversions_boost_templates.h ice_conversions/ice_conversions_templates.h ice_conversions/ice_conversions_templates.tpp $
Definition: CMakeLists.txt:12
armarx::MotionPlanningTask::setTaskStatus
bool setTaskStatus(TaskStatus::Status newTaskStatus, const Ice::Current &=Ice::emptyCurrent) override
Definition: MotionPlanningTask.cpp:30
armarx::armem::server::ltm::detail::mixin::Path
std::filesystem::path Path
Definition: DiskStorageMixin.h:17
armarx::birrt::Task::getOriginalCSpace
SimoxCSpacePtr getOriginalCSpace() const
Definition: Task.cpp:228
ARMARX_WARNING
#define ARMARX_WARNING
Definition: Logging.h:186