-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathidf_search.rs
475 lines (439 loc) · 15.9 KB
/
idf_search.rs
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
use std::{
fmt::Debug,
sync::{
mpsc::{channel, Receiver, Sender},
Arc,
},
};
use cubing::{
alg::{Alg, AlgNode, Move},
kpuzzle::KPuzzle,
};
use serde::{Deserialize, Serialize};
use crate::_internal::{
canonical_fsm::{
canonical_fsm::{
CanonicalFSM, CanonicalFSMConstructionOptions, CanonicalFSMState,
CANONICAL_FSM_START_STATE,
},
search_generators::SearchGenerators,
},
cli::args::MetricEnum,
errors::SearchError,
puzzle_traits::puzzle_traits::SemiGroupActionPuzzle,
search::pattern_stack::PatternStack,
};
use super::{
super::{
pattern_traversal_filter_trait::PatternTraversalFilter,
prune_table_trait::{Depth, PruneTable},
recursive_work_tracker::RecursiveWorkTracker,
search_logger::SearchLogger,
transformation_traversal_filter_trait::TransformationTraversalFilter,
},
search_adaptations::{DefaultSearchAdaptations, SearchAdaptations},
};
// TODO: right now we return 0 solutions if we blow past this, should we return an explicit error,
// or panic instead?
const MAX_SUPPORTED_SEARCH_DEPTH: Depth = Depth(500); // TODO: increase
// TODO: use https://doc.rust-lang.org/std/ops/enum.ControlFlow.html as a wrapper instead?
#[allow(clippy::enum_variant_names)]
enum SearchRecursionResult {
DoneSearching(),
ContinueSearchingDefault(),
ContinueSearchingExcludingCurrentMoveClass(),
}
struct SolutionPreviousMoves<'a> {
latest_move: &'a Move,
previous_moves: &'a SolutionMoves<'a>,
}
#[derive(Clone)]
struct SolutionMoves<'a>(Option<&'a SolutionPreviousMoves<'a>>);
impl<'a> From<SolutionMoves<'a>> for Alg {
fn from(value: SolutionMoves<'a>) -> Self {
let nodes = value.get_alg_nodes();
Alg { nodes }
}
}
impl SolutionMoves<'_> {
fn get_alg_nodes(&self) -> Vec<AlgNode> {
match self.0 {
Some(solution_previous_moves) => {
let mut nodes = solution_previous_moves.previous_moves.get_alg_nodes();
nodes.push(cubing::alg::AlgNode::MoveNode(
solution_previous_moves.latest_move.clone(),
));
nodes
}
None => vec![],
}
}
}
pub struct SearchSolutions {
receiver: Receiver<Option<Alg>>,
done: bool,
}
impl SearchSolutions {
pub fn construct() -> (Sender<Option<Alg>>, Self) {
// TODO: use `sync_channel` to control resumption?
let (sender, receiver) = channel::<Option<Alg>>();
(
sender,
Self {
receiver,
done: false,
},
)
}
}
impl Iterator for SearchSolutions {
type Item = Alg;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
None
} else {
let received = match self.receiver.recv() {
Ok(received) => received,
Err(_) => {
// TODO: this could be either a channel failure or no solutions found. We should find a way for the latter to avoid hitting this code path.
self.done = true;
return None;
}
};
match received {
Some(alg) => Some(alg),
None => {
self.done = true;
None
}
}
}
}
}
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IndividualSearchOptions {
pub min_num_solutions: Option<usize>,
pub min_depth: Option<Depth>, // inclusive
pub max_depth: Option<Depth>, // exclusive
pub canonical_fsm_pre_moves: Option<Vec<Move>>,
pub canonical_fsm_post_moves: Option<Vec<Move>>,
}
impl IndividualSearchOptions {
pub fn get_min_num_solutions(&self) -> usize {
self.min_num_solutions.unwrap_or(1)
}
pub fn get_min_depth(&self) -> Depth {
self.min_depth.unwrap_or(Depth(0))
}
pub fn get_max_depth(&self) -> Depth {
self.max_depth.unwrap_or(MAX_SUPPORTED_SEARCH_DEPTH)
}
}
struct IndividualSearchData {
individual_search_options: IndividualSearchOptions,
recursive_work_tracker: RecursiveWorkTracker,
num_solutions_sofar: usize,
solution_sender: Sender<Option<Alg>>,
}
pub struct IDFSearchAPIData<TPuzzle: SemiGroupActionPuzzle> {
pub search_generators: SearchGenerators<TPuzzle>,
pub canonical_fsm: CanonicalFSM<TPuzzle>, // TODO: move this into `SearchAdaptations`
pub tpuzzle: TPuzzle,
pub target_pattern: TPuzzle::Pattern,
pub search_logger: Arc<SearchLogger>,
}
/// For information on [`SearchAdaptations`], see the documentation for that trait.
pub struct IDFSearch<
TPuzzle: SemiGroupActionPuzzle + DefaultSearchAdaptations<TPuzzle> = KPuzzle,
Adaptations: SearchAdaptations<TPuzzle> = <TPuzzle as DefaultSearchAdaptations<
TPuzzle,
>>::Adaptations,
> {
pub api_data: Arc<IDFSearchAPIData<TPuzzle>>,
pub prune_table: Adaptations::PruneTable, // TODO: push this into the associated data for the adaptations.
}
pub struct IDFSearchConstructionOptions {
pub search_logger: Arc<SearchLogger>,
pub metric: MetricEnum,
pub random_start: bool,
pub min_prune_table_size: Option<usize>,
pub canonical_fsm_construction_options: CanonicalFSMConstructionOptions,
}
impl Default for IDFSearchConstructionOptions {
fn default() -> Self {
Self {
search_logger: Default::default(),
metric: MetricEnum::Hand,
random_start: Default::default(),
min_prune_table_size: Default::default(),
canonical_fsm_construction_options: Default::default(),
}
}
}
impl<
TPuzzle: SemiGroupActionPuzzle + DefaultSearchAdaptations<TPuzzle>,
Adaptations: SearchAdaptations<TPuzzle>,
> IDFSearch<TPuzzle, Adaptations>
{
pub fn try_new(
tpuzzle: TPuzzle,
generator_moves: Vec<Move>, // TODO: turn this back into `Generators`
target_pattern: TPuzzle::Pattern,
options: IDFSearchConstructionOptions,
) -> Result<Self, SearchError> {
let search_generators = SearchGenerators::try_new(
&tpuzzle,
generator_moves,
&options.metric,
options.random_start,
)?;
let canonical_fsm = CanonicalFSM::try_new(
tpuzzle.clone(),
search_generators.clone(),
options.canonical_fsm_construction_options,
)?; // TODO: avoid a clone
let api_data = Arc::new(IDFSearchAPIData {
search_generators,
canonical_fsm,
tpuzzle: tpuzzle.clone(),
target_pattern,
search_logger: options.search_logger.clone(),
});
let prune_table = Adaptations::PruneTable::new(
tpuzzle,
api_data.clone(),
options.search_logger,
options.min_prune_table_size,
); // TODO: make the prune table reusable across searches.
Ok(Self {
api_data,
prune_table,
})
}
pub fn search(
&mut self,
search_pattern: &TPuzzle::Pattern,
mut individual_search_options: IndividualSearchOptions,
) -> SearchSolutions {
// TODO: do validation more consistently.
if let Some(min_depth) = individual_search_options.min_depth {
if min_depth > MAX_SUPPORTED_SEARCH_DEPTH {
self.api_data
.search_logger
.write_error("Min depth too large, capping at maximum.");
individual_search_options.min_depth = Some(MAX_SUPPORTED_SEARCH_DEPTH);
}
}
if let Some(max_depth) = individual_search_options.max_depth {
if max_depth > MAX_SUPPORTED_SEARCH_DEPTH {
self.api_data
.search_logger
.write_error("Max depth too large, capping at maximum.");
individual_search_options.max_depth = Some(MAX_SUPPORTED_SEARCH_DEPTH);
}
}
let (solution_sender, search_solutions) = SearchSolutions::construct();
let mut individual_search_data = IndividualSearchData {
individual_search_options,
recursive_work_tracker: RecursiveWorkTracker::new(
"Search".to_owned(),
self.api_data.search_logger.clone(),
),
num_solutions_sofar: 0,
solution_sender,
};
let search_pattern = search_pattern.clone();
// TODO: combine `KPatternStack` with `SolutionMoves`?
let mut pattern_stack = PatternStack::new(self.api_data.tpuzzle.clone(), search_pattern);
for remaining_depth in *individual_search_data
.individual_search_options
.get_min_depth()
..*individual_search_data
.individual_search_options
.get_max_depth()
{
let remaining_depth = Depth(remaining_depth);
self.api_data.search_logger.write_info("----------------");
self.prune_table.extend_for_search_depth(
remaining_depth,
individual_search_data
.recursive_work_tracker
.estimate_next_level_num_recursive_calls(),
);
individual_search_data
.recursive_work_tracker
.start_depth(remaining_depth, Some("Starting search…"));
let initial_state = self
.apply_optional_fsm_moves(
CANONICAL_FSM_START_STATE,
&individual_search_data
.individual_search_options
.canonical_fsm_pre_moves,
)
.expect("TODO: invalid canonical FSM pre-moves.");
let recursion_result = self.recurse(
&mut individual_search_data,
&mut pattern_stack,
initial_state,
remaining_depth,
SolutionMoves(None),
);
individual_search_data
.recursive_work_tracker
.finish_latest_depth();
if let SearchRecursionResult::DoneSearching() = recursion_result {
break;
}
}
search_solutions
}
fn recurse(
&self,
individual_search_data: &mut IndividualSearchData,
pattern_stack: &mut PatternStack<TPuzzle>,
current_state: CanonicalFSMState,
remaining_depth: Depth,
solution_moves: SolutionMoves,
) -> SearchRecursionResult {
let current_pattern = pattern_stack.current_pattern();
// TODO: apply invalid checks only to intermediate state (i.e. exclude remaining_depth == 0)?
if !Adaptations::PatternTraversalFilter::is_valid(current_pattern) {
return SearchRecursionResult::ContinueSearchingDefault();
}
individual_search_data
.recursive_work_tracker
.record_recursive_call();
if remaining_depth == Depth(0) {
return self.base_case(
individual_search_data,
current_pattern,
current_state,
solution_moves,
);
}
let prune_table_depth = self.prune_table.lookup(current_pattern);
if prune_table_depth > remaining_depth + Depth(1) {
return SearchRecursionResult::ContinueSearchingExcludingCurrentMoveClass();
}
if prune_table_depth > remaining_depth {
return SearchRecursionResult::ContinueSearchingDefault();
}
for (move_class_index, move_transformation_multiples) in
self.api_data.search_generators.by_move_class.iter()
{
let Some(next_state) = self
.api_data
.canonical_fsm
.next_state(current_state, move_class_index)
else {
continue;
};
for move_transformation_info in move_transformation_multiples {
if !Adaptations::TransformationTraversalFilter::keep_move(
move_transformation_info,
remaining_depth,
) {
continue;
}
if !pattern_stack.push(&move_transformation_info.transformation) {
continue;
}
let recursive_result = self.recurse(
individual_search_data,
pattern_stack,
next_state,
remaining_depth - Depth(1),
SolutionMoves(Some(&SolutionPreviousMoves {
latest_move: &move_transformation_info.r#move,
previous_moves: &solution_moves,
})),
);
pattern_stack.pop();
match recursive_result {
SearchRecursionResult::DoneSearching() => {
return SearchRecursionResult::DoneSearching();
}
SearchRecursionResult::ContinueSearchingDefault() => {}
SearchRecursionResult::ContinueSearchingExcludingCurrentMoveClass() => {
break;
}
}
}
}
SearchRecursionResult::ContinueSearchingDefault()
}
// Returns `None` if the moves cannot be applied, else returns the result of applying the moves.
fn apply_optional_fsm_moves(
&self,
start_state: CanonicalFSMState,
moves: &Option<Vec<Move>>,
) -> Option<CanonicalFSMState> {
let mut current_state = start_state;
if let Some(moves) = moves {
for r#move in moves {
let move_class_index = self
.api_data
.search_generators
.by_move
.get(r#move)
.expect("move!")
.move_class_index;
current_state = match self
.api_data
.canonical_fsm
.next_state(current_state, move_class_index)
{
Some(next_state) => next_state,
None => return None,
}
}
}
Some(current_state)
}
fn base_case(
&self,
individual_search_data: &mut IndividualSearchData,
current_pattern: &TPuzzle::Pattern,
current_state: CanonicalFSMState,
solution_moves: SolutionMoves,
) -> SearchRecursionResult {
if current_pattern != &self.api_data.target_pattern {
return SearchRecursionResult::ContinueSearchingDefault();
}
if self
.apply_optional_fsm_moves(
current_state,
&individual_search_data
.individual_search_options
.canonical_fsm_post_moves,
)
.is_none()
{
self.api_data.search_logger.write_info(&format!(
"Rejecting potential solution for invalid end moves: {}",
Alg::from(solution_moves)
));
return SearchRecursionResult::ContinueSearchingDefault();
}
let alg = Alg::from(solution_moves);
individual_search_data.num_solutions_sofar += 1;
individual_search_data
.solution_sender
.send(Some(alg))
.expect("Internal error: could not send solution");
if individual_search_data.num_solutions_sofar
>= individual_search_data
.individual_search_options
.get_min_num_solutions()
{
individual_search_data
.solution_sender
.send(None)
.expect("Internal error: could not send end of search");
SearchRecursionResult::DoneSearching()
} else {
SearchRecursionResult::ContinueSearchingDefault()
}
}
}