10 #ifndef CLEVMARQGSO_IMPL_H 11 #define CLEVMARQGSO_IMPL_H 13 namespace mrpt {
namespace graphslam {
namespace optimizers {
18 template<
class GRAPH_T>
20 m_first_time_call(false),
21 m_has_read_config(false),
22 m_autozoom_active(true),
23 m_last_total_num_of_nodes(5),
24 m_optimization_policy(FOP_USE_LC),
25 m_curr_used_consec_lcs(0),
26 m_curr_ignored_consec_lcs(0),
27 m_just_fully_optimized_graph(false),
28 m_min_nodes_for_optimization(3)
36 template<
class GRAPH_T>
43 template<
class GRAPH_T>
45 mrpt::obs::CActionCollectionPtr action,
46 mrpt::obs::CSensoryFramePtr observations,
47 mrpt::obs::CObservationPtr observation ) {
50 this->logFmt(LVL_DEBUG,
"In updateOptimizerState... ");
83 template<
class GRAPH_T>
95 template<
class GRAPH_T>
109 template<
class GRAPH_T>
111 const std::map<std::string, bool>& events_occurred) {
120 if (events_occurred.find(
137 if (events_occurred.find(
"mouse_clicked")->second) {
152 template<
class GRAPH_T>
160 "Toggle Graph visualization");
163 "Fit Graph in view");
172 template<
class GRAPH_T>
179 this->logFmt(mrpt::utils::LVL_DEBUG,
"In the updateGraphVisualization function");
186 CRenderizablePtr prev_object = scene->getByName(
"optimized_graph");
187 bool prev_visibility =
true;
189 prev_visibility = prev_object->isVisible();
191 scene->removeObject(prev_object);
195 CSetOfObjectsPtr graph_obj = CSetOfObjects::Create();
198 graph_obj->setName(
"optimized_graph");
199 graph_obj->setVisibility(prev_visibility);
200 scene->insert(graph_obj);
204 format(
"Optimized Graph: #nodes %d",
205 static_cast<int>(this->
m_graph->nodeCount())),
218 template<
class GRAPH_T>
225 CRenderizablePtr graph_obj = scene->getByName(
"optimized_graph");
226 graph_obj->setVisibility(!graph_obj->isVisible());
234 template<
class GRAPH_T>
240 "\nVisualization of data was requested but no CDisplayWindow3D pointer was given\n");
244 CRenderizablePtr
obj = scene->getByName(
"optimized_graph");
245 CSetOfObjectsPtr graph_obj =
static_cast<CSetOfObjectsPtr
>(
obj);
250 CGridPlaneXYPtr obj_grid =
253 float x_min,x_max, y_min,y_max;
255 const float z_min = obj_grid->getPlaneZcoord();
257 0.5*(x_min+x_max), 0.5*(y_min+y_max), z_min);
259 2.0f * std::max(10.0f, std::max(x_max-x_min, y_max-y_min)));
268 template<
class GRAPH_T>
276 "Toggle optimization distance on/off");
280 "Manually trigger a full graph optimization");
286 obj->setPose(initial_pose);
287 obj->setName(
"optimization_distance_obj");
301 format(
"Radius for graph optimization"),
307 template<
class GRAPH_T>
313 CDiskPtr
obj = CDisk::Create();
321 template<
class GRAPH_T>
327 CSpherePtr
obj = CSphere::Create();
338 template<
class GRAPH_T>
347 CRenderizablePtr
obj = scene->getByName(
"optimization_distance_obj");
348 obj->setPose(this->
m_graph->nodes.rbegin()->second);
356 template<
class GRAPH_T>
363 CRenderizablePtr
obj = scene->getByName(
"optimization_distance_obj");
364 obj->setVisibility(!
obj->isVisible());
374 template<
class GRAPH_T>
378 this->logFmt(mrpt::utils::LVL_DEBUG,
379 "In optimizeGraph\n\tThreadID: %lu\n\tTrying to grab lock... ",
385 this->logFmt(mrpt::utils::LVL_DEBUG,
"2nd thread grabbed the lock..");
390 template<
class GRAPH_T>
403 optimization_timer.
Tic();
406 std::set< mrpt::utils::TNodeID>* nodes_to_optimize;
410 if (is_full_update) {
413 nodes_to_optimize = NULL;
416 nodes_to_optimize =
new std::set<mrpt::utils::TNodeID>;
424 nodes_to_optimize->insert(this->
m_graph->nodeCount()-1);
437 if (is_full_update) {
445 double elapsed_time = optimization_timer.
Tac();
446 this->logFmt(mrpt::utils::LVL_DEBUG,
447 "Optimization of graph took: %fs", elapsed_time);
450 delete nodes_to_optimize;
451 nodes_to_optimize = NULL;
458 template<
class GRAPH_T>
462 bool is_loop_closure =
false;
463 typename GRAPH_T::edges_map_t curr_pair_nodes_to_edge = this->
m_graph->edges;
472 curr_pair_nodes_to_edge.begin(); it != curr_pair_nodes_to_edge.end();
477 curr_pair = it->first;
480 static_cast<int>(curr_pair.first) -
481 static_cast<int>(curr_pair.second) ) >
484 this->logFmt(mrpt::utils::LVL_DEBUG,
"Registering loop closure... ");
485 is_loop_closure =
true;
493 return is_loop_closure;
498 template<
class GRAPH_T>
500 bool is_full_update =
false;
518 return is_full_update;
522 bool use_limit_reached =
525 bool ignore_limit_reached =
529 if (ignore_limit_reached || use_limit_reached) {
534 if (ignore_limit_reached) {
537 if (use_limit_reached) {
553 is_full_update =
false;
555 "*PARTIAL* graph optimization.. ignoring new loop closure");
558 is_full_update =
true;
561 return is_full_update;
565 template<
class GRAPH_T>
571 template<
class GRAPH_T>
573 const GRAPH_T &graph,
575 const size_t max_iter,
576 const double cur_sq_error )
579 template<
class GRAPH_T>
581 std::set<mrpt::utils::TNodeID> *nodes_set,
589 nodeID < this->
m_graph->nodeCount()-1;
591 double curr_distance = this->
m_graph->nodes[nodeID].distanceTo(
592 this->
m_graph->nodes[cur_nodeID]);
594 nodes_set->insert(nodeID);
599 this->
m_graph->getAllNodes(*nodes_set);
605 template<
class GRAPH_T>
612 template<
class GRAPH_T>
625 "OptimizerParameters",
626 "max_used_consecutive_loop_closures",
630 "OptimizerParameters",
631 "max_ignored_consecutive_loop_closures",
636 int min_verbosity_level =
source.read_int(
637 "OptimizerParameters",
640 this->setMinLoggingLevel(VerbosityLevel(min_verbosity_level));
642 this->logFmt(mrpt::utils::LVL_DEBUG,
"Successfully loaded Params. ");
648 template<
class GRAPH_T>
657 stringstream class_props_ss;
658 class_props_ss <<
"Levenberg Marquardt Optimization Summary: " << std::endl;
663 const std::string output_res = this->getLogAsString();
669 *report_str += class_props_ss.str();
672 *report_str += time_res;
675 *report_str += output_res;
684 template<
class GRAPH_T>
686 optimization_distance_color(0, 201, 87),
687 keystroke_optimization_distance(
"u"),
688 keystroke_optimize_graph(
"w")
690 template<
class GRAPH_T>
693 template<
class GRAPH_T>
698 out.
printf(
"------------------[ Levenberg-Marquardt Optimization ]------------------\n");
699 out.
printf(
"Optimization on second thread = %s\n",
700 optimization_on_second_thread ?
"TRUE" :
"FALSE");
701 out.
printf(
"Optimize nodes in distance = %.2f\n", optimization_distance);
702 out.
printf(
"Min. node difference for LC = %d\n", LC_min_nodeid_diff);
704 out.
printf(
"%s", cfg.getAsString().c_str());
705 std::cout << std::endl;
709 template<
class GRAPH_T>
714 optimization_on_second_thread =
source.read_bool(
716 "optimization_on_second_thread",
718 LC_min_nodeid_diff =
source.read_int(
719 "GeneralConfiguration",
720 "LC_min_nodeid_diff",
722 optimization_distance =
source.read_double(
724 "optimization_distance",
728 optimization_distance > 0,
729 format(
"Invalid value for optimization distance: %.2f",
730 optimization_distance) );
733 cfg[
"verbose"] =
source.read_bool(
737 cfg[
"profiler"] =
source.read_bool(
741 cfg[
"max_iterations"] =
source.read_double(
745 cfg[
"scale_hessian"] =
source.read_double(
749 cfg[
"tau"] =
source.read_double(
759 template<
class GRAPH_T>
761 keystroke_graph_toggle(
"s"),
762 keystroke_graph_autofit(
"a")
765 template<
class GRAPH_T>
768 template<
class GRAPH_T>
773 out.
printf(
"-----------[ Graph Visualization Parameters ]-----------\n");
774 out.
printf(
"Visualize optimized graph = %s\n",
775 visualize_optimized_graph ?
"TRUE" :
"FALSE");
777 out.
printf(
"%s", cfg.getAsString().c_str());
779 std::cout << std::endl;
783 template<
class GRAPH_T>
788 using namespace utils;
790 visualize_optimized_graph =
source.read_bool(
792 "visualize_optimized_graph",
795 cfg[
"show_ID_labels"] =
source.read_bool(
797 "optimized_show_ID_labels",
799 cfg[
"show_ground_grid"] =
source.read_double(
801 "optimized_show_ground_grid",
803 cfg[
"show_edges"] =
source.read_bool(
805 "optimized_show_edges",
807 cfg[
"edge_color"] =
source.read_int(
809 "optimized_edge_color",
811 cfg[
"edge_width"] =
source.read_double(
813 "optimized_edge_width",
815 cfg[
"show_node_corners"] =
source.read_bool(
817 "optimized_show_node_corners",
819 cfg[
"show_edge_rel_poses"] =
source.read_bool(
821 "optimized_show_edge_rel_poses",
823 cfg[
"edge_rel_poses_color"] =
source.read_int(
825 "optimized_edge_rel_poses_color",
827 cfg[
"nodes_edges_corner_scale"] =
source.read_double(
829 "optimized_nodes_edges_corner_scale",
831 cfg[
"nodes_corner_scale"] =
source.read_double(
833 "optimized_nodes_corner_scale",
835 cfg[
"nodes_point_size"] =
source.read_int(
837 "optimized_nodes_point_size",
839 cfg[
"nodes_point_color"] =
source.read_int(
841 "optimized_nodes_point_color",
void optimize_graph_spa_levmarq(GRAPH_T &graph, TResultInfoSpaLevMarq &out_info, const std::set< mrpt::utils::TNodeID > *in_nodes_to_optimize=NULL, const mrpt::utils::TParametersDouble &extra_params=mrpt::utils::TParametersDouble(), typename graphslam_traits< GRAPH_T >::TFunctorFeedback functor_feedback=NULL)
Optimize a graph of pose constraints using the Sparse Pose Adjustment (SPA) sparse representation and...
void initGraphVisualization()
Initialize objects relateed to the Graph Visualization.
virtual void notifyOfWindowEvents(const std::map< std::string, bool > &events_occurred)
Get a list of the window events that happened since the last call.
void unlockAccess3DScene()
Unlocks the access to the internal 3D scene.
A class acquiring a CCriticalSection at its constructor, and releasing it at destructor.
static void levMarqFeedback(const GRAPH_T &graph, const size_t iter, const size_t max_iter, const double cur_sq_error)
Feedback of the Levenberg-Marquardt graph optimization procedure.
std::string keystroke_graph_autofit
Classes for serialization, sockets, ini-file manipulation, streams, list of properties-values, timewatch, extensions to STL.
bool checkForFullOptimization()
Decide whether to issue a full graph optimization.
void loadFromConfigFile(const mrpt::utils::CConfigFileBase &source, const std::string §ion)
This method load the options from a ".ini"-like file or memory-stored string list.
GraphVisualizationParams()
mrpt::gui::CDisplayWindow3D * m_win
Window to use.
unsigned long BASE_IMPEXP getCurrentThreadId() MRPT_NO_THROWS
Returns the ID of the current thread.
A grid of lines over the XY plane.
virtual void loadParams(const std::string &source_fname)
Load the necessary for the decider/optimizer configuration parameters.
void updateGraphVisualization()
Called internally for updating the visualization scene for the graph building procedure.
void toggleGraphVisualization()
Toggle the graph visualization on and off.
void optimizeGraph()
Wrapper around _optimizeGraph which first locks the section and then calls the _optimizeGraph method...
virtual void printParams() const
Print the problem parameters - relevant to the decider/optimizer to the screen in a unified/compact w...
mrpt::synch::CCriticalSection * m_graph_section
This class allows loading and storing values and vectors of different types from ".ini" files easily.
void setCameraPointingToPoint(float x, float y, float z)
Changes the camera parameters programmatically.
static const std::string header_sep
Separator string to be used in debugging messages.
bool m_just_fully_optimized_graph
Indicates whether a full graph optimization was just issued.
mrpt::graphslam::CWindowObserver * m_win_observer
CWindowObserver object for monitoring various visual-oriented events.
mrpt::utils::TParametersDouble cfg
bool justFullyOptimizedGraph() const
Used by the caller to query for possible full graph optimization on the latest optimizer run...
const Scalar * const_iterator
void setCameraProjective(bool isProjective)
Sets the camera as projective, or orthogonal.
void registerKeystroke(const std::string key_str, const std::string key_desc)
Make new keystrokes available in the help message box.
void addTextMessage(const double x, const double y, const std::string &text, const mrpt::utils::TColorf &color=mrpt::utils::TColorf(1.0, 1.0, 1.0), const size_t unique_index=0)
Wrapper around the CDisplayWindow3D::addTextMessage method, so that the user does not have to specify...
std::string keystroke_optimize_graph
Keystroke to manually trigger a full graph optimization.
void Tic()
Starts the stopwatch.
GLsizei GLsizei GLuint * obj
~GraphVisualizationParams()
mrpt::utils::TColor optimization_distance_color
double optimization_distance
optimize only for the nodes found in a certain distance from the current position.
void getNearbyNodesOf(std::set< mrpt::utils::TNodeID > *nodes_set, const mrpt::utils::TNodeID &cur_nodeID, double distance)
Get a list of the nodeIDs whose position is within a certain distance to the specified nodeID...
void printParams() const
Print the problem parameters - relevant to the decider/optimizer to the screen in a unified/compact w...
void toggleOptDistanceVisualization()
toggle the optimization distance object on and off
This class allows loading and storing values and vectors of different types from a configuration text...
OptimizationParams opt_params
Parameters relevant to the optimizatio nfo the graph.
void dumpToTextStream(mrpt::utils::CStream &out) const
This method should clearly display all the contents of the structure in textual form, sending it to a CStream.
mrpt::graphslam::CWindowManager * m_win_manager
Pointer to the CWindowManager object used to store visuals-related instances.
void initOptDistanceVisualization()
Initialize the Disk/Sphere used for visualizing the optimization distance.
mrpt::opengl::COpenGLScenePtr & get3DSceneAndLock()
Gets a reference to the smart shared pointer that holds the internal scene (carefuly read introductio...
This base class is used to provide a unified interface to files,memory buffers,..Please see the deriv...
void loadFromConfigFileName(const std::string &config_file, const std::string §ion)
Behaves like loadFromConfigFile, but you can pass directly a file name and a temporary CConfigFile ob...
GRAPH_T::edges_map_t last_pair_nodes_to_edge
uint64_t TNodeID
The type for node IDs in graphs of different types.
virtual void initializeVisuals()
Initialize visual objects in CDisplayWindow (e.g.
void initializeVisuals()
Initialize visual objects in CDisplayWindow (e.g.
#define MRPT_UNUSED_PARAM(a)
Can be used to avoid "not used parameters" warnings from the compiler.
void loadParams(const std::string &source_fname)
Load the necessary for the decider/optimizer configuration parameters.
static const std::string report_sep
std::string getStatsAsText(const size_t column_width=80) const
Dump all stats to a multi-line text string.
This class implements a high-performance stopwatch.
FullOptimizationPolicy m_optimization_policy
Should I fully optimize the graph on loop closure?
size_t m_min_nodes_for_optimization
Minimum number of nodes before we try optimizing the graph.
std::string BASE_IMPEXP format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
bool optimization_on_second_thread
std::pair< TNodeID, TNodeID > TPairNodeIDs
A pair of node IDs.
int text_index_optimization_distance
void notifyOfWindowEvents(const std::map< std::string, bool > &events_occurred)
Get a list of the window events that happened since the last call.
size_t m_max_ignored_consec_lcs
Number of consecutive loop closures to ignore after m_max_used_consec_lcs have already been issued...
void dumpToTextStream(mrpt::utils::CStream &out) const
This method should clearly display all the contents of the structure in textual form, sending it to a CStream.
#define MRPT_LOG_WARN_STREAM(__CONTENTS)
virtual void getDescriptiveReport(std::string *report_str) const
Fill the provided string with a detailed report of the decider/optimizer state.
virtual void initializeLoggers(const std::string &name)
Initialize the COutputLogger, CTimeLogger instances given the name of the decider/optimizer at hand...
size_t m_last_total_num_of_nodes
GRAPH_T * m_graph
Pointer to the graph that is under construction.
mrpt::utils::TParametersDouble cfg
GLsizei const GLchar ** string
bool visualize_optimized_graph
GRAPH_T::constraint_t::type_value pose_t
bool updateState(mrpt::obs::CActionCollectionPtr action, mrpt::obs::CSensoryFramePtr observations, mrpt::obs::CObservationPtr observation)
Generic method for fetching the incremental action/observation readings from the calling function...
bool checkForLoopClosures()
Check if a loop closure edge was added in the graph.
mrpt::opengl::CRenderizablePtr initOptDistanceVisualizationInternal(const mrpt::poses::CPose2D &p_unused)
Setup the corresponding Disk/Sphere instance.
TThreadHandle createThreadFromObjectMethod(CLASS *obj, void(CLASS::*func)(PARAM), PARAM param)
Creates a new thread running a non-static method (so it will have access to "this") from another meth...
size_t m_curr_ignored_consec_lcs
Consecutive Loop Closures that have currently been ignored.
std::string keystroke_optimization_distance
Keystroke to toggle the optimization distance on/off.
void forceRepaint()
Repaints the window. forceRepaint, repaint and updateWindow are all aliases of the same method...
std::string keystroke_graph_toggle
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
void updateOptDistanceVisualization()
Update the position of the disk indicating the distance in which Levenberg-Marquardt graph optimizati...
mrpt::utils::CTimeLogger m_time_logger
Time logger instance.
A class used to store a 2D pose, including the 2D coordinate point and a heading (phi) angle...
A class used to store a 3D pose (a 3D translation + a rotation in 3D).
void loadFromConfigFile(const mrpt::utils::CConfigFileBase &source, const std::string §ion)
This method load the options from a ".ini"-like file or memory-stored string list.
virtual void updateVisuals()
Update the relevant visual features in CDisplayWindow.
size_t m_max_used_consec_lcs
Number of maximum cosecutive loop closures that are allowed to be issued.
Output information for mrpt::graphslam::optimize_graph_spa_levmarq()
mrpt::system::TThreadHandle m_thread_optimize
void setCameraZoom(float zoom)
Changes the camera parameters programmatically.
The namespace for 3D scene representation and rendering.
double Tac()
Stops the stopwatch.
GLsizei GLsizei GLchar * source
A RGB color - floats in the range [0,1].
double leave(const char *func_name)
End of a named section.
void dumpToConsole() const
Just like dumpToTextStream() but sending the text to the console (std::cout)
GraphVisualizationParams viz_params
Parameters relevant to the visualization of the graph.
double offset_y_optimization_distance
GLenum GLsizei GLenum format
size_t m_curr_used_consec_lcs
Number of consecutive loop closures that are currently registered.
Levenberg-Marquardt non-linear graph slam optimization scheme.
void enter(const char *func_name)
Start of a named section.
#define MRPT_LOG_DEBUG_STREAM(__CONTENTS)
#define ASSERTMSG_(f, __ERROR_MSG)
void getPlaneLimits(float &xmin, float &xmax, float &ymin, float &ymax) const
void fitGraphInView()
Set the camera parameters of the CDisplayWindow3D so that the whole graph is viewed in the window...
void getDescriptiveReport(std::string *report_str) const
Fill the provided string with a detailed report of the decider/optimizer state.
double BASE_IMPEXP distance(const TPoint2D &p1, const TPoint2D &p2)
Gets the distance between two points in a 2D space.
void updateVisuals()
Update the relevant visual features in CDisplayWindow.
void setCameraAzimuthDeg(float deg)
Changes the camera parameters programmatically.
virtual int printf(const char *fmt,...) MRPT_printf_format_check(2
Writes a string to the stream in a textual form.
void assignTextMessageParameters(double *offset_y, int *text_index)
Assign the next available offset_y and text_index for the textMessage under construction.
void setCameraElevationDeg(float deg)
Changes the camera parameters programmatically.
void BASE_IMPEXP joinThread(const TThreadHandle &threadHandle)
Waits until the given thread ends.
void _optimizeGraph(bool is_full_update=false)
Optimize the given graph.