33 turningRadiusReference(.10),
35 m_stepTimeDuration(0.01),
36 m_collisionGrid(-1, 1, -1, 1, 0.5, this)
59 v_max_mps,
double,
V_MAX, cfg, sSection);
61 w_max_dps,
double,
W_MAX, cfg, sSection);
68 const int WN = 25, WV = 30;
74 "Resolution of the collision-check look-up-table [m].");
76 sSection,
"v_max_mps",
V_MAX, WN, WV,
77 "Maximum linear velocity for trajectories [m/s].");
80 "Maximum angular velocity for trajectories [deg/s].");
83 "An approximate dimension of the robot (not a critical parameter) "
94 o <<
p.x <<
p.y <<
p.phi <<
p.t <<
p.dist <<
p.v <<
p.w;
100 i >>
p.x >>
p.y >>
p.phi >>
p.t >>
p.dist >>
p.v >>
p.w;
109 float max_time,
float max_dist,
unsigned int max_n,
float diferencial_t,
110 float min_dist,
float* out_max_acc_v,
float* out_max_acc_w)
121 const float radio_max_robot = 1.0f;
128 float ult_dist, ult_dist1, ult_dist2;
131 float x_min = 1e3f, x_max = -1e3;
132 float y_min = 1e3f, y_max = -1e3;
135 float max_acc_lin, max_acc_ang;
137 max_acc_lin = max_acc_ang = 0;
148 float t = .0f, dist = .0f, girado = .0f;
149 float x = .0f,
y = .0f, phi = .0f,
v = .0f,
w = .0f, _x = .0f,
150 _y = .0f, _phi = .0f;
154 float last_vs[2] = {.0f, .0f}, last_ws[2] = {.0f, .0f};
160 while (
t < max_time && dist < max_dist &&
points.size() < max_n &&
161 fabs(girado) < 1.95 *
M_PI)
167 fabs((last_vs[0] - last_vs[1]) / diferencial_t);
169 fabs((last_ws[0] - last_ws[1]) / diferencial_t);
178 last_vs[1] = last_vs[0];
179 last_ws[1] = last_ws[0];
185 x += cos(phi) *
v * diferencial_t;
186 y += sin(phi) *
v * diferencial_t;
187 phi +=
w * diferencial_t;
190 girado +=
w * diferencial_t;
195 dist += v_inTPSpace * diferencial_t;
201 ult_dist2 = fabs(radio_max_robot * (_phi - phi));
202 ult_dist = std::max(ult_dist1, ult_dist2);
204 if (ult_dist > min_dist)
221 x_max = std::max(x_max,
x);
223 y_max = std::max(y_max,
y);
237 if (out_max_acc_v) *out_max_acc_v = max_acc_lin;
238 if (out_max_acc_w) *out_max_acc_w = max_acc_ang;
245 x_min - 0.5f, x_max + 0.5f, y_min - 0.5f, y_max + 0.5f, 0.25f,
268 "[CPTG_DiffDrive_CollisionGridBased::simulateTrajectories] "
269 "Simulation aborted: unexpected exception!\n");
294 const float obsX,
const float obsY)
const
298 return cell !=
nullptr ? *cell : emptyCell;
306 const unsigned int icx,
const unsigned int icy,
const uint16_t k,
322 if (itK == cell->end())
324 cell->push_back(std::make_pair(k, dist));
328 if (dist < itK->second) itK->second = dist;
392 if (!f)
return false;
394 const uint8_t serialize_version =
401 *f << computed_robotShape;
404 *f << m_parent->getDescription() << m_parent->getAlphaValuesCount()
405 <<
static_cast<float>(m_parent->getMax_V())
406 <<
static_cast<float>(m_parent->getMax_W());
408 *f << m_x_min << m_x_max << m_y_min << m_y_max;
419 *f << m_map[i][k].
first << m_map[i][k].second;
439 if (!f)
return false;
450 *f >> serialized_version;
452 switch (serialized_version)
459 const bool shapes_match =
460 (stored_shape.size() == current_robotShape.size() &&
462 stored_shape.begin(), stored_shape.end(),
463 current_robotShape.begin()));
479 const std::string expected_desc = m_parent->getDescription();
482 if (desc != expected_desc)
return false;
485 #define READ_UINT16_CHECK_IT_MATCHES_STORED(_VAR) \
489 if (ff != _VAR) return false; \
491 #define READ_FLOAT_CHECK_IT_MATCHES_STORED(_VAR) \
495 if (std::abs(ff - _VAR) > 1e-4f) return false; \
497 #define READ_DOUBLE_CHECK_IT_MATCHES_STORED(_VAR) \
501 if (std::abs(ff - _VAR) > 1e-6) return false; \
527 *f >> m_map[i][k].
first >> m_map[i][k].second;
532 catch (std::exception& e)
534 std::cerr <<
"[CCollisionGrid::loadFromFile] " << e.what();
544 double x,
double y,
int& out_k,
double& out_d,
double tolerance_dist)
const
550 "Have you called simulateTrajectories() first?");
560 bool at_least_one =
false;
567 for (
int cx = cx0 - 1; cx <= cx0 + 1; cx++)
569 for (
int cy = cy0 - 1; cy <= cy0 + 1; cy++)
598 float selected_d = 0;
599 float selected_dist = std::numeric_limits<float>::max();
604 for (
int k = k_min; k <= k_max; k++)
614 if (dist_a_punto < selected_dist)
616 selected_dist = dist_a_punto;
624 if (selected_k != -1)
628 return (selected_dist <=
square(tolerance_dist));
638 selected_dist = std::numeric_limits<float>::max();
646 if (dist_a_punto < selected_dist)
648 selected_dist = dist_a_punto;
650 selected_d = dist_a_punto;
654 selected_d = std::sqrt(selected_d);
663 const float target_dist = std::sqrt(
x *
x +
y *
y);
664 return (target_dist > target_dist);
671 "Changing reference distance not allowed in this class after "
680 "Changing robot shape not allowed in this class after initialization!");
689 const std::string& cacheFilename,
const bool verbose)
697 <<
"[CPTG_DiffDrive_CollisionGridBased::initialize] Starting... "
698 "*** THIS MAY TAKE A WHILE, BUT MUST BE COMPUTED ONLY ONCE!! **"
704 m_robotShape.size() >= 3,
"Robot shape must have 3 or more vertices");
713 if (verbose) cout <<
"Initializing PTG '" << cacheFilename <<
"'...";
716 const float min_dist = 0.015f;
734 ASSERTMSG_(Ki > 0,
"The PTG seems to be not initialized!");
739 if (verbose) cout <<
"loaded from file OK" << endl;
755 std::vector<mrpt::math::TPoint2D> transf_shape(
760 for (
size_t k = 0; k < Ki; k++)
764 for (
size_t n = 0;
n < (nPoints - 1);
n++)
771 std::numeric_limits<double>::max(),
772 std::numeric_limits<double>::max());
774 -std::numeric_limits<double>::max(),
775 -std::numeric_limits<double>::max());
777 for (
size_t m = 0; m < nVerts; m++)
804 for (
int ix = ix_min; ix < ix_max; ix++)
808 for (
int iy = iy_min; iy < iy_max; iy++)
820 ix - 1, iy - 1, k, d);
827 if (verbose) cout << k <<
"/" << Ki <<
",";
830 if (verbose) cout <<
format(
"Done! [%.03f sec]\n", tictac.
Tac());
875 for (
size_t n = 0;
n < numPoints - 1;
n++)
884 out_step = numPoints - 1;
889 double ox,
double oy, std::vector<double>& tp_obstacles)
const
896 const double dist = i->second;
902 double ox,
double oy,
uint16_t k,
double& tp_obstacle_k)
const
910 const double dist = i->second;
#define READ_FLOAT_CHECK_IT_MATCHES_STORED(_VAR)
const uint32_t COLGRID_FILE_MAGIC
#define READ_DOUBLE_CHECK_IT_MATCHES_STORED(_VAR)
#define READ_UINT16_CHECK_IT_MATCHES_STORED(_VAR)
This class allows loading and storing values and vectors of different types from a configuration text...
void write(const std::string §ion, const std::string &name, enum_t value, const int name_padding_width=-1, const int value_padding_width=-1, const std::string &comment=std::string())
void setSize(const double x_min, const double x_max, const double y_min, const double y_max, const double resolution, const T *fill_value=nullptr)
Changes the size of the grid, ERASING all previous contents.
int y2idx(double y) const
double getResolution() const
Returns the resolution of the grid map.
TCollisionCell * cellByPos(double x, double y)
Returns a pointer to the contents of a cell given by its coordinates, or nullptr if it is out of the ...
size_t getSizeX() const
Returns the horizontal size of grid map in cells count.
double idx2x(int cx) const
Transform a cell index into a coordinate value of the cell central point.
size_t getSizeY() const
Returns the vertical size of grid map in cells count.
int x2idx(double x) const
Transform a coordinate values into cell indexes.
double idx2y(int cy) const
Saves data to a file and transparently compress the data using the given compression level.
bool fileOpenCorrectly() const
Returns true if the file was open without errors.
Kinematic model for Ackermann-like or differential-driven vehicles.
double ang_vel
Angular velocity (rad/s)
double lin_vel
Linear velocity (m/s)
std::shared_ptr< CVehicleVelCmd > Ptr
A wrapper of a TPolygon2D class, implementing CSerializable.
size_t verticesCount() const
Returns the vertices count in the polygon:
double GetVertex_x(size_t i) const
Methods for accessing the vertices.
double GetVertex_y(size_t i) const
2D polygon, inheriting from std::vector<TPoint2D>.
bool contains(const TPoint2D &point) const
Check whether a point is inside (or within geometryEpsilon of a polygon edge).
const TCollisionCell & getTPObstacle(const float obsX, const float obsY) const
For an obstacle (x,y), returns a vector with all the pairs (a,d) such as the robot collides.
bool loadFromFile(mrpt::serialization::CArchive *fil, const mrpt::math::CPolygon ¤t_robotShape)
Load from file, true = OK.
void updateCellInfo(const unsigned int icx, const unsigned int icy, const uint16_t k, const float dist)
Updates the info into a cell: It updates the cell only if the distance d for the path k is lower than...
bool saveToFile(mrpt::serialization::CArchive *fil, const mrpt::math::CPolygon &computed_robotShape) const
Save to file, true = OK.
CPTG_DiffDrive_CollisionGridBased()
Constructor: possible values in "params":
mrpt::containers::CDynamicGrid< TCellForLambdaFunction > m_lambdaFunctionOptimizer
This grid will contain indexes data for speeding-up the default, brute-force lambda function.
virtual bool inverseMap_WS2TP(double x, double y, int &out_k, double &out_d, double tolerance_dist=0.10) const override
The default implementation in this class relies on a look-up-table.
void updateTPObstacleSingle(double ox, double oy, uint16_t k, double &tp_obstacle_k) const override
Like updateTPObstacle() but for one direction only (k) in TP-Space.
virtual mrpt::kinematics::CVehicleVelCmd::Ptr directionToMotionCommand(uint16_t k) const override
In this class, out_action_cmd contains: [0]: linear velocity (m/s), [1]: angular velocity (rad/s).
void internal_processNewRobotShape() override
Will be called whenever the robot shape is set / updated.
virtual void loadDefaultParams() override
Loads a set of default parameters; provided exclusively for the PTG-configurator tool.
void internal_initialize(const std::string &cacheFilename=std::string(), const bool verbose=true) override
Must be called after setting all PTG parameters and before requesting converting obstacles to TP-Spac...
std::vector< std::pair< uint16_t, float > > TCollisionCell
A list of all the pairs (alpha,distance) such as the robot collides at that cell.
double turningRadiusReference
CCollisionGrid m_collisionGrid
The collision grid.
bool getPathStepForDist(uint16_t k, double dist, uint32_t &out_step) const override
Access path k ([0,N-1]=>[-pi,pi] in alpha): largest step count for which the traversed distance is < ...
void internal_readFromStream(mrpt::serialization::CArchive &in) override
void internal_deinitialize() override
This must be called to de-initialize the PTG if some parameter is to be changed.
virtual void loadFromConfigFile(const mrpt::config::CConfigFileBase &cfg, const std::string &sSection) override
Possible values in "params" (those in CParameterizedTrajectoryGenerator, which is called internally,...
bool loadColGridsFromFile(const std::string &filename, const mrpt::math::CPolygon ¤t_robotShape)
double m_stepTimeDuration
double getPathStepDuration() const override
Returns the duration (in seconds) of each "step".
virtual void saveToConfigFile(mrpt::config::CConfigFileBase &cfg, const std::string &sSection) const override
This method saves the options to a ".ini"-like file or memory-stored string list.
std::vector< TCPointVector > m_trajectory
void updateTPObstacle(double ox, double oy, std::vector< double > &tp_obstacles) const override
Updates the radial map of closest TP-Obstacles given a single obstacle point at (ox,...
double getPathDist(uint16_t k, uint32_t step) const override
Access path k ([0,N-1]=>[-pi,pi] in alpha): traversed distance at discrete step step.
size_t getPathStepCount(uint16_t k) const override
Access path k ([0,N-1]=>[-pi,pi] in alpha): number of discrete "steps" along the trajectory.
void simulateTrajectories(float max_time, float max_dist, unsigned int max_n, float diferencial_t, float min_dist, float *out_max_acc_v=nullptr, float *out_max_acc_w=nullptr)
Numerically solve the diferential equations to generate a family of trajectories.
bool saveColGridsToFile(const std::string &filename, const mrpt::math::CPolygon &computed_robotShape) const
virtual void ptgDiffDriveSteeringFunction(float alpha, float t, float x, float y, float phi, float &v, float &w) const =0
The main method to be implemented in derived classes: it defines the differential-driven differential...
void getPathPose(uint16_t k, uint32_t step, mrpt::math::TPose2D &p) const override
Access path k ([0,N-1]=>[-pi,pi] in alpha): pose of the vehicle at discrete step step.
void internal_writeToStream(mrpt::serialization::CArchive &out) const override
virtual void setRefDistance(const double refDist) override
Launches an exception in this class: it is not allowed in numerical integration-based PTGs to change ...
virtual mrpt::kinematics::CVehicleVelCmd::Ptr getSupportedKinematicVelocityCommand() const override
Returns an empty kinematic velocity command object of the type supported by this PTG.
void saveToConfigFile(mrpt::config::CConfigFileBase &cfg, const std::string &sSection) const override
This method saves the options to a ".ini"-like file or memory-stored string list.
void internal_shape_saveToStream(mrpt::serialization::CArchive &out) const
void loadDefaultParams() override
Loads a set of default parameters; provided exclusively for the PTG-configurator tool.
void internal_shape_loadFromStream(mrpt::serialization::CArchive &in)
mrpt::math::CPolygon m_robotShape
void loadShapeFromConfigFile(const mrpt::config::CConfigFileBase &source, const std::string §ion)
virtual void saveToConfigFile(mrpt::config::CConfigFileBase &cfg, const std::string &sSection) const override
This method saves the options to a ".ini"-like file or memory-stored string list.
uint16_t m_alphaValuesCount
The number of discrete values for "alpha" between -PI and +PI.
virtual void internal_writeToStream(mrpt::serialization::CArchive &out) const
virtual void internal_readFromStream(mrpt::serialization::CArchive &in)
void internal_TPObsDistancePostprocess(const double ox, const double oy, const double new_tp_obs_dist, double &inout_tp_obs) const
To be called by implementors of updateTPObstacle() and updateTPObstacleSingle() to honor the user set...
double index2alpha(uint16_t k) const
Alpha value for the discrete corresponding value.
uint16_t getAlphaValuesCount() const
Get the number of different, discrete paths in this family.
virtual void loadFromConfigFile(const mrpt::config::CConfigFileBase &cfg, const std::string &sSection) override
Parameters accepted by this base class:
virtual void loadDefaultParams()
Loads a set of default parameters into the PTG.
Virtual base class for "archives": classes abstracting I/O streams.
A high-performance stopwatch, with typical resolution of nanoseconds.
void Tic() noexcept
Starts the stopwatch.
double Tac() noexcept
Stops the stopwatch.
#define MRPT_LOAD_HERE_CONFIG_VAR_DEGREES_NO_DEFAULT( variableName, variableType, targetVariable, configFileObject, sectionNameStr)
#define MRPT_LOAD_HERE_CONFIG_VAR_NO_DEFAULT( variableName, variableType, targetVariable, configFileObject, sectionNameStr)
#define MRPT_LOAD_CONFIG_VAR( variableName, variableType, configFileObject, sectionNameStr)
An useful macro for loading variables stored in a INI-like file under a key with the same name that t...
const Scalar * const_iterator
#define ASSERT_(f)
Defines an assertion mechanism.
#define ASSERT_BELOW_(__A, __B)
#define MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(__V)
For use in CSerializable implementations.
#define ASSERTMSG_(f, __ERROR_MSG)
Defines an assertion mechanism.
GLubyte GLubyte GLubyte GLubyte w
GLclampf GLclampf GLclampf alpha
GLsizei const GLfloat * points
GLsizei const GLchar ** string
std::string format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
mrpt::serialization::CArchive & operator<<(mrpt::serialization::CArchive &o, const mrpt::nav::TCPoint &p)
mrpt::serialization::CArchive & operator>>(mrpt::serialization::CArchive &i, mrpt::nav::TCPoint &p)
std::vector< TCPoint > TCPointVector
CArchiveStreamBase< STREAM > archiveFrom(STREAM &s)
Helper function to create a templatized wrapper CArchive object for a: MRPT's CStream,...
void keep_min(T &var, const K test_val)
If the second argument is below the first one, set the first argument to this lower value.
T square(const T x)
Inline function for the square of a number.
void keep_max(T &var, const K test_val)
If the second argument is above the first one, set the first argument to this higher value.
double RAD2DEG(const double x)
Radians to degrees.
double DEG2RAD(const double x)
Degrees to radians.
unsigned __int16 uint16_t
unsigned __int32 uint32_t
Specifies the min/max values for "k" and "n", respectively.
Trajectory points in C-Space for non-holonomic robots.