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
//! The explicit search space ([`SearchSpace`]): every state seen so far, its best known path
//! cost and its parent link, for duplicate detection and solution extraction.
use alloc::vec::Vec;
use core::hash::{BuildHasher, Hash};
use hashbrown::{DefaultHashBuilder, HashTable};
use search_core::{Cost, Goal};
use crate::outcome::Solution;
/// Index of a node in a [`SearchSpace`]. Stable for the lifetime of the space.
pub(crate) type NodeId = usize;
/// One state of the search space.
struct Node<S, A, C> {
/// The state. Stored once; the hash index refers to it by [`NodeId`].
state: S,
/// Best known path cost from the start state.
g: C,
/// The node this one was reached from with its best known path, the edge label and the
/// edge cost. `None` only for the start node.
parent: Option<Parent<A, C>>,
}
/// A parent link: the parent node, the edge label and the edge cost.
type Parent<A, C> = (NodeId, A, C);
/// What [`SearchSpace::reach`] did with a newly generated edge target.
pub(crate) enum Reach {
/// The state was not known before and got a fresh node.
New(NodeId),
/// The state was known, and the new path is cheaper; its cost and parent were updated.
Improved(NodeId),
/// The state was known, and the new path is not cheaper (or improvements are ignored).
Stale,
}
/// All states seen by one search, stored in an arena and indexed by hash.
///
/// States are stored once. The hash table holds [`NodeId`]s and hashes the state they point
/// to, so lookups need no second copy of a state.
pub(crate) struct SearchSpace<S, A, C> {
/// The nodes in creation order. The start node is `0`.
nodes: Vec<Node<S, A, C>>,
/// Hash index from state to node.
index: HashTable<NodeId>,
/// Hashes states for [`SearchSpace::index`].
hasher: DefaultHashBuilder,
}
impl<S: Hash + Eq, A, C: Cost> SearchSpace<S, A, C> {
/// Creates a space from the start states, each at cost zero.
///
/// Repeated starts are stored once, so the starts are nodes `0..space.len()` in order
/// of first appearance. Stops early and returns the node of the first start that
/// satisfies `goal`, if any.
pub(crate) fn seed<T: Goal<S> + ?Sized>(
starts: impl IntoIterator<Item = S>,
goal: &T,
) -> (Self, Option<NodeId>) {
let mut space = Self {
nodes: Vec::new(),
index: HashTable::new(),
hasher: DefaultHashBuilder::default(),
};
for start in starts {
if space.find(&start).is_some() {
continue;
}
let id = space.insert(start, C::ZERO, None);
if goal.is_goal(space.state(id)) {
return (space, Some(id));
}
}
(space, None)
}
/// The number of nodes in the space.
pub(crate) fn len(&self) -> usize {
self.nodes.len()
}
/// The state of node `id`.
pub(crate) fn state(&self, id: NodeId) -> &S {
&self.nodes[id].state
}
/// The best known path cost of node `id`.
pub(crate) fn g(&self, id: NodeId) -> C {
self.nodes[id].g
}
/// The parent link of node `id`: the parent node, the edge label and the edge cost.
/// `None` for start nodes.
pub(crate) fn parent(&self, id: NodeId) -> Option<(NodeId, &A, C)> {
self.nodes[id]
.parent
.as_ref()
.map(|(parent, action, cost)| (*parent, action, *cost))
}
/// Records that `state` is reachable from node `parent` through `action` at edge cost
/// `cost`.
///
/// A known state is updated only if `improve` is set and the new path is strictly
/// cheaper.
pub(crate) fn reach(
&mut self,
state: S,
parent: NodeId,
action: A,
cost: C,
improve: bool,
) -> Reach {
let g = self.nodes[parent].g + cost;
let Some(id) = self.find(&state) else {
return Reach::New(self.insert(state, g, Some((parent, action, cost))));
};
let node = &mut self.nodes[id];
if !improve || g.cmp(&node.g).is_ge() {
return Reach::Stale;
}
node.g = g;
node.parent = Some((parent, action, cost));
Reach::Improved(id)
}
/// Looks up the node of `state`.
pub(crate) fn find(&self, state: &S) -> Option<NodeId> {
let hash = self.hasher.hash_one(state);
let nodes = &self.nodes;
self.index
.find(hash, |&id| nodes[id].state == *state)
.copied()
}
/// Adds a node for `state`, which must not be known yet, and returns its id.
fn insert(&mut self, state: S, g: C, parent: Option<Parent<A, C>>) -> NodeId {
let id = self.nodes.len();
let hash = self.hasher.hash_one(&state);
let (nodes, hasher) = (&self.nodes, &self.hasher);
self.index
.insert_unique(hash, id, |&other| hasher.hash_one(&nodes[other].state));
self.nodes.push(Node { state, g, parent });
id
}
}
impl<S: Clone, A: Clone, C: Cost> SearchSpace<S, A, C> {
/// Follows the parent links from node `goal` back to the start and returns the path.
///
/// The cost is summed along the links rather than read from the goal's `g`: with
/// reopening, an ancestor may have been improved after the goal was reached.
pub(crate) fn solution(&self, goal: NodeId) -> Solution<S, A, C> {
let mut path = self.walk_to_root(goal);
path.states.reverse();
path.actions.reverse();
path
}
/// The parent links from node `from` to its root, in walking order: `states[0]` is
/// `from`, and `actions[i]` is the label of the link from `states[i]` to
/// `states[i + 1]`. The cost is summed along the links.
///
/// In a backward search, whose links point towards the goal, this is the forward path
/// from `from` to the goal.
pub(crate) fn walk_to_root(&self, from: NodeId) -> Solution<S, A, C> {
let mut states = Vec::new();
let mut actions = Vec::new();
let mut cost = C::ZERO;
let mut current = from;
states.push(self.nodes[current].state.clone());
while let Some((parent, action, edge_cost)) = &self.nodes[current].parent {
actions.push(action.clone());
cost = cost + *edge_cost;
states.push(self.nodes[*parent].state.clone());
current = *parent;
}
Solution {
states,
actions,
cost,
}
}
}