Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
state_search_common.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
49# ifndef STATE_SEARCH_COMMON_H
50# define STATE_SEARCH_COMMON_H
51
52#include <chrono>
53#include <concepts>
54#include <cstddef>
55#include <limits>
56#include <optional>
57#include <type_traits>
58#include <utility>
59
60#include <ah-concepts.H>
61#include <ah-errors.H>
62#include <htlist.H>
64#include <tpl_array.H>
65#include <tpl_hash.H>
66
67namespace Aleph {
68
70inline constexpr size_t Search_Unlimited = std::numeric_limits<size_t>::max();
71
80
87template <typename T>
88concept SearchState = std::movable<T> and std::copy_constructible<T>;
89
98template <typename T>
99concept SearchMove = Aleph::ArrayStorable<T> and std::copyable<T>;
100
102template <SearchMove Move>
104
105using SearchClock = std::chrono::steady_clock;
106
107[[nodiscard]] inline double search_elapsed_ms(const SearchClock::duration &duration) noexcept
108{
109 return std::chrono::duration<double, std::milli>(duration).count();
110}
111
119template <typename Key,
120 typename Data,
121 template <typename, typename, class> class HashMapTable = MapOLhash,
124
131template <typename Key,
132 template <typename, class> class HashSetTable = OLhashTable,
135
145template <typename Set, typename Key>
146concept VisitedStateSet = requires(Set &set, const Key &key) {
147 { set.contains(key) } -> std::convertible_to<bool>;
148 set.insert(key);
149};
150
165template <typename Map, typename Key, typename Objective>
166concept VisitedBoundMap = requires(Map &map, const Key &key, const Objective &obj) {
167 map.insert(key, obj);
168 map.remove(key);
169 { map.search(key) == nullptr } -> std::convertible_to<bool>;
170 map.search(key)->second = obj;
171};
172
193template <typename Domain>
195 requires(Domain &domain,
196 const typename Domain::State &state,
197 const typename Domain::Move &move) {
198 { domain.bound_after(state, move) }
199 -> std::convertible_to<typename Domain::Objective>;
200 };
201
218template <typename Domain>
220 requires(Domain &domain,
221 const typename Domain::State &state,
222 const typename Domain::Move &move) {
223 { domain.evaluate_after(state, move) }
224 -> std::convertible_to<typename Domain::Score>;
225 };
226
245template <typename Engine>
246concept SupportsBestFirst = Engine::supports_best_first;
247
264
278
279template <SearchMove Move>
280inline void reserve_search_path(SearchPath<Move> &path, const SearchLimits &limits)
281{
282 if (limits.max_depth != Search_Unlimited)
283 path.reserve(limits.max_depth + 1);
284}
285
318
328template <SearchState State, SearchMove Move>
330{
331 State state;
333 size_t depth = 0;
334};
335
343template <typename Solution>
345{
346 bool operator()(const Solution &, const Solution &) const noexcept
347 {
348 return false;
349 }
350};
351
354{
360 template <typename Solution>
361 bool operator()(const Solution &) const noexcept
362 {
363 return true;
364 }
365};
366
372template <typename Visitor, typename Solution>
373concept SearchSolutionVisitor = requires(Visitor &visitor, const Solution &solution) {
374 { visitor(solution) } -> std::convertible_to<bool>;
375};
376
385template <typename Solution>
387{
388public:
390 using Solution_Type = Solution;
393
396
400 explicit SearchSolutionCollector(const size_t max_solutions) : limit_(max_solutions)
401 {
403 << "SearchSolutionCollector: max_solutions must be positive";
404 }
405
411
423 : solutions_(std::move(other.solutions_)), count_(std::exchange(other.count_, 0)),
424 limit_(other.limit_)
425 {}
426
433
441 {
442 swap(other);
443 return *this;
444 }
445
450 void swap(SearchSolutionCollector &other) noexcept
451 {
452 solutions_.swap(other.solutions_);
453 std::swap(count_, other.count_);
454 std::swap(limit_, other.limit_);
455 }
456
458 bool operator()(const Solution &solution)
459 {
460 solutions_.append(solution);
461 ++count_;
462 return count_ < limit_;
463 }
464
466 void clear() noexcept
467 {
469 count_ = 0;
470 }
471
473 [[nodiscard]] size_t size() const noexcept
474 {
475 return count_;
476 }
477
479 [[nodiscard]] bool is_empty() const noexcept
480 {
481 return count_ == 0;
482 }
483
485 [[nodiscard]] const Container_Type &solutions() const noexcept
486 {
487 return solutions_;
488 }
489
491 [[nodiscard]] Container_Type &solutions() noexcept
492 {
493 return solutions_;
494 }
495
496private:
498 size_t count_ = 0;
500};
501
510template <typename Solution, typename Compare = KeepFirstSolution<Solution>>
513{
514public:
516 using Solution_Type = Solution;
518 using Compare_Type = Compare;
519
521 BestSolution() = default;
522
526 explicit BestSolution(Compare compare) : compare_(std::move(compare))
527 {
528 // empty
529 }
530
532 [[nodiscard]] bool has_value() const noexcept
533 {
534 return current_.has_value();
535 }
536
538 void clear() noexcept
539 {
540 current_.reset();
541 }
542
546 [[nodiscard]] const Solution &get() const
547 {
549 << "BestSolution::get: no incumbent solution available";
550 return *current_;
551 }
552
556 [[nodiscard]] Solution &get()
557 {
559 << "BestSolution::get: no incumbent solution available";
560 return *current_;
561 }
562
564 [[nodiscard]] const Compare &compare() const noexcept
565 {
566 return compare_;
567 }
568
572 bool consider(const Solution &candidate)
573 {
574 if (not current_.has_value() or compare_(candidate, *current_))
575 {
576 current_ = candidate;
577 return true;
578 }
579
580 return false;
581 }
582
586 bool consider(Solution &&candidate)
587 {
588 if (not current_.has_value() or compare_(candidate, *current_))
589 {
590 current_ = std::move(candidate);
591 return true;
592 }
593
594 return false;
595 }
596
597private:
598 Compare compare_ = {};
599 std::optional<Solution> current_;
600};
601
603template <typename Solution, typename Compare = KeepFirstSolution<Solution>>
605
614template <typename Domain>
615concept SuccessorGenerator = requires(Domain &d, const typename Domain::State &state) {
616 typename Domain::State;
617 typename Domain::Move;
620 {
621 d.for_each_successor(state,
622 [](const typename Domain::Move &) -> bool
623 {
624 return true;
625 })
626 } -> std::convertible_to<bool>;
627};
628
644template <typename Domain>
645concept GoalPredicate = requires(Domain &d, const typename Domain::State &state) {
646 { d.is_goal(state) } -> std::convertible_to<bool>;
647};
648
650template <typename Domain>
651concept TerminalPredicate = requires(const Domain &d, const typename Domain::State &state) {
652 { d.is_terminal(state) } -> std::convertible_to<bool>;
653};
654
661template <typename Domain>
662concept DomainPruner = requires(Domain &d, const typename Domain::State &state, const size_t depth) {
663 { d.should_prune(state, depth) } -> std::convertible_to<bool>;
664};
665
667template <typename Domain>
668concept MoveKeyProvider = requires(Domain &d, const typename Domain::Move &move) {
669 typename Domain::Move_Key;
670 { d.move_key(move) } -> std::convertible_to<typename Domain::Move_Key>;
671};
672
677template <typename Provider>
678concept SearchStateKeyProvider = requires(const Provider &provider, const typename Provider::State &state) {
679 typename Provider::State_Key;
680 { provider.state_key(state) } -> std::convertible_to<typename Provider::State_Key>;
681};
682
689template <typename Domain>
690concept HeuristicEvaluator = requires(Domain &d, const typename Domain::State &state) {
691 typename Domain::Distance;
692 { d.heuristic(state) } -> std::convertible_to<typename Domain::Distance>;
693};
694
700template <typename Domain>
702 = requires(Domain &d, const typename Domain::State &state, const typename Domain::Move &move) {
703 typename Domain::Distance;
704 { d.cost(state, move) } -> std::convertible_to<typename Domain::Distance>;
705 };
706
718template <typename Domain>
721and requires(Domain &d, typename Domain::State &state, const typename Domain::Move &move) {
722 { d.apply(state, move) } -> std::same_as<void>;
723 { d.undo(state, move) } -> std::same_as<void>;
724 };
725
731template <typename Solution, typename Compare = KeepFirstSolution<Solution>>
734{
736 using Solution_Type = Solution;
738 using Compare_Type = Compare;
741
747
749 SearchResult() = default;
750
754 explicit SearchResult(Compare compare) : best_solution(std::move(compare))
755 {
756 // empty
757 }
758
760 [[nodiscard]] bool found_solution() const noexcept
761 {
762 return best_solution.has_value();
763 }
764
766 [[nodiscard]] bool exhausted() const noexcept
767 {
769 }
770
772 [[nodiscard]] bool stopped_on_solution() const noexcept
773 {
775 }
776
778 [[nodiscard]] bool limit_reached() const noexcept
779 {
781 }
782};
783
791namespace search_engine_detail {
792
803template <typename Domain>
804[[nodiscard]] bool is_terminal_state(const Domain &domain,
805 const typename Domain::State &state)
806{
807 if constexpr (TerminalPredicate<Domain>)
808 return domain.is_terminal(state);
809 else
810 return false;
811}
812
824template <typename Domain>
825[[nodiscard]] bool should_prune_state(Domain &domain,
826 const typename Domain::State &state,
827 const size_t depth)
828{
829 if constexpr (DomainPruner<Domain>)
830 return domain.should_prune(state, depth);
831 else
832 return false;
833}
834
843template <typename Result>
844void register_visit(const size_t depth, Result &result)
845{
846 ++result.stats.visited_states;
847 if (depth > result.stats.max_depth_reached)
848 result.stats.max_depth_reached = depth;
849}
850
863template <typename Result>
864[[nodiscard]] bool expansion_limit_reached(Result &result, const SearchLimits &limits)
865{
866 if (result.stats.expanded_states >= limits.max_expansions)
867 {
868 ++result.stats.limit_hits;
869 result.status = SearchStatus::LimitReached;
870 return true;
871 }
872
873 return false;
874}
875
896template <typename Result>
897[[nodiscard]] bool stop_after_solution(Result &result,
898 const ExplorationPolicy &policy,
899 const SearchLimits &limits)
900{
901 if (limits.max_solutions != Search_Unlimited
902 and result.stats.solutions_found >= limits.max_solutions)
903 {
904 ++result.stats.limit_hits;
905 result.status = SearchStatus::LimitReached;
906 return true;
907 }
908
909 if (policy.stop_at_first_solution)
910 {
911 result.status = SearchStatus::StoppedOnSolution;
912 return true;
913 }
914
915 return false;
916}
917
918} // end namespace search_engine_detail
919
920} // end namespace Aleph
921
922# endif // STATE_SEARCH_COMMON_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
Definition ah-errors.H:399
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
Tracks the best solution seen so far according to a comparator.
bool has_value() const noexcept
Return true if an incumbent exists.
Solution & get()
Mutable access to the current incumbent.
std::optional< Solution > current_
Compare Compare_Type
Type of the comparison policy.
bool consider(Solution &&candidate)
Consider a candidate by move.
const Compare & compare() const noexcept
Access the ordering functor used by this incumbent.
void clear() noexcept
Remove the stored incumbent, if any.
BestSolution(Compare compare)
Build a tracker with a custom comparator.
bool consider(const Solution &candidate)
Consider a candidate by copy.
BestSolution()=default
Build an empty incumbent tracker.
const Solution & get() const
Read the current incumbent.
Solution Solution_Type
Type of stored solutions.
T & append(const T &item)
Definition htlist.H:1362
void empty() noexcept
empty the list
Definition htlist.H:1576
DynList & swap(DynList &l) noexcept
Definition htlist.H:1253
Open addressing hash table with linear probing collision resolution.
Definition tpl_olhash.H:175
Collector that stores accepted solutions in an Aleph list.
SearchSolutionCollector & operator=(const SearchSolutionCollector &other)=default
Copy the solutions and the limit of another collector.
bool operator()(const Solution &solution)
Append one solution and report whether enumeration should continue.
Container_Type & solutions() noexcept
Mutable access to the collected solutions.
size_t size() const noexcept
Number of collected solutions.
const Container_Type & solutions() const noexcept
Access the collected solutions.
void swap(SearchSolutionCollector &other) noexcept
Exchange in O(1) the solutions and the limits of this collector and another.
SearchSolutionCollector(const SearchSolutionCollector &other)=default
Copy the solutions and the limit of another collector.
bool is_empty() const noexcept
Return true if no solution has been collected.
SearchSolutionCollector(const size_t max_solutions)
Build a collector that stops after max_solutions.
void clear() noexcept
Remove all collected solutions.
SearchSolutionCollector(SearchSolutionCollector &&other) noexcept
Take the solutions of another collector, which is left empty, with the same limit.
Solution Solution_Type
Type of collected solutions.
SearchSolutionCollector & operator=(SearchSolutionCollector &&other) noexcept
Exchange this collector with another, which is left with the previous solutions and limit of this one...
SearchSolutionCollector()=default
Build a collector with no limit.
Concept for domains that provide the cost of applying a move.
An element type the Aleph arrays can store.
Minimal contract for DFS/backtracking domains.
A callable that takes two const T& and returns bool.
Optional concept for domain-side pruning hooks.
Concept for domains that can recognize goal states.
Concept for domains that provide an admissible heuristic.
Concept for domains that can estimate a move's bound without modifying state (incremental bound for B...
Concept for adversarial-search domains that can estimate a child score without modifying state (incre...
Optional concept for domains that can key moves for history heuristics.
Minimal requirement for search moves.
Concept for callbacks invoked on each accepted solution.
Generic concept for domains that can expose a stable state key.
Minimal requirement for mutable search states.
Concept for lazy successor generation.
Concept that checks whether a search engine supports the Best_First exploration strategy at compile t...
Optional concept for explicit non-solution terminal states.
Concept for a map tracking the best bound seen per visited state.
Concept for a set suitable for tracking globally visited states.
Singly linked list implementations with head-tail access.
bool should_prune_state(Domain &domain, const typename Domain::State &state, const size_t depth)
Dispatch helper for the optional should_prune hook.
bool is_terminal_state(const Domain &domain, const typename Domain::State &state)
Dispatch helper for the optional is_terminal hook.
bool stop_after_solution(Result &result, const ExplorationPolicy &policy, const SearchLimits &limits)
Decide whether to stop the search after a solution was accepted.
void register_visit(const size_t depth, Result &result)
Update visit counters and max-depth statistic.
bool expansion_limit_reached(Result &result, const SearchLimits &limits)
Check whether the expansion limit has been reached.
Main namespace for Aleph-w library functions.
std::chrono::steady_clock SearchClock
Monotonic clock used for search timings.
constexpr size_t Search_Unlimited
Sentinel used by SearchLimits to mean "no bound".
SearchStatus
Final state of a search execution.
@ LimitReached
Search stopped because an external hard limit was hit.
@ Exhausted
Search space within the configured bounds was exhausted.
@ StoppedOnSolution
Search stopped because solution handling requested it.
@ NotStarted
Search object exists but no traversal has run yet.
void reserve_search_path(SearchPath< Move > &path, const SearchLimits &limits)
and
Check uniqueness with explicit hash + equality functors.
double search_elapsed_ms(const SearchClock::duration &duration) noexcept
MoveOrderingMode
Built-in move-ordering modes supported by the framework.
@ Domain
Preserve the order emitted by for_each_successor().
STL namespace.
Shared support for configurable successor ordering heuristics.
Default solution visitor that always continues the search.
bool operator()(const Solution &) const noexcept
Accepts any solution and returns true.
Exploration controls shared across engines.
bool stop_at_first_solution
Stop when the first goal is found.
Strategy strategy
Traversal strategy.
MoveOrderingMode move_ordering
Successor-ordering mode.
Strategy
Traversal strategy supported by the engine.
@ Best_First
Priority-guided expansion; only supported by Branch_And_Bound.
@ Depth_First
Recursive depth-first traversal (all engines).
bool use_history_heuristic
Enable experimental history heuristic where supported.
bool use_killer_moves
Enable experimental killer heuristic where supported.
Comparison policy that keeps the first solution seen.
bool operator()(const Solution &, const Solution &) const noexcept
Open addressing hash map using linear probing.
Statistics collected by engines that reorder successor batches.
Hard bounds applied by the search engine.
size_t max_expansions
Maximum expanded states.
size_t max_solutions
Maximum accepted solutions.
size_t max_depth
Maximum expansion depth.
Aggregates the outcome of one search execution.
bool limit_reached() const noexcept
Return true if a hard search limit stopped the traversal.
SearchStats stats
Statistics collected during the run.
bool found_solution() const noexcept
Return true if at least one solution was retained.
bool stopped_on_solution() const noexcept
Return true if search stopped because solution handling requested it.
ExplorationPolicy policy
Exploration policy used for the run.
Solution Solution_Type
Type of solutions in this result.
SearchResult()=default
Build an empty result.
Compare Compare_Type
Type of the comparison policy.
bool exhausted() const noexcept
Return true if the search exhausted the configured region.
SearchLimits limits
Limits used for the run.
SearchStatus status
Final execution state.
Incumbent_Type best_solution
Best incumbent retained by the engine.
SearchResult(Compare compare)
Build a result with a specific solution comparator.
Snapshot of a concrete solution encountered during the traversal.
SearchPath< Move > path
Move sequence leading to state.
State state
Snapshot of the terminal state.
size_t depth
Path depth of the solution.
Counters collected during a search run.
size_t limit_hits
Number of hard-limit stops triggered.
size_t pruned_by_visited
States skipped because already seen (visited-set duplicate suppression).
size_t pruned_by_domain
States discarded by domain-side pruning.
size_t terminal_states
Non-solution terminal states cut by the domain.
double elapsed_ms
Wall-clock time spent inside the search call.
MoveOrderingStats move_ordering
Successor-ordering activity for this run.
size_t pruned_by_depth
States not expanded due to max depth.
size_t generated_successors
Number of successor moves emitted.
size_t max_depth_reached
Deepest path depth visited.
size_t solutions_found
Number of goal states accepted.
size_t expanded_states
Number of non-terminal states expanded.
size_t visited_states
Number of states entered by the engine.
Dynamic array container with automatic resizing.
Unified hash table interface.