Main MRPT website > C++ reference for MRPT 1.9.9
CGraphSlamHandler_impl.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-2017, 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 
10 #ifndef CGRAPHSLAMHANDLER_IMPL_H
11 #define CGRAPHSLAMHANDLER_IMPL_H
12 
13 // Implementation file for CGraphSlamHandler class
14 #include "CGraphSlamHandler.h"
15 
16 template <class GRAPH_T>
18  mrpt::utils::COutputLogger* logger,
20  const bool enable_visuals /*=true*/)
21  : m_logger(logger),
22  m_options_checker(options_checker),
23  m_do_save_results(true),
24  m_has_set_fnames(false),
25  m_enable_visuals(enable_visuals)
26 {
27  using namespace mrpt::system;
30 
31  m_engine = NULL;
32  m_win_manager = NULL;
33  m_win_observer = NULL;
34  m_win = NULL;
35  if (m_enable_visuals)
36  {
37  this->initVisualization();
38  }
39 }
40 
41 //////////////////////////////////////////////////////////////////////////////
42 
43 //////////////////////////////////////////////////////////////////////////////
44 template <class GRAPH_T>
46 {
47  using namespace mrpt::utils;
48 
49  m_logger->logFmt(LVL_WARN, "graphslam-engine has finished.");
50 
51  // keep the window open until user closes it.
52  if (m_win)
53  {
54  m_logger->logFmt(
55  LVL_WARN,
56  "Application will exit when the display window is closed.");
57  bool break_exec = false;
58  while (m_win->isOpen() && break_exec == false)
59  {
60  break_exec = !this->queryObserverForEvents();
61  std::this_thread::sleep_for(100ms);
63  }
64  }
65 
67  {
69  if (m_engine)
70  {
72  }
73  }
74 
75  if (m_engine)
76  {
77  delete m_engine;
78  }
79 
80  if (m_enable_visuals)
81  {
82  if (m_win)
83  {
84  m_logger->logFmt(
85  LVL_DEBUG, "Releasing CDisplayWindow3D instance...");
86  delete m_win;
87  }
88 
89  if (m_win_observer)
90  {
91  m_logger->logFmt(
92  LVL_DEBUG, "Releasing CWindowObserver instance...");
93  delete m_win_observer;
94  }
95 
96  if (m_win_manager)
97  {
98  m_logger->logFmt(LVL_DEBUG, "Releasing CWindowManager instance...");
99  delete m_win_manager;
100  }
101  }
102  m_logger->logFmt(LVL_INFO, "Exited.");
103 }
104 
105 template <class GRAPH_T>
107  const std::string& output_dir_fname /* = graphslam_results */)
108 {
109  MRPT_START;
110  using namespace std;
111  using namespace mrpt::utils;
112  using namespace mrpt::system;
113  using namespace mrpt;
114 
115  m_logger->logFmt(
116  LVL_INFO, "Setting up output directory: %s", output_dir_fname.c_str());
117 
118  // current time vars - handy in the rest of the function.
120  string cur_date_str(timeToString(cur_date));
121  string cur_date_validstr(fileNameStripInvalidChars(cur_date_str));
122 
123  // Determine what to do with existing results if previous output directory
124  // exists
125  if (directoryExists(output_dir_fname))
126  {
127  int answer_int;
129  {
130  stringstream question;
131  string answer;
132 
133  question << "Directory exists. Choose between the "
134  << "following options" << std::endl;
135  question << "\t 1: Rename current folder and start new "
136  << "output directory (default)" << std::endl;
137  question << "\t 2: Remove existing contents and continue execution "
138  << std::endl;
139  question << "\t 3: Handle potential conflict manually "
140  "(Halts program execution)"
141  << std::endl;
142  question << "\t [ 1 | 2 | 3 ] --> ";
143  std::cout << question.str();
144 
145  getline(cin, answer);
146  answer = mrpt::system::trim(answer);
147  answer_int = atoi(&answer[0]);
148  }
149  else
150  {
151  answer_int = 2;
152  }
153 
154  switch (answer_int)
155  {
156  case 2:
157  {
158  m_logger->logFmt(LVL_INFO, "Deleting existing files...");
159  // purge directory
161  output_dir_fname,
162  /*deleteDirectoryAsWell = */ false);
163  break;
164  }
165  case 3:
166  {
167  // I don't need to exit gracefully here..
168  exit(0);
169  }
170  case 1:
171  default:
172  {
173  // rename the whole directory to DATE_TIME_${OUTPUT_DIR_NAME}
174  string dst_fname = output_dir_fname + cur_date_validstr;
175  m_logger->logFmt(
176  LVL_INFO, "Renaming directory to: %s", dst_fname.c_str());
177  string error_msg;
178  bool did_rename =
179  renameFile(output_dir_fname, dst_fname, &error_msg);
180  ASSERTMSG_(
181  did_rename, format(
182  "\nError while trying to rename the output "
183  "directory: %s",
184  error_msg.c_str()));
185  break;
186  }
187  } // SWITCH (ANSWER_INT)
188  } // IF DIRECTORY EXISTS..
189 
190  // Now rebuild the directory from scratch
191  m_logger->logFmt(LVL_INFO, "Creating the new directory structure...");
192  string cur_fname;
193 
194  // debug_fname
195  createDirectory(output_dir_fname);
196  m_logger->logFmt(LVL_INFO, "Finished initializing output directory.");
197 
198  MRPT_END;
199 } // end of initOutputDir
200 
201 //////////////////////////////////////////////////////////////////////////////
202 template <class GRAPH_T>
204  const std::string& ini_fname, const std::string& rawlog_fname,
205  const std::string& ground_truth_fname /*=std::string()*/)
206 {
207  this->m_ini_fname = ini_fname;
208  this->m_rawlog_fname = rawlog_fname;
209  this->m_gt_fname = ground_truth_fname;
210 
212 
213  m_has_set_fnames = true;
214 }
215 
216 ////////////////////////////////////////////////////////////////////////////////
217 
218 template <class GRAPH_T>
220 {
221  using namespace mrpt::utils;
222 
223  ASSERTMSG_(
225  mrpt::format("\nConfiguration file not found: \n%s\n", fname.c_str()));
226 
227  m_logger->logFmt(LVL_INFO, "Reading the .ini file... ");
228 
229  CConfigFile cfg_file(fname);
230 
232  "GeneralConfiguration", "user_decides_about_output_dir", false, false);
233  m_output_dir_fname = cfg_file.read_string(
234  "GeneralConfiguration", "output_dir_fname", "graphslam_results", false);
235  m_save_graph =
236  cfg_file.read_bool("GeneralConfiguration", "save_graph", true, false);
238  cfg_file.read_bool("GeneralConfiguration", "save_3DScene", true, false);
239  m_save_map =
240  cfg_file.read_bool("GeneralConfiguration", "save_map", true, false);
241  m_save_graph_fname = cfg_file.read_string(
242  "GeneralConfiguration", "save_graph_fname", "output_graph.graph",
243  false);
245  "GeneralConfiguration", "save_3DScene_fname", "scene.3DScene", false);
246  m_save_map_fname = cfg_file.read_string(
247  "GeneralConfiguration", "save_map_fname", "output_map", false);
248 }
249 
250 template <class GRAPH_T>
252  const std::string& node_reg_str, const std::string& edge_reg_str,
253  const std::string& optimizer_str)
254 {
255  using namespace mrpt;
256 
258 
259  ASSERTMSG_(
260  m_options_checker->checkRegistrationDeciderExists(node_reg_str, "node"),
261  format(
262  "\nNode Registration Decider %s is not available.\n",
263  node_reg_str.c_str()));
264  ASSERTMSG_(
265  m_options_checker->checkRegistrationDeciderExists(edge_reg_str, "edge"),
266  format(
267  "\nEdge Registration Decider %s is not available.\n",
268  edge_reg_str.c_str()));
269  ASSERTMSG_(
270  m_options_checker->checkOptimizerExists(optimizer_str),
271  format("\nOptimizer %s is not available\n", optimizer_str.c_str()));
272 
275  m_options_checker->node_regs_map[node_reg_str](),
276  m_options_checker->edge_regs_map[edge_reg_str](),
277  m_options_checker->optimizers_map[optimizer_str]());
278 }
279 
280 //////////////////////////////////////////////////////////////////////////////
281 
282 template <class GRAPH_T>
284 {
285  std::cout << this->getParamsAsString() << std::endl;
286  m_engine->printParams();
287 }
288 
289 //////////////////////////////////////////////////////////////////////////////
290 template <class GRAPH_T>
292 {
293  using namespace std;
294 
295  ASSERT_(str);
296 
297  stringstream ss_out("");
298 
299  ss_out << "\n------------[ graphslam-engine_app Parameters ]------------"
300  << std::endl;
301 
302  // general configuration parameters
303  ss_out << "User decides about output dir? = "
304  << (m_user_decides_about_output_dir ? "TRUE" : "FALSE") << std::endl;
305  ss_out << "Output directory = " << m_output_dir_fname
306  << std::endl;
307  ss_out << "Generate .graph file? = "
308  << (m_save_graph ? "TRUE" : "FALSE") << std::endl;
309  ss_out << "Generate .3DScene file? = "
310  << (m_save_3DScene ? "TRUE" : "FALSE") << std::endl;
311  if (m_save_graph)
312  {
313  ss_out << "Generated .graph filename = " << m_save_graph_fname
314  << std::endl;
315  }
316  if (m_save_3DScene)
317  {
318  ss_out << "Generated .3DScene filename = " << m_save_3DScene_fname
319  << std::endl;
320  }
321  ss_out << "Rawlog filename = " << m_rawlog_fname
322  << std::endl;
323 
324  *str = ss_out.str();
325 }
326 //////////////////////////////////////////////////////////////////////////////
327 template <class GRAPH_T>
329 {
330  std::string str;
331  this->getParamsAsString(&str);
332  return str;
333 }
334 
335 //////////////////////////////////////////////////////////////////////////////
336 
337 template <class GRAPH_T>
339 {
340  using namespace mrpt::utils;
341 
343  m_logger->logFmt(
344  LVL_WARN, "Overriding .ini Results directory -> %s...",
345  m_output_dir_fname.c_str());
346 }
347 
348 template <class GRAPH_T>
350  const std::string& output_dir_fname)
351 {
352  using namespace mrpt::utils;
353  ASSERT_(m_engine);
354 
355  m_logger->logFmt(LVL_INFO, "Generating overall report...");
356  m_engine->generateReportFiles(output_dir_fname);
357  // save the graph and the 3DScene
358  if (m_save_graph)
359  {
360  std::string save_graph_fname =
361  output_dir_fname + "/" + m_save_graph_fname;
362  m_engine->saveGraph(&save_graph_fname);
363  }
365  {
366  std::string save_3DScene_fname =
367  output_dir_fname + "/" + m_save_3DScene_fname;
368  m_engine->save3DScene(&save_3DScene_fname);
369  }
370 
371  // get the occupancy map that was built
372  if (m_save_map)
373  {
374  this->saveMap(output_dir_fname + "/" + m_save_map_fname);
375  }
376 
377  m_logger->logFmt(LVL_INFO, "Generated report.");
378 }
379 
380 template <class GRAPH_T>
382 {
384  mrpt::make_aligned_shared<mrpt::maps::COccupancyGridMap2D>();
385  m_engine->getMap(map);
386  // map->saveAsBitmapFile(fname); // doesn't work.
387  map->saveMetricMapRepresentationToFile(fname);
388 }
389 
390 template <class GRAPH_T>
392 {
393  using namespace mrpt::obs;
394  using namespace mrpt::utils;
395  ASSERT_(m_engine);
396 
397  // Variables initialization
398  CFileGZInputStream rawlog_stream(m_rawlog_fname);
399  CActionCollection::Ptr action;
400  CSensoryFrame::Ptr observations;
401  CObservation::Ptr observation;
402  size_t curr_rawlog_entry;
403 
404  // Read the dataset and pass the measurements to CGraphSlamEngine
405  bool cont_exec = true;
406  while (CRawlog::getActionObservationPairOrObservation(
407  rawlog_stream, action, observations, observation,
408  curr_rawlog_entry) &&
409  cont_exec)
410  {
411  // actual call to the graphSLAM execution method
412  // Exit if user pressed C-c
413  cont_exec = m_engine->_execGraphSlamStep(
414  action, observations, observation, curr_rawlog_entry);
415  }
416  m_logger->logFmt(LVL_WARN, "Finished graphslam execution.");
417 }
418 
419 //////////////////////////////////////////////////////////////////////////////
420 template <class GRAPH_T>
422 {
423  using namespace mrpt::opengl;
424  using namespace mrpt::gui;
425  using namespace mrpt::utils;
426  using namespace mrpt::graphslam;
427 
429  m_win = new CDisplayWindow3D("GraphSlam building procedure", 800, 600);
430  m_win->setPos(400, 200);
432  {
434  COpenGLViewport::Ptr main_view = scene->getViewport("main");
435  m_win_observer->observeBegin(*main_view);
437  }
438 
439  m_logger->logFmt(LVL_DEBUG, "Initialized CDisplayWindow3D...");
440  m_logger->logFmt(LVL_DEBUG, "Listening to CDisplayWindow3D events...");
441 
442  // pass the window and the observer pointers to the CWindowManager instance
446 }
447 
448 //////////////////////////////////////////////////////////////////////////////
449 template <class GRAPH_T>
451 {
452  std::map<std::string, bool> events_occurred;
454  &events_occurred,
455  /* reset_keypresses = */ false);
456  bool request_to_exit = events_occurred.find("Ctrl+c")->second;
457 
458  return !request_to_exit;
459 }
460 
461 #endif /* end of include guard: CGRAPHSLAMHANDLER_IMPL_H */
void setResultsDirName(const std::string &dirname)
Override the results directory filename that was initially set in the .ini file.
uint64_t TTimeStamp
A system independent time type, it holds the the number of 100-nanosecond intervals since January 1...
Definition: datetime.h:32
void setCDisplayWindow3DPtr(mrpt::gui::CDisplayWindow3D *win_in)
Store the CDisplayWindow3D pointer in the CWindowManager instance.
void readConfigFname(const std::string &fname)
Read configuration variables for the current graphSLAM execution from a .ini file.
virtual bool checkRegistrationDeciderExists(std::string given_reg, std::string reg_type) const
Check if the given registrator decider exists in the vector of deciders.
void unlockAccess3DScene()
Unlocks the access to the internal 3D scene.
void printParams() const
Print in a formatted manner the general configuraiton variables for the current graphSLAM execution...
bool createDirectory(const std::string &dirName)
Creates a directory.
Definition: filesystem.cpp:158
bool read_bool(const std::string &section, const std::string &name, bool defaultValue, bool failIfNotFound=false) const
Classes for serialization, sockets, ini-file manipulation, streams, list of properties-values, timewatch, extensions to STL.
std::shared_ptr< COpenGLViewport > Ptr
std::string m_rawlog_fname
std::string m_save_graph_fname
This namespace provides a OS-independent interface to many useful functions: filenames manipulation...
Definition: math_frwds.h:30
mrpt::opengl::COpenGLScene::Ptr & get3DSceneAndLock()
Gets a reference to the smart shared pointer that holds the internal scene (carefuly read introductio...
mrpt::system::TTimeStamp getCurrentTime()
Returns the current (UTC) system time.
Definition: datetime.cpp:73
void setWindowObserverPtr(mrpt::graphslam::CWindowObserver *obsever_in)
Store the CWindowObserver pointer in the CWindowManager instance.
void saveResults(const std::string &output_dir_fname)
This class allows loading and storing values and vectors of different types from ".ini" files easily.
Definition: CConfigFile.h:35
bool queryObserverForEvents()
Query the CWindowObserver instance for any pressed keys that might be of interest (e...
std::string m_output_dir_fname
bool fileExists(const std::string &fileName)
Test if a given file (or directory) exists.
Definition: filesystem.cpp:127
bool renameFile(const std::string &oldFileName, const std::string &newFileName, std::string *error_msg=nullptr)
Renames a file - If the target path is different and the filesystem allows it, it will be moved to th...
Definition: filesystem.cpp:307
std::string read_string(const std::string &section, const std::string &name, const std::string &defaultValue, bool failIfNotFound=false) const
void returnEventsStruct(std::map< std::string, bool > *codes_to_pressed, bool reset_keypresses=true)
Return a map of key code to a boolean indicating whether it was pressed since the previous time the c...
std::string timeToString(const mrpt::system::TTimeStamp t)
Convert a timestamp into this textual form (UTC): HH:MM:SS.MMMMMM.
Definition: datetime.cpp:337
STL namespace.
std::string fileNameStripInvalidChars(const std::string &filename, const char replacement_to_invalid_chars='_')
Replace invalid filename chars by underscores (&#39;_&#39;) or any other user-given char. ...
Definition: filesystem.cpp:327
std::string m_save_map_fname
std::shared_ptr< COccupancyGridMap2D > Ptr
std::string getParamsAsString() const
void initVisualization()
Initialize visualization (e.g.
SLAM methods related to graphs of pose constraints.
CGraphSlamHandler(mrpt::utils::COutputLogger *logger, mrpt::graphslam::apps::TUserOptionsChecker< GRAPH_T > *options_checker, const bool enable_visuals)
Constructor.
#define MRPT_END
void setPos(int x, int y) override
Changes the position of the window on the screen.
Transparently opens a compressed "gz" file and reads uncompressed data from it.
bool isOpen()
Returns false if the user has already closed the window.
void observeBegin(CObservable &obj)
Starts the subscription of this observer to the given object.
Definition: CObserver.cpp:26
Main file for the GraphSlamEngine.
This namespace contains representation of robot actions and observations.
std::string format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
Definition: format.cpp:19
std::shared_ptr< CSensoryFrame > Ptr
Definition: CSensoryFrame.h:56
void saveMap(const std::string &fname)
std::shared_ptr< CObservation > Ptr
Definition: CObservation.h:43
GLsizei const GLchar ** string
Definition: glext.h:4101
mrpt::graphslam::CWindowManager * m_win_manager
void forceRepaint()
Repaints the window.
#define MRPT_START
void execute()
Method to be called for parsing the rawlog file provided and for running graphSLAM using that informa...
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
mrpt::gui::CDisplayWindow3D * m_win
std::shared_ptr< CActionCollection > Ptr
mrpt::utils::COutputLogger * m_logger
Monitor events in the visualization window.
void setFNames(const std::string &ini_fname, const std::string &rawlog_fname, const std::string &ground_truth_fname=std::string())
Set the relevant filenames for instantiating CGraphSlamEngine instance.
std::shared_ptr< COpenGLScene > Ptr
Definition: COpenGLScene.h:62
The namespace for 3D scene representation and rendering.
Definition: CGlCanvasBase.h:15
#define ASSERT_(f)
bool deleteFilesInDirectory(const std::string &s, bool deleteDirectoryAsWell=false)
Delete all the files in a given directory (nothing done if directory does not exists, or path is a file).
Definition: filesystem.cpp:214
std::string trim(const std::string &str)
Removes leading and trailing spaces.
GLenum GLsizei GLenum format
Definition: glext.h:3531
Classes for creating GUI windows for 2D and 3D visualization.
Definition: about_box.h:16
virtual bool checkOptimizerExists(std::string given_opt) const
Check if the given optimizer exists in the vector of optimizers.
bool directoryExists(const std::string &fileName)
Test if a given directory exists (it fails if the given path refers to an existing file)...
Definition: filesystem.cpp:136
void initEngine(const std::string &node_reg_str, const std::string &edge_reg_str, const std::string &optimizer_str)
std::string m_save_3DScene_fname
mrpt::graphslam::CGraphSlamEngine< GRAPH_T > * m_engine
Pointer to the engine instance.
void initOutputDir(const std::string &output_dir_fname="graphslam_results")
Initialize (clean up and create new files) the output directory.
#define ASSERTMSG_(f, __ERROR_MSG)
mrpt::graphslam::CWindowObserver * m_win_observer
~CGraphSlamHandler()
Destructor.
Class acts as a container for storing pointers to mrpt::gui::CDisplayWindow3D, mrpt::graphslam::CWind...
A graphical user interface (GUI) for efficiently rendering 3D scenes in real-time.
mrpt::graphslam::apps::TUserOptionsChecker< GRAPH_T > * m_options_checker
TUserOptionsChecker instance whose task is to evaluate the Registration Decider, Optimizer instances ...



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: ae4571287 Thu Nov 23 00:06:53 2017 +0100 at dom oct 27 23:51:55 CET 2019