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
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate pathfinding;
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
use pathfinding::astar;
pub type State = BTreeMap<String, bool>;
#[derive(Serialize, Deserialize, PartialEq, Eq)]
pub struct Action {
pub name: String,
pub cost: usize,
pub pre_conditions: State,
pub post_conditions: State,
}
impl Action {
pub fn new(name: String, cost: usize) -> Action {
Action {
name: name,
cost: cost,
pre_conditions: State::new(),
post_conditions: State::new(),
}
}
}
#[derive(PartialEq, Eq, Clone)]
struct PlanNode<'a> {
current_state: State,
action: Option<&'a Action>,
}
impl<'a> Hash for PlanNode<'a> {
fn hash<H>(&self, state: &mut H)
where H: Hasher
{
if let Some(action) = self.action {
action.name.hash(state);
}
for (key, value) in &self.current_state {
key.hash(state);
value.hash(state);
}
}
}
impl<'a> PlanNode<'a> {
fn initial(initial_state: &'a State) -> PlanNode<'a> {
PlanNode {
current_state: initial_state.clone(),
action: None,
}
}
fn child(parent_state: State, action: &'a Action) -> PlanNode<'a> {
let mut child = PlanNode {
current_state: parent_state.clone(),
action: Some(action),
};
for (name, value) in &action.post_conditions {
child.current_state.insert(name.clone(), value.clone());
}
child
}
fn possible_next_nodes(&self, actions: &'a [Action]) -> Vec<(PlanNode<'a>, usize)> {
let mut nodes: Vec<(PlanNode<'a>, usize)> = vec![];
for action in actions {
if self.matches(&action.pre_conditions) {
nodes.push((PlanNode::child(self.current_state.clone(), action), action.cost));
}
}
nodes
}
fn mismatch_count(&self, target: &State) -> usize {
let mut count: usize = 0;
for (name, target_value) in target {
if let Some(current_value) = self.current_state.get(name) {
if current_value != target_value {
count += 1;
}
} else {
count += 1;
}
}
count
}
fn matches(&self, target: &State) -> bool {
self.mismatch_count(target) == 0
}
}
pub fn plan<'a>(initial_state: &'a State,
goal_state: &State,
allowed_actions: &'a [Action])
-> Option<Vec<&'a Action>> {
let start = PlanNode::initial(initial_state);
if let Some((plan, _)) = astar(&start,
|ref node| node.possible_next_nodes(allowed_actions),
|ref node| node.mismatch_count(goal_state),
|ref node| node.matches(goal_state)) {
Some(plan.into_iter().skip(1).map(|ref node| node.action.unwrap()).collect())
} else {
None
}
}
#[cfg(test)]
mod tests {
extern crate serde_json;
use super::*;
use std::path::Path;
use std::fs;
#[derive(Deserialize)]
struct TestCase {
#[serde(skip_deserializing)]
case_name: String,
actions: Vec<Action>,
initial_state: State,
goal_state: State,
expected_actions: Vec<String>,
}
impl TestCase {
fn from_case_file(path: &Path) -> TestCase {
let file = fs::File::open(path).unwrap();
let mut case: TestCase = serde_json::from_reader(file).unwrap();
case.case_name = String::from(path.file_name().unwrap().to_str().unwrap());
case
}
fn assert_plan(&self) {
let plan = plan(&self.initial_state, &self.goal_state, &self.actions);
if let Some(actions_list) = plan {
let actions_names: Vec<String> =
actions_list.iter().map(|&action| action.name.clone()).collect();
if self.expected_actions != actions_names {
panic!("{} failed: expected {:?}, got {:?}",
self.case_name,
self.expected_actions,
actions_names);
}
} else {
if self.expected_actions.len() > 0 {
panic!("{} failed: expected {:?}, got no plan",
self.case_name,
self.expected_actions);
}
}
}
}
#[test]
fn run_all_test_cases() {
let paths = fs::read_dir("./data").unwrap();
for path in paths {
let case = TestCase::from_case_file(path.unwrap().path().as_path());
case.assert_plan();
}
}
}