GraspablePredicateProvider.cpp
Go to the documentation of this file.
1 /*
2 * This file is part of ArmarX.
3 *
4 * ArmarX is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * ArmarX is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 * @package ArmarX::
17 * @author Valerij Wittenbeck ( valerij.wittenbeck at kit dot edu)
18 * @date 2015
19 * @copyright http://www.gnu.org/licenses/gpl-2.0.txt
20 * GNU General Public License
21 */
22 
24 
25 #include <SimoxUtility/algorithm/string/string_tools.h>
26 #include <VirtualRobot/Grasping/Grasp.h>
27 #include <VirtualRobot/Grasping/GraspSet.h>
28 
30 
32 
37 
38 using namespace memoryx;
39 
41  leftColor(armarx::DrawColor{0.f, 0.f, 1.f, 0.25f}),
42  rightColor(armarx::DrawColor{0.f, 1.f, 0.f, 0.25f}),
43  leftGraspable(PredicateInfo{"leftgraspable", 1}),
44  rightGraspable(PredicateInfo{"rightgraspable", 1})
45 {
46 }
47 
48 std::vector<Box>
49 GraspablePredicateProvider::stringToBoxes(const std::string& boxesString)
50 {
51  std::vector<Box> result;
52  std::vector<std::string> boxTuples = simox::alg::split(boxesString, ";");
53 
54  for (const auto& boxTupleString : boxTuples)
55  {
56  std::vector<std::string> boxTuple = simox::alg::split(boxTupleString, " ");
57  ARMARX_CHECK_EXPRESSION(boxTuple.size() == 6);
58 
59  result.push_back(Box{std::stof(boxTuple[0]),
60  std::stof(boxTuple[1]),
61  std::stof(boxTuple[2]),
62  std::stof(boxTuple[3]),
63  std::stof(boxTuple[4]),
64  std::stof(boxTuple[5])});
65  }
66 
67  return result;
68 }
69 
70 void
72 {
73  boxesL = stringToBoxes(getProperty<std::string>("BoundingBoxesL").getValue());
74  boxesR = stringToBoxes(getProperty<std::string>("BoundingBoxesR").getValue());
75 
76  usingProxy("WorkingMemory");
77  usingProxy("PriorKnowledge");
78 
79  debugDrawerTopicName = getProperty<std::string>("DebugDrawerTopicName").getValue();
80 
81  if (!debugDrawerTopicName.empty())
82  {
83  offeringTopic(debugDrawerTopicName);
84  }
85 }
86 
87 void
89 {
90  wm = getProxy<WorkingMemoryInterfacePrx>("WorkingMemory");
91  objectInstances = wm->getObjectInstancesSegment();
92  prior = getProxy<PriorKnowledgeInterfacePrx>("PriorKnowledge");
93  objectClasses = prior->getObjectClassesSegment();
94  fileManager =
95  memoryx::GridFileManagerPtr(new memoryx::GridFileManager(prior->getCommonStorage()));
96 
97  if (!debugDrawerTopicName.empty())
98  {
100  getTopic<armarx::DebugDrawerInterfacePrx>(debugDrawerTopicName);
101 
102  for (size_t i = 0; i < boxesL.size(); ++i)
103  {
104  boxesL[i].drawTo(debugDrawer,
105  getDefaultName(),
106  leftGraspable.name + "_box_" + std::to_string(i),
107  leftColor);
108  }
109 
110  for (size_t i = 0; i < boxesR.size(); ++i)
111  {
112  boxesR[i].drawTo(debugDrawer,
113  getDefaultName(),
114  rightGraspable.name + "_box_" + std::to_string(i),
115  rightColor);
116  }
117  }
118 }
119 
120 std::string
122 {
123  return "GraspablePredicateProvider";
124 }
125 
126 PredicateInfoList
128 {
129  return {leftGraspable, rightGraspable};
130 }
131 
132 void
133 GraspablePredicateProvider::addPredicateIfInside(PredicateInstanceList& result,
134  const std::string& predicateName,
135  const ObjectInstancePtr& obj,
136  const std::vector<Box>& boxes)
137 {
138  bool inside = false;
139  auto pos = obj->getPosition();
140 
141  if (pos->getFrame() != armarx::GlobalFrame && !pos->getFrame().empty())
142  {
143  pos = armarx::FramedPosePtr::dynamicCast(
144  wm->getAgentInstancesSegment()->convertToWorldPose(pos->agent, obj->getPose()))
145  ->getPosition();
146  }
147 
148  ARMARX_DEBUG << "Obj: " << obj->getName() << " pos: " << *pos;
149 
150  for (const auto& box : boxes)
151  {
152  inside |= box.inside(pos);
153  }
154 
155  if (inside)
156  {
157  ARMARX_DEBUG << obj->getName() << " " << predicateName;
158  result.push_back(PredicateInstance{
159  predicateName, {objectInstances->getEntityRefById(obj->getId())}, true});
160  }
161 }
162 
163 PredicateInstanceList
165 {
166  PredicateInstanceList result;
167 
168  for (const auto& entity : objectInstances->getAllEntities())
169  {
170  ObjectInstancePtr object = ObjectInstancePtr::dynamicCast(entity);
171  const std::string className = object->getMostProbableClass();
172 
173  auto graspabilityDescriptorIt = std::find_if(graspabilityDescriptors.cbegin(),
174  graspabilityDescriptors.cend(),
175  [&](const GraspabilityDescriptor& gd)
176  { return gd.className == className; });
177 
178  if (graspabilityDescriptorIt == graspabilityDescriptors.cend())
179  {
180  auto parents =
181  objectClasses->getObjectClassByNameWithAllParents(className)->getParentClasses();
182 
183  bool hasGraspableSuperclass =
184  std::find(parents.cbegin(), parents.cend(), "graspable") != parents.cend();
185  hasGraspableSuperclass |=
186  std::find(parents.cbegin(), parents.cend(), "bothhandsgraspable") != parents.cend();
187  GraspabilityDescriptor gd{className, hasGraspableSuperclass, false, false};
188 
189  ObjectClassPtr objectClass =
190  ObjectClassPtr::dynamicCast(objectClasses->getEntityByName(className));
191  memoryx::EntityWrappers::SimoxObjectWrapperPtr simoxWrapper = objectClass->addWrapper(
193  VirtualRobot::ManipulationObjectPtr mo = simoxWrapper->getManipulationObject();
194 
195  gd.hasLeftGrasp = false;
196  gd.hasRightGrasp = false;
197  if (mo)
198  {
199  auto hasGrasp = [](VirtualRobot::GraspSetPtr set)
200  {
201  if (!set)
202  {
203  return false;
204  }
205 
206  for (size_t i = 0; i < set->getSize(); ++i)
207  {
208  if (armarx::Contains(set->getGrasp(i)->getName(), "Grasp", true))
209  {
210  return true;
211  }
212  }
213  return false;
214  };
215  gd.hasLeftGrasp = hasGrasp(mo->getGraspSet("TCP L"));
216  gd.hasRightGrasp = hasGrasp(mo->getGraspSet("TCP R"));
217  }
218 
219  graspabilityDescriptors.push_back(gd);
220  graspabilityDescriptorIt = std::prev(graspabilityDescriptors.cend());
221 
222  ARMARX_INFO << "new graspability descriptor: [className: '" << className
223  << "'; child of graspable/bothhandsgraspable: " << gd.hasGraspableSuperclass
224  << "; has left grasp: " << gd.hasLeftGrasp
225  << "; has right grasp: " << gd.hasRightGrasp << "]";
226  }
227 
228  const auto& gd = *graspabilityDescriptorIt;
229  ARMARX_DEBUG << "checking " << className << "/" << gd.className << " "
230  << gd.hasGraspableSuperclass << " " << gd.hasLeftGrasp << " "
231  << gd.hasRightGrasp;
232 
233  if (!gd.hasGraspableSuperclass)
234  {
235  continue;
236  }
237 
238  if (gd.hasLeftGrasp)
239  {
240  addPredicateIfInside(result, leftGraspable.name, object, boxesL);
241  }
242 
243  if (gd.hasRightGrasp)
244  {
245  addPredicateIfInside(result, rightGraspable.name, object, boxesR);
246  }
247  }
248 
249  return result;
250 }
memoryx::GraspablePredicateProvider::getPredicateInfos
PredicateInfoList getPredicateInfos(const Ice::Current &=Ice::emptyCurrent) override
Definition: GraspablePredicateProvider.cpp:127
armarx::Contains
bool Contains(const ContainerType &container, const ElementType &searchElement)
Definition: algorithm.h:330
armarx::GlobalFrame
const std::string GlobalFrame
Definition: FramedPose.h:65
memoryx
VirtualRobot headers.
Definition: CommonPlacesTester.cpp:48
memoryx::GraspablePredicateProvider::GraspablePredicateProvider
GraspablePredicateProvider()
Definition: GraspablePredicateProvider.cpp:40
ObjectClass.h
StringHelpers.h
memoryx::GraspablePredicateProvider::getDefaultName
std::string getDefaultName() const override
Retrieve default name of component.
Definition: GraspablePredicateProvider.cpp:121
IceInternal::Handle< ObjectInstance >
FramedPose.h
memoryx::GraspablePredicateProvider::calcPredicates
PredicateInstanceList calcPredicates(const Ice::Current &=Ice::emptyCurrent) override
Definition: GraspablePredicateProvider.cpp:164
ARMARX_DEBUG
#define ARMARX_DEBUG
Definition: Logging.h:184
memoryx::GraspablePredicateProvider::onConnectWorldStateUpdater
void onConnectWorldStateUpdater() override
Definition: GraspablePredicateProvider.cpp:88
MemoryXCoreObjectFactories.h
memoryx::EntityWrappers::SimoxObjectWrapper
SimoxObjectWrapper offers a simplified access to the Simox ManipulationObject (i.e visualization,...
Definition: SimoxObjectWrapper.h:46
memoryx::GraspablePredicateProvider::onInitWorldStateUpdater
void onInitWorldStateUpdater() override
Definition: GraspablePredicateProvider.cpp:71
armarx::to_string
const std::string & to_string(const std::string &s)
Definition: StringHelpers.h:41
ObjectInstance.h
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
memoryx::Box
Definition: Box.hpp:32
ARMARX_INFO
#define ARMARX_INFO
Definition: Logging.h:181
memoryx::GridFileManagerPtr
std::shared_ptr< GridFileManager > GridFileManagerPtr
Definition: AbstractEntityWrapper.h:33
magic_enum::detail::find
constexpr std::size_t find(string_view str, char_type c) noexcept
Definition: magic_enum.hpp:309
armarx::ManagedIceObject::offeringTopic
void offeringTopic(const std::string &name)
Registers a topic for retrival after initialization.
Definition: ManagedIceObject.cpp:300
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
IceInternal::ProxyHandle<::IceProxy::armarx::DebugDrawerInterface >
memoryx::GridFileManager
GridFileManager provides utility functions for working with files in Mongo GridFS and links to them s...
Definition: GridFileManager.h:41
MemoryXTypesObjectFactories.h
armarx::ManagedIceObject::usingProxy
bool usingProxy(const std::string &name, const std::string &endpoints="")
Registers a proxy for retrieval after initialization and adds it to the dependency list.
Definition: ManagedIceObject.cpp:154
GraspablePredicateProvider.h
armarx
This file offers overloads of toIce() and fromIce() functions for STL container types.
Definition: ArmarXTimeserver.cpp:27
armarx::split
std::vector< std::string > split(const std::string &source, const std::string &splitBy, bool trimElements=false, bool removeEmptyElements=false)
Definition: StringHelpers.cpp:38