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",
224 static_cast<int>(this->
m_graph->nodeCount())),
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 " 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>
379 obj->setPose(this->
m_graph->nodes.rbegin()->second);
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>;
463 nodes_to_optimize, this->
m_graph->nodeCount() - 1,
465 nodes_to_optimize->insert(this->
m_graph->nodeCount() - 1);
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,
648 nodeID < this->
m_graph->nodeCount() - 1; ++nodeID)
650 double curr_distance = this->
m_graph->nodes[nodeID].distanceTo(
651 this->
m_graph->nodes[cur_nodeID]);
654 nodes_set->insert(nodeID);
660 this->
m_graph->getAllNodes(*nodes_set);
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);
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.
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.
std::pair< TNodeID, TNodeID > TPairNodeIDs
A pair of node IDs.
GraphVisualizationParams()
mrpt::gui::CDisplayWindow3D * m_win
Window to use.
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.
mrpt::opengl::CRenderizable::Ptr initOptDistanceVisualizationInternal(const mrpt::poses::CPose2D &p_unused)
Setup the corresponding Disk/Sphere instance.
void updateGraphVisualization()
Called internally for updating the visualization scene for the graph building procedure.
void toggleGraphVisualization()
Toggle the graph visualization on and off.
A set of object, which are referenced to the coordinates framework established in this object...
mrpt::opengl::COpenGLScene::Ptr & get3DSceneAndLock()
Gets a reference to the smart shared pointer that holds the internal scene (carefuly read introductio...
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...
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.
std::shared_ptr< CRenderizable > Ptr
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.
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...
std::thread m_thread_optimize
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?
std::shared_ptr< CSetOfObjects > Ptr
size_t m_min_nodes_for_optimization
Minimum number of nodes before we try optimizing the graph.
std::string format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
bool optimization_on_second_thread
int text_index_optimization_distance
std::shared_ptr< CSensoryFrame > Ptr
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
std::shared_ptr< CObservation > Ptr
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 checkForLoopClosures()
Check if a loop closure edge was added in the graph.
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.
std::string keystroke_graph_toggle
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
std::shared_ptr< CActionCollection > Ptr
void updateOptDistanceVisualization()
Update the position of the disk indicating the distance in which Levenberg-Marquardt graph optimizati...
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...
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.
std::shared_ptr< COpenGLScene > Ptr
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()
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.
std::shared_ptr< CDisk > Ptr
std::mutex * m_graph_section
Levenberg-Marquardt non-linear graph slam optimization scheme.
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 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
std::shared_ptr< CSphere > Ptr
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 distance(const TPoint2D &p1, const TPoint2D &p2)
Gets the distance between two points in a 2D space.
std::shared_ptr< CGridPlaneXY > Ptr
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 _optimizeGraph(bool is_full_update=false)
Optimize the given graph.