35 constexpr
auto sect =
"MappingApplication";
51 " rbpf-slam - Part of the MRPT\n" 52 " MRPT C++ Library: %s - Sources timestamp: %s\n\n",
63 const std::string configFile = std::string(
argv[1]);
95 int LOG_FREQUENCY = 5;
96 bool GENERATE_LOG_JOINT_H =
false;
97 bool GENERATE_LOG_INFO =
false;
98 bool SAVE_POSE_LOG =
false;
99 bool SAVE_MAP_IMAGES =
false;
100 bool SAVE_3D_SCENE =
false;
101 bool CAMERA_3DSCENE_FOLLOWS_ROBOT =
true;
102 bool SHOW_PROGRESS_IN_WINDOW =
false;
103 int SHOW_PROGRESS_IN_WINDOW_DELAY_MS = 1;
104 std::string METRIC_MAP_CONTINUATION_GRIDMAP_FILE;
105 std::string SIMPLEMAP_CONTINUATION;
107 int PROGRESS_WINDOW_WIDTH = 600, PROGRESS_WINDOW_HEIGHT = 500;
108 int RANDOM_SEED = -1;
109 const string OUT_DIR_STD =
119 const auto& s =
sect;
132 METRIC_MAP_CONTINUATION_START_POSE.
x =
133 c.read_double(s,
"METRIC_MAP_CONTINUATION_START_POSE_X", .0);
134 METRIC_MAP_CONTINUATION_START_POSE.
y =
135 c.read_double(s,
"METRIC_MAP_CONTINUATION_START_POSE_Y", .0);
136 METRIC_MAP_CONTINUATION_START_POSE.
phi =
DEG2RAD(
137 c.read_double(s,
"METRIC_MAP_CONTINUATION_START_POSE_PHI_DEG", .0));
142 const char* OUT_DIR = OUT_DIR_STD.c_str();
147 CTicTac tictac, tictacGlobal, tictac_JH;
164 mapBuilder = std::make_shared<CMetricMapBuilderRBPF>(rbpfMappingOptions);
168 std::stringstream ss;
174 if (!METRIC_MAP_CONTINUATION_GRIDMAP_FILE.empty())
179 startPose.
mean.
x(METRIC_MAP_CONTINUATION_START_POSE.
x);
180 startPose.
mean.
y(METRIC_MAP_CONTINUATION_START_POSE.
y);
181 startPose.
mean.
phi(METRIC_MAP_CONTINUATION_START_POSE.
phi);
187 METRIC_MAP_CONTINUATION_GRIDMAP_FILE);
191 mapBuilder->initialize(dummySimpleMap, &startPose);
193 for (
auto& m_particle :
mapBuilder->mapPDF.m_particles)
201 "No gridmap in multimetric map definition, but metric map " 202 "continuation was set (!)");
203 it_grid->copyMapContentFrom(gridmap);
206 if (!SIMPLEMAP_CONTINUATION.empty())
220 mapBuilder->options.debugForceInsertion =
false;
223 if (RANDOM_SEED >= 0)
224 rng.randomize(RANDOM_SEED);
233 string OUT_DIR_MAPS =
format(
"%s/maps", OUT_DIR);
234 string OUT_DIR_3D =
format(
"%s/3D", OUT_DIR);
252 "%% time_step execution_time(ms) map_size(#frames) frame_inserted? " 254 "%%-------------------------------------------------------------------" 258 "%% EMI H EMMI effecMappedArea effecMappedCells \n" 259 "%%-------------------------------------------------------\n");
262 "%% time_step x y z yaw pitch roll timestamp \n" 263 "%%--------------------------------------------\n");
266 "%% time_step x y z yaw pitch roll \n" 267 "%%----------------------------------\n");
270 "%% time_step #particles ESS \n" 271 "%%------------------------------\n");
280 if (SHOW_PROGRESS_IN_WINDOW)
282 win3D = CDisplayWindow3D::Create(
283 "RBPF-SLAM @ MRPT C++ Library", PROGRESS_WINDOW_WIDTH,
284 PROGRESS_WINDOW_HEIGHT);
285 win3D->setCameraZoom(40);
286 win3D->setCameraAzimuthDeg(-50);
287 win3D->setCameraElevationDeg(70);
311 action->getBestMovementEstimation();
313 odoPose = odoPose +
CPose3D(act->poseChange->getMeanVal());
318 if (act3D) odoPose = odoPose + act3D->poseChange.mean;
323 if (observations && !observations->empty())
324 observations_timestamp = (*observations->begin())->timestamp;
329 mapBuilder->processActionObservation(*action, *observations);
330 t_exec = tictac.
Tac();
336 "%u %f %i %i\n", static_cast<unsigned int>(step), 1000.0f * t_exec,
338 mapBuilder->m_statsLastIteration.observationsInserted ? int(1)
351 if (LOG_FREQUENCY > 0 && 0 == (step % LOG_FREQUENCY))
354 mapBuilder->mapPDF.getCurrentMostLikelyMetricMap();
356 if (GENERATE_LOG_INFO)
361 mapBuilder->mapPDF.getAveragedMetricMapEstimation();
365 grid->computeEntropy(entropy);
367 grid->saveAsBitmapFile(
368 format(
"%s/EMMI_gridmap_%03u.png", OUT_DIR, step));
371 "%f %f %f %f %lu\n", entropy.
I, entropy.
H, entropy.
mean_I,
374 "Log information saved. EMI = %.04f EMMI=%.04f (in " 376 entropy.
I, entropy.
mean_I, 1000.0f * tictac_JH.
Tac());
384 format(
"%s/mapbuild_posepdf_%03u.txt", OUT_DIR, step));
396 format(
"%s/mapbuilt_%05u_", OUT_DIR_MAPS.c_str(), step));
401 mapBuilder->drawCurrentEstimationToImage(&img);
403 format(
"%s/mapping_%05u.png", OUT_DIR, step));
409 if (SAVE_3D_SCENE || SHOW_PROGRESS_IN_WINDOW)
411 scene = std::make_shared<COpenGLScene>();
416 -200, 200, -200, 200, 0, 5);
417 groundPlane->setColor(0.4f, 0.4f, 0.4f);
418 scene->insert(groundPlane);
421 if (CAMERA_3DSCENE_FOLLOWS_ROBOT)
428 objCam->setPointingAt(robotPose);
429 objCam->setAzimuthDegrees(-30);
430 objCam->setElevationDegrees(30);
431 scene->insert(objCam);
440 size_t M =
mapBuilder->mapPDF.particlesCount();
443 objLines->setColor(0, 1, 1);
444 for (
size_t i = 0; i < M; i++)
446 std::deque<TPose3D> path;
449 float x0 = 0, y0 = 0, z0 = 0;
452 objLines->appendLine(
453 x0, y0, z0 + 0.001, k.x, k.y, k.z + 0.001);
459 scene->insert(objLines);
463 float minDistBtwPoses = -1;
464 std::deque<TPose3D> dummyPath;
466 for (
int k = (
int)dummyPath.size() - 1; k >= 0; k--)
469 mapBuilder->mapPDF.getEstimatedPosePDFAtTime(k, poseParts);
471 const auto [COV, meanPose] =
474 if (meanPose.distanceTo(lastMeanPose) > minDistBtwPoses)
478 minDistBtwPoses = 6 * sqrt(COV3(0, 0) + COV3(1, 1));
483 objEllip->setLocation(
484 meanPose.x(), meanPose.y(),
485 meanPose.z() + 0.001);
486 objEllip->setCovMatrix(COV3.
blockCopy<2, 2>());
487 objEllip->setColor(0, 0, 1);
488 objEllip->enableDrawSolid3D(
false);
489 scene->insert(objEllip);
494 objEllip->setLocation(
495 meanPose.x(), meanPose.y(),
496 meanPose.z() + 0.001);
497 objEllip->setCovMatrix(COV3);
498 objEllip->setColor(0, 0, 1);
499 objEllip->enableDrawSolid3D(
false);
500 scene->insert(objEllip);
503 lastMeanPose = meanPose;
511 "%s/buildingmap_%05u.3Dscene", OUT_DIR_3D.c_str(), step));
515 if (SHOW_PROGRESS_IN_WINDOW)
519 win3D->unlockAccess3DScene();
521 win3D->forceRepaint();
523 SHOW_PROGRESS_IN_WINDOW_DELAY_MS - t_exec * 1000;
525 std::this_thread::sleep_for(
526 std::chrono::milliseconds(add_delay));
531 if (GENERATE_LOG_JOINT_H)
535 double H_joint =
mapBuilder->getCurrentJointEntropy();
536 double H_path =
mapBuilder->mapPDF.getCurrentEntropyOfPaths();
537 f_jinfo.
printf(
"%e %e\n", H_joint, H_path);
539 "Saving joing H info. joint-H=%f\t(in %.03fms)", H_joint,
540 1000.0f * tictac_JH.
Tac());
550 format(
"%s/log_MemoryUsage.txt", OUT_DIR).c_str(),
"at");
557 "Saving memory usage: %.04f MiB", memUsage / (1024.0 * 1024.0));
562 "%u %u %f\n", (
unsigned int)step, (
unsigned int)curPDF.
size(),
567 mapBuilder->getCurrentPoseEstimation()->getMean(meanPose);
570 "%u %f %f %f %f %f %f %f\n", (
unsigned int)step, meanPose.
x(),
571 meanPose.
y(), meanPose.z(), meanPose.
yaw(), meanPose.
pitch(),
579 "%i\t%f\t%f\t%f\t%f\t%f\t%f\n", step, odoPose.
x(), odoPose.
y(),
580 odoPose.z(), odoPose.
yaw(), odoPose.
pitch(), odoPose.
roll());
588 "----------- **END** (total time: %.03f sec) ---------",
599 mapBuilder->mapPDF.getCurrentMostLikelyMetricMap();
601 format(
"%s/finalMap", OUT_DIR));
606 os::sprintf(strFil, 1000,
"%s/most_likely_path.txt", OUT_DIR);
609 ASSERT_(f_pathPart !=
nullptr);
611 std::deque<TPose3D> outPath;
612 std::deque<TPose3D>::iterator itPath;
614 mapBuilder->getCurrentMostLikelyPath(outPath);
616 for (itPath = outPath.begin(); itPath != outPath.end(); itPath++)
618 f_pathPart,
"%.3f %.3f %.3f\n", itPath->x, itPath->y, itPath->yaw);
623 if (win3D) win3D->waitForKey();
641 m_rawlogFileName = std::string(
argv[2]);
644 sect,
"rawlog_file", std::string(
"log.rawlog"),
true);
651 std::string rawlog_images_path =
653 rawlog_images_path +=
"/Images";
static double toDouble(const time_point t) noexcept
Converts a timestamp to a UNIX time_t-like number, with fractional part.
mrpt::math::TPose3D asTPose() const
std::size_t countMapsByClass() const
Count how many maps exist of the given class (or derived class)
void getAs3DObject(mrpt::opengl::CSetOfObjects::Ptr &outObj) const override
Returns a 3D object representing the map.
CMatrixFixed< Scalar, BLOCK_ROWS, BLOCK_COLS > blockCopy(int start_row=0, int start_col=0) const
const blockCopy(): Returns a copy of the given block
virtual bool impl_get_next_observations(mrpt::obs::CActionCollection::Ptr &action, mrpt::obs::CSensoryFrame::Ptr &observations, mrpt::obs::CObservation::Ptr &observation)=0
Get next sensory data.
virtual int printf(const char *fmt,...) MRPT_printf_format_check(2
Writes a string to the stream in a textual form.
double Tac() noexcept
Stops the stopwatch.
bool createDirectory(const std::string &dirName)
Creates a directory.
#define MRPT_LOG_DEBUG(_STRING)
Use: MRPT_LOG_DEBUG("message");
CPose2D mean
The mean value.
VerbosityLevel
Enumeration of available verbosity levels.
void run()
Runs with the current parameter set.
bool saveToTextFile(const std::string &file) const override
Save PDF's m_particles to a text file.
std::string read_string(const std::string §ion, const std::string &name, const std::string &defaultValue, bool failIfNotFound=false) const
int getch() noexcept
An OS-independent version of getch, which waits until a key is pushed.
std::string std::string format(std::string_view fmt, ARGS &&... args)
This class stores a sequence of <Probabilistic Pose,SensoryFrame> pairs, thus a "metric map" can be t...
int void fclose(FILE *f)
An OS-independent version of fclose.
double effectiveMappedArea
The target variable for the area of cells with information, i.e.
#define MRPT_LOAD_CONFIG_VAR_CS(variableName, variableType)
Shortcut for MRPT_LOAD_CONFIG_VAR() for config file object named c and section string named s ...
A high-performance stopwatch, with typical resolution of nanoseconds.
void setMinLoggingLevel(const VerbosityLevel level)
Set the minimum logging level for which the incoming logs are going to be taken into account...
double ESS() const override
Returns the normalized ESS (Estimated Sample Size), in the range [0,1].
double pitch() const
Get the PITCH angle (in radians)
double yaw() const
Get the YAW angle (in radians)
static Ptr Create(Args &&... args)
std::string MRPT_getCompilationDate()
Returns the MRPT source code timestamp, according to the Reproducible-Builds specifications: https://...
T::Ptr mapByClass(size_t ith=0) const
Returns the i'th map of a given class (or of a derived class), or empty smart pointer if there is no ...
mrpt::math::CMatrixDouble33 cov
The 3x3 covariance matrix.
static Ptr Create(Args &&... args)
virtual std::string impl_get_usage() const =0
int read_int(const std::string §ion, const std::string &name, int defaultValue, bool failIfNotFound=false) const
ENUMTYPE read_enum(const std::string §ion, const std::string &name, const ENUMTYPE &defaultValue, bool failIfNotFound=false) const
Reads an "enum" value, where the value in the config file can be either a numerical value or the symb...
CArchiveStreamBase< STREAM > archiveFrom(STREAM &s)
Helper function to create a templatized wrapper CArchive object for a: MRPT's CStream, std::istream, std::ostream, std::stringstream.
VerbosityLevel getMinLoggingLevel() const
#define ASSERT_(f)
Defines an assertion mechanism.
mrpt::Clock::time_point TTimeStamp
A system independent time type, it holds the the number of 100-nanosecond intervals since January 1...
void getMean(CPose3D &mean_pose) const override
Returns an estimate of the pose, (the mean, or mathematical expectation of the PDF), computed as a weighted average over all m_particles.
Represents a probabilistic 3D (6D) movement.
double H
The target variable for absolute entropy, computed as: H(map)=Sumx,y{ -p(x,y)*ln(p(x,y)) -(1-p(x,y))*ln(1-p(x,y)) }
This base provides a set of functions for maths stuff.
Declares a class that represents a Probability Density function (PDF) of a 2D pose ...
void initialize(int argc, const char **argv)
Initializes the application from CLI parameters.
double phi() const
Get the phi angle of the 2D pose (in radians)
constexpr double DEG2RAD(const double x)
Degrees to radians.
void setLoggerName(const std::string &name)
Set the name of the COutputLogger instance.
double I
The target variable for absolute "information", defining I(x) = 1 - H(x)
This namespace contains representation of robot actions and observations.
size_t size() const
Get the m_particles count (equivalent to "particlesCount")
#define IS_CLASS(obj, class_name)
True if the given reference to object (derived from mrpt::rtti::CObject) is of the given class...
#define ASSERTMSG_(f, __ERROR_MSG)
Defines an assertion mechanism.
double x() const
Common members of all points & poses classes.
This CStream derived class allow using a file as a write-only, binary stream.
std::tuple< cov_mat_t, type_value > getCovarianceAndMean() const override
Returns an estimate of the pose covariance matrix (6x6 cov matrix) and the mean, both at once...
std::shared_ptr< mrpt::slam::CMetricMapBuilderRBPF > mapBuilder
bool keyExists(const std::string §ion, const std::string &key) const
Checks if a given key exists inside a section (case insensitive)
Classes for 2D/3D geometry representation, both of single values and probability density distribution...
double roll() const
Get the ROLL angle (in radians)
Auxiliary class used in mrpt::maps::CMultiMetricMapPDF.
void dumpToTextStream(std::ostream &out) const override
This method should clearly display all the contents of the structure in textual form, sending it to a std::ostream.
int fprintf(FILE *fil, const char *format,...) noexcept MRPT_printf_format_check(2
An OS-independent version of fprintf.
A class for storing an occupancy grid map.
void loadFromConfigFile(const mrpt::config::CConfigFileBase &source, const std::string §ion) override
This method load the options from a ".ini"-like file or memory-stored string list.
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
unsigned long getMemoryUsage()
Returns the memory occupied by this process, in bytes.
unsigned long effectiveMappedCells
The mapped area in cells.
mrpt::config::CConfigFileMemory params
Populated in initialize().
A class used to store a 3D pose (a 3D translation + a rotation in 3D).
static Ptr Create(Args &&... args)
void setContent(const std::vector< std::string > &stringList)
Changes the contents of the virtual "config file".
The namespace for 3D scene representation and rendering.
bool kbhit() noexcept
An OS-independent version of kbhit, which returns true if a key has been pushed.
std::string file_get_contents(const std::string &fileName)
Loads an entire text file and return its contents as a single std::string.
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).
FILE * fopen(const char *fileName, const char *mode) noexcept
An OS-independent version of fopen.
Classes for creating GUI windows for 2D and 3D visualization.
void impl_initialize(int argc, const char **argv) override
bool saveToFile(const std::string &fileName, int jpeg_quality=95) const
Save the image to a file, whose format is determined from the extension (internally uses OpenCV)...
std::string MRPT_getVersion()
Returns a string describing the MRPT version.
Saves data to a file and transparently compress the data using the given compression level...
void Tic() noexcept
Starts the stopwatch.
This class stores any customizable set of metric maps.
#define ASSERT_FILE_EXISTS_(FIL)
#define THROW_EXCEPTION_FMT(_FORMAT_STRING,...)
double mean_I
The target variable for mean information, defined as information per cell: mean_I(map) = I(map) / (ce...
CRandomGenerator & getRandomGenerator()
A static instance of a CRandomGenerator class, for use in single-thread applications.
std::map< mrpt::system::TTimeStamp, mrpt::math::TPose3D > out_estimated_path
Used for returning entropy related information.
static void setImagesPathBase(const std::string &path)
static Ptr Create(Args &&... args)
double phi
Orientation (rads)
Options for building a CMetricMapBuilderRBPF object, passed to the constructor.
static Ptr Create(Args &&... args)
CMultiMetricMap mapTillNow
#define MRPT_LOG_INFO_FMT(_FMT_STRING,...)
std::string extractFileDirectory(const std::string &filePath)
Extract the whole path (the directory) of a filename from a complete path plus name plus extension...
static Ptr Create(Args &&... args)
bool quits_with_esc_key
If enabled (default), stdin will be watched and application quits if ESC is pressed.
int sprintf(char *buf, size_t bufSize, const char *format,...) noexcept MRPT_printf_format_check(3
An OS-independent version of sprintf (Notice the bufSize param, which may be ignored in some compiler...
void saveMetricMapRepresentationToFile(const std::string &filNamePrefix) const override
This virtual method saves the map to a file "filNamePrefix"+< some_file_extension >...
Declares a class that represents a Probability Density function (PDF) of a 3D pose.
A class for storing images as grayscale or RGB bitmaps.
virtual void impl_initialize(int argc, const char **argv)=0
#define MRPT_LOG_INFO(_STRING)