MRPT  1.9.9
test.cpp
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 
10 #include <mrpt/graphslam/levmarq.h>
11 #include <mrpt/gui.h>
12 #include <mrpt/img/TColor.h>
16 #include <mrpt/random.h>
18 #include <iostream>
19 
20 using namespace mrpt;
21 using namespace mrpt::graphs;
22 using namespace mrpt::graphslam;
23 using namespace mrpt::poses;
24 using namespace mrpt::math;
25 using namespace mrpt::gui;
26 using namespace mrpt::opengl;
27 using namespace mrpt::random;
28 using namespace mrpt::img;
29 using namespace std;
30 using namespace mrpt::system;
31 
32 // Level of noise in nodes initial positions:
33 const double STD_NOISE_NODE_XYZ = 0.5;
34 const double STD_NOISE_NODE_ANG = DEG2RAD(5);
35 
36 // Level of noise in edges:
37 const double STD_NOISE_EDGE_XYZ = 0.001;
38 const double STD_NOISE_EDGE_ANG = DEG2RAD(0.01);
39 
40 const double STD4EDGES_COV_MATRIX = 10;
41 const double ERROR_IN_INCOMPATIBLE_EDGE = 0.3; // ratio [0,1]
42 
43 /**
44  * Generic struct template
45  * Auxiliary class to add a new edge to the graph. The edge is annotated with
46  * the relative position of the two nodes
47  */
48 template <class GRAPH, bool EDGES_ARE_PDF = GRAPH::edge_t::is_PDF_val>
49 struct EdgeAdders;
50 
51 /**
52  * Specific templates based on the above EdgeAdders template
53  * Non-PDF version:
54  */
55 template <class GRAPH>
56 struct EdgeAdders<GRAPH, false>
57 {
58  static const int DIM = GRAPH::edge_t::type_value::static_size;
59  typedef CMatrixFixed<double, DIM, DIM> cov_t;
60 
61  static void addEdge(
62  TNodeID from, TNodeID to,
63  const typename GRAPH::global_poses_t& real_poses, GRAPH& graph,
64  const cov_t& COV_MAT)
65  {
66  /**
67  * No covariance argument here (although it is passed in the function
68  * declaration above)
69  * See also :
70  * https://groups.google.com/d/msg/mrpt-users/Sr9LSydArgY/vRNM5V_uA-oJ
71  * for a more detailed explanation on how it is treated
72  */
73  typename GRAPH::edge_t RelativePose(
74  real_poses.find(to)->second - real_poses.find(from)->second);
75  graph.insertEdge(from, to, RelativePose);
76  }
77 };
78 // PDF version:
79 template <class GRAPH>
80 struct EdgeAdders<GRAPH, true>
81 {
82  static const int DIM = GRAPH::edge_t::type_value::static_size;
83  typedef CMatrixFixed<double, DIM, DIM> cov_t;
84 
85  static void addEdge(
86  TNodeID from, TNodeID to,
87  const typename GRAPH::global_poses_t& real_poses, GRAPH& graph,
88  const cov_t& COV_MAT)
89  {
90  typename GRAPH::edge_t RelativePose(
91  real_poses.find(to)->second - real_poses.find(from)->second,
92  COV_MAT);
93  graph.insertEdge(from, to, RelativePose);
94  }
95 };
96 
97 // Container to handle the propagation of the square root error of the problem
98 vector<double> log_sq_err_evolution;
99 
100 // This example lives inside this template class, which can be instanced for
101 // different kind of graphs (see main()):
102 template <class my_graph_t>
104 {
105  template <class GRAPH_T>
106  static void my_levmarq_feedback(
107  const GRAPH_T& graph, const size_t iter, const size_t max_iter,
108  const double cur_sq_error)
109  {
110  log_sq_err_evolution.push_back(std::log(cur_sq_error));
111  if ((iter % 100) == 0)
112  cout << "Progress: " << iter << " / " << max_iter
113  << ", total sq err = " << cur_sq_error << endl;
114  }
115 
116  // ------------------------------------------------------
117  // GraphSLAMDemo
118  // ------------------------------------------------------
119  void run(bool add_extra_tightening_edge)
120  {
121  // The graph: nodes + edges:
122  my_graph_t graph;
123 
124  // The global poses of the graph nodes (without covariance):
125  typename my_graph_t::global_poses_t real_node_poses;
126 
127  /**
128  * Initialize the PRNG from the given random seed.
129  * Method used to initially randomise the generator
130  */
132 
133  // ----------------------------
134  // Create a random graph:
135  // ----------------------------
136  const size_t N_VERTEX = 50;
137  const double DIST_THRES = 7;
138  const double NODES_XY_MAX = 20;
139 
140  /**
141  * First add all the nodes (so that, when I add edges, I can refer to
142  * them
143  */
144  for (TNodeID j = 0; j < N_VERTEX; j++)
145  {
146  // Use evenly distributed nodes:
147  static double ang = 2 * M_PI / N_VERTEX;
148  const double R = NODES_XY_MAX + 2 * (j % 2 ? 1 : -1);
149  CPose2D p(R * cos(ang * j), R * sin(ang * j), ang);
150 
151  // Save real pose:
152  real_node_poses[j] = p;
153 
154  // Copy the nodes to the graph, and add some noise:
155  graph.nodes[j] = p;
156  }
157 
158  /**
159  * Add some edges
160  * Also initialize the information matrix used for EACH constraint. For
161  * simplicity the same information matrix is used for each one of the
162  * edges. This information matrix is RELATIVE to each constraint/edge
163  * (not in global ref. frame) see also:
164  * https://groups.google.com/d/msg/mrpt-users/Sr9LSydArgY/wYFeU2BXr4kJ
165  */
166  typedef EdgeAdders<my_graph_t> edge_adder_t;
167  typename edge_adder_t::cov_t inf_matrix;
168  inf_matrix.setDiagonal(
169  edge_adder_t::cov_t::RowsAtCompileTime,
171 
172  /**
173  * add the edges using the node ids added to the graph before
174  */
175  for (TNodeID i = 0; i < N_VERTEX; i++)
176  {
177  for (TNodeID j = i + 1; j < N_VERTEX; j++)
178  {
179  if (real_node_poses[i].distanceTo(real_node_poses[j]) <
180  DIST_THRES)
182  i, j, real_node_poses, graph, inf_matrix);
183  }
184  }
185 
186  // Add an additional edge to deform the graph?
187  if (add_extra_tightening_edge)
188  {
189  // inf_matrix.setIdentity(square(1.0/(STD4EDGES_COV_MATRIX)));
191  0, N_VERTEX / 2, real_node_poses, graph, inf_matrix);
192 
193  // Tweak this last node to make it incompatible with the rest:
194  // It must exist, don't check errors...
195  typename my_graph_t::edge_t& ed =
196  graph.edges.find(make_pair(TNodeID(0), TNodeID(N_VERTEX / 2)))
197  ->second;
198  ed.getPoseMean().x(
199  (1 - ERROR_IN_INCOMPATIBLE_EDGE) * ed.getPoseMean().x());
200  }
201 
202  // The root node (the origin of coordinates):
203  graph.root = TNodeID(0);
204 
205  // This is the ground truth graph (make a copy for later use):
206  const my_graph_t graph_GT = graph;
207 
208  cout << "graph nodes: " << graph_GT.nodeCount() << endl;
209  cout << "graph edges: " << graph_GT.edgeCount() << endl;
210 
211  // Add noise to edges & nodes:
212  for (typename my_graph_t::edges_map_t::iterator itEdge =
213  graph.edges.begin();
214  itEdge != graph.edges.end(); ++itEdge)
215  {
216  const typename my_graph_t::edge_t::type_value delta_noise(CPose3D(
217  getRandomGenerator().drawGaussian1D(0, STD_NOISE_EDGE_XYZ),
218  getRandomGenerator().drawGaussian1D(0, STD_NOISE_EDGE_XYZ),
219  getRandomGenerator().drawGaussian1D(0, STD_NOISE_EDGE_XYZ),
220  getRandomGenerator().drawGaussian1D(0, STD_NOISE_EDGE_ANG),
221  getRandomGenerator().drawGaussian1D(0, STD_NOISE_EDGE_ANG),
222  getRandomGenerator().drawGaussian1D(0, STD_NOISE_EDGE_ANG)));
223  itEdge->second.getPoseMean() +=
224  typename my_graph_t::edge_t::type_value(delta_noise);
225  }
226 
227  for (typename my_graph_t::global_poses_t::iterator itNode =
228  graph.nodes.begin();
229  itNode != graph.nodes.end(); ++itNode)
230  if (itNode->first != graph.root)
231  itNode->second.getPoseMean() +=
232  typename my_graph_t::edge_t::type_value(CPose3D(
233  getRandomGenerator().drawGaussian1D(
234  0, STD_NOISE_NODE_XYZ),
235  getRandomGenerator().drawGaussian1D(
236  0, STD_NOISE_NODE_XYZ),
237  getRandomGenerator().drawGaussian1D(
238  0, STD_NOISE_NODE_XYZ),
239  getRandomGenerator().drawGaussian1D(
240  0, STD_NOISE_NODE_ANG),
241  getRandomGenerator().drawGaussian1D(
242  0, STD_NOISE_NODE_ANG),
243  getRandomGenerator().drawGaussian1D(
244  0, STD_NOISE_NODE_ANG)));
245 
246  // This is the initial input graph (make a copy for later use):
247  const my_graph_t graph_initial = graph;
248  // graph_GT.saveToTextFile("test_GT.graph");
249  // graph_initial.saveToTextFile("test.graph");
250 
251  // ----------------------------
252  // Run graph slam:
253  // ----------------------------
255  // params["verbose"] = 1;
256  params["profiler"] = 1;
257  params["max_iterations"] = 500;
258  params["scale_hessian"] = 0.1; // If <1, will "exagerate" the scale of
259  // the gradient and, normally, will
260  // converge much faster.
261  params["tau"] = 1e-3;
262 
263  // e2: Lev-marq algorithm iteration stopping criterion #2: |delta_incr|
264  // < e2*(x_norm+e2)
265  // params["e1"] = 1e-6;
266  // params["e2"] = 1e-6;
267 
269  log_sq_err_evolution.clear();
270 
271  cout << "Global graph RMS error / edge = "
272  << std::sqrt(graph.getGlobalSquareError(false) / graph.edgeCount())
273  << endl;
274  cout << "Global graph RMS error / edge = "
275  << std::sqrt(graph.getGlobalSquareError(true) / graph.edgeCount())
276  << " (ignoring information matrices)." << endl;
277 
278  // Do the optimization
280  graph, levmarq_info,
281  nullptr, // List of nodes to optimize. nullptr -> all but the root
282  // node.
283  params, &my_levmarq_feedback<my_graph_t>);
284 
285  cout << "Global graph RMS error / edge = "
286  << std::sqrt(graph.getGlobalSquareError(false) / graph.edgeCount())
287  << endl;
288  cout << "Global graph RMS error / edge = "
289  << std::sqrt(graph.getGlobalSquareError(true) / graph.edgeCount())
290  << " (ignoring information matrices)." << endl;
291 
292  // ----------------------------
293  // Display results:
294  // ----------------------------
295  CDisplayWindow3D win("graph-slam demo results");
296  CDisplayWindow3D win2("graph-slam demo initial state");
297 
298  // The final optimized graph:
299  TParametersDouble graph_render_params1;
300  graph_render_params1["show_edges"] = 1;
301  graph_render_params1["edge_width"] = 1;
302  graph_render_params1["nodes_corner_scale"] = 1;
303  CSetOfObjects::Ptr gl_graph1 =
305  graph, graph_render_params1);
306 
307  // The initial noisy graph:
308  TParametersDouble graph_render_params2;
309  graph_render_params2["show_ground_grid"] = 0;
310  graph_render_params2["show_edges"] = 0;
311  graph_render_params2["show_node_corners"] = 0;
312  graph_render_params2["nodes_point_size"] = 7;
313 
314  CSetOfObjects::Ptr gl_graph2 =
316  graph_initial, graph_render_params2);
317 
318  graph_render_params2["nodes_point_size"] = 5;
319  CSetOfObjects::Ptr gl_graph5 =
321  graph, graph_render_params2);
322 
323  // The ground truth graph:
324  TParametersDouble graph_render_params3;
325  graph_render_params3["show_ground_grid"] = 0;
326  graph_render_params3["show_ID_labels"] = 1;
327  graph_render_params3["show_edges"] = 1;
328  graph_render_params3["edge_width"] = 3;
329  graph_render_params3["nodes_corner_scale"] = 2;
330  CSetOfObjects::Ptr gl_graph3 =
332  graph_GT, graph_render_params3);
333  CSetOfObjects::Ptr gl_graph4 =
335  graph_initial, graph_render_params3);
336 
337  win.addTextMessage(
338  5, 5, "Ground truth: Big corners & thick edges", TColorf(0, 0, 0),
339  1000 /* arbitrary, unique text label ID */,
341  win.addTextMessage(
342  5, 5 + 15, "Initial graph: Gray thick points.", TColorf(0, 0, 0),
343  1001 /* arbitrary, unique text label ID */,
345  win.addTextMessage(
346  5, 5 + 30, "Final graph: Small corners & thin edges",
347  TColorf(0, 0, 0), 1002 /* arbitrary, unique text label ID */,
349 
350  win2.addTextMessage(
351  5, 5, "Ground truth: Big corners & thick edges", TColorf(0, 0, 0),
352  1000 /* arbitrary, unique text label ID */,
354  win2.addTextMessage(
355  5, 5 + 15, "Initial graph: Small corners & thin edges",
356  TColorf(0, 0, 0), 1001 /* arbitrary, unique text label ID */,
358 
359  {
360  COpenGLScene::Ptr& scene = win.get3DSceneAndLock();
361  scene->insert(gl_graph1);
362  scene->insert(gl_graph3);
363  scene->insert(gl_graph2);
364  scene->insert(gl_graph5);
365  win.unlockAccess3DScene();
366  win.repaint();
367  }
368 
369  {
370  COpenGLScene::Ptr& scene = win2.get3DSceneAndLock();
371  scene->insert(gl_graph3);
372  scene->insert(gl_graph4);
373  win2.unlockAccess3DScene();
374  win2.repaint();
375  }
376 
377  // Show progress of error:
378  CDisplayWindowPlots win_err("Evolution of log(sq. error)");
379  win_err.plot(log_sq_err_evolution, "-b");
380  win_err.axis_fit();
381 
382  // wait end:
383  cout << "Close any window to end...\n";
384  while (win.isOpen() && win2.isOpen() && win_err.isOpen() &&
386  {
387  std::this_thread::sleep_for(10ms);
388  }
389  }
390 };
391 
392 int main()
393 {
394  try
395  {
396  // typedef CNetworkOfPoses<CPose2D,map_traits_map_as_vector> my_graph_t;
397 
398  cout << "Select the type of graph to optimize:\n"
399  "1. CNetworkOfPoses2D \n"
400  "2. CNetworkOfPoses2DInf \n"
401  "3. CNetworkOfPoses3D \n"
402  "4. CNetworkOfPoses3DInf \n";
403 
404  cout << ">> ";
405 
406  int i = 0;
407  {
408  string l;
409  std::getline(cin, l);
410  l = mrpt::system::trim(l);
411  i = atoi(&l[0]);
412  }
413 
414  bool add_extra_tightening_edge;
415  cout << "Add an extra, incompatible tightening edge? [y/N] ";
416  {
417  string l;
418  std::getline(cin, l);
419  l = mrpt::system::trim(l);
420  add_extra_tightening_edge = l[0] == 'Y' || l[0] == 'y';
421  }
422 
423  switch (i)
424  {
425  case 1:
426  {
428  demo.run(add_extra_tightening_edge);
429  }
430  break;
431  case 2:
432  {
434  demo.run(add_extra_tightening_edge);
435  }
436  break;
437  case 3:
438  {
440  demo.run(add_extra_tightening_edge);
441  }
442  break;
443  case 4:
444  {
446  demo.run(add_extra_tightening_edge);
447  }
448  break;
449  };
450 
451  std::this_thread::sleep_for(20ms);
452  return 0;
453  }
454  catch (exception& e)
455  {
456  cout << "MRPT exception caught: " << e.what() << endl;
457  return -1;
458  }
459  catch (...)
460  {
461  printf("Another exception!!");
462  return -1;
463  }
464 }
A namespace of pseudo-random numbers generators of diferent distributions.
Generic struct template Auxiliary class to add a new edge to the graph.
void addEdge(TNodeID from, TNodeID to, const std::map< TNodeID, CPose2D > &real_poses, CNetworkOfPoses2D &graph_links)
void optimize_graph_spa_levmarq(GRAPH_T &graph, TResultInfoSpaLevMarq &out_info, const std::set< mrpt::graphs::TNodeID > *in_nodes_to_optimize=nullptr, const mrpt::system::TParametersDouble &extra_params=mrpt::system::TParametersDouble(), FEEDBACK_CALLABLE functor_feedback=FEEDBACK_CALLABLE())
Optimize a graph of pose constraints using the Sparse Pose Adjustment (SPA) sparse representation and...
Definition: levmarq.h:79
Create a GUI window and display plots with MATLAB-like interfaces and commands.
double DEG2RAD(const double x)
Degrees to radians.
Abstract graph and tree data structures, plus generic graph algorithms.
void randomize(const uint32_t seed)
Initialize the PRNG from the given random seed.
STL namespace.
T square(const T x)
Inline function for the square of a number.
SLAM methods related to graphs of pose constraints.
const double STD_NOISE_NODE_XYZ
This base provides a set of functions for maths stuff.
mrpt::gui::CDisplayWindow3D::Ptr win
Classes for 2D/3D geometry representation, both of single values and probability density distribution...
const double STD4EDGES_COV_MATRIX
const double STD_NOISE_EDGE_ANG
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
void run(bool add_extra_tightening_edge)
A class used to store a 2D pose, including the 2D coordinate point and a heading (phi) angle...
Definition: CPose2D.h:39
const float R
A class used to store a 3D pose (a 3D translation + a rotation in 3D).
Definition: CPose3D.h:84
A RGB color - floats in the range [0,1].
Definition: TColor.h:77
Output information for mrpt::graphslam::optimize_graph_spa_levmarq()
The namespace for 3D scene representation and rendering.
Definition: CGlCanvasBase.h:15
bool kbhit() noexcept
An OS-independent version of kbhit, which returns true if a key has been pushed.
Definition: os.cpp:394
CSetOfObjects::Ptr graph_visualize(const GRAPH_T &g, const mrpt::system::TParametersDouble &extra_params=mrpt::system::TParametersDouble())
Returns an opengl objects representation of an arbitrary graph, as a network of 3D pose frames...
uint64_t TNodeID
A generic numeric type for unique IDs of nodes or entities.
Definition: TNodeID.h:16
std::string trim(const std::string &str)
Removes leading and trailing spaces.
const double STD_NOISE_NODE_ANG
Classes for creating GUI windows for 2D and 3D visualization.
Definition: about_box.h:14
CRandomGenerator & getRandomGenerator()
A static instance of a CRandomGenerator class, for use in single-thread applications.
GLfloat GLfloat p
Definition: glext.h:6398
GLenum const GLfloat * params
Definition: glext.h:3538
const double STD_NOISE_EDGE_XYZ
A graphical user interface (GUI) for efficiently rendering 3D scenes in real-time.
const double ERROR_IN_INCOMPATIBLE_EDGE
vector< double > log_sq_err_evolution



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