ism.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 '''
4 Copyright (c) 2016, Allgeyer Tobias, Aumann Florian, Borella Jocelyn, Hutmacher Robin, Karrenbauer Oliver, Marek Felix, Meissner Pascal, Trautmann Jeremias, Wittenbeck Valerij
5 
6 All rights reserved.
7 
8 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
9 
10 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
11 
12 2. 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.
13 
14 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
15 
16 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 HOLDER 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.
17 '''
18 
19 import roslib
20 import rospy
21 import smach
22 import smach_ros
23 import __builtin__
24 import imp
25 
26 from asr_recognizer_prediction_ism.srv import FindScenes, GetPointCloud
27 from asr_msgs.msg import AsrObject, AsrTypeAndId
28 from asr_msgs.msg import AsrAttributedPointCloud, AsrAttributedPoint
29 from asr_world_model.msg import CompletePattern
30 from asr_world_model.srv import GetFoundObjectList, GetMissingObjectList, GetCompletePatterns
31 
32 from common.evaluation_decorators import *
33 
34 
35 """
36 Contains states for pose prediction and scene recognition. Both states use
37 service calls to the ism node in the recognizer_predictin_ism package.
38 """
39 
40 class SceneRecognition(smach.State):
41  """
42  Tries to recognize scene with the objects saved in the world model.
43  Active scene recognition finishes, once all object in all scenes are found. Otherwise the pose prediction
44  in the ism node receives all found scenes and this state returns with
45  'found_scenes'.
46 
47  Note that we don't get the actual scene recognition results any other format
48  than a serialized stream.
49  """
50 
51  def __init__(self):
52  smach.State.__init__(
53  self,
54  outcomes=['found_scenes', 'aborted', 'found_all_objects', 'found_all_required_scenes'])
55  self.isInitDone = 0
56 
57 
58  def initNode(self):
59  rospy.loginfo('Init SceneRecognition')
60  self.isInitDone = 1
61  dbfilename = rospy.get_param('/rp_ism_node/dbfilename');
62  dbPathSplit = dbfilename.split("/")
63  dbName = dbPathSplit[-1]
64 
65  path = rospy.get_param('/scene_exploration_sm/CompletePatternsPath')
66  path = path.replace("XXX", dbName);
67  rospy.loginfo("Parsed CompletePatternsPath: " + str(path))
68 
69  try:
70  self.evaluateCompletePatternsModule = imp.load_source("evaluateCompletePatterns", path)
71  except IOError:
72  rospy.logwarn("No CompletePatternsFile found -> no abortion through found_all_required_scenes")
74 
75  @log
76  @key_press
77  @timed
78  def execute(self, userdata):
79  rospy.loginfo('Executing SCENE_RECOGNITION')
80  if (self.isInitDone == 0):
81  if self.initNode() == 'aborted':
82  return 'aborted'
83 
84  # Get all found objects from world_model
85  detected_objects = []
86 
87  try:
88  rospy.wait_for_service('/env/asr_world_model/get_found_object_list', timeout=5)
89  get_detected_objects =rospy.ServiceProxy(
90  '/env/asr_world_model/get_found_object_list', GetFoundObjectList)
91  detected_objects_response = get_detected_objects()
92  detected_objects = detected_objects_response.object_list
93  rospy.loginfo("World model returns " + str(len(detected_objects)) + " found objects:")
94  # extract asr_object and print found objects
95  for obj in detected_objects:
96  rospy.loginfo("["+ obj.type + ", " + obj.identifier + "]")
97  except (rospy.ServiceException, rospy.exceptions.ROSException), e:
98  rospy.logwarn(str(e))
99  rospy.logwarn("service exception from world_model")
100  return 'aborted'
101 
102  rospy.loginfo("Now calling find_scenes service for all found objects.")
103  # find scenes with objects from world_model
104  try:
105  rospy.wait_for_service('/rp_ism_node/find_scenes', timeout=5)
106  except rospy.exceptions.ROSException, e:
107  rospy.logwarn("Could not find find_scenes service")
108  return 'aborted'
109 
110  try:
111  scene_recognizer = rospy.ServiceProxy(
112  '/rp_ism_node/find_scenes',
113  FindScenes)
114  scene_results = scene_recognizer(detected_objects)
115 
116  rospy.loginfo("Response of service call: " + str(scene_results))
117  if hasattr(__builtin__, 'log_dir'):
118  with open(__builtin__.log_dir + '/scene_results.txt', 'a') as log:
119  log.write(str(scene_results))
120  log.write("========================================================\n")
121 
122  try:
123  rospy.wait_for_service('/env/asr_world_model/get_missing_object_list', timeout=5)
124  get_found_all =rospy.ServiceProxy(
125  '/env/asr_world_model/get_missing_object_list', GetMissingObjectList)
126  get_missing_object_list_response = get_found_all()
127  except (rospy.ServiceException, rospy.exceptions.ROSException), e:
128  rospy.logwarn(str(e))
129  rospy.logwarn("service exception from world_model")
130  return 'aborted'
131 
132  rospy.loginfo('Objects still not found: ')
133  for missing in get_missing_object_list_response.missingObjects:
134  rospy.loginfo('[' + missing.type + ', ' + missing.identifier + ']')
135  if len(get_missing_object_list_response.missingObjects) == 0 :
136  return 'found_all_objects'
137 
138  if self.checkAllRequiredScenesWhereFound() is True:
139  return 'found_all_required_scenes'
140  else:
141  return 'found_scenes'
142 
143  except rospy.ServiceException, e:
144  rospy.logwarn("ServiceException on calling find_scenes")
145  rospy.logwarn(e)
146  return 'aborted'
147 
148 
150  if self.evaluateCompletePatternsModule is None:
151  return False
152 
153  rospy.wait_for_service('/env/asr_world_model/get_complete_patterns', timeout=5)
154  get_complete_patterns_list = rospy.ServiceProxy('/env/asr_world_model/get_complete_patterns', GetCompletePatterns)
155  complete_patterns = get_complete_patterns_list().completePatterns
156  rospy.loginfo("Got complete_patterns from world_model:\n" + str(complete_patterns))
157 
158  result = self.evaluateCompletePatternsModule.evaluateCompletePatterns(complete_patterns)
159  rospy.loginfo("Result of evaluateCompletePatterns: " + str(result))
160  return result
161 
162 class PosePrediction(smach.State):
163  """
164  Generates AttributedPointCloud for scene hypotheses resampled by particle filter in rp_ism_node. The scene
165  hypotheses (all from scene recognition) for resampling is not passed in the userdata, but directly inside the
166  asr_recognizer_prediction_ism package. We get into this state if the scene recognition
167  recognized at least one scene.
168  """
169 
170  def __init__(self):
171  smach.State.__init__(
172  self,
173  outcomes=['succeeded', 'aborted', 'no_predictions_left'],
174  output_keys=['object_pointcloud'])
175 
176  @log
177  @key_press
178  @timed
179  def execute(self, userdata):
180  rospy.loginfo('Executing OBJECT_POSE_PREDICTION')
181 
182  rospy.loginfo("Now calling get_point_cloud service to get predicted object poses.")
183  try:
184  rospy.wait_for_service('/rp_ism_node/get_point_cloud',
185  timeout=5)
186  except rospy.exceptions.ROSException, e:
187 
188  rospy.logwarn(e)
189  return 'aborted'
190 
191  # Get all found objects from world_model
192  detected_objects = []
193 
194  try:
195  rospy.wait_for_service('/env/asr_world_model/get_found_object_list', timeout=5)
196  get_detected_objects =rospy.ServiceProxy(
197  '/env/asr_world_model/get_found_object_list', GetFoundObjectList)
198  detected_objects_response = get_detected_objects()
199  detected_objects = detected_objects_response.object_list
200  rospy.loginfo("World model returns " + str(len(detected_objects)) + " found objects:")
201  # extract asr_object and print found objects
202  for obj in detected_objects:
203  rospy.loginfo("["+ obj.type + ", " + obj.identifier + "]")
204  except (rospy.ServiceException, rospy.exceptions.ROSException), e:
205  rospy.logwarn(str(e))
206  rospy.logwarn("service exception from world_model")
207  return 'aborted'
208 
209  try:
210  pose_predictor = rospy.ServiceProxy(
211  '/rp_ism_node/get_point_cloud',
212  GetPointCloud)
213  pose_prediction = pose_predictor(detected_objects)
214  result_pointcloud = pose_prediction.point_cloud
215 
216  rospy.loginfo("Response of service call (pointcloud omitted): " + str(pose_prediction.output))
217  if hasattr(__builtin__, 'log_dir'):
218  with open(__builtin__.log_dir + '/prediction_results.txt', 'a') as log:
219  log.write(str(pose_prediction.output))
220  log.write("========================================================\n")
221 
222  if len(result_pointcloud.elements) == 0:
223  # TODO better abort criterion
224  rospy.loginfo("Empty pointcloud from pose prediction")
225  return 'no_predictions_left'
226 
227  userdata.object_pointcloud = result_pointcloud
228  return 'succeeded'
229  except rospy.ServiceException, e:
230  rospy.logwarn("Service exception on calling get_point_cloud")
231  rospy.logwarn(str(e))
232  return 'aborted'
233 
234 
235 
236 
def execute(self, userdata)
Definition: ism.py:179
def execute(self, userdata)
Definition: ism.py:78


asr_state_machine
Author(s): Allgeyer Tobias, Aumann Florian, Borella Jocelyn, Hutmacher Robin, Karrenbauer Oliver, Marek Felix, Meißner Pascal, Trautmann Jeremias, Wittenbeck Valerij
autogenerated on Mon Feb 28 2022 21:53:50