10 #ifndef CLEVMARQGSO_IMPL_H
11 #define CLEVMARQGSO_IMPL_H
22 template <
class GRAPH_T>
24 : m_first_time_call(false),
25 m_has_read_config(false),
26 m_autozoom_active(true),
27 m_last_total_num_of_nodes(5),
28 m_optimization_policy(FOP_USE_LC),
29 m_curr_used_consec_lcs(0),
30 m_curr_ignored_consec_lcs(0),
31 m_just_fully_optimized_graph(false),
32 m_min_nodes_for_optimization(3)
40 template <
class GRAPH_T>
49 template <
class GRAPH_T>
57 this->logFmt(LVL_DEBUG,
"In updateOptimizerState... ");
89 template <
class GRAPH_T>
102 template <
class GRAPH_T>
118 template <
class GRAPH_T>
120 const std::map<std::string, bool>& events_occurred)
150 if (events_occurred.find(
"mouse_clicked")->second)
166 template <
class GRAPH_T>
186 template <
class GRAPH_T>
195 mrpt::utils::LVL_DEBUG,
"In the updateGraphVisualization function");
203 bool prev_visibility =
true;
206 prev_visibility = prev_object->isVisible();
208 scene->removeObject(prev_object);
215 graph_obj->setName(
"optimized_graph");
216 graph_obj->setVisibility(prev_visibility);
217 scene->insert(graph_obj);
223 "Optimized Graph: #nodes %d",
238 template <
class GRAPH_T>
247 graph_obj->setVisibility(!graph_obj->isVisible());
255 template <
class GRAPH_T>
263 "\nVisualization of data was requested but no CDisplayWindow3D pointer "
270 std::dynamic_pointer_cast<CSetOfObjects>(
obj);
279 float x_min, x_max, y_min, y_max;
281 const float z_min = obj_grid->getPlaneZcoord();
283 0.5 * (x_min + x_max), 0.5 * (y_min + y_max), z_min);
285 2.0f * std::max(10.0f, std::max(x_max - x_min, y_max - y_min)));
294 template <
class GRAPH_T>
304 "Toggle optimization distance on/off");
308 "Manually trigger a full graph optimization");
314 obj->setPose(initial_pose);
315 obj->setName(
"optimization_distance_obj");
329 format(
"Radius for graph optimization"),
335 template <
class GRAPH_T>
350 template <
class GRAPH_T>
368 template <
class GRAPH_T>
387 template <
class GRAPH_T>
396 obj->setVisibility(!
obj->isVisible());
404 template <
class GRAPH_T>
411 "optimizeGraph:: ThreadID:" << endl
412 <<
"\t" << std::this_thread::get_id()
415 <<
"Trying to grab lock... ");
420 this->logFmt(mrpt::utils::LVL_DEBUG,
"2nd thread grabbed the lock..");
425 template <
class GRAPH_T>
440 optimization_timer.
Tic();
443 std::set<mrpt::utils::TNodeID>* nodes_to_optimize;
452 nodes_to_optimize = NULL;
456 nodes_to_optimize =
new std::set<mrpt::utils::TNodeID>;
484 double elapsed_time = optimization_timer.
Tac();
486 mrpt::utils::LVL_DEBUG,
"Optimization of graph took: %fs",
490 delete nodes_to_optimize;
491 nodes_to_optimize =
nullptr;
498 template <
class GRAPH_T>
503 bool is_loop_closure =
false;
504 typename GRAPH_T::edges_map_t curr_pair_nodes_to_edge =
515 curr_pair_nodes_to_edge.begin();
516 it != curr_pair_nodes_to_edge.end(); ++it)
522 curr_pair = it->first;
525 static_cast<int>(curr_pair.first) -
526 static_cast<int>(curr_pair.second)) >
530 mrpt::utils::LVL_DEBUG,
"Registering loop closure... ");
531 is_loop_closure =
true;
539 return is_loop_closure;
544 template <
class GRAPH_T>
547 bool is_full_update =
false;
568 return is_full_update;
573 bool use_limit_reached =
576 bool ignore_limit_reached =
580 if (ignore_limit_reached || use_limit_reached)
586 if (ignore_limit_reached)
590 if (use_limit_reached)
611 is_full_update =
false;
613 "*PARTIAL* graph optimization.. ignoring new loop closure");
617 is_full_update =
true;
620 return is_full_update;
624 template <
class GRAPH_T>
630 template <
class GRAPH_T>
632 const GRAPH_T& graph,
const size_t iter,
const size_t max_iter,
633 const double cur_sq_error)
637 template <
class GRAPH_T>
639 std::set<mrpt::utils::TNodeID>* nodes_set,
650 double curr_distance = this->
m_graph->
nodes[nodeID].distanceTo(
654 nodes_set->insert(nodeID);
666 template <
class GRAPH_T>
674 template <
class GRAPH_T>
688 "OptimizerParameters",
"max_used_consecutive_loop_closures", 2,
false);
691 "OptimizerParameters",
"max_ignored_consecutive_loop_closures", 15,
696 int min_verbosity_level =
697 source.read_int(
"OptimizerParameters",
"class_verbosity", 1,
false);
698 this->setMinLoggingLevel(VerbosityLevel(min_verbosity_level));
700 this->logFmt(mrpt::utils::LVL_DEBUG,
"Successfully loaded Params. ");
706 template <
class GRAPH_T>
716 stringstream class_props_ss;
717 class_props_ss <<
"Levenberg Marquardt Optimization Summary: " << std::endl;
722 const std::string output_res = this->getLogAsString();
728 *report_str += class_props_ss.str();
731 *report_str += time_res;
734 *report_str += output_res;
742 template <
class GRAPH_T>
744 : optimization_distance_color(0, 201, 87),
745 keystroke_optimization_distance(
"u"),
746 keystroke_optimize_graph(
"w")
749 template <
class GRAPH_T>
753 template <
class GRAPH_T>
760 "------------------[ Levenberg-Marquardt Optimization "
761 "]------------------\n");
763 "Optimization on second thread = %s\n",
764 optimization_on_second_thread ?
"TRUE" :
"FALSE");
766 "Optimize nodes in distance = %.2f\n", optimization_distance);
767 out.
printf(
"Min. node difference for LC = %d\n", LC_min_nodeid_diff);
769 out.
printf(
"%s", cfg.getAsString().c_str());
770 std::cout << std::endl;
774 template <
class GRAPH_T>
779 optimization_on_second_thread =
source.read_bool(
780 section,
"optimization_on_second_thread",
false,
false);
781 LC_min_nodeid_diff =
source.read_int(
782 "GeneralConfiguration",
"LC_min_nodeid_diff", 30,
false);
783 optimization_distance =
784 source.read_double(section,
"optimization_distance", 5,
false);
787 optimization_distance == -1 || optimization_distance > 0,
789 "Invalid value for optimization distance: %.2f",
790 optimization_distance));
793 cfg[
"verbose"] =
source.read_bool(section,
"verbose", 0,
false);
794 cfg[
"profiler"] =
source.read_bool(section,
"profiler", 0,
false);
795 cfg[
"max_iterations"] =
796 source.read_double(section,
"max_iterations", 100,
false);
797 cfg[
"scale_hessian"] =
798 source.read_double(
"Optimization",
"scale_hessian", 0.2,
false);
799 cfg[
"tau"] =
source.read_double(section,
"tau", 1e-3,
false);
806 template <
class GRAPH_T>
808 : keystroke_graph_toggle(
"s"), keystroke_graph_autofit(
"a")
811 template <
class GRAPH_T>
815 template <
class GRAPH_T>
821 out.
printf(
"-----------[ Graph Visualization Parameters ]-----------\n");
823 "Visualize optimized graph = %s\n",
824 visualize_optimized_graph ?
"TRUE" :
"FALSE");
826 out.
printf(
"%s", cfg.getAsString().c_str());
828 std::cout << std::endl;
832 template <
class GRAPH_T>
837 using namespace utils;
839 visualize_optimized_graph =
840 source.read_bool(section,
"visualize_optimized_graph", 1,
false);
842 cfg[
"show_ID_labels"] =
843 source.read_bool(section,
"optimized_show_ID_labels", 0,
false);
844 cfg[
"show_ground_grid"] =
845 source.read_double(section,
"optimized_show_ground_grid", 1,
false);
847 source.read_bool(section,
"optimized_show_edges", 1,
false);
849 source.read_int(section,
"optimized_edge_color", 4286611456,
false);
851 source.read_double(section,
"optimized_edge_width", 1.5,
false);
852 cfg[
"show_node_corners"] =
853 source.read_bool(section,
"optimized_show_node_corners", 1,
false);
854 cfg[
"show_edge_rel_poses"] =
855 source.read_bool(section,
"optimized_show_edge_rel_poses", 1,
false);
856 cfg[
"edge_rel_poses_color"] =
source.read_int(
857 section,
"optimized_edge_rel_poses_color", 1090486272,
false);
858 cfg[
"nodes_edges_corner_scale"] =
source.read_double(
859 section,
"optimized_nodes_edges_corner_scale", 0.4,
false);
860 cfg[
"nodes_corner_scale"] =
861 source.read_double(section,
"optimized_nodes_corner_scale", 0.7,
false);
862 cfg[
"nodes_point_size"] =
863 source.read_int(section,
"optimized_nodes_point_size", 5,
false);
864 cfg[
"nodes_point_color"] =
source.read_int(
865 section,
"optimized_nodes_point_color", 10526880,
false);
#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::CSetOfObjects::Ptr 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.
std::mutex * m_graph_section
mrpt::graphslam::CWindowManager * m_win_manager
Pointer to the CWindowManager object used to store visuals-related instances.
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.
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.
bool updateState(mrpt::obs::CActionCollection::Ptr action, mrpt::obs::CSensoryFrame::Ptr observations, mrpt::obs::CObservation::Ptr observation)
Generic method for fetching the incremental action/observation readings from the calling function.
void loadParams(const std::string &source_fname)
Load the necessary for the decider/optimizer configuration parameters.
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::CRenderizable::Ptr 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.
std::thread m_thread_optimize
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.
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.
mrpt::opengl::COpenGLScene::Ptr & get3DSceneAndLock()
Gets a reference to the smart shared pointer that holds the internal scene (carefuly read introductio...
void setCameraAzimuthDeg(float deg)
Changes the camera parameters programmatically.
void setCameraElevationDeg(float deg)
Changes the camera parameters programmatically.
std::shared_ptr< CActionCollection > Ptr
std::shared_ptr< CObservation > Ptr
std::shared_ptr< CSensoryFrame > Ptr
std::shared_ptr< CDisk > Ptr
A grid of lines over the XY plane.
void getPlaneLimits(float &xmin, float &xmax, float &ymin, float &ymax) const
std::shared_ptr< CGridPlaneXY > Ptr
std::shared_ptr< COpenGLScene > Ptr
std::shared_ptr< CRenderizable > Ptr
std::shared_ptr< CSetOfObjects > Ptr
std::shared_ptr< CSphere > Ptr
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).
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 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=nullptr, const mrpt::utils::TParametersDouble &extra_params=mrpt::utils::TParametersDouble(), typename graphslam_traits< GRAPH_T >::TFunctorFeedback functor_feedback=typename graphslam_traits< GRAPH_T >::TFunctorFeedback())
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.
#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 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].