18 #include <Eigen/Dense> 31 const
unsigned int INVALID_K =
std::numeric_limits<
unsigned int>::max();
36 m_last_selected_sector(
std::numeric_limits<
unsigned int>::max())
38 if (INI_FILE !=
nullptr) initialize(*INI_FILE);
43 options.saveToConfigFile(
c, getConfigFileSectionName());
48 options.loadFromConfigFile(
c, getConfigFileSectionName());
53 int k_from{-1}, k_to{-1};
55 bool contains_target_k{
false};
60 : min_eval(
std::numeric_limits<double>::max()),
61 max_eval(-
std::numeric_limits<double>::max())
67 CHolonomicFullEval::EvalOutput::EvalOutput() : best_k(
INVALID_K) {}
72 const auto target = ni.
targets[target_idx];
79 const double ptg_ref_dist = ptg ? ptg->getRefDistance() : 1.0;
82 const double target_dir = ::atan2(target.y, target.x);
83 const unsigned int target_k =
85 const double target_dist = target.norm();
90 std::vector<mrpt::math::TPoint2D> obstacles_2d(nDirs);
98 for (
unsigned int i = 0; i < nDirs; i++)
100 obstacles_2d[i].x = ni.
obstacles[i] * sc_lut.ccos[i];
101 obstacles_2d[i].y = ni.
obstacles[i] * sc_lut.csin[i];
104 const int NUM_FACTORS = 5;
108 for (
unsigned int i = 0; i < nDirs; i++)
110 double scores[NUM_FACTORS];
119 for (
int l = 0; l < NUM_FACTORS; l++)
m_dirs_scores(i, l) = .0;
126 const double x = d * sc_lut.ccos[i];
127 const double y = d * sc_lut.csin[i];
137 std::max(target_dist, ni.
obstacles[i]) / (target_dist * 1.05);
149 const double max_real_freespace =
150 ptg->getActualUnloopedPathLength(i);
151 const double max_real_freespace_norm =
152 max_real_freespace / ptg->getRefDistance();
167 double min_dist_target_along_path = sg.
distance(target);
173 const double endpt_dist_to_target = (target -
TPoint2D(
x,
y)).
norm();
174 const double endpt_dist_to_target_norm =
175 std::min(1.0, endpt_dist_to_target);
177 if ((endpt_dist_to_target_norm > target_dist &&
178 endpt_dist_to_target_norm >= 0.95 * target_dist) &&
179 min_dist_target_along_path >
182 endpt_dist_to_target_norm)
190 min_dist_target_along_path = sg.
distance(target);
193 scores[1] = 1.0 / (1.0 +
square(min_dist_target_along_path));
198 scores[2] = std::sqrt(
199 1.01 - endpt_dist_to_target_norm);
229 const double query_dist_norm =
std::min(0.99, target_dist * 0.95);
231 i , query_dist_norm,
true );
233 i , query_dist_norm,
false );
234 scores[4] = 0.5 * (avr_path_clearance + point_clearance);
238 for (
int l = 0; l < NUM_FACTORS; l++)
m_dirs_scores(i, l) = scores[l];
243 for (
int l = 0; l < NUM_FACTORS; l++)
250 if (
span <= .0)
continue;
261 std::vector<double> weights_sum_phase(NUM_PHASES, .0),
262 weights_sum_phase_inv(NUM_PHASES);
263 for (
unsigned int i = 0; i < NUM_PHASES; i++)
267 ASSERT_(weights_sum_phase[i] > .0);
268 weights_sum_phase_inv[i] = 1.0 / weights_sum_phase[i];
272 NUM_PHASES, std::vector<double>(nDirs, .0));
274 double last_phase_threshold = -1.0;
276 for (
unsigned int phase_idx = 0; phase_idx < NUM_PHASES; phase_idx++)
278 double phase_min = std::numeric_limits<double>::max(), phase_max = .0;
280 for (
unsigned int i = 0; i < nDirs; i++)
282 double this_dir_eval = 0;
287 phase_scores[phase_idx - 1][i] <
288 last_phase_threshold)
302 this_dir_eval *= weights_sum_phase_inv[phase_idx];
303 this_dir_eval = std::exp(this_dir_eval);
305 phase_scores[phase_idx][i] = this_dir_eval;
317 last_phase_threshold =
323 auto& dirs_eval = *phase_scores.rbegin();
330 double phase_min = std::numeric_limits<double>::max(), phase_max = .0;
331 for (
unsigned int i = 0; i < nDirs; i++)
336 last_phase_threshold =
346 std::vector<TGap> gaps;
347 int best_gap_idx = -1;
348 int gap_idx_for_target_dir = -1;
350 bool inside_gap =
false;
351 for (
unsigned int i = 0; i < nDirs; i++)
353 const double val = dirs_eval[i];
354 if (
val < last_phase_threshold)
359 auto& active_gap = *gaps.rbegin();
360 active_gap.k_to = i - 1;
373 gaps.emplace_back(new_gap);
380 auto& active_gap = *gaps.rbegin();
381 if (
val >= active_gap.max_eval)
383 active_gap.k_best_eval = i;
390 active_gap.contains_target_k =
true;
391 gap_idx_for_target_dir = gaps.size() - 1;
394 if (best_gap_idx == -1 ||
val > gaps[best_gap_idx].max_eval)
396 best_gap_idx = gaps.size() - 1;
404 auto& active_gap = *gaps.rbegin();
405 active_gap.k_to = nDirs - 1;
410 ASSERT_(best_gap_idx >= 0 && best_gap_idx <
int(gaps.size()));
412 const TGap& best_gap = gaps[best_gap_idx];
417 if (best_gap_idx == gap_idx_for_target_dir)
422 const auto cl_right =
425 const auto smallest_clearance_in_k_units =
std::min(cl_left, cl_right);
426 const unsigned int clearance_threshold =
429 const unsigned int gap_width = best_gap.
k_to - best_gap.
k_from;
430 const unsigned int width_threshold =
434 if (smallest_clearance_in_k_units >= clearance_threshold &&
435 gap_width >= width_threshold &&
436 ni.
obstacles[target_k] > target_dist * 1.01)
455 if (target_dist < 0.99 &&
458 (ni.
obstacles[target_k] > target_dist * 1.01 &&
460 target_k ,
std::min(0.99, target_dist * 0.95),
465 (target_dist + 0.15 / ptg_ref_dist) &&
466 target_dist < (1.5 / ptg_ref_dist))) &&
467 dirs_eval[target_k] >
475 phase_scores[NUM_PHASES - 1][target_k] += 2.0;
488 std::make_shared<CLogFileRecord_FullEval>();
491 const size_t numTrgs = ni.
targets.size();
493 std::vector<EvalOutput> evals(numTrgs);
494 double best_eval = .0;
495 unsigned int best_trg_idx = 0;
497 for (
unsigned int trg_idx = 0; trg_idx < numTrgs; trg_idx++)
499 auto& eo = evals[trg_idx];
505 best_eval = eo.best_eval;
506 best_trg_idx = trg_idx;
521 const double ptg_ref_dist = ptg ? ptg->getRefDistance() : 1.0;
524 evals[best_trg_idx].best_k, ni.
obstacles.size());
528 const double targetNearnessFactor =
531 1.0, ni.
targets[best_trg_idx].norm() /
536 const double obs_dist =
537 ni.
obstacles[evals[best_trg_idx].best_k];
539 const double obs_dist_th = std::max(
543 double riskFactor = 1.0;
563 log->selectedTarget = best_trg_idx;
564 log->selectedSector = evals[best_trg_idx].best_k;
565 log->evaluation = evals[best_trg_idx].best_eval;
566 log->dirs_eval = evals[best_trg_idx].phase_scores;
576 const double a,
const unsigned int N)
582 return static_cast<unsigned int>(idx);
640 : factorWeights{0.1, 0.5, 0.5, 0.01, 1},
641 factorNormalizeOrNot{0, 0, 0, 0, 1},
642 PHASE_FACTORS{{1, 2}, {4}, {0, 2}},
643 PHASE_THRESHOLDS{0.5, 0.6, 0.7}
663 s,
"factorWeights", std::vector<double>(), factorWeights,
true);
664 ASSERT_(factorWeights.size() == 5);
667 s,
"factorNormalizeOrNot", factorNormalizeOrNot, factorNormalizeOrNot);
668 ASSERT_(factorNormalizeOrNot.size() == factorWeights.size());
674 PHASE_FACTORS.resize(PHASE_COUNT);
675 PHASE_THRESHOLDS.resize(PHASE_COUNT);
676 for (
int i = 0; i < PHASE_COUNT; i++)
680 PHASE_FACTORS[i],
true);
683 PHASE_THRESHOLDS[i] =
c.read_double(
685 ASSERT_(PHASE_THRESHOLDS[i] >= .0 && PHASE_THRESHOLDS[i] <= 1.0);
701 "Directions with collision-free distances below this threshold are not " 704 TARGET_SLOW_APPROACHING_DISTANCE,
705 "Start to reduce speed when closer than this to target.");
707 OBSTACLE_SLOW_DOWN_DISTANCE,
708 "Start to reduce speed when clearance is below this value ([0,1] ratio " 709 "wrt obstacle reference/max distance)");
711 HYSTERESIS_SECTOR_COUNT,
712 "Range of `sectors` (directions) for hysteresis over successive " 715 LOG_SCORE_MATRIX,
"Save the entire score matrix in log files");
717 clearance_threshold_ratio,
718 "Ratio [0,1], times path_count, gives the minimum number of paths at " 719 "each side of a target direction to be accepted as desired direction");
721 gap_width_ratio_threshold,
722 "Ratio [0,1], times path_count, gives the minimum gap width to accept " 723 "a direct motion towards target.");
729 "[0]=Free space, [1]=Dist. in sectors, [2]=Closer to target " 730 "(Euclidean), [3]=Hysteresis, [4]=clearance along path");
732 s,
"factorNormalizeOrNot",
734 "Normalize factors or not (1/0)");
737 s,
"PHASE_COUNT", PHASE_FACTORS.size(), WN, WV,
738 "Number of evaluation phases to run (params for each phase below)");
740 for (
unsigned int i = 0; i < PHASE_FACTORS.size(); i++)
743 s,
mrpt::format(
"PHASE%u_THRESHOLD", i + 1), PHASE_THRESHOLDS[i],
745 "Phase scores must be above this relative range threshold [0,1] to " 746 "be considered in next phase (Default:`0.75`)");
750 "Indices of the factors above to be considered in this phase");
827 std::vector<double>& dir_evals,
const NavInput& ni,
unsigned int trg_idx)
double index2alpha(uint16_t k) const
Alpha value for the discrete corresponding value.
unsigned int direction2sector(const double a, const unsigned int N)
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)
mrpt::obs::CSinCosLookUpTableFor2DScans m_sincos_lut
A class for storing extra information about the execution of CHolonomicFullEval navigation.
const TSinCosValues & getSinCosForScan(const CObservation2DRangeScan &scan) const
Return two vectors with the cos and the sin of the angles for each of the rays in a scan...
void serializeFrom(mrpt::serialization::CArchive &in, uint8_t serial_version) override
Pure virtual method for reading (deserializing) from an abstract archive.
void resize(size_t row, size_t col)
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. ...
int MRPT_SAVE_NAME_PADDING()
Default padding sizes for macros MRPT_SAVE_CONFIG_VAR_COMMENT(), etc.
double distance(const TPoint2D &point) const
Distance to point.
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].
mrpt::nav const unsigned int INVALID_K
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...
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
bool m_enableApproachTargetSlowDown
Whether to decrease speed when approaching target.
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...
CLogFileRecord_FullEval()
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...
double getClearance(uint16_t k, double TPS_query_distance, bool integrate_over_path) const
Gets the clearance for path k and distance TPS_query_distance in one of two modes: ...
T square(const T x)
Inline function for the square of a number.
int mmin(const int t1, const int t2)
#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.
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...
#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.
T abs_diff(const T a, const T b)
Efficient and portable evaluation of the absolute difference of two unsigned integer values (but will...
int MRPT_SAVE_VALUE_PADDING()
void evalSingleTarget(unsigned int target_idx, const NavInput &ni, EvalOutput &eo)
Evals one single target of the potentially many of them in NavInput.
#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.
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.
GLsizei const GLchar ** string
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.
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...
TPoint2D point1
Origin point.
double desiredSpeed
The desired motion speed in that direction, from 0 up to NavInput::maxRobotSpeed. ...
#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.
void navigate(const NavInput &ni, NavOutput &no) override
Invokes the holonomic navigation algorithm itself.
uint8_t serializeGetVersion() const override
Must return the current versioning number of the object.
mrpt::math::CMatrixD m_dirs_scores
Individual scores for each direction: (i,j), i (row) are directions, j (cols) are scores...
std::string format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
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.
GLenum GLenum GLvoid GLvoid GLvoid * span
GLubyte GLubyte GLubyte a
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
mrpt::nav::CParameterizedTrajectoryGenerator * getAssociatedPTG() const
Returns the pointer set by setAssociatedPTG()
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...
bool LOG_SCORE_MATRIX
(default:false, to save space)
uint16_t alpha2index(double alpha) const
Discrete index value for the corresponding alpha value.
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.