-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathState_Search_IDA_Star.H
More file actions
486 lines (415 loc) · 16.5 KB
/
State_Search_IDA_Star.H
File metadata and controls
486 lines (415 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/*
Aleph_w
Data structures & Algorithms
version 2.0.0b
https://github.com/lrleon/Aleph-w
This file is part of Aleph-w library
Copyright (c) 2002-2026 Leandro Rabindranath Leon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/** @file State_Search_IDA_Star.H
* @brief IDA* (Iterative Deepening A*) over implicit state spaces.
*
* IDA* combines the memory efficiency of DFS with the optimality guarantee of
* A* for admissible heuristics. Each iteration performs a depth-limited DFS
* that prunes branches whose estimated total cost f = g + h exceeds the
* current threshold. The threshold is set to the minimum f-value that
* exceeded the limit in the previous pass. The process repeats until a goal
* is found or the space is exhausted.
*
* The domain contract is given by @ref Aleph::IDAStarDomain, which extends
* @ref Aleph::BacktrackingDomain with @ref Aleph::HeuristicEvaluator and
* @ref Aleph::ActionCostProvider. Admissibility requires `heuristic(state) <= true
* cost to goal` for all states.
*
* @author Leandro Rabindranath León
*/
# ifndef STATE_SEARCH_IDA_STAR_H
# define STATE_SEARCH_IDA_STAR_H
#include <limits>
#include <type_traits>
#include <utility>
#include <ah-errors.H>
#include <state_search_common.H>
#include <Backtracking.H>
namespace Aleph {
/** @brief Minimal contract for IDA* domains.
*
* Extends @ref Aleph::BacktrackingDomain with:
*
* - `heuristic(state)` — admissible cost estimate to the nearest goal,
* - `cost(state, move)` — non-negative step cost.
*
* Both must expose a `Distance` type (numeric, typically `int` or `double`).
* The heuristic must be admissible (never overestimates the true cost) for
* IDA\* to return an optimal solution.
*/
template <typename Domain>
concept IDAStarDomain
= BacktrackingDomain<Domain> and HeuristicEvaluator<Domain> and ActionCostProvider<Domain>;
/** @brief Result of one threshold pass of IDA*.
*
* Each pass is a depth-limited DFS with a fixed f-cost threshold. This struct
* records how many states were visited, whether a solution was found and what
* the next threshold should be.
*
* @tparam Distance numeric cost type from the domain.
*/
template <typename Distance>
struct IDAStarIteration
{
Distance threshold = Distance{}; ///< F-cost threshold used for this pass.
size_t visited_states = 0; ///< States visited during this pass.
bool found_solution = false; ///< True if a goal was reached at or below threshold.
Distance next_threshold = Distance{}; ///< Minimum f-value that exceeded `threshold`.
};
/** @brief Aggregated result of a complete IDA* run.
*
* Extends @ref SearchResult with per-iteration data and the total optimal
* cost once a solution is found.
*
* @tparam Solution solution snapshot type (see @ref SearchSolution).
* @tparam Distance numeric cost type from the domain.
*/
template <typename Solution, typename Distance>
struct IDAStarResult : SearchResult<Solution>
{
using Base = SearchResult<Solution>;
using Distance_Type = Distance;
Distance total_cost = Distance{}; ///< Optimal path cost (valid when found_solution()).
Array<IDAStarIteration<Distance>> iterations; ///< One entry per completed threshold pass.
IDAStarResult() = default;
};
namespace ida_star_detail {
/** @brief Sentinel value representing an unreachable or pruned f-cost.
*
* For floating-point `Distance` types returns `infinity()`, which is well
* above any finite heuristic value and compares correctly with admissible
* heuristics that may themselves return `infinity()`. For integer types,
* where `infinity()` is not defined, returns `max()` instead.
*
* @tparam Distance Numeric cost type from the domain.
*/
template <typename Distance>
[[nodiscard]] constexpr Distance distance_unreachable() noexcept
{
if constexpr (std::is_floating_point_v<Distance>)
return std::numeric_limits<Distance>::infinity();
else
return std::numeric_limits<Distance>::max();
}
/** @brief Outcome of one recursive DFS step inside IDA*. */
template <typename Distance>
struct DFSResult
{
bool found = false;
Distance next_bound = distance_unreachable<Distance>();
};
/** @brief Core recursive DFS used by IDA* for a single threshold pass.
*
* Returns `found = true` immediately when a goal is reached. Otherwise
* propagates the minimum f-value that exceeded `threshold` upward so the
* caller can set the next iteration's threshold.
*/
template <IDAStarDomain Domain, typename Solution, typename OnSolution>
requires SearchSolutionVisitor<OnSolution, Solution>
DFSResult<typename Domain::Distance> dfs(Domain &domain,
typename Domain::State &state,
SearchPath<typename Domain::Move> &path,
const typename Domain::Distance g,
const typename Domain::Distance threshold,
const size_t depth,
IDAStarResult<Solution, typename Domain::Distance> &result,
OnSolution &on_solution)
{
using Distance = typename Domain::Distance;
++result.stats.visited_states;
if (depth > result.stats.max_depth_reached)
result.stats.max_depth_reached = depth;
const Distance h = domain.heuristic(state);
const Distance f = g + h;
if (f > threshold)
return {false, f};
if (domain.is_goal(state))
{
++result.stats.solutions_found;
Solution solution{state, path, depth};
if (result.best_solution.consider(solution))
result.total_cost = g;
const bool keep_searching = on_solution(solution);
if (not keep_searching)
result.status = SearchStatus::StoppedOnSolution;
return {true, threshold};
}
if (search_engine_detail::is_terminal_state(domain, state))
{
++result.stats.terminal_states;
return {false, distance_unreachable<Distance>()};
}
if (search_engine_detail::should_prune_state(domain, state, depth))
{
++result.stats.pruned_by_domain;
return {false, distance_unreachable<Distance>()};
}
if (depth >= result.limits.max_depth)
{
++result.stats.pruned_by_depth;
return {false, distance_unreachable<Distance>()};
}
if (result.stats.expanded_states >= result.limits.max_expansions)
{
++result.stats.limit_hits;
result.status = SearchStatus::LimitReached;
return {false, distance_unreachable<Distance>()};
}
++result.stats.expanded_states;
using Move = typename Domain::Move;
DFSResult<Distance> out{false, distance_unreachable<Distance>()};
(void) domain.for_each_successor(state,
[&](const Move &move) -> bool
{
if (result.status == SearchStatus::LimitReached
or result.status == SearchStatus::StoppedOnSolution)
return false;
++result.stats.generated_successors;
const Distance step = domain.cost(state, move);
bool applied = false;
bool path_appended = false;
DFSResult<Distance> child;
try
{
domain.apply(state, move);
applied = true;
path.append(move);
path_appended = true;
child = dfs(domain, state, path, g + step, threshold, depth + 1, result, on_solution);
}
catch (...)
{
if (path_appended)
(void) path.remove_last();
if (applied)
domain.undo(state, move);
throw;
}
(void) path.remove_last();
domain.undo(state, move);
if (child.found)
{
out.found = true;
return false;
}
if (result.status == SearchStatus::LimitReached
or result.status == SearchStatus::StoppedOnSolution)
return false;
if (child.next_bound < out.next_bound)
out.next_bound = child.next_bound;
return true;
});
return out;
}
} // end namespace ida_star_detail
/** @brief IDA* engine for implicit state spaces with an admissible heuristic.
*
* The engine performs iterative threshold-bounded DFS. Each pass prunes
* branches whose estimated total cost f = g + h exceeds the current
* threshold. The threshold advances to the minimum cost that exceeded it in
* the previous pass.
*
* ### Optimality
* With an admissible heuristic, IDA\* guarantees an optimal solution. The
* path returned in `result.best_solution.get().path` reaches the goal in
* exactly `result.total_cost` cost.
*
* ### Memory
* Only the current path from root to the node under expansion is stored
* (one `SearchPath` of depth at most `max_depth`). No open/closed lists.
*
* @tparam Domain problem adapter satisfying @ref Aleph::IDAStarDomain.
*/
template <IDAStarDomain Domain>
class IDA_Star_State_Search
{
public:
/// Type of the problem domain.
using Domain_Type = Domain;
/// Concrete search state type.
using State = typename Domain::State;
/// Move type.
using Move = typename Domain::Move;
/// Numeric distance/cost type.
using Distance = typename Domain::Distance;
/// Solution type containing state and path.
using Solution = SearchSolution<State, Move>;
/// Aggregated result type for IDA* search.
using Result = IDAStarResult<Solution, Distance>;
/** @brief Compile-time marker: IDA_Star_State_Search only supports
* Depth_First strategy.
*
* Passing `ExplorationPolicy::Strategy::Best_First` to this engine raises
* `std::invalid_argument` at runtime. Check this constant before
* constructing a policy to detect the mismatch at compile time.
*/
static constexpr bool supports_best_first = false;
/** @brief Construct an engine bound to one domain adapter.
* @param domain Problem adapter.
* @param policy Exploration settings.
* @param limits Resource constraints.
*/
explicit IDA_Star_State_Search(Domain domain, ExplorationPolicy policy = {},
const SearchLimits &limits = {})
: domain_(std::move(domain)), policy_(policy), limits_(limits)
{
// empty
}
/** @brief Read-only access to the bound domain adapter. */
[[nodiscard]] const Domain &domain() const noexcept
{
return domain_;
}
/** @brief Mutable access to the bound domain adapter. */
[[nodiscard]] Domain &domain() noexcept
{
return domain_;
}
/** @brief Current exploration policy. */
[[nodiscard]] const ExplorationPolicy &policy() const noexcept
{
return policy_;
}
/** @brief Current hard limits. */
[[nodiscard]] const SearchLimits &limits() const noexcept
{
return limits_;
}
/** @brief Replace the exploration policy for future runs. */
void set_policy(const ExplorationPolicy &policy) noexcept
{
policy_ = policy;
}
/** @brief Replace the hard limits for future runs. */
void set_limits(const SearchLimits &limits) noexcept
{
limits_ = limits;
}
/** @brief Run IDA* from `initial_state`.
*
* Iterates threshold passes until a goal is found, the space is exhausted
* or a hard limit is reached.
*
* @param[in] initial_state Root state to expand. Mutated during search and
* restored to its original value before this function returns.
* @return @ref IDAStarResult with solution, stats and per-iteration data.
*
* @throws std::invalid_argument if the policy requests Best_First strategy
* (IDA\* is DFS-only) or if max_solutions is zero.
* @note @p max_depth in @ref SearchLimits limits the depth of each pass.
*/
[[nodiscard]] Result search(State initial_state)
{
ContinueSearch on_solution;
return search(std::move(initial_state), on_solution);
}
/** @brief Run IDA* and invoke `on_solution` when the goal is reached.
*
* The callback receives a solution snapshot and returns `true` to allow the
* search to continue according to the exploration policy and limits, or
* `false` to stop immediately. IDA\* is typically used with
* stop-at-first-solution. This implementation stops at the first goal
* reached within each threshold pass; with non-negative step costs and an
* admissible heuristic the first solution encountered is already optimal,
* so raising the threshold in later passes cannot produce a cheaper
* solution, only potentially explore alternative states subject to the
* configured limits.
*/
template <typename OnSolution>
requires SearchSolutionVisitor<OnSolution, Solution>
[[nodiscard]] Result search(State initial_state, OnSolution &on_solution)
{
ah_invalid_argument_if(policy_.strategy != ExplorationPolicy::Strategy::Depth_First)
<< "IDA_Star_State_Search only supports depth-first strategy";
ah_invalid_argument_if(limits_.max_solutions == 0)
<< "SearchLimits::max_solutions must be positive or Search_Unlimited";
Result result;
result.policy = policy_;
result.limits = limits_;
const auto start_time = SearchClock::now();
SearchPath<Move> path;
reserve_search_path(path, limits_);
Distance threshold = domain_.heuristic(initial_state);
for (;;)
{
IDAStarIteration<Distance> iteration;
iteration.threshold = threshold;
const size_t stats_before = result.stats.visited_states;
auto [found, next_bound] = ida_star_detail::dfs(
domain_, initial_state, path, Distance{}, threshold, 0, result, on_solution);
iteration.visited_states = result.stats.visited_states - stats_before;
iteration.found_solution = found;
iteration.next_threshold = found ? threshold : next_bound;
result.iterations.append(iteration);
if (result.status == SearchStatus::StoppedOnSolution)
break;
if (found)
{
if (result.status != SearchStatus::LimitReached)
result.status = SearchStatus::StoppedOnSolution;
break;
}
if (result.status == SearchStatus::LimitReached)
break;
if (next_bound >= ida_star_detail::distance_unreachable<Distance>())
{
result.status = SearchStatus::Exhausted;
break;
}
threshold = next_bound;
}
if (result.status == SearchStatus::NotStarted)
result.status = SearchStatus::Exhausted;
result.stats.elapsed_ms = search_elapsed_ms(SearchClock::now() - start_time);
return result;
}
private:
Domain domain_;
ExplorationPolicy policy_;
SearchLimits limits_;
};
/** @brief Convenience wrapper for a one-shot IDA* search. */
template <IDAStarDomain Domain>
[[nodiscard]] auto ida_star_search(Domain domain,
typename Domain::State initial_state,
ExplorationPolicy policy = {},
SearchLimits limits = {})
{
IDA_Star_State_Search<Domain> engine(std::move(domain), policy, limits);
return engine.search(std::move(initial_state));
}
/** @brief Convenience wrapper for IDA* with a solution callback. */
template <IDAStarDomain Domain, typename OnSolution>
requires SearchSolutionVisitor<OnSolution, SearchSolution<typename Domain::State, typename Domain::Move>>
[[nodiscard]] auto ida_star_search(Domain domain,
typename Domain::State initial_state,
OnSolution &on_solution,
ExplorationPolicy policy = {},
SearchLimits limits = {})
{
IDA_Star_State_Search<Domain> engine(std::move(domain), policy, limits);
return engine.search(std::move(initial_state), on_solution);
}
} // end namespace Aleph
# endif // STATE_SEARCH_IDA_STAR_H