ObjectLocalizerDynamicSimulation.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of ArmarX.
3  *
4  * Copyright (C) 2013-2016, 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 ArmarXSimulation::ArmarXObjects::ObjectLocalizerDynamicSimulation
19  * @author welke ( welke at kit dot edu )
20  * @date 2013
21  * @copyright http://www.gnu.org/licenses/gpl-2.0.txt
22  * GNU General Public License
23  */
24 
26 
31 
32 // EarlyVision
33 //#include <MemoryX/libraries/helpers/EarlyVisionHelpers/EarlyVisionConverters.h>
34 //#include <MemoryX/libraries/helpers/EarlyVisionHelpers/UnscentedTransform.h>
35 
36 
37 using namespace armarx;
38 
39 
42 {
43  defineOptionalProperty<std::string>("SimulatorProxyName", "Simulator", "name of dynamics simulator proxy");
44  defineOptionalProperty<std::string>("RobotName", "Armar3", "Name of robot used for calculating reference frame");
45  defineOptionalProperty<std::string>("ReferenceFrameName", "EyeLeftCamera", "Name of reference frame to use for pose");
46  //defineRequiredProperty<std::string>("CalibrationFile", "Camera calibration file, will be used for uncertainty calculation");
47  //defineOptionalProperty<float>("2DLocalizationNoise", 4.0, "2D localization noise of object recognition. Used in order to calculate the 3D world localization noise.");
48  defineOptionalProperty<float>("RecognitionCertainty", 0.9f, "Certainty of recognition used in simulation (0...1).");
49  defineOptionalProperty<bool>("VisibilityCheck", false, "Whether to simulate camera and checking visibility within camera");
50 }
51 
52 
54 {
55  // using dynamic simulation
56  usingProxy(getProperty<std::string>("SimulatorProxyName").getValue());
57 
58  robotName = getProperty<std::string>("RobotName").getValue();
59  frameName = getProperty<std::string>("ReferenceFrameName").getValue();
60 
61  recognitionCertainty = getProperty<float>("RecognitionCertainty").getValue();
62  performVisibilityCheck = getProperty<bool>("VisibilityCheck").getValue();
63 
64  if (performVisibilityCheck)
65  {
66  ARMARX_WARNING << "Visibility check is nyi...";
67  }
68 
69 
70  // stereo calibration
71  /*std::string calibrationFileName = getProperty<std::string>("CalibrationFile") .getValue();
72  std::string fullCalibrationFileName;
73 
74  if(!ArmarXDataPath::getAbsolutePath(calibrationFileName, fullCalibrationFileName))
75  {
76  ARMARX_ERROR << "Could not find camera calibration file in ArmarXDataPath: " << calibrationFileName;
77  }
78 
79  if (!stereoCalibration.LoadCameraParameters(
80  fullCalibrationFileName.c_str(), true))
81  {
82  ARMARX_ERROR << "Error loading camera calibration file: " << fullCalibrationFileName;
83  }
84 
85  // setup noise
86  imageNoiseLeft(0) = imageNoiseLeft(1) = getProperty<float>("2DLocalizationNoise").getValue();
87  imageNoiseRight(0) = imageNoiseRight(1) = getProperty<float>("2DLocalizationNoise").getValue();
88  */
89 
90  ARMARX_VERBOSE << "Simulating object localization of type " << getName() << " for robot " << robotName;
91 
92 }
93 
95 {
96  simulatorPrx = getProxy<SimulatorInterfacePrx>(getProperty<std::string>("SimulatorProxyName").getValue());
97 }
98 
99 
101 {
103  mean.push_back(pos(0));
104  mean.push_back(pos(1));
105  mean.push_back(pos(2));
106 
107  // assuming 2 mm noise
109  posDist->setMean(mean);
110  posDist->setCovariance(0, 0, 2.0f);
111  posDist->setCovariance(1, 1, 2.0f);
112  posDist->setCovariance(2, 2, 2.0f);
113  return posDist;
114 }
115 
116 memoryx::ObjectLocalizationResultList ObjectLocalizerDynamicSimulation::localizeObjectClasses(
117  const memoryx::ObjectClassNameList& objectClassNames, const Ice::Current&)
118 {
119  // ARMARX_VERBOSE << "Entering localizeObjectClasses" << flush;
120  memoryx::ObjectLocalizationResultList resultList;
121 
122  // assure is fully connected
123  getObjectScheduler()->waitForObjectState(eManagedIceObjectStarted);
124 
125  // go through requested object classes
126  for (const auto& className : objectClassNames)
127  {
128  // query simulator for class
129  ARMARX_INFO << deactivateSpam(5) << robotName << " " << frameName << " " << className << flush;
130  ObjectClassInformationSequence objectInstances = simulatorPrx->getObjectClassPoses(robotName, frameName, className);
131 
132  // go through instances
133  for (const auto& instanceInfo : objectInstances)
134  {
135  memoryx::ObjectLocalizationResult result;
136 
137  result.timeStamp = new TimestampVariant(instanceInfo.timestampMicroSeconds);
138 
139  // class name
140  result.objectClassName = instanceInfo.className;
141 
142  // pose
143  armarx::FramedPosePtr pose = armarx::FramedPosePtr::dynamicCast(instanceInfo.pose);
144  ARMARX_INFO << deactivateSpam(5) << className << " pose: " << pose->output();
145  FramedPositionPtr position = pose->getPosition();
146  result.position = position;
147  result.orientation = pose->getOrientation();
148 
149  // uncertainties
150  result.positionNoise = computePositionNoise(position->toEigen());
151  result.recognitionCertainty = recognitionCertainty;
152 
153  resultList.push_back(result);
154 
155  /*
156  if(performVisibilityCheck)
157  {
158  if(isVisible(armarx::FramedPositionPtr::dynamicCast(result.position)->toEigen()))
159  resultList.push_back(result);
160  } else
161  resultList.push_back(result);
162  */
163  }
164  }
165 
166 
167  ARMARX_VERBOSE << deactivateSpam(5) << "Found " << resultList.size() << " instances";
168 
169  TimeUtil::SleepMS(50);
170 
171  return resultList;
172 }
173 
175 {
176  return "ObjectLocalizerDynamicSimulation";
177 }
178 
179 /*
180 memoryx::MultivariateNormalDistributionPtr ObjectLocalizerDynamicSimulation::calculateLocalizationUncertainty(Vec2d left_point, Vec2d right_point)
181 {
182  // initialize noise
183  UnscentedTransform ut;
184 
185  Eigen::MatrixXd combinedNoise(4,4);
186  combinedNoise.setZero();
187  combinedNoise(0,0) = imageNoiseLeft(0);
188  combinedNoise(1,1) = imageNoiseLeft(1);
189  combinedNoise(2,2) = imageNoiseRight(0);
190  combinedNoise(3,3) = imageNoiseRight(1);
191 
192  Eigen::VectorXd mean(4);
193  mean << left_point.x, left_point.y, right_point.x, right_point.y;
194 
195  Gaussian imageSpaceNoise(4);
196  imageSpaceNoise.setCovariance(combinedNoise);
197  imageSpaceNoise.setMean(mean);
198 
199  // calculate sigma points
200  Eigen::MatrixXd sigmapoints = ut.getSigmaPoints(imageSpaceNoise);
201 
202  // pass sigma points through system
203  Vec2d l,r;
204  Vec3d w;
205  Eigen::VectorXd base(4);
206  Eigen::VectorXd world(4);
207 
208  Eigen::MatrixXd processedpoints(3,sigmapoints.cols());
209 
210  for(int n = 0 ; n < sigmapoints.cols() ; n++)
211  {
212 
213  Math2d::SetVec(l, sigmapoints(0, n), sigmapoints(1, n));
214  Math2d::SetVec(r, sigmapoints(2, n), sigmapoints(3, n));
215 
216  // calc 3d point (2D points are rectified but not distorted)
217  stereoCalibration.Calculate3DPoint(l, r, w, true, true);
218  world << w.x, w.y, w.z, 1.0f;
219 
220  processedpoints(0, n) = world(0);
221  processedpoints(1, n) = world(1);
222  processedpoints(2, n) = world(2);
223  }
224 
225  // recover covariance
226  Gaussian worldSpaceNoise = ut.extractGaussian(processedpoints);
227 
228  return memoryx::EarlyVisionConverters::convertToMemoryX_MULTI(worldSpaceNoise);
229  }
230 
231 memoryx::MultivariateNormalDistributionPtr ObjectLocalizerDynamicSimulation::calculateLocalizationUncertainty(const Eigen::Vector3f& position)
232 {
233  // calculate 2d points for localization uncerainty
234  Vec2d left2d, right2d;
235  getImagePositions(position, left2d, right2d);
236 
237  return calculateLocalizationUncertainty(left2d, right2d);
238 }
239 
240 bool ObjectLocalizerDynamicSimulation::isVisible(const Eigen::Vector3f& position)
241 {
242  // calculate 2d points for localization uncerainty
243  Vec2d left2d, right2d;
244  getImagePositions(position, left2d, right2d);
245 
246  // check if within image
247  const CCalibration::CCameraParameters& leftParams = stereoCalibration.GetLeftCalibration()->GetCameraParameters();
248  const CCalibration::CCameraParameters& rightParams = stereoCalibration.GetRightCalibration()->GetCameraParameters();
249 
250  bool visibleInLeft = true;
251  if( (left2d.x < 0) || (left2d.x >= leftParams.width) )
252  visibleInLeft = false;
253  if( (left2d.y < 0) || (left2d.y >= leftParams.height) )
254  visibleInLeft = false;
255 
256  bool visibleInRight = true;
257  if( (right2d.x < 0) || (right2d.x >= rightParams.width) )
258  visibleInRight = false;
259  if( (right2d.y < 0) || (right2d.y >= rightParams.height) )
260  visibleInRight = false;
261 
262  ARMARX_INFO << "ObjectLocalizer: " << visibleInRight << " " << visibleInLeft << flush;
263 
264  return visibleInLeft && visibleInRight;
265 }
266 
267 void ObjectLocalizerDynamicSimulation::getImagePositions(const Eigen::Vector3f& position, Vec2d& left_point, Vec2d& right_point)
268 {
269  Vec2d left2d, right2d;
270  Vec3d pos;
271  Math3d::SetVec(pos, position(0), position(1), position(2));
272 
273  stereoCalibration.GetLeftCalibration()->WorldToImageCoordinates(pos, left2d);
274  stereoCalibration.GetRightCalibration()->WorldToImageCoordinates(pos, right2d);
275 
276  // transform to rectified coordinates
277  Mat3d inverseHLeft, inverseHRight;
278  Math3d::Invert(stereoCalibration.rectificationHomographyLeft, inverseHLeft);
279  Math3d::Invert(stereoCalibration.rectificationHomographyRight, inverseHRight);
280  Math2d::ApplyHomography(inverseHLeft, left2d, left_point);
281  Math2d::ApplyHomography(inverseHRight, right2d, right_point);
282 }*/
283 
284 
286 {
288 }
ARMARX_VERBOSE
#define ARMARX_VERBOSE
Definition: Logging.h:180
armarx::ObjectLocalizerDynamicSimulation::onConnectComponent
void onConnectComponent() override
Pure virtual hook for the subclass.
Definition: ObjectLocalizerDynamicSimulation.cpp:94
armarx::ObjectLocalizerDynamicSimulation::computePositionNoise
::memoryx::MultivariateNormalDistributionPtr computePositionNoise(const Eigen::Vector3f &pos)
Definition: ObjectLocalizerDynamicSimulation.cpp:100
armarx::TimestampVariant
Definition: TimestampVariant.h:54
armarx::ObjectLocalizerDynamicSimulationPropertyDefinitions
Definition: ObjectLocalizerDynamicSimulation.h:41
armarx::ObjectLocalizerDynamicSimulation::onInitComponent
void onInitComponent() override
Pure virtual hook for the subclass.
Definition: ObjectLocalizerDynamicSimulation.cpp:53
armarx::ObjectLocalizerDynamicSimulation::getDefaultName
std::string getDefaultName() const override
Definition: ObjectLocalizerDynamicSimulation.cpp:174
armarx::ObjectLocalizerDynamicSimulation::localizeObjectClasses
memoryx::ObjectLocalizationResultList localizeObjectClasses(const memoryx::ObjectClassNameList &objectClassNames, const Ice::Current &c=Ice::emptyCurrent) override
localizes simulated object instances
Definition: ObjectLocalizerDynamicSimulation.cpp:116
IceInternal::Handle
Definition: forward_declarations.h:8
armarx::mean
std::optional< float > mean(const boost::circular_buffer< NameValueMap > &buffer, const std::string &key)
Definition: KinematicUnitGuiPlugin.cpp:1615
FramedPose.h
armarx::FloatVector
::std::vector< ::Ice::Float > FloatVector
Definition: KinematicUnitGuiPlugin.h:327
armarx::flush
const LogSender::manipulator flush
Definition: LogSender.h:251
TimestampVariant.h
ObjectLocalizerDynamicSimulation.h
ArmarXObjectScheduler.h
armarx::ObjectLocalizerDynamicSimulationPropertyDefinitions::ObjectLocalizerDynamicSimulationPropertyDefinitions
ObjectLocalizerDynamicSimulationPropertyDefinitions(std::string prefix)
Definition: ObjectLocalizerDynamicSimulation.cpp:40
armarx::Component::getConfigIdentifier
std::string getConfigIdentifier()
Retrieve config identifier for this component as set in constructor.
Definition: Component.cpp:74
armarx::TimeUtil::SleepMS
static void SleepMS(float milliseconds)
Definition: TimeUtil.h:195
armarx::ComponentPropertyDefinitions
Default component property definition container.
Definition: Component.h:70
ARMARX_INFO
#define ARMARX_INFO
Definition: Logging.h:174
IceUtil::Handle< class PropertyDefinitionContainer >
armarx::ObjectLocalizerDynamicSimulation::createPropertyDefinitions
EIGEN_MAKE_ALIGNED_OPERATOR_NEW armarx::PropertyDefinitionsPtr createPropertyDefinitions() override
Definition: ObjectLocalizerDynamicSimulation.cpp:285
armarx::Logging::deactivateSpam
SpamFilterDataPtr deactivateSpam(float deactivationDurationSec=10.0f, const std::string &identifier="", bool deactivate=true) const
disables the logging for the current line for the given amount of seconds.
Definition: Logging.cpp:92
armarx::ManagedIceObject::getName
std::string getName() const
Retrieve name of object.
Definition: ManagedIceObject.cpp:107
ARMARX_WARNING
#define ARMARX_WARNING
Definition: Logging.h:186
armarx::PropertyDefinitionsPtr
IceUtil::Handle< class PropertyDefinitionContainer > PropertyDefinitionsPtr
PropertyDefinitions smart pointer type.
Definition: forward_declarations.h:34
ArmarXDataPath.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:151
armarx
This file offers overloads of toIce() and fromIce() functions for STL container types.
Definition: ArmarXTimeserver.cpp:28
armarx::ManagedIceObject::getObjectScheduler
ArmarXObjectSchedulerPtr getObjectScheduler() const
Definition: ManagedIceObject.cpp:731
armarx::VariantType::MultivariateNormalDistribution
const armarx::VariantTypeId MultivariateNormalDistribution
Definition: ProbabilityMeasures.h:36