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",
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");
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>;
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,
591 double curr_distance = this->
m_graph->
nodes[nodeID].distanceTo(
594 nodes_set->insert(nodeID);
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",
#define MRPT_LOG_DEBUG_STREAM(__CONTENTS)
#define MRPT_LOG_WARN_STREAM(__CONTENTS)
void getAllNodes(std::set< TNodeID > &lstNode_IDs) const
Return a list of all the node_ID's of the graph, generated from all the nodes that appear in the list...
edges_map_t edges
The public member with the directed edges in the graph.
global_poses_t nodes
The nodes (vertices) of the graph, with their estimated "global" (with respect to root) position,...
void getAs3DObject(mrpt::opengl::CSetOfObjectsPtr object, const mrpt::utils::TParametersDouble &viz_params) const
Return 3D Visual Representation of the edges and nodes in the network of poses.
size_t nodeCount() const
Return number of nodes in the list nodes of global coordinates (may be different that all nodes appea...
virtual void updateVisuals()
Update the relevant visual features in CDisplayWindow.
mrpt::utils::CTimeLogger m_time_logger
Time logger instance.
mrpt::graphslam::CWindowObserver * m_win_observer
CWindowObserver object for monitoring various visual-oriented events.
mrpt::graphslam::CWindowManager * m_win_manager
Pointer to the CWindowManager object used to store visuals-related instances.
mrpt::synch::CCriticalSection * m_graph_section
virtual void initializeVisuals()
Initialize visual objects in CDisplayWindow (e.g.
virtual void initializeLoggers(const std::string &name)
Initialize the COutputLogger, CTimeLogger instances given the name of the decider/optimizer at hand.
static const std::string report_sep
virtual void loadParams(const std::string &source_fname)
Load the necessary for the decider/optimizer configuration parameters.
virtual void notifyOfWindowEvents(const std::map< std::string, bool > &events_occurred)
Get a list of the window events that happened since the last call.
mrpt::gui::CDisplayWindow3D * m_win
Window to use.
virtual void getDescriptiveReport(std::string *report_str) const
Fill the provided string with a detailed report of the decider/optimizer state.
static const std::string header_sep
Separator string to be used in debugging messages.
virtual void printParams() const
Print the problem parameters - relevant to the decider/optimizer to the screen in a unified/compact w...
typename mrpt::graphs::CNetworkOfPoses2DInf * m_graph
Pointer to the graph that is under construction.
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...
void assignTextMessageParameters(double *offset_y, int *text_index)
Assign the next available offset_y and text_index for the textMessage under construction.
void registerKeystroke(const std::string key_str, const std::string key_desc)
Make new keystrokes available in the help message box.
Levenberg-Marquardt non-linear graph slam optimization scheme.
bool checkForLoopClosures()
Check if a loop closure edge was added in the graph.
void updateOptDistanceVisualization()
Update the position of the disk indicating the distance in which Levenberg-Marquardt graph optimizati...
void _optimizeGraph(bool is_full_update=false)
Optimize the given graph.
void fitGraphInView()
Set the camera parameters of the CDisplayWindow3D so that the whole graph is viewed in the window.
mrpt::system::TThreadHandle m_thread_optimize
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 updateGraphVisualization()
Called internally for updating the visualization scene for the graph building procedure.
void initGraphVisualization()
Initialize objects relateed to the Graph Visualization.
size_t m_curr_used_consec_lcs
Number of consecutive loop closures that are currently registered.
void toggleGraphVisualization()
Toggle the graph visualization on and off.
GraphVisualizationParams viz_params
Parameters relevant to the visualization of the graph.
size_t m_max_used_consec_lcs
Number of maximum cosecutive loop closures that are allowed to be issued.
void updateVisuals()
Update the relevant visual features in CDisplayWindow.
void getDescriptiveReport(std::string *report_str) const
Fill the provided string with a detailed report of the decider/optimizer state.
void loadParams(const std::string &source_fname)
Load the necessary for the decider/optimizer configuration parameters.
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.
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.
void optimizeGraph()
Wrapper around _optimizeGraph which first locks the section and then calls the _optimizeGraph method.
size_t m_last_total_num_of_nodes
void notifyOfWindowEvents(const std::map< std::string, bool > &events_occurred)
Get a list of the window events that happened since the last call.
bool m_just_fully_optimized_graph
Indicates whether a full graph optimization was just issued.
FullOptimizationPolicy m_optimization_policy
Should I fully optimize the graph on loop closure?
mrpt::opengl::CRenderizablePtr initOptDistanceVisualizationInternal(const mrpt::poses::CPose2D &p_unused)
Setup the corresponding Disk/Sphere instance.
OptimizationParams opt_params
Parameters relevant to the optimizatio nfo the graph.
GRAPH_T::constraint_t::type_value pose_t
void initializeVisuals()
Initialize visual objects in CDisplayWindow (e.g.
bool checkForFullOptimization()
Decide whether to issue a full graph optimization.
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
void initOptDistanceVisualization()
Initialize the Disk/Sphere used for visualizing the optimization distance.
size_t m_min_nodes_for_optimization
Minimum number of nodes before we try optimizing the graph.
size_t m_curr_ignored_consec_lcs
Consecutive Loop Closures that have currently been ignored.
bool justFullyOptimizedGraph() const
Used by the caller to query for possible full graph optimization on the latest optimizer run.
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 setCameraPointingToPoint(float x, float y, float z)
Changes the camera parameters programmatically.
void forceRepaint()
Repaints the window. forceRepaint, repaint and updateWindow are all aliases of the same method.
void unlockAccess3DScene()
Unlocks the access to the internal 3D scene.
void setCameraZoom(float zoom)
Changes the camera parameters programmatically.
void setCameraProjective(bool isProjective)
Sets the camera as projective, or orthogonal.
void setCameraAzimuthDeg(float deg)
Changes the camera parameters programmatically.
mrpt::opengl::COpenGLScenePtr & get3DSceneAndLock()
Gets a reference to the smart shared pointer that holds the internal scene (carefuly read introductio...
void setCameraElevationDeg(float deg)
Changes the camera parameters programmatically.
A grid of lines over the XY plane.
void getPlaneLimits(float &xmin, float &xmax, float &ymin, float &ymax) const
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).
A class acquiring a CCriticalSection at its constructor, and releasing it at destructor.
This class allows loading and storing values and vectors of different types from a configuration text...
This class allows loading and storing values and vectors of different types from "....
void dumpToConsole() const
Just like dumpToTextStream() but sending the text to the console (std::cout)
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...
This base class is used to provide a unified interface to files,memory buffers,..Please see the deriv...
virtual int printf(const char *fmt,...) MRPT_printf_format_check(2
Writes a string to the stream in a textual form.
This class implements a high-performance stopwatch.
double Tac()
Stops the stopwatch.
void Tic()
Starts the stopwatch.
std::string getStatsAsText(const size_t column_width=80) const
Dump all stats to a multi-line text string.
void enter(const char *func_name)
Start of a named section.
double leave(const char *func_name)
End of a named section.
const Scalar * const_iterator
GLsizei GLsizei GLuint * obj
GLenum GLsizei GLenum format
GLsizei const GLchar ** string
GLsizei GLsizei GLchar * source
double BASE_IMPEXP distance(const TPoint2D &p1, const TPoint2D &p2)
Gets the distance between two points in a 2D space.
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...
uint64_t TNodeID
The type for node IDs in graphs of different types.
std::pair< TNodeID, TNodeID > TPairNodeIDs
A pair of node IDs.
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...
void BASE_IMPEXP joinThread(TThreadHandle &threadHandle)
Waits until the given thread ends.
unsigned long BASE_IMPEXP getCurrentThreadId() MRPT_NO_THROWS
Returns the ID of the current thread.
#define MRPT_UNUSED_PARAM(a)
Can be used to avoid "not used parameters" warnings from the compiler.
#define ASSERTMSG_(f, __ERROR_MSG)
The namespace for 3D scene representation and rendering.
Classes for serialization, sockets, ini-file manipulation, streams, list of properties-values,...
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
std::string BASE_IMPEXP format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
Output information for mrpt::graphslam::optimize_graph_spa_levmarq()
void dumpToTextStream(mrpt::utils::CStream &out) const
This method should clearly display all the contents of the structure in textual form,...
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.
std::string keystroke_graph_toggle
GraphVisualizationParams()
~GraphVisualizationParams()
bool visualize_optimized_graph
std::string keystroke_graph_autofit
mrpt::utils::TParametersDouble cfg
void dumpToTextStream(mrpt::utils::CStream &out) const
This method should clearly display all the contents of the structure in textual form,...
double optimization_distance
optimize only for the nodes found in a certain distance from the current position.
mrpt::utils::TParametersDouble cfg
bool optimization_on_second_thread
double offset_y_optimization_distance
std::string keystroke_optimization_distance
Keystroke to toggle the optimization distance on/off.
std::string keystroke_optimize_graph
Keystroke to manually trigger a full graph optimization.
GRAPH_T::edges_map_t last_pair_nodes_to_edge
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.
mrpt::utils::TColor optimization_distance_color
int text_index_optimization_distance
A RGB color - floats in the range [0,1].