MRPT  1.9.9
CNetworkOfPoses.h
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | https://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
6  | See: https://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See: https://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 #pragma once
10 
11 /** \file The main class in this file is mrpt::poses::CNetworkOfPoses<>, a
12  generic
13  basic template for predefined 2D/3D graphs of pose contraints.
14 */
15 
16 #include <iostream>
17 
23 #include <mrpt/graphs/dijkstra.h>
26 #include <mrpt/math/utils.h>
28 #include <mrpt/poses/poses_frwds.h>
32 #include <mrpt/system/os.h>
33 
34 #include <algorithm>
35 #include <iterator>
36 #include <memory>
37 #include <optional>
38 #include <type_traits> // is_base_of()
39 
40 namespace mrpt
41 {
42 namespace graphs
43 {
44 /** Internal functions for MRPT */
45 namespace detail
46 {
47 template <class GRAPH_T>
48 struct graph_ops;
49 
50 // forward declaration of CVisualizer
51 template <
52  class CPOSE, // Type of edges
53  class MAPS_IMPLEMENTATION, class NODE_ANNOTATIONS, class EDGE_ANNOTATIONS>
55 // forward declaration of CMRVisualizer
56 template <
57  class CPOSE, // Type of edges
58  class MAPS_IMPLEMENTATION, class NODE_ANNOTATIONS, class EDGE_ANNOTATIONS>
59 class CMRVisualizer;
60 } // namespace detail
61 
62 /** A directed graph of pose constraints, with edges being the relative poses
63  *between pairs of nodes identified by their numeric IDs (of type
64  *mrpt::graphs::TNodeID).
65  * A link or edge between two nodes "i" and "j", that is, the pose \f$ p_{ij}
66  *\f$, holds the relative position of "j" with respect to "i".
67  * These poses are stored in the edges in the format specified by the template
68  *argument CPOSE. Users should employ the following derived classes
69  * depending on the desired representation of edges:
70  * - mrpt::graphs::CNetworkOfPoses2D : 2D edges as a simple CPose2D (x y
71  *phi)
72  * - mrpt::graphs::CNetworkOfPoses3D : 3D edges as a simple
73  *mrpt::poses::CPose3D (x y z yaw pitch roll)
74  * - mrpt::graphs::CNetworkOfPoses2DInf : 2D edges as a Gaussian PDF with
75  *information matrix (CPosePDFGaussianInf)
76  * - mrpt::graphs::CNetworkOfPoses3DInf : 3D edges as a Gaussian PDF with
77  *information matrix (CPose3DPDFGaussianInf)
78  * - mrpt::graphs::CNetworkOfPoses2DCov : 2D edges as a Gaussian PDF with
79  *covariance matrix (CPosePDFGaussian). It's more efficient to use the
80  *information matrix version instead!
81  * - mrpt::graphs::CNetworkOfPoses3DCov : 3D edges as a Gaussian PDF with
82  *covariance matrix (CPose3DPDFGaussian). It's more efficient to use the
83  *information matrix version instead!
84  *
85  * Two main members store all the information in this class:
86  * - \a edges (in the base class mrpt::graphs::CDirectedGraph::edges): A
87  *map
88  *from pairs of node ID -> pose constraints.
89  * - \a nodes : A map from node ID -> estimated pose of that node
90  *(actually,
91  *read below on the template argument MAPS_IMPLEMENTATION).
92  *
93  * Graphs can be loaded and saved to text file in the format used by TORO &
94  *HoG-man (more on the format <a
95  *href="http://www.mrpt.org/Robotics_file_formats" >here</a>),
96  * using \a loadFromTextFile and \a saveToTextFile.
97  *
98  * This class is the base for representing networks of poses, which are the
99  *main data type of a series
100  * of SLAM algorithms implemented in the library mrpt-slam, in the namespace
101  *mrpt::graphslam.
102  *
103  * The template arguments are:
104  * - CPOSE: The type of the edges, which hold a relative pose (2D/3D, just
105  *a
106  *value or a Gaussian, etc.)
107  * - MAPS_IMPLEMENTATION: Can be either mrpt::containers::map_traits_stdmap
108  *or mrpt::containers::map_traits_map_as_vector. Determines the type of the list
109  *of global poses (member \a nodes).
110  *
111  * \sa mrpt::graphslam
112  * \ingroup mrpt_graphs_grp
113  */
114 template <
115  class CPOSE, // Type of edges
116  class MAPS_IMPLEMENTATION =
117  mrpt::containers::map_traits_stdmap, // Use std::map<> vs.
118  // std::vector<>
119  class NODE_ANNOTATIONS = mrpt::graphs::detail::TNodeAnnotationsEmpty,
120  class EDGE_ANNOTATIONS = mrpt::graphs::detail::edge_annotations_empty>
122  : public mrpt::graphs::CDirectedGraph<CPOSE, EDGE_ANNOTATIONS>
123 {
124  public:
125  /** @name Typedef's
126  @{ */
127  /** The base class "CDirectedGraph<CPOSE,EDGE_ANNOTATIONS>" */
129  /** My own type */
130  using self_t = CNetworkOfPoses<
131  CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS>;
132 
133  /** The type of PDF poses in the contraints (edges) (=CPOSE template
134  * argument) */
135  using constraint_t = CPOSE;
136  /** The extra annotations in nodes, apart from a \a constraint_no_pdf_t */
137  using node_annotations_t = NODE_ANNOTATIONS;
138  /** The extra annotations in edges, apart from a \a constraint_t */
139  using edge_annotations_t = EDGE_ANNOTATIONS;
140 
141  /** The type of map's implementation (=MAPS_IMPLEMENTATION template
142  * argument) */
143  using maps_implementation_t = MAPS_IMPLEMENTATION;
144  /** The type of edges or their means if they are PDFs (that is, a simple
145  * "edge" value) */
146  using constraint_no_pdf_t = typename CPOSE::type_value;
147 
148  constexpr static auto getClassName()
149  {
150  using namespace mrpt::typemeta;
151  return literal("mrpt::graphs::CNetworkOfPoses<") +
152  TTypeName<CPOSE>::get() + literal(",") +
156  }
157 
158  /** The type of each global pose in \a nodes: an extension of the \a
159  * constraint_no_pdf_t pose with any optional user-defined data
160  */
161  struct global_pose_t : public constraint_no_pdf_t, public NODE_ANNOTATIONS
162  {
163  using self_t = typename CNetworkOfPoses<
164  CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS,
165  EDGE_ANNOTATIONS>::global_pose_t;
166 
167  constexpr static auto getClassName()
168  {
169  using namespace mrpt::typemeta;
170  return literal("global_pose_t<") +
173  }
174 
175  /**\brief Potential class constructors
176  */
177  /**\{ */
179  template <typename ARG1>
180  inline global_pose_t(const ARG1& a1) : constraint_no_pdf_t(a1)
181  {
182  }
183  template <typename ARG1, typename ARG2>
184  inline global_pose_t(const ARG1& a1, const ARG2& a2)
186  {
187  }
188  /**\} */
189 
190  /**\brief Copy constructor - delegate copying to the NODE_ANNOTATIONS
191  * struct
192  */
193  inline global_pose_t(const global_pose_t& other)
194  : constraint_no_pdf_t(other), NODE_ANNOTATIONS(other)
195  {
196  }
197 
198  inline bool operator==(const global_pose_t& other) const
199  {
200  return (
201  static_cast<const constraint_no_pdf_t>(*this) ==
202  static_cast<const constraint_no_pdf_t>(other) &&
203  static_cast<const NODE_ANNOTATIONS>(*this) ==
204  static_cast<const NODE_ANNOTATIONS>(other));
205  }
206  inline bool operator!=(const global_pose_t& other) const
207  {
208  return (!(*this == other));
209  }
210 
211  inline friend std::ostream& operator<<(
212  std::ostream& o, const self_t& global_pose)
213  {
214  o << global_pose.asString() << "| "
215  << global_pose.retAnnotsAsString();
216  return o;
217  }
218  };
219 
220  /** A map from pose IDs to their global coordinate estimates, with
221  * uncertainty */
222  using global_poses_pdf_t = typename MAPS_IMPLEMENTATION::template map<
224 
225  /** A map from pose IDs to their global coordinate estimates, without
226  * uncertainty (the "most-likely value") */
227  using global_poses_t = typename MAPS_IMPLEMENTATION::template map<
229 
230  /** @} */
231 
232  /** @name Data members
233  @{ */
234 
235  /** The nodes (vertices) of the graph, with their estimated "global"
236  * (with respect to \a root) position, without an associated covariance.
237  * \sa dijkstra_nodes_estimate
238  */
240 
241  /** The ID of the node that is the origin of coordinates, used as
242  * reference by all coordinates in \a nodes. By default, root is the ID
243  * "0". */
245 
246  /** False (default) if an edge i->j stores the normal relative pose of j
247  * as seen from i: \f$ \Delta_i^j = j \ominus i \f$ True if an edge i->j
248  * stores the inverse relateive pose, that is, i as seen from j: \f$
249  * \Delta_i^j = i \ominus j \f$
250  */
252 
253  /** @} */
254 
255  /** @name I/O methods
256  @{ */
257 
258  /** Saves to a text file in the format used by TORO, HoG-man, G2O.
259  * See: https://www.mrpt.org/Graph-SLAM_maps
260  * \sa saveToBinaryFile, loadFromTextFile, writeAsText
261  * \exception On any error
262  */
263  void saveToTextFile(const std::string& fileName) const
264  {
266  this, fileName);
267  }
268  /** Writes as text in the format used by TORO, HoG-man, G2O.
269  * See: https://www.mrpt.org/Graph-SLAM_maps
270  * \sa saveToBinaryFile, loadFromTextFile, saveToTextFile, readAsText
271  * \exception On any error
272  */
273  void writeAsText(std::ostream& o) const
274  {
276  }
277 
278  /** Loads from a text file in the format used by TORO & HoG-man (more on the
279  * format <a href="http://www.mrpt.org/Robotics_file_formats" >here</a>)
280  * Recognized line entries are: VERTEX2, VERTEX3, EDGE2, EDGE3, EQUIV.
281  * If an unknown entry is found, a warning is dumped to std::cerr (only
282  * once for each unknown keyword).
283  * An exception will be raised if trying to load a 3D graph into a 2D
284  * class (in the opposite case, missing 3D data will default to zero).
285  *
286  * \param[in] fileName The file to load.
287  * \param[in] collapse_dup_edges If true, \a collapseDuplicatedEdges will be
288  * called automatically after loading (note that this operation may take
289  * significant time for very large graphs).
290  *
291  * \sa loadFromBinaryFile, saveToTextFile
292  *
293  * \exception On any error, as a malformed line or loading a 3D graph in
294  * a 2D graph.
295  */
296  inline void loadFromTextFile(
297  const std::string& fileName, bool collapse_dup_edges = true)
298  {
300  this, fileName);
301  if (collapse_dup_edges) this->collapseDuplicatedEdges();
302  }
303 
304  /** Reads as text in the format used by TORO, HoG-man, G2O.
305  * See: https://www.mrpt.org/Graph-SLAM_maps
306  * \sa saveToBinaryFile, loadFromTextFile, saveToTextFile
307  * \exception On any error
308  */
309  void readAsText(std::istream& i)
310  {
312  this, i);
313  }
314 
315  /** @} */
316 
317  /** @name Utility methods
318  @{ */
319  /**\brief Return 3D Visual Representation of the edges and nodes in the
320  * network of poses
321  *
322  * Method makes the call to the corresponding method of the CVisualizer
323  * class instance.
324  */
325  inline void getAs3DObject(
327  const mrpt::system::TParametersDouble& viz_params) const
328  {
329  using visualizer_t = mrpt::graphs::detail::CVisualizer<
330  CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS>;
331  using visualizer_multirobot_t = mrpt::graphs::detail::CMRVisualizer<
332  CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS>;
333 
334  bool is_multirobot = false;
335  std::unique_ptr<visualizer_t> viz;
336  is_multirobot =
337  (std::is_base_of_v<
339  if (is_multirobot)
340  {
341  viz.reset(new visualizer_multirobot_t(*this));
342  }
343  else
344  {
345  viz.reset(new visualizer_t(*this));
346  }
347  viz->getAs3DObject(object, viz_params);
348  }
349 
350  /** Spanning tree computation of a simple estimation of the global
351  * coordinates of each node just from the information in all edges,
352  * sorted in a Dijkstra tree based on the current "root" node.
353  *
354  * \note The "global" coordinates are with respect to the node with the
355  * ID specified in \a root.
356  *
357  * \note This method takes into account the
358  * value of \a edges_store_inverse_poses
359  *
360  * \sa node, root
361  */
363  std::optional<std::reference_wrapper<std::map<TNodeID, size_t>>>
364  topological_distances = std::nullopt)
365  {
367  this, topological_distances ? &topological_distances.value().get()
368  : nullptr);
369  }
370 
371  /** Look for duplicated edges (even in opposite directions) between all
372  * pairs of nodes and fuse them. Upon return, only one edge remains
373  * between each pair of nodes with the mean & covariance (or information
374  * matrix) corresponding to the Bayesian fusion of all the Gaussians.
375  *
376  * \return Overall number of removed edges.
377  */
378  inline size_t collapseDuplicatedEdges()
379  {
381  this);
382  }
383 
384  /** Returns the total chi-squared error of the graph. Shortcut for
385  * getGlobalSquareError(false). */
386  double chi2() const { return getGlobalSquareError(false); }
387  /** Evaluates the graph total square error (ignoreCovariances=true) or
388  * chi2 (ignoreCovariances=false) from all the pose constraints (edges)
389  * with respect to the global poses in \a nodes.
390  * \sa getEdgeSquareError
391  * \exception std::exception On global poses not in \a nodes
392  */
393  double getGlobalSquareError(bool ignoreCovariances = true) const
394  {
395  double sqErr = 0;
396  for (auto it = BASE::edges.begin(); it != BASE::edges.end(); ++it)
398  this, it, ignoreCovariances);
399  return sqErr;
400  }
401 
402  /**\brief Find the edges between the nodes in the node_IDs set and fill
403  * given graph pointer accordingly.
404  *
405  * \param[in] node_IDs Set of nodes, between which, edges should be found
406  * and inserted in the given sub_graph pointer
407  * \param[in] root_node_in Node ID to be used as the root node of
408  * sub_graph. If this is not given, the lowest nodeID is to be used.
409  * \param[out] CNetworkOfPoses pointer that is to be filled.
410  *
411  * \param[in] auto_expand_set If true and in case the node_IDs set
412  * contains non-consecutive nodes the returned set is expanded with the
413  * in-between nodes. This makes sure that the final graph is always
414  * connected.
415  * If auto_expand_set is false but there exist
416  * non-consecutive nodes, virtual edges are inserted in the parts that
417  * the graph is not connected
418  */
420  const std::set<TNodeID>& node_IDs, self_t* sub_graph,
421  const TNodeID root_node_in = INVALID_NODEID,
422  const bool& auto_expand_set = true) const
423  {
424  using namespace std;
425  using namespace mrpt;
426  using namespace mrpt::math;
427  using namespace mrpt::graphs::detail;
428 
429  using dijkstra_t = CDijkstra<self_t, MAPS_IMPLEMENTATION>;
430 
431  // assert that the given pointers are valid
432  ASSERTMSG_(
433  sub_graph,
434  "\nInvalid pointer to a CNetworkOfPoses instance is given. "
435  "Exiting..\n");
436  sub_graph->clear();
437 
438  // assert that the root_node actually exists in the given node_IDs set
439  TNodeID root_node = root_node_in;
440  if (root_node != INVALID_NODEID)
441  {
442  ASSERTMSG_(
443  node_IDs.find(root_node) != node_IDs.end(),
444  "\nRoot_node does not exist in the given node_IDs set. "
445  "Exiting.\n");
446  }
447 
448  // ask for at least 2 nodes
449  ASSERTMSG_(
450  node_IDs.size() >= 2,
451  format(
452  "Very few nodes [%lu] for which to extract a subgraph. "
453  "Exiting\n",
454  static_cast<unsigned long>(node_IDs.size())));
455 
456  // find out if querry contains non-consecutive nodes.
457  // Assumption: Set elements are in standard, ascending order.
458  bool is_fully_connected_graph = true;
459  std::set<TNodeID> node_IDs_real; // actual set of nodes to be used.
460  if (*node_IDs.rbegin() - *node_IDs.begin() + 1 == node_IDs.size())
461  {
462  node_IDs_real = node_IDs;
463  }
464  else
465  { // contains non-consecutive nodes
466  is_fully_connected_graph = false;
467 
468  if (auto_expand_set)
469  { // set auto-expansion
470  for (TNodeID curr_node_ID = *node_IDs.begin();
471  curr_node_ID != *node_IDs.rbegin(); ++curr_node_ID)
472  {
473  node_IDs_real.insert(curr_node_ID);
474  }
475  }
476  else
477  { // virtual_edge_addition strategy
478  node_IDs_real = node_IDs;
479  }
480  }
481 
482  // add all the nodes of the node_IDs_real set to sub_graph
483  for (unsigned long node_IDs_it : node_IDs_real)
484  {
485  // assert that current node exists in *own* graph
486  typename global_poses_t::const_iterator own_it;
487  for (own_it = nodes.begin(); own_it != nodes.end(); ++own_it)
488  {
489  if (node_IDs_it == own_it->first)
490  {
491  break; // I throw exception afterwards
492  }
493  }
494  ASSERTMSG_(
495  own_it != nodes.end(),
496  format(
497  "NodeID [%lu] can't be found in the initial graph.",
498  static_cast<unsigned long>(node_IDs_it)));
499 
500  global_pose_t curr_node(nodes.at(node_IDs_it));
501  sub_graph->nodes.insert(make_pair(node_IDs_it, curr_node));
502  }
503  // cout << "Extracting subgraph for nodeIDs: " <<
504  // getSTLContainerAsString(node_IDs_real) << endl;
505 
506  // set the root of the extracted graph
507  if (root_node == INVALID_NODEID)
508  {
509  // smallest nodeID by default: already ordered inside std::map
510  root_node = sub_graph->nodes.begin()->first;
511  }
512  sub_graph->root = root_node;
513 
514  // find all edges (in the initial graph), that exist in the given set
515  // of nodes; add them to the given graph
516  sub_graph->clearEdges();
517  for (const auto& e : BASE::edges)
518  {
519  const TNodeID& from = e.first.first;
520  const TNodeID& to = e.first.second;
521  const typename BASE::edge_t& curr_edge = e.second;
522 
523  // if both nodes exist in the given set, add the corresponding edge
524  if (sub_graph->nodes.find(from) != sub_graph->nodes.end() &&
525  sub_graph->nodes.find(to) != sub_graph->nodes.end())
526  {
527  sub_graph->insertEdge(from, to, curr_edge);
528  }
529  }
530 
531  if (!auto_expand_set && !is_fully_connected_graph)
532  {
533  // Addition of virtual edges between non-connected graph parts is
534  // necessary
535 
536  // make sure that the root nodeID is connected to at least one node
537  {
538  std::set<TNodeID> root_neighbors;
539  sub_graph->getNeighborsOf(sub_graph->root, root_neighbors);
540 
541  if (root_neighbors.empty())
542  {
543  // add an edge between the root and an adjacent nodeID
544  typename global_poses_t::iterator root_it =
545  sub_graph->nodes.find(sub_graph->root);
546  ASSERT_(root_it != sub_graph->nodes.end());
547  if ((*root_it == *sub_graph->nodes.rbegin()))
548  { // is the last nodeID
549  // add with previous node
550  TNodeID next_to_root = (--root_it)->first;
552  sub_graph, next_to_root, sub_graph->root);
553  // cout << "next_to_root = " << next_to_root;
554  }
555  else
556  {
557  TNodeID next_to_root = (++root_it)->first;
558  // cout << "next_to_root = " << next_to_root;
560  sub_graph, sub_graph->root, next_to_root);
561  }
562  }
563  }
564 
565  // as long as the graph is unconnected (as indicated by Dijkstra)
566  // add a virtual edge between
567  bool dijkstra_runs_successfully = false;
568 
569  // loop until the graph is fully connected (i.e. I can reach every
570  // node of the graph starting from its root)
571  while (!dijkstra_runs_successfully)
572  {
573  try
574  {
575  dijkstra_t dijkstra(*sub_graph, sub_graph->root);
576  dijkstra_runs_successfully = true;
577  }
579  {
580  dijkstra_runs_successfully = false;
581 
582  set<TNodeID> unconnected_nodeIDs;
583  ex.getUnconnectedNodeIDs(&unconnected_nodeIDs);
584  // cout << "Unconnected nodeIDs: " <<
585  // mrpt::math::getSTLContainerAsString(unconnected_nodeIDs)
586  // << endl;
587  // mainland: set of nodes that the root nodeID is in
588  // island: set of nodes that the Dijkstra graph traversal
589  // can't
590  // reach starting from the root.
591  // [!] There may be multiple sets of these nodes
592 
593  // set::rend() is the element with the highest value
594  // set::begin() is the element with the lowest value
595  const TNodeID& island_highest =
596  *unconnected_nodeIDs.rbegin();
597  const TNodeID& island_lowest = *unconnected_nodeIDs.begin();
598  // cout << "island_highest: " << island_highest << endl;
599  // cout << "island_lowest: " << island_lowest << endl;
600  // cout << "root: " << sub_graph->root << endl;
601 
602  // find out which nodes are in the same partition with the
603  // root
604  // (i.e. mainland)
605  std::set<TNodeID> mainland;
606  // for all nodes in sub_graph
607  for (typename global_poses_t::const_iterator n_it =
608  sub_graph->nodes.begin();
609  n_it != sub_graph->nodes.end(); ++n_it)
610  {
611  bool is_there = false;
612 
613  // for all unconnected nodes
614  for (unsigned long unconnected_nodeID :
615  unconnected_nodeIDs)
616  {
617  if (n_it->first == unconnected_nodeID)
618  {
619  is_there = true;
620  break;
621  }
622  }
623 
624  if (!is_there)
625  {
626  mainland.insert(n_it->first);
627  }
628  }
629 
630  bool is_single_island =
631  (island_highest - island_lowest + 1 ==
632  unconnected_nodeIDs.size());
633 
634  if (is_single_island)
635  { // single island
636  // Possible scenarios:
637  // | island |
638  // | mainland |
639  // | <low nodeIDs> island_highest| --- <virtual_edge>
640  // --->> | mainland_lowest <high nodeIDs> ... root ...|
641  // --- OR ---
642  // | mainland |
643  // | island |
644  // | <low nodeIDs> mainland_highest| ---
645  // <virtual_edge> --->> | island_lowest <high nodeIDs>
646  // |
647 
648  const std::set<TNodeID>& island = unconnected_nodeIDs;
650  sub_graph, island, mainland);
651  }
652  else
653  { // multiple islands
654  // add a virtual edge between the last group before the
655  // mainland and the mainland
656 
657  // split the unconnected_nodeIDs to smaller groups of
658  // nodes
659  // we only care about the nodes that are prior to the
660  // root
661  std::vector<std::set<TNodeID>> vec_of_islands;
662  std::set<TNodeID> curr_island;
663  TNodeID prev_nodeID = *unconnected_nodeIDs.begin();
664  curr_island.insert(
665  prev_nodeID); // add the initial node;
666  for (auto it = ++unconnected_nodeIDs.begin();
667  *it < sub_graph->root &&
668  it != unconnected_nodeIDs.end();
669  ++it)
670  {
671  if (!(absDiff(*it, prev_nodeID) == 1))
672  {
673  vec_of_islands.push_back(curr_island);
674  curr_island.clear();
675  }
676  curr_island.insert(*it);
677 
678  // update the previous nodeID
679  prev_nodeID = *it;
680  }
681  vec_of_islands.push_back(curr_island);
682 
683  // cout << "last_island: " <<
684  // getSTLContainerAsString(vec_of_islands.back()) <<
685  // endl;
686  // cout << "mainland: " <<
687  // getSTLContainerAsString(mainland) << endl;
689  sub_graph, vec_of_islands.back(), mainland);
690  }
691  }
692  }
693  }
694 
695  // estimate the node positions according to the edges - root is (0, 0,
696  // 0)
697  // just execute dijkstra once for grabbing the updated node positions.
698  sub_graph->dijkstra_nodes_estimate();
699 
700  } // end of extractSubGraph
701 
702  /**\brief Integrate given graph into own graph using the list of provided
703  * common THypotheses. Nodes of the other graph are renumbered upon
704  * integration in own graph.
705  *
706  * \param[in] other Graph (of the same type) that is to be integrated with
707  * own graph.
708  * \param[in] Hypotheses that join own and other graph.
709  * \param[in] hypots_from_other_to_self Specify the direction of the
710  * THypothesis objects in the common_hypots. If true (default) they are
711  * directed from other to own graph (other \rightarrow own),
712  *
713  * \param[out] old_to_new_nodeID_mappings_out Map from the old nodeIDs
714  * that are in the given graph to the new nodeIDs that have been inserted
715  * (by this method) in own graph.
716  */
717  inline void mergeGraph(
718  const self_t& other,
719  const typename std::vector<detail::THypothesis<self_t>>& common_hypots,
720  const bool hypots_from_other_to_self = true,
721  std::map<TNodeID, TNodeID>* old_to_new_nodeID_mappings_out = nullptr)
722  {
723  MRPT_START;
724  using namespace mrpt::graphs;
725  using namespace mrpt::graphs::detail;
726  using namespace std;
727 
728  using hypots_cit_t =
729  typename vector<THypothesis<self_t>>::const_iterator;
730  using nodes_cit_t = typename global_poses_t::const_iterator;
731 
732  const self_t& graph_from = (hypots_from_other_to_self ? other : *this);
733  const self_t& graph_to = (hypots_from_other_to_self ? *this : other);
734 
735  // assert that both own and other graph have at least two nodes.
736  ASSERT_(graph_from.nodes.size() >= 2);
737  ASSERT_(graph_to.nodes.size() >= 2);
738 
739  // Assert that from-nodeIds, to-nodeIDs in common_hypots exist in own
740  // and other graph respectively
741  for (hypots_cit_t h_cit = common_hypots.begin();
742  h_cit != common_hypots.end(); ++h_cit)
743  {
744  ASSERTMSG_(
745  graph_from.nodes.find(h_cit->from) != graph_from.nodes.end(),
746  format("NodeID %lu is not found in (from) graph", h_cit->from));
747  ASSERTMSG_(
748  graph_to.nodes.find(h_cit->to) != graph_to.nodes.end(),
749  format("NodeID %lu is not found in (to) graph", h_cit->to));
750  }
751 
752  // find the max nodeID in existing graph
753  TNodeID max_nodeID = 0;
754  for (nodes_cit_t n_cit = this->nodes.begin();
755  n_cit != this->nodes.end(); ++n_cit)
756  {
757  if (n_cit->first > max_nodeID)
758  {
759  max_nodeID = n_cit->first;
760  }
761  }
762  TNodeID renum_start = max_nodeID + 1;
763  size_t renum_counter = 0;
764  // cout << "renum_start: " << renum_start << endl;
765 
766  // Renumber nodeIDs of other graph so that they don't overlap with own
767  // graph nodeIDs
768  std::map<TNodeID, TNodeID>* old_to_new_nodeID_mappings;
769 
770  // map of TNodeID->TNodeID correspondences to address to if the
771  // old_to_new_nodeID_mappings_out is not given.
772  // Handy for not having to allocate old_to_new_nodeID_mappings in the
773  // heap
774  std::map<TNodeID, TNodeID> mappings_tmp;
775 
776  // If given, use the old_to_new_nodeID_mappings map.
777  if (old_to_new_nodeID_mappings_out)
778  {
779  old_to_new_nodeID_mappings = old_to_new_nodeID_mappings_out;
780  }
781  else
782  {
783  old_to_new_nodeID_mappings = &mappings_tmp;
784  }
785  old_to_new_nodeID_mappings->clear();
786 
787  // add all nodes of other graph - Take care of renumbering them
788  // cout << "Adding nodes of other graph" << endl;
789  // cout << "====================" << endl;
790  for (nodes_cit_t n_cit = other.nodes.begin();
791  n_cit != other.nodes.end(); ++n_cit)
792  {
793  TNodeID new_nodeID = renum_start + renum_counter++;
794  old_to_new_nodeID_mappings->insert(
795  make_pair(n_cit->first, new_nodeID));
796  this->nodes.insert(make_pair(new_nodeID, n_cit->second));
797 
798  // cout << "Adding nodeID: " << new_nodeID << endl;
799  }
800 
801  // add common constraints
802  // cout << "Adding common constraints" << endl;
803  // cout << "====================" << endl;
804  for (hypots_cit_t h_cit = common_hypots.begin();
805  h_cit != common_hypots.end(); ++h_cit)
806  {
807  TNodeID from, to;
808  if (hypots_from_other_to_self)
809  {
810  from = old_to_new_nodeID_mappings->at(h_cit->from);
811  to = h_cit->to;
812  }
813  else
814  {
815  from = h_cit->from;
816  to = old_to_new_nodeID_mappings->at(h_cit->to);
817  }
818  this->insertEdge(from, to, h_cit->getEdge());
819  // cout << from << " -> " << to << " => " << h_cit->getEdge() <<
820  // endl;
821  }
822 
823  // add all constraints of the other graph
824  // cout << "Adding constraints of other graph" << endl;
825  // cout << "====================" << endl;
826  for (typename self_t::const_iterator g_cit = other.begin();
827  g_cit != other.end(); ++g_cit)
828  {
829  TNodeID new_from =
830  old_to_new_nodeID_mappings->at(g_cit->first.first);
831  TNodeID new_to =
832  old_to_new_nodeID_mappings->at(g_cit->first.second);
833  this->insertEdge(new_from, new_to, g_cit->second);
834 
835  // cout << "[" << new_from << "] -> [" << new_to << "]" << " => " <<
836  // g_cit->second << endl;
837  }
838 
839  // run Dijkstra to update the node positions
840  this->dijkstra_nodes_estimate();
841 
842  MRPT_END;
843  }
844 
845  /**\brief Add an edge between the last node of the group with the lower
846  * nodeIDs and the first node of the higher nodeIDs.
847  *
848  * Given groups of nodes should only contain consecutive nodeIDs and
849  * there should be no overlapping between them
850  *
851  * \note It is assumed that the sets of nodes are \b already in ascending
852  * order (default std::set behavior.
853  */
854  inline static void connectGraphPartitions(
855  self_t* sub_graph, const std::set<TNodeID>& groupA,
856  const std::set<TNodeID>& groupB)
857  {
858  using namespace mrpt::math;
859 
860  ASSERTMSG_(
861  sub_graph,
862  "\nInvalid pointer to a CNetworkOfPoses instance is given. "
863  "Exiting..\n");
864  ASSERTMSG_(!groupA.empty(), "\ngroupA is empty.");
865  ASSERTMSG_(!groupB.empty(), "\ngroupB is empty.");
866 
867  // assertion - non-overlapping groups
868  ASSERTMSG_(
869  *groupA.rend() < *groupB.rbegin() ||
870  *groupA.rbegin() > *groupB.rend(),
871  "Groups A, B contain overlapping nodeIDs");
872 
873  // decide what group contains the low/high nodeIDs
874  // just compare any two nodes of the sets (they are non-overlapping
875  const std::set<TNodeID>& low_nodeIDs =
876  *groupA.rbegin() < *groupB.rbegin() ? groupA : groupB;
877  const std::set<TNodeID>& high_nodeIDs =
878  *groupA.rbegin() > *groupB.rbegin() ? groupA : groupB;
879 
880  // add virtual edge
881  const TNodeID& from_nodeID = *low_nodeIDs.rbegin();
882  const TNodeID& to_nodeID = *high_nodeIDs.begin();
883  self_t::addVirtualEdge(sub_graph, from_nodeID, to_nodeID);
884  }
885 
886  /** Computes the square error of one pose constraints (edge) with respect
887  * to the global poses in \a nodes If \a ignoreCovariances is false, the
888  * squared Mahalanobis distance will be computed instead of the straight
889  * square error.
890  *
891  * \exception std::exception On global poses not in \a nodes
892  */
893  inline double getEdgeSquareError(
894  const typename BASE::edges_map_t::const_iterator& itEdge,
895  bool ignoreCovariances = true) const
896  {
898  this, itEdge, ignoreCovariances);
899  }
900 
901  /** Computes the square error of one pose constraints (edge) with respect
902  * to the global poses in \a nodes If \a ignoreCovariances is false, the
903  * squared Mahalanobis distance will be computed instead of the straight
904  * square error.
905  *
906  * \exception std::exception On edge not existing or global poses not in
907  * \a nodes
908  */
910  const mrpt::graphs::TNodeID from_id, const mrpt::graphs::TNodeID to_id,
911  bool ignoreCovariances = true) const
912  {
913  const typename BASE::edges_map_t::const_iterator itEdge =
914  BASE::edges.find(std::make_pair(from_id, to_id));
915  ASSERTMSG_(
916  itEdge != BASE::edges.end(),
917  format(
918  "Request for edge %u->%u that doesn't exist in graph.",
919  static_cast<unsigned int>(from_id),
920  static_cast<unsigned int>(to_id)));
921  return getEdgeSquareError(itEdge, ignoreCovariances);
922  }
923 
924  /** Empty all edges, nodes and set root to ID 0. */
925  inline void clear()
926  {
927  BASE::edges.clear();
928  nodes.clear();
929  root = 0;
931  }
932 
933  /** Return number of nodes in the list \a nodes of global coordinates
934  * (may be different that all nodes appearing in edges)
935  *
936  * \sa mrpt::graphs::CDirectedGraph::countDifferentNodesInEdges
937  */
938  inline size_t nodeCount() const { return nodes.size(); }
939  /** @} */
940 
941  private:
942  /**\brief Add a virtual edge between two nodes in the given graph.
943  *
944  * Edge is called virtual as its value will be determined solely on the
945  * pose difference of the given nodeIDs
946  */
947  inline static void addVirtualEdge(
948  self_t* graph, const TNodeID& from, const TNodeID& to)
949  {
950  ASSERTMSG_(
951  graph, "Invalid pointer to the graph instance was provided.");
952 
953  typename self_t::global_pose_t& p_from = graph->nodes.at(from);
954  typename self_t::global_pose_t& p_to = graph->nodes.at(to);
955  const typename BASE::edge_t& virt_edge(p_to - p_from);
956 
957  graph->insertEdge(from, to, virt_edge);
958  }
959 };
960 
961 /** Binary serialization (write) operator "stream << graph" */
962 template <
963  class CPOSE, class MAPS_IMPLEMENTATION, class NODE_ANNOTATIONS,
964  class EDGE_ANNOTATIONS>
967  const CNetworkOfPoses<
968  CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS>& obj)
969 {
970  using graph_t = CNetworkOfPoses<
971  CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS>;
973  return out;
974 }
975 
976 /** Binary serialization (read) operator "stream >> graph" */
977 template <
978  class CPOSE, class MAPS_IMPLEMENTATION, class NODE_ANNOTATIONS,
979  class EDGE_ANNOTATIONS>
983  CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS>& obj)
984 {
985  using graph_t = CNetworkOfPoses<
986  CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS>;
988  return in;
989 }
990 
991 /** \addtogroup mrpt_graphs_grp
992  * \name Handy typedefs for CNetworkOfPoses commonly used types
993  @{ */
994 
995 /** The specialization of CNetworkOfPoses for poses of type CPose2D (not a
996  * PDF!), also implementing serialization. */
998 /** The specialization of CNetworkOfPoses for poses of type mrpt::poses::CPose3D
999  * (not a PDF!), also implementing serialization. */
1001 /** The specialization of CNetworkOfPoses for poses of type CPosePDFGaussian,
1002  * also implementing serialization. */
1004 /** The specialization of CNetworkOfPoses for poses of type CPose3DPDFGaussian,
1005  * also implementing serialization. */
1007 /** The specialization of CNetworkOfPoses for poses of type CPosePDFGaussianInf,
1008  * also implementing serialization. */
1010 /** The specialization of CNetworkOfPoses for poses of type
1011  * CPose3DPDFGaussianInf, also implementing serialization. */
1012 using CNetworkOfPoses3DInf =
1014 
1015 /**\brief Specializations of CNetworkOfPoses for graphs whose nodes inherit from
1016  * TMRSlamNodeAnnotations struct */
1017 /**\{ */
1024 /**\} */
1025 
1026 /** @} */ // end of grouping
1027 
1028 } // namespace graphs
1029 
1030 // Specialization of TTypeName must occur in the same namespace:
1031 // These ones are here instead of into mrpt-containers, to avoid
1032 // the dependency mrpt-containers -> mrpt-typemeta
1033 namespace typemeta
1034 {
1037 } // namespace typemeta
1038 
1039 } // namespace mrpt
1040 
1041 // Implementation of templates (in a separate file for clarity)
1042 #include "CNetworkOfPoses_impl.h"
1043 
1044 // Visualization related template classes
1045 #include <mrpt/graphs/CMRVisualizer.h>
1046 #include <mrpt/graphs/CVisualizer.h>
A directed graph with the argument of the template specifying the type of the annotations in the edge...
static void save_graph_of_poses_to_binary_file(const graph_t *g, mrpt::serialization::CArchive &out)
mrpt::serialization::CArchive & operator>>(mrpt::serialization::CArchive &in, CNetworkOfPoses< CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS > &obj)
Binary serialization (read) operator "stream >> graph".
double getGlobalSquareError(bool ignoreCovariances=true) const
Evaluates the graph total square error (ignoreCovariances=true) or chi2 (ignoreCovariances=false) fro...
#define MRPT_START
Definition: exceptions.h:241
typename MAPS_IMPLEMENTATION::template map< mrpt::graphs::TNodeID, CPOSE > global_poses_pdf_t
A map from pose IDs to their global coordinate estimates, with uncertainty.
global_pose_t(const global_pose_t &other)
Copy constructor - delegate copying to the NODE_ANNOTATIONS struct.
void clear()
Empty all edges, nodes and set root to ID 0.
mrpt::graphs::TNodeID root
The ID of the node that is the origin of coordinates, used as reference by all coordinates in nodes...
void dijkstra_nodes_estimate(std::optional< std::reference_wrapper< std::map< TNodeID, size_t >>> topological_distances=std::nullopt)
Spanning tree computation of a simple estimation of the global coordinates of each node just from the...
size_t collapseDuplicatedEdges()
Look for duplicated edges (even in opposite directions) between all pairs of nodes and fuse them...
edges_map_t edges
The public member with the directed edges in the graph.
GLint * first
Definition: glext.h:3833
EDGE_ANNOTATIONS edge_annotations_t
The extra annotations in edges, apart from a constraint_t.
void saveToTextFile(const std::string &fileName) const
Saves to a text file in the format used by TORO, HoG-man, G2O.
friend std::ostream & operator<<(std::ostream &o, const self_t &global_pose)
Abstract graph and tree data structures, plus generic graph algorithms.
static constexpr auto getClassName()
void getNeighborsOf(const TNodeID nodeID, std::set< TNodeID > &neighborIDs) const
Return the list of all neighbors of "nodeID", by creating a list of their node IDs.
void loadFromTextFile(const std::string &fileName, bool collapse_dup_edges=true)
Loads from a text file in the format used by TORO & HoG-man (more on the format here) Recognized line...
CPOSE constraint_t
The type of PDF poses in the contraints (edges) (=CPOSE template argument)
double chi2() const
Returns the total chi-squared error of the graph.
STL namespace.
void getUnconnectedNodeIDs(std::set< mrpt::graphs::TNodeID > *set_nodeIDs) const
Fill set with the nodeIDs Dijkstra algorithm could not reach starting from the root node...
Definition: dijkstra.h:46
static void read_graph_of_poses_from_binary_file(graph_t *g, mrpt::serialization::CArchive &in)
GLsizei GLsizei GLuint * obj
Definition: glext.h:4085
double getEdgeSquareError(const typename BASE::edges_map_t::const_iterator &itEdge, bool ignoreCovariances=true) const
Computes the square error of one pose constraints (edge) with respect to the global poses in nodes If...
void clearEdges()
Erase all edges.
A template to obtain the type of its argument as a string at compile time.
Definition: TTypeName.h:69
double getEdgeSquareError(const mrpt::graphs::TNodeID from_id, const mrpt::graphs::TNodeID to_id, bool ignoreCovariances=true) const
Computes the square error of one pose constraints (edge) with respect to the global poses in nodes If...
Base class for C*Visualizer classes.
A directed graph of pose constraints, with edges being the relative poses between pairs of nodes iden...
#define ASSERT_(f)
Defines an assertion mechanism.
Definition: exceptions.h:120
Internal functions for MRPT.
static void save_graph_of_poses_to_ostream(const graph_t *g, std::ostream &f)
This base provides a set of functions for maths stuff.
typename CPOSE::type_value constraint_no_pdf_t
The type of edges or their means if they are PDFs (that is, a simple "edge" value) ...
constexpr auto literal(const char(&lit)[N_PLUS_1]) -> string_literal< N_PLUS_1 - 1 >
Definition: static_string.h:46
The type of each global pose in nodes: an extension of the constraint_no_pdf_t pose with any optional...
void insertEdge(TNodeID from_nodeID, TNodeID to_nodeID, const edge_t &edge_value)
Insert an edge (from -> to) with the given edge value.
void getAs3DObject(mrpt::opengl::CSetOfObjects::Ptr object, const mrpt::system::TParametersDouble &viz_params) const
Return 3D Visual Representation of the edges and nodes in the network of poses.
typename MAPS_IMPLEMENTATION::template map< mrpt::graphs::TNodeID, global_pose_t > global_poses_t
A map from pose IDs to their global coordinate estimates, without uncertainty (the "most-likely value...
#define ASSERTMSG_(f, __ERROR_MSG)
Defines an assertion mechanism.
Definition: exceptions.h:108
void mergeGraph(const self_t &other, const typename std::vector< detail::THypothesis< self_t >> &common_hypots, const bool hypots_from_other_to_self=true, std::map< TNodeID, TNodeID > *old_to_new_nodeID_mappings_out=nullptr)
Integrate given graph into own graph using the list of provided common THypotheses.
bool operator!=(const global_pose_t &other) const
static void connectGraphPartitions(self_t *sub_graph, const std::set< TNodeID > &groupA, const std::set< TNodeID > &groupB)
Add an edge between the last node of the group with the lower nodeIDs and the first node of the highe...
void writeAsText(std::ostream &o) const
Writes as text in the format used by TORO, HoG-man, G2O.
GLsizei const GLchar ** string
Definition: glext.h:4116
static void load_graph_of_poses_from_text_stream(graph_t *g, std::istream &f, const std::string &fil=std::string("(none)"))
size_t nodeCount() const
Return number of nodes in the list nodes of global coordinates (may be different that all nodes appea...
void extractSubGraph(const std::set< TNodeID > &node_IDs, self_t *sub_graph, const TNodeID root_node_in=INVALID_NODEID, const bool &auto_expand_set=true) const
Find the edges between the nodes in the node_IDs set and fill given graph pointer accordingly...
Traits for using a std::map<> (sparse representation)
Definition: traits_map.h:24
global_pose_t()
Potential class constructors.
static size_t graph_of_poses_collapse_dup_edges(graph_t *g)
static void save_graph_of_poses_to_text_file(const graph_t *g, const std::string &fil)
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
A Probability Density function (PDF) of a 2D pose as a Gaussian with a mean and the inverse of the c...
Traits for using a mrpt::containers::map_as_vector<> (dense, fastest representation) ...
Definition: traits_map.h:32
Virtual base class for "archives": classes abstracting I/O streams.
Definition: CArchive.h:53
std::string format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
Definition: format.cpp:16
static double graph_edge_sqerror(const graph_t *g, const typename mrpt::graphs::CDirectedGraph< typename graph_t::constraint_t >::edges_map_t::const_iterator &itEdge, bool ignoreCovariances)
a helper struct with static template functions
#define MRPT_END
Definition: exceptions.h:245
Declares a class that represents a Probability Density function (PDF) of a 3D pose as a Gaussian des...
GLuint in
Definition: glext.h:7391
void readAsText(std::istream &i)
Reads as text in the format used by TORO, HoG-man, G2O.
typename edges_map_t::const_iterator const_iterator
uint64_t TNodeID
A generic numeric type for unique IDs of nodes or entities.
Definition: TNodeID.h:16
static void graph_of_poses_dijkstra_init(graph_t *g, std::map< TNodeID, size_t > *topological_distances=nullptr)
static void load_graph_of_poses_from_text_file(graph_t *g, const std::string &fil)
MAPS_IMPLEMENTATION maps_implementation_t
The type of map&#39;s implementation (=MAPS_IMPLEMENTATION template argument)
global_poses_t nodes
The nodes (vertices) of the graph, with their estimated "global" (with respect to root) position...
global_pose_t(const ARG1 &a1, const ARG2 &a2)
The Dijkstra algorithm for finding the shortest path between a given source node in a (weighted) dire...
Definition: dijkstra.h:97
#define INVALID_NODEID
Definition: TNodeID.h:19
T absDiff(const T &lhs, const T &rhs)
Absolute difference between two numbers.
bool edges_store_inverse_poses
False (default) if an edge i->j stores the normal relative pose of j as seen from i: True if an edge...
bool operator==(const global_pose_t &other) const
An edge hypothesis between two nodeIDs.
Definition: THypothesis.h:32
Struct to be used as the NODE_ANNOTATIONS template argument in CNetworkOfPoses class instances for us...
Struct to be used as the NODE_ANNOTATIONS template argument in CNetworkOfPoses class instances for us...
Wrapper class that provides visualization of a network of poses that have been registered by many gra...
Definition: CMRVisualizer.h:36
Custom exception class that passes information in case an unconnected graph is passed to a Dijkstra i...
Definition: dijkstra.h:30
NODE_ANNOTATIONS node_annotations_t
The extra annotations in nodes, apart from a constraint_no_pdf_t.
typename CNetworkOfPoses< CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS >::global_pose_t self_t
#define MRPT_DECLARE_TTYPENAME(_TYPE)
Definition: TTypeName.h:111
static void addVirtualEdge(self_t *graph, const TNodeID &from, const TNodeID &to)
Add a virtual edge between two nodes in the given graph.



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: 8fe78517f Sun Jul 14 19:43:28 2019 +0200 at lun oct 28 02:10:00 CET 2019