19 #include <Eigen/Dense> 37 m_last_selected_sector(
std::numeric_limits<
unsigned int>::max())
39 if (INI_FILE !=
nullptr)
initialize(*INI_FILE);
44 options.saveToConfigFile(c, getConfigFileSectionName());
49 options.loadFromConfigFile(c, getConfigFileSectionName());
54 int k_from{-1}, k_to{-1};
56 bool contains_target_k{
false};
61 : min_eval(
std::numeric_limits<double>::max()),
62 max_eval(-
std::numeric_limits<double>::max())
68 void CHolonomicFullEval::evalSingleTarget(
72 const auto target = ni.
targets[target_idx];
78 const auto ptg = getAssociatedPTG();
81 const double target_dir = ::atan2(target.y, target.x);
82 const unsigned int target_k =
83 CParameterizedTrajectoryGenerator::alpha2index(target_dir, nDirs);
84 const double target_dist = target.norm();
86 m_dirs_scores.resize(nDirs, options.factorWeights.size() + 2);
89 std::vector<mrpt::math::TPoint2D> obstacles_2d(nDirs);
95 const auto& sc_lut = m_sincos_lut.getSinCosForScan(sp);
97 for (
unsigned int i = 0; i < nDirs; i++)
99 obstacles_2d[i].x = ni.
obstacles[i] * sc_lut.ccos[i];
100 obstacles_2d[i].y = ni.
obstacles[i] * sc_lut.csin[i];
107 for (
unsigned int i = 0; i < nDirs; i++)
113 if (ni.
obstacles[i] < options.TOO_CLOSE_OBSTACLE &&
114 !(i == target_k && ni.
obstacles[i] > 1.02 * target_dist))
116 for (
size_t l = 0; l <
NUM_FACTORS; l++) m_dirs_scores(i, l) = .0;
120 const double d = std::min(ni.
obstacles[i], 0.95 * target_dist);
123 const double x = d * sc_lut.ccos[i];
124 const double y = d * sc_lut.csin[i];
129 target_dist < 1.0 - options.TOO_CLOSE_OBSTACLE &&
134 std::max(target_dist, ni.
obstacles[i]) / (target_dist * 1.05);
139 std::max(0.0, ni.
obstacles[i] - options.TOO_CLOSE_OBSTACLE);
146 const double max_real_freespace =
147 ptg->getActualUnloopedPathLength(i);
148 const double max_real_freespace_norm =
149 max_real_freespace / ptg->getRefDistance();
165 double min_dist_target_along_path = sg.
distance(target);
171 const double endpt_dist_to_target = (target -
TPoint2D(x, y)).
norm();
172 const double endpt_dist_to_target_norm =
173 std::min(1.0, endpt_dist_to_target);
175 if ((endpt_dist_to_target_norm > target_dist &&
176 endpt_dist_to_target_norm >= 0.95 * target_dist) &&
178 min_dist_target_along_path >
179 1.05 * std::min(target_dist, endpt_dist_to_target_norm))
184 min_dist_target_along_path = sg.
distance(target);
187 scores[1] = 1.0 / (1.0 +
square(min_dist_target_along_path));
193 scores[2] = std::sqrt(1.01 - endpt_dist_to_target_norm);
194 scores[5] = scores[2];
201 if (m_last_selected_sector != std::numeric_limits<unsigned int>::max())
204 const unsigned int hist_dist =
207 if (hist_dist >= options.HYSTERESIS_SECTOR_COUNT)
209 1.0 - (hist_dist - options.HYSTERESIS_SECTOR_COUNT) /
229 double& closest_obs = scores[4];
233 const int W = std::max(1,
round(nDirs * 0.1));
234 const int i_min = std::max(0, static_cast<int>(i) - W);
236 std::min(static_cast<int>(nDirs) - 1, static_cast<int>(i) + W);
237 for (
int oi = i_min; oi <= i_max; oi++)
253 if (target_dist < 1.0 - options.TOO_CLOSE_OBSTACLE &&
264 m_dirs_scores(i, l) = scores[l];
272 if (!options.factorNormalizeOrNot[l])
continue;
274 const double mmax = m_dirs_scores.col(l).maxCoeff();
275 const double mmin = m_dirs_scores.col(l).minCoeff();
276 const double span = mmax - mmin;
277 if (span <= .0)
continue;
279 m_dirs_scores.col(l).array() -= mmin;
280 m_dirs_scores.col(l).array() /= span;
285 const unsigned int NUM_PHASES = options.PHASE_FACTORS.size();
288 std::vector<double> weights_sum_phase(NUM_PHASES, .0),
289 weights_sum_phase_inv(NUM_PHASES);
290 for (
unsigned int i = 0; i < NUM_PHASES; i++)
292 for (
unsigned int l : options.PHASE_FACTORS[i])
293 weights_sum_phase[i] += options.factorWeights.at(l);
294 ASSERT_(weights_sum_phase[i] > .0);
295 weights_sum_phase_inv[i] = 1.0 / weights_sum_phase[i];
299 NUM_PHASES, std::vector<double>(nDirs, .0));
301 double last_phase_threshold = -1.0;
303 for (
unsigned int phase_idx = 0; phase_idx < NUM_PHASES; phase_idx++)
305 double phase_min = std::numeric_limits<double>::max(), phase_max = .0;
307 for (
unsigned int i = 0; i < nDirs; i++)
309 double this_dir_eval = 0;
312 options.TOO_CLOSE_OBSTACLE ||
314 phase_scores[phase_idx - 1][i] <
315 last_phase_threshold)
324 for (
unsigned int l : options.PHASE_FACTORS[phase_idx])
326 options.factorWeights.at(l) *
327 std::log(std::max(1e-6, m_dirs_scores(i, l)));
329 this_dir_eval *= weights_sum_phase_inv[phase_idx];
330 this_dir_eval = std::exp(this_dir_eval);
332 phase_scores[phase_idx][i] = this_dir_eval;
339 ASSERT_(options.PHASE_THRESHOLDS.size() == NUM_PHASES);
341 options.PHASE_THRESHOLDS[phase_idx] > .0 &&
342 options.PHASE_THRESHOLDS[phase_idx] < 1.0);
344 last_phase_threshold =
345 options.PHASE_THRESHOLDS[phase_idx] * phase_max +
346 (1.0 - options.PHASE_THRESHOLDS[phase_idx]) * phase_min;
350 auto& dirs_eval = phase_scores.back();
352 postProcessDirectionEvaluations(dirs_eval, ni, target_idx);
357 double phase_min = std::numeric_limits<double>::max(), phase_max = .0;
358 for (
unsigned int i = 0; i < nDirs; i++)
363 last_phase_threshold =
364 options.PHASE_THRESHOLDS.back() * phase_max +
365 (1.0 - options.PHASE_THRESHOLDS.back()) * phase_min;
369 for (
unsigned int i = 0; i < nDirs; i++)
371 double&
val = dirs_eval[i];
372 if (
val < last_phase_threshold)
val = .0;
384 auto log = std::make_shared<CLogFileRecord_FullEval>();
388 const size_t numTrgs = ni.
targets.size();
389 std::vector<EvalOutput> evals(numTrgs);
390 for (
unsigned int trg_idx = 0; trg_idx < numTrgs; trg_idx++)
392 evalSingleTarget(trg_idx, ni, evals[trg_idx]);
396 const auto nDirs = evals.front().phase_scores.back().size();
401 std::vector<double> overall_scores;
402 overall_scores.assign(nDirs, .0);
403 for (
const auto& e : evals)
405 for (
unsigned int i = 0; i < nDirs; i++)
406 overall_scores[i] += e.phase_scores.back()[i];
409 for (
unsigned int i = 0; i < nDirs; i++)
410 overall_scores[i] *= (1.0 / numTrgs);
416 std::vector<TGap> gaps;
417 std::size_t best_gap_idx = std::string::npos;
419 bool inside_gap =
false;
420 for (
unsigned int i = 0; i < nDirs; i++)
422 const double val = overall_scores[i];
430 auto& active_gap = *gaps.rbegin();
431 active_gap.k_to = i - 1;
444 gaps.emplace_back(new_gap);
451 auto& active_gap = *gaps.rbegin();
452 if (
val >= active_gap.max_eval)
454 active_gap.k_best_eval = i;
459 if (best_gap_idx == std::string::npos ||
460 val > gaps[best_gap_idx].max_eval)
462 best_gap_idx = gaps.size() - 1;
470 auto& active_gap = *gaps.rbegin();
471 active_gap.k_to = nDirs - 1;
478 double best_dir_eval = 0;
483 ASSERT_(best_gap_idx < gaps.size());
484 const TGap& best_gap = gaps[best_gap_idx];
485 best_dir_k = best_gap.k_best_eval;
486 best_dir_eval = overall_scores.at(best_dir_k);
490 if (best_dir_eval == .0)
499 const auto ptg = getAssociatedPTG();
500 const double ptg_ref_dist = ptg ? ptg->getRefDistance() : 1.0;
503 CParameterizedTrajectoryGenerator::index2alpha(best_dir_k, nDirs);
507 const double targetNearnessFactor =
508 m_enableApproachTargetSlowDown
510 1.0, ni.
targets.front().norm() /
511 (options.TARGET_SLOW_APPROACHING_DISTANCE /
515 const double obs_dist = ni.
obstacles[best_dir_k];
517 const double obs_dist_th = std::max(
518 options.TOO_CLOSE_OBSTACLE,
520 double riskFactor = 1.0;
521 if (obs_dist <= options.TOO_CLOSE_OBSTACLE)
526 obs_dist < obs_dist_th && obs_dist_th > options.TOO_CLOSE_OBSTACLE)
528 riskFactor = (obs_dist - options.TOO_CLOSE_OBSTACLE) /
529 (obs_dist_th - options.TOO_CLOSE_OBSTACLE);
532 ni.
maxRobotSpeed * std::min(riskFactor, targetNearnessFactor);
535 m_last_selected_sector = best_dir_k;
540 log->selectedTarget = 0;
541 log->selectedSector = best_dir_k;
542 log->evaluation = best_dir_eval;
546 log->dirs_eval = evals.front().phase_scores;
547 log->dirs_eval.back() = overall_scores;
549 if (options.LOG_SCORE_MATRIX)
551 log->dirs_scores = m_dirs_scores;
556 unsigned int CHolonomicFullEval::direction2sector(
557 const double a,
const unsigned int N)
563 return static_cast<unsigned int>(idx);
566 CLogFileRecord_FullEval::CLogFileRecord_FullEval() : dirs_scores() {}
621 : factorWeights{0.1, 0.5, 0.5, 0.01, 1, 1, 1},
622 factorNormalizeOrNot{0, 0, 0, 0, 1, 0, 0},
623 PHASE_FACTORS{{1, 2}, {4}, {0, 2}},
624 PHASE_THRESHOLDS{0.5, 0.6, 0.7}
644 s,
"factorWeights", std::vector<double>(), factorWeights,
true);
648 s,
"factorNormalizeOrNot", factorNormalizeOrNot, factorNormalizeOrNot);
649 ASSERT_EQUAL_(factorNormalizeOrNot.size(), factorWeights.size());
655 PHASE_FACTORS.resize(PHASE_COUNT);
656 PHASE_THRESHOLDS.resize(PHASE_COUNT);
657 for (
int i = 0; i < PHASE_COUNT; i++)
660 s,
mrpt::format(
"PHASE%i_FACTORS", i + 1), PHASE_FACTORS[i],
661 PHASE_FACTORS[i],
true);
666 ASSERT_(PHASE_THRESHOLDS[i] >= .0 && PHASE_THRESHOLDS[i] <= 1.0);
682 "Directions with collision-free distances below this threshold are not " 685 TARGET_SLOW_APPROACHING_DISTANCE,
686 "Start to reduce speed when closer than this to target.");
688 OBSTACLE_SLOW_DOWN_DISTANCE,
689 "Start to reduce speed when clearance is below this value ([0,1] ratio " 690 "wrt obstacle reference/max distance)");
692 HYSTERESIS_SECTOR_COUNT,
693 "Range of `sectors` (directions) for hysteresis over successive " 696 LOG_SCORE_MATRIX,
"Save the entire score matrix in log files");
698 clearance_threshold_ratio,
699 "Ratio [0,1], times path_count, gives the minimum number of paths at " 700 "each side of a target direction to be accepted as desired direction");
702 gap_width_ratio_threshold,
703 "Ratio [0,1], times path_count, gives the minimum gap width to accept " 704 "a direct motion towards target.");
710 "[0]=Free space, [1]=Dist. in sectors, [2]=Closer to target " 711 "(Euclidean), [3]=Hysteresis, [4]=clearance along path, [5]=Like [2] " 712 "without decimation if path obstructed");
714 s,
"factorNormalizeOrNot",
716 "Normalize factors or not (1/0)");
719 s,
"PHASE_COUNT", PHASE_FACTORS.size(), WN, WV,
720 "Number of evaluation phases to run (params for each phase below)");
722 for (
unsigned int i = 0; i < PHASE_FACTORS.size(); i++)
725 s,
mrpt::format(
"PHASE%u_THRESHOLD", i + 1), PHASE_THRESHOLDS[i],
727 "Phase scores must be above this relative range threshold [0,1] to " 728 "be considered in next phase (Default:`0.75`)");
732 "Indices of the factors above to be considered in this phase");
809 std::vector<double>& dir_evals,
const NavInput& ni,
unsigned int trg_idx)
double gap_width_ratio_threshold
Ratio [0,1], times path_count, gives the minimum gap width to accept a direct motion towards target...
virtual void postProcessDirectionEvaluations(std::vector< double > &dir_evals, const NavInput &ni, unsigned int trg_idx)
If desired, override in a derived class to manipulate the final evaluations of each directions...
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...
A class for storing extra information about the execution of CHolonomicFullEval navigation.
double distance(const TPoint2D &point) const
Distance to point.
void serializeFrom(mrpt::serialization::CArchive &in, uint8_t serial_version) override
Pure virtual method for reading (deserializing) from an abstract archive.
TPoint2D_< double > TPoint2D
Lightweight 2D point.
app initialize(argc, argv)
double TOO_CLOSE_OBSTACLE
Directions with collision-free distances below this threshold are not elegible.
void saveToConfigFile(mrpt::config::CConfigFileBase &cfg, const std::string §ion) const override
This method saves the options to a ".ini"-like file or memory-stored string list. ...
std::string std::string format(std::string_view fmt, ARGS &&... args)
int MRPT_SAVE_NAME_PADDING()
Default padding sizes for macros MRPT_SAVE_CONFIG_VAR_COMMENT(), etc.
void serializeTo(mrpt::serialization::CArchive &out) const override
Pure virtual method for writing (serializing) to an abstract archive.
This file implements several operations that operate element-wise on individual or pairs of container...
A base class for holonomic reactive navigation methods.
double TARGET_SLOW_APPROACHING_DISTANCE
Start to reduce speed when closer than this to target [m].
int32_t selectedTarget
Normally = 0.
std::vector< int32_t > factorNormalizeOrNot
0/1 to normalize factors.
IMPLEMENTS_SERIALIZABLE(CLogFileRecord_FullEval, CHolonomicLogFileRecord, mrpt::nav) IMPLEMENTS_SERIALIZABLE(CHolonomicFullEval
uint8_t serializeGetVersion() const override
Must return the current versioning number of the object.
double clearance_threshold_ratio
Ratio [0,1], times path_count, gives the minimum number of paths at each side of a target direction t...
std::vector< double > PHASE_THRESHOLDS
Phase 1,2,N-1...
TOptions options
Parameters of the algorithm (can be set manually or loaded from CHolonomicFullEval::initialize or opt...
#define MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(__V)
For use in CSerializable implementations.
double OBSTACLE_SLOW_DOWN_DISTANCE
Start to reduce speed when clearance is below this value ([0,1] ratio wrt obstacle reference/max dist...
mrpt::nav const unsigned NUM_FACTORS
#define ASSERT_(f)
Defines an assertion mechanism.
int32_t selectedSector
Member data.
This class allows loading and storing values and vectors of different types from a configuration text...
This base provides a set of functions for maths stuff.
2D segment, consisting of two points.
#define ASSERT_EQUAL_(__A, __B)
Assert comparing two values, reporting their actual values upon failure.
Auxiliary struct that holds all the relevant geometry information about a 2D scan.
A base class for log records for different holonomic navigation methods.
double desiredDirection
The desired motion direction, in the range [-PI, PI].
mrpt::config::CConfigFileBase CConfigFileBase
std::vector< double > factorWeights
See docs above.
int MRPT_SAVE_VALUE_PADDING()
#define MRPT_LOAD_CONFIG_VAR_NO_DEFAULT( variableName, variableType, configFileObject, sectionNameStr)
CHolonomicLogFileRecord::Ptr logRecord
The navigation method will create a log record and store it here via a smart pointer.
double read_double(const std::string §ion, const std::string &name, double defaultValue, bool failIfNotFound=false) const
TPoint2D point2
Destiny point.
void serializeFrom(mrpt::serialization::CArchive &in, uint8_t serial_version) override
Pure virtual method for reading (deserializing) from an abstract archive.
T wrapToPi(T a)
Modifies the given angle to translate it into the ]-pi,pi] range.
Full evaluation of all possible directions within the discrete set of input directions.
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())
std::vector< std::vector< double > > dirs_eval
Final [N-1] and earlier stages [0...N-1] evaluation scores for each direction, in the same order of T...
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...
TPoint2D point1
Origin point.
double desiredSpeed
The desired motion speed in that direction, from 0 up to NavInput::maxRobotSpeed. ...
return_t square(const num_t x)
Inline function for the square of a number.
#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...
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
Virtual base class for "archives": classes abstracting I/O streams.
uint8_t serializeGetVersion() const override
Must return the current versioning number of the object.
mrpt::vision::TStereoCalibResults out
#define ASSERT_ABOVE_(__A, __B)
double HYSTERESIS_SECTOR_COUNT
Range of "sectors" (directions) for hysteresis over successive timesteps.
#define MRPT_SAVE_CONFIG_VAR_COMMENT(variableName, __comment)
unsigned int m_last_selected_sector
void serializeTo(mrpt::serialization::CArchive &out) const override
Pure virtual method for writing (serializing) to an abstract archive.
bool rightToLeft
Angles storage order: true=counterclockwise; false=clockwise.
Output for CAbstractHolonomicReactiveMethod::navigate()
mrpt::math::CMatrixD dirs_scores
Individual scores for each direction: (i,j), i (row) are directions, j (cols) are scores...
std::string sprintf_container(const char *fmt, const T &V)
Generates a string for a container in the format [A,B,C,...], and the fmt string for each vector elem...
std::vector< std::vector< double > > phase_scores
std::vector< std::vector< int32_t > > PHASE_FACTORS
Factor indices [0,4] for the factors to consider in each phase 1,2,...N of the movement decision (Def...
T abs_diff(const T a, const T b)
Efficient and portable evaluation of the absolute difference of two unsigned integer values (but will...
void read_vector(const std::string §ion, const std::string &name, const VECTOR_TYPE &defaultValue, VECTOR_TYPE &outValues, bool failIfNotFound=false) const
Reads a configuration parameter of type vector, stored in the file as a string: "[v1 v2 v3 ...
CONTAINER::Scalar norm(const CONTAINER &v)
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.
int round(const T value)
Returns the closer integer (int) to x.