Main MRPT website > C++ reference for MRPT 1.3.2
CRangeBearingKFSLAM.h
Go to the documentation of this file.
1 /* +---------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | http://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2015, Individual contributors, see AUTHORS file |
6  | See: http://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See details in http://www.mrpt.org/License |
8  +---------------------------------------------------------------------------+ */
9 #ifndef CRangeBearingKFSLAM_H
10 #define CRangeBearingKFSLAM_H
11 
17 
19 #include <mrpt/utils/bimap.h>
20 
21 #include <mrpt/obs/CSensoryFrame.h>
27 #include <mrpt/maps/CLandmark.h>
28 #include <mrpt/maps/CSimpleMap.h>
31 
32 #include <mrpt/slam/link_pragmas.h>
33 
34 namespace mrpt
35 {
36  namespace slam
37  {
38  /** An implementation of EKF-based SLAM with range-bearing sensors, odometry, a full 6D robot pose, and 3D landmarks.
39  * The main method is "processActionObservation" which processes pairs of action/observation.
40  * The state vector comprises: 3D robot position, a quaternion for its attitude, and the 3D landmarks in the map.
41  *
42  * The following Wiki page describes an front-end application based on this class:
43  * http://www.mrpt.org/Application:kf-slam
44  *
45  * For the theory behind this implementation, see the technical report in:
46  * http://www.mrpt.org/6D-SLAM
47  *
48  * \sa An implementation for 2D only: CRangeBearingKFSLAM2D
49  * \ingroup metric_slam_grp
50  */
52  public bayes::CKalmanFilterCapable<7 /* x y z qr qx qy qz*/,3 /* range yaw pitch */, 3 /* x y z */, 7 /* Ax Ay Az Aqr Aqx Aqy Aqz */ >
53  // <size_t VEH_SIZE, size_t OBS_SIZE, size_t FEAT_SIZE, size_t ACT_SIZE, size typename kftype = double>
54  {
55  public:
56  typedef mrpt::math::TPoint3D landmark_point_t; //!< Either mrpt::math::TPoint2D or mrpt::math::TPoint3D
57 
58  /** Constructor. */
60 
61  /** Destructor: */
62  virtual ~CRangeBearingKFSLAM();
63 
64  void reset(); //!< Reset the state of the SLAM filter: The map is emptied and the robot put back to (0,0,0).
65 
66  /** Process one new action and observations to update the map and robot pose estimate. See the description of the class at the top of this page.
67  * \param action May contain odometry
68  * \param SF The set of observations, must contain at least one CObservationBearingRange
69  */
70  void processActionObservation(
71  mrpt::obs::CActionCollectionPtr &action,
72  mrpt::obs::CSensoryFramePtr &SF );
73 
74  /** Returns the complete mean and cov.
75  * \param out_robotPose The mean and the 7x7 covariance matrix of the robot 6D pose
76  * \param out_landmarksPositions One entry for each of the M landmark positions (3D).
77  * \param out_landmarkIDs Each element[index] (for indices of out_landmarksPositions) gives the corresponding landmark ID.
78  * \param out_fullState The complete state vector (7+3M).
79  * \param out_fullCovariance The full (7+3M)x(7+3M) covariance matrix of the filter.
80  * \sa getCurrentRobotPose
81  */
82  void getCurrentState(
84  std::vector<mrpt::math::TPoint3D> &out_landmarksPositions,
85  std::map<unsigned int,mrpt::maps::CLandmark::TLandmarkID> &out_landmarkIDs,
86  mrpt::math::CVectorDouble &out_fullState,
87  mrpt::math::CMatrixDouble &out_fullCovariance
88  ) const;
89 
90  /** Returns the complete mean and cov.
91  * \param out_robotPose The mean and the 7x7 covariance matrix of the robot 6D pose
92  * \param out_landmarksPositions One entry for each of the M landmark positions (3D).
93  * \param out_landmarkIDs Each element[index] (for indices of out_landmarksPositions) gives the corresponding landmark ID.
94  * \param out_fullState The complete state vector (7+3M).
95  * \param out_fullCovariance The full (7+3M)x(7+3M) covariance matrix of the filter.
96  * \sa getCurrentRobotPose
97  */
98  inline void getCurrentState(
99  mrpt::poses::CPose3DPDFGaussian &out_robotPose,
100  std::vector<mrpt::math::TPoint3D> &out_landmarksPositions,
101  std::map<unsigned int,mrpt::maps::CLandmark::TLandmarkID> &out_landmarkIDs,
102  mrpt::math::CVectorDouble &out_fullState,
103  mrpt::math::CMatrixDouble &out_fullCovariance
104  ) const
105  {
107  this->getCurrentState(q,out_landmarksPositions,out_landmarkIDs,out_fullState,out_fullCovariance);
108  out_robotPose = mrpt::poses::CPose3DPDFGaussian(q);
109  }
110 
111  /** Returns the mean & the 7x7 covariance matrix of the robot 6D pose (with rotation as a quaternion).
112  * \sa getCurrentState, getCurrentRobotPoseMean
113  */
114  void getCurrentRobotPose( mrpt::poses::CPose3DQuatPDFGaussian &out_robotPose ) const;
115 
116  /** Get the current robot pose mean, as a 3D+quaternion pose.
117  * \sa getCurrentRobotPose
118  */
119  mrpt::poses::CPose3DQuat getCurrentRobotPoseMean() const;
120 
121  /** Returns the mean & the 6x6 covariance matrix of the robot 6D pose (with rotation as 3 angles).
122  * \sa getCurrentState
123  */
124  inline void getCurrentRobotPose( mrpt::poses::CPose3DPDFGaussian &out_robotPose ) const
125  {
127  this->getCurrentRobotPose(q);
128  out_robotPose = mrpt::poses::CPose3DPDFGaussian(q);
129  }
130 
131  /** Returns a 3D representation of the landmarks in the map and the robot 3D position according to the current filter state.
132  * \param out_objects
133  */
134  void getAs3DObject( mrpt::opengl::CSetOfObjectsPtr &outObj ) const;
135 
136  /** Load options from a ini-like file/text
137  */
138  void loadOptions( const mrpt::utils::CConfigFileBase &ini );
139 
140  /** The options for the algorithm
141  */
143  {
144  /** Default values
145  */
146  TOptions();
147 
148  /** Load from a config file/text
149  */
150  void loadFromConfigFile(
151  const mrpt::utils::CConfigFileBase &source,
152  const std::string &section);
153 
154  /** This method must display clearly all the contents of the structure in textual form, sending it to a CStream.
155  */
156  void dumpToTextStream(mrpt::utils::CStream &out) const;
157 
158  /** A 7-length vector with the std. deviation of the transition model in (x,y,z, qr,qx,qy,qz) used only when there is no odometry (if there is odo, its uncertainty values will be used instead); x y z: In meters.
159  */
161 
162  /** The std. deviation of the sensor (for the matrix R in the kalman filters), in meters and radians.
163  */
164  float std_sensor_range, std_sensor_yaw, std_sensor_pitch;
165 
166  /** Additional std. dev. to sum to the motion model in the z axis (useful when there is only 2D odometry and we want to put things hard to the algorithm) (default=0)
167  */
169 
170  /** If set to true (default=false), map will be partitioned using the method stated by partitioningMethod
171  */
173 
174  /** Default = 3
175  */
177 
178  /** Applicable only if "doPartitioningExperiment=true".
179  * 0: Automatically detect partition through graph-cut.
180  * N>=1: Cut every "N" observations.
181  */
183 
184  // Data association:
187  double data_assoc_IC_chi2_thres; //!< Threshold in [0,1] for the chi2square test for individual compatibility between predictions and observations (default: 0.99)
188  TDataAssociationMetric data_assoc_IC_metric; //!< Whether to use mahalanobis (->chi2 criterion) vs. Matching likelihood.
189  double data_assoc_IC_ml_threshold;//!< Only if data_assoc_IC_metric==ML, the log-ML threshold (Default=0.0)
190 
191  bool create_simplemap; //!< Whether to fill m_SFs (default=false)
192 
193  bool force_ignore_odometry; //!< Whether to ignore the input odometry and behave as if there was no odometry at all (default: false)
194  } options;
195 
196  /** Information for data-association:
197  * \sa getLastDataAssociation
198  */
200  {
202  Y_pred_means(0,0),
203  Y_pred_covs(0,0)
204  {
205  }
206 
207  void clear() {
208  results.clear();
209  predictions_IDs.clear();
210  newly_inserted_landmarks.clear();
211  }
212 
213  // Predictions from the map:
216 
217  /** Map from the 0-based index within the last observation and the landmark 0-based index in the map (the robot-map state vector)
218  Only used for stats and so. */
219  std::map<size_t,size_t> newly_inserted_landmarks;
220 
221  // DA results:
223  };
224 
225  /** Returns a read-only reference to the information on the last data-association */
227  return m_last_data_association;
228  }
229 
230 
231  /** Return the last partition of the sequence of sensoryframes (it is NOT a partition of the map!!)
232  * Only if options.doPartitioningExperiment = true
233  * \sa getLastPartitionLandmarks
234  */
235  void getLastPartition( std::vector<vector_uint> &parts )
236  {
237  parts = m_lastPartitionSet;
238  }
239 
240  /** Return the partitioning of the landmarks in clusters accoring to the last partition.
241  * Note that the same landmark may appear in different clusters (the partition is not in the space of landmarks)
242  * Only if options.doPartitioningExperiment = true
243  * \param landmarksMembership The i'th element of this vector is the set of clusters to which the i'th landmark in the map belongs to (landmark index != landmark ID !!).
244  * \sa getLastPartition
245  */
246  void getLastPartitionLandmarks( std::vector<vector_uint> &landmarksMembership ) const;
247 
248  /** For testing only: returns the partitioning as "getLastPartitionLandmarks" but as if a fixed-size submaps (size K) were have been used.
249  */
250  void getLastPartitionLandmarksAsIfFixedSubmaps( size_t K, std::vector<vector_uint> &landmarksMembership );
251 
252 
253  /** Computes the ratio of the missing information matrix elements which are ignored under a certain partitioning of the landmarks.
254  * \sa getLastPartitionLandmarks, getLastPartitionLandmarksAsIfFixedSubmaps
255  */
256  double computeOffDiagonalBlocksApproximationError( const std::vector<vector_uint> &landmarksMembership ) const;
257 
258 
259  /** The partitioning of the entire map is recomputed again.
260  * Only when options.doPartitioningExperiment = true.
261  * This can be used after changing the parameters of the partitioning method.
262  * After this method, you can call getLastPartitionLandmarks.
263  * \sa getLastPartitionLandmarks
264  */
265  void reconsiderPartitionsNow();
266 
267 
268  /** Provides access to the parameters of the map partitioning algorithm.
269  */
271  {
272  return &mapPartitioner.options;
273  }
274 
275  /** Save the current state of the filter (robot pose & map) to a MATLAB script which displays all the elements in 2D
276  */
277  void saveMapAndPath2DRepresentationAsMATLABFile(
278  const std::string &fil,
279  float stdCount=3.0f,
280  const std::string &styleLandmarks = std::string("b"),
281  const std::string &stylePath = std::string("r"),
282  const std::string &styleRobot = std::string("r") ) const;
283 
284 
285 
286  protected:
287 
288  /** @name Virtual methods for Kalman Filter implementation
289  @{
290  */
291 
292  /** Must return the action vector u.
293  * \param out_u The action vector which will be passed to OnTransitionModel
294  */
295  void OnGetAction( KFArray_ACT &out_u ) const;
296 
297  /** Implements the transition model \f$ \hat{x}_{k|k-1} = f( \hat{x}_{k-1|k-1}, u_k ) \f$
298  * \param in_u The vector returned by OnGetAction.
299  * \param inout_x At input has \f[ \hat{x}_{k-1|k-1} \f] , at output must have \f$ \hat{x}_{k|k-1} \f$ .
300  * \param out_skip Set this to true if for some reason you want to skip the prediction step (to do not modify either the vector or the covariance). Default:false
301  */
302  void OnTransitionModel(
303  const KFArray_ACT &in_u,
304  KFArray_VEH &inout_x,
305  bool &out_skipPrediction
306  ) const;
307 
308  /** Implements the transition Jacobian \f$ \frac{\partial f}{\partial x} \f$
309  * \param out_F Must return the Jacobian.
310  * The returned matrix must be \f$V \times V\f$ with V being either the size of the whole state vector (for non-SLAM problems) or VEH_SIZE (for SLAM problems).
311  */
312  void OnTransitionJacobian( KFMatrix_VxV &out_F ) const;
313 
314  /** Implements the transition noise covariance \f$ Q_k \f$
315  * \param out_Q Must return the covariance matrix.
316  * The returned matrix must be of the same size than the jacobian from OnTransitionJacobian
317  */
318  void OnTransitionNoise( KFMatrix_VxV &out_Q ) const;
319 
320  /** This is called between the KF prediction step and the update step, and the application must return the observations and, when applicable, the data association between these observations and the current map.
321  *
322  * \param out_z N vectors, each for one "observation" of length OBS_SIZE, N being the number of "observations": how many observed landmarks for a map, or just one if not applicable.
323  * \param out_data_association An empty vector or, where applicable, a vector where the i'th element corresponds to the position of the observation in the i'th row of out_z within the system state vector (in the range [0,getNumberOfLandmarksInTheMap()-1]), or -1 if it is a new map element and we want to insert it at the end of this KF iteration.
324  * \param in_S The full covariance matrix of the observation predictions (i.e. the "innovation covariance matrix"). This is a M*O x M*O matrix with M=length of "in_lm_indices_in_S".
325  * \param in_lm_indices_in_S The indices of the map landmarks (range [0,getNumberOfLandmarksInTheMap()-1]) that can be found in the matrix in_S.
326  *
327  * This method will be called just once for each complete KF iteration.
328  * \note It is assumed that the observations are independent, i.e. there are NO cross-covariances between them.
329  */
330  void OnGetObservationsAndDataAssociation(
331  vector_KFArray_OBS &out_z,
332  vector_int &out_data_association,
333  const vector_KFArray_OBS &in_all_predictions,
334  const KFMatrix &in_S,
335  const vector_size_t &in_lm_indices_in_S,
336  const KFMatrix_OxO &in_R
337  );
338 
339  void OnObservationModel(
340  const vector_size_t &idx_landmarks_to_predict,
341  vector_KFArray_OBS &out_predictions
342  ) const;
343 
344  /** Implements the observation Jacobians \f$ \frac{\partial h_i}{\partial x} \f$ and (when applicable) \f$ \frac{\partial h_i}{\partial y_i} \f$.
345  * \param idx_landmark_to_predict The index of the landmark in the map whose prediction is expected as output. For non SLAM-like problems, this will be zero and the expected output is for the whole state vector.
346  * \param Hx The output Jacobian \f$ \frac{\partial h_i}{\partial x} \f$.
347  * \param Hy The output Jacobian \f$ \frac{\partial h_i}{\partial y_i} \f$.
348  */
349  void OnObservationJacobians(
350  const size_t &idx_landmark_to_predict,
351  KFMatrix_OxV &Hx,
352  KFMatrix_OxF &Hy
353  ) const;
354 
355  /** Computes A=A-B, which may need to be re-implemented depending on the topology of the individual scalar components (eg, angles).
356  */
357  void OnSubstractObservationVectors(KFArray_OBS &A, const KFArray_OBS &B) const;
358 
359  /** Return the observation NOISE covariance matrix, that is, the model of the Gaussian additive noise of the sensor.
360  * \param out_R The noise covariance matrix. It might be non diagonal, but it'll usually be.
361  */
362  void OnGetObservationNoise(KFMatrix_OxO &out_R) const;
363 
364  /** This will be called before OnGetObservationsAndDataAssociation to allow the application to reduce the number of covariance landmark predictions to be made.
365  * For example, features which are known to be "out of sight" shouldn't be added to the output list to speed up the calculations.
366  * \param in_all_prediction_means The mean of each landmark predictions; the computation or not of the corresponding covariances is what we're trying to determined with this method.
367  * \param out_LM_indices_to_predict The list of landmark indices in the map [0,getNumberOfLandmarksInTheMap()-1] that should be predicted.
368  * \note This is not a pure virtual method, so it should be implemented only if desired. The default implementation returns a vector with all the landmarks in the map.
369  * \sa OnGetObservations, OnDataAssociation
370  */
371  void OnPreComputingPredictions(
372  const vector_KFArray_OBS &in_all_prediction_means,
373  vector_size_t &out_LM_indices_to_predict ) const;
374 
375  /** If applicable to the given problem, this method implements the inverse observation model needed to extend the "map" with a new "element".
376  * \param in_z The observation vector whose inverse sensor model is to be computed. This is actually one of the vector<> returned by OnGetObservations().
377  * \param out_yn The F-length vector with the inverse observation model \f$ y_n=y(x,z_n) \f$.
378  * \param out_dyn_dxv The \f$F \times V\f$ Jacobian of the inv. sensor model wrt the robot pose \f$ \frac{\partial y_n}{\partial x_v} \f$.
379  * \param out_dyn_dhn The \f$F \times O\f$ Jacobian of the inv. sensor model wrt the observation vector \f$ \frac{\partial y_n}{\partial h_n} \f$.
380  *
381  * - O: OBS_SIZE
382  * - V: VEH_SIZE
383  * - F: FEAT_SIZE
384  *
385  * \note OnNewLandmarkAddedToMap will be also called after calling this method if a landmark is actually being added to the map.
386  */
387  void OnInverseObservationModel(
388  const KFArray_OBS & in_z,
389  KFArray_FEAT & out_yn,
390  KFMatrix_FxV & out_dyn_dxv,
391  KFMatrix_FxO & out_dyn_dhn ) const;
392 
393  /** If applicable to the given problem, do here any special handling of adding a new landmark to the map.
394  * \param in_obsIndex The index of the observation whose inverse sensor is to be computed. It corresponds to the row in in_z where the observation can be found.
395  * \param in_idxNewFeat The index that this new feature will have in the state vector (0:just after the vehicle state, 1: after that,...). Save this number so data association can be done according to these indices.
396  * \sa OnInverseObservationModel
397  */
398  void OnNewLandmarkAddedToMap(
399  const size_t in_obsIdx,
400  const size_t in_idxNewFeat );
401 
402 
403  /** This method is called after the prediction and after the update, to give the user an opportunity to normalize the state vector (eg, keep angles within -pi,pi range) if the application requires it.
404  */
405  void OnNormalizeStateVector();
406 
407  /** @}
408  */
409 
410  /** Set up by processActionObservation */
411  mrpt::obs::CActionCollectionPtr m_action;
412 
413  /** Set up by processActionObservation */
414  mrpt::obs::CSensoryFramePtr m_SF;
415 
416  /** The mapping between landmark IDs and indexes in the Pkk cov. matrix: */
418 
419 
420  /** Used for map partitioning experiments */
421  CIncrementalMapPartitioner mapPartitioner;
422 
423  /** The sequence of all the observations and the robot path (kept for debugging, statistics,etc)
424  */
427  std::vector<vector_uint> m_lastPartitionSet;
429  TDataAssocInfo m_last_data_association; //!< Last data association
430 
431  /** Return the last odometry, as a pose increment. */
432  mrpt::poses::CPose3DQuat getIncrementFromOdometry() const;
433 
434  }; // end class
435  } // End of namespace
436 } // End of namespace
437 
438 
439 
440 
441 #endif
mrpt::math::TPoint3D landmark_point_t
Either mrpt::math::TPoint2D or mrpt::math::TPoint3D.
An implementation of EKF-based SLAM with range-bearing sensors, odometry, a full 6D robot pose...
bool force_ignore_odometry
Whether to ignore the input odometry and behave as if there was no odometry at all (default: false) ...
This class stores a sequence of <Probabilistic Pose,SensoryFrame> pairs, thus a "metric map" can be t...
CArrayNumeric is an array for numeric types supporting several mathematical operations (actually...
Definition: CArrayNumeric.h:25
Column vector, like Eigen::MatrixX*, but automatically initialized to zeros since construction...
Definition: eigen_frwds.h:35
void getLastPartition(std::vector< vector_uint > &parts)
Return the last partition of the sequence of sensoryframes (it is NOT a partition of the map!!) Only ...
mrpt::math::CMatrixTemplateNumeric< kftype > Y_pred_means
Declares a class that represents a Probability Density function (PDF) of a 3D pose using a quaternion...
This class allows loading and storing values and vectors of different types from a configuration text...
CIncrementalMapPartitioner::TOptions * mapPartitionOptions()
Provides access to the parameters of the map partitioning algorithm.
This base class is used to provide a unified interface to files,memory buffers,..Please see the deriv...
Definition: CStream.h:38
A numeric matrix of compile-time fixed size.
int partitioningMethod
Applicable only if "doPartitioningExperiment=true".
TDataAssociationMetric
Different metrics for data association, used in mrpt::slam::data_association For a comparison of both...
void getCurrentRobotPose(mrpt::poses::CPose3DPDFGaussian &out_robotPose) const
Returns the mean & the 6x6 covariance matrix of the robot 6D pose (with rotation as 3 angles)...
mrpt::aligned_containers< KFArray_OBS >::vector_t vector_KFArray_OBS
Virtual base for Kalman Filter (EKF,IEKF,UKF) implementations.
A bidirectional version of std::map, declared as bimap<KEY,VALUE> and which actually contains two std...
Definition: bimap.h:28
TDataAssociationMetric data_assoc_IC_metric
Whether to use mahalanobis (->chi2 criterion) vs. Matching likelihood.
A class used to store a 3D pose as a translation (x,y,z) and a quaternion (qr,qx,qy,qz).
Definition: CPose3DQuat.h:41
double data_assoc_IC_ml_threshold
Only if data_assoc_IC_metric==ML, the log-ML threshold (Default=0.0)
void getCurrentState(mrpt::poses::CPose3DPDFGaussian &out_robotPose, std::vector< mrpt::math::TPoint3D > &out_landmarksPositions, std::map< unsigned int, mrpt::maps::CLandmark::TLandmarkID > &out_landmarkIDs, mrpt::math::CVectorDouble &out_fullState, mrpt::math::CMatrixDouble &out_fullCovariance) const
Returns the complete mean and cov.
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
This class can be used to make partitions on a map/graph build from observations taken at some poses/...
const TDataAssocInfo & getLastDataAssociation() const
Returns a read-only reference to the information on the last data-association.
Declares a class that represents a Probability Density function (PDF) of a 3D pose ...
std::vector< size_t > vector_size_t
Definition: types_simple.h:25
bool create_simplemap
Whether to fill m_SFs (default=false)
std::vector< int32_t > vector_int
Definition: types_simple.h:23
bool doPartitioningExperiment
If set to true (default=false), map will be partitioned using the method stated by partitioningMethod...
The results from mrpt::slam::data_association.
Lightweight 3D point.
TDataAssociationMethod
Different algorithms for data association, used in mrpt::slam::data_association.
double data_assoc_IC_chi2_thres
Threshold in [0,1] for the chi2square test for individual compatibility between predictions and obser...
std::map< size_t, size_t > newly_inserted_landmarks
Map from the 0-based index within the last observation and the landmark 0-based index in the map (the...
This is a virtual base class for sets of options than can be loaded from and/or saved to configuratio...
mrpt::math::CVectorFloat stds_Q_no_odo
A 7-length vector with the std.
std::vector< size_t > vector_size_t



Page generated by Doxygen 1.8.12 for MRPT 1.3.2 SVN: at Thu Nov 10 13:22:34 UTC 2016