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
use std::collections::{HashMap, HashSet, BTreeSet, VecDeque};
use log::{debug};
use itertools::Itertools;
use std::iter::FromIterator;
use crate::proposition::Proposition;
use crate::action::Action;
use crate::pairset::{pairs_from_sets};
use crate::layer::{MutexPairs};
use crate::plangraph::{PlanGraph, Solution};


pub trait GraphPlanSolver {
    /// Searches a plangraph for a sequence of collection of actions
    /// that satisfy the goals
    fn search(&self, plangraph: &PlanGraph) -> Option<Solution>;
}

pub struct SimpleSolver;

impl SimpleSolver {
    pub fn new() -> SimpleSolver {
        SimpleSolver {}
    }
}

type GoalIndex = usize;
type Attempts = HashMap<usize, BTreeSet<Action>>;

#[derive(Clone, Debug, PartialEq)]
struct ActionCombination(HashMap<GoalIndex, Action>);

impl ActionCombination {
    pub fn as_set(&self) -> HashSet<Action> {
        self.0.values()
            .cloned()
            .into_iter()
            .collect::<HashSet<Action>>()
    }

    pub fn as_vec(&self) -> Vec<Action> {
        self.0.values()
            .cloned()
            .into_iter()
            .collect::<Vec<Action>>()
    }
}

#[derive(Clone, Debug)]
struct GoalSetActionGenerator {
    goals: Vec<Proposition>,
    actions: BTreeSet<Action>,
    mutexes: Option<MutexPairs<Action>>,
}

impl GoalSetActionGenerator {
    pub fn new(goals: Vec<Proposition>,
               actions: BTreeSet<Action>,
               mutexes: Option<MutexPairs<Action>>,) -> GoalSetActionGenerator {
        GoalSetActionGenerator {goals, actions, mutexes}
    }
}

impl IntoIterator for GoalSetActionGenerator {
    type Item = ActionCombination;
    type IntoIter = ActionCombinationIterator;

    fn into_iter(self) -> Self::IntoIter {
        ActionCombinationIterator::new(self)
    }
}

#[derive(Clone, Debug)]
struct ActionCombinationIterator {
    meta: GoalSetActionGenerator, // defines goals we are trying achieve
    attempts: Attempts, // previous attempts to meet a goal
    goals_met: bool, // flag indicating all goals are met or restart
    accum: HashMap<GoalIndex, Action> // combination of actions
}

impl ActionCombinationIterator {
    pub fn new(action_combinations: GoalSetActionGenerator) -> ActionCombinationIterator {
        ActionCombinationIterator {
            meta: action_combinations,
            attempts: Attempts::new(),
            goals_met: false,
            accum: HashMap::new(),
        }
    }
}

impl Iterator for ActionCombinationIterator {
    type Item = ActionCombination;

    fn next(&mut self) -> Option<Self::Item> {
        let goals = &self.meta.goals;
        let actions = &self.meta.actions;
        let goal_len = goals.len();

        let mut stack = VecDeque::new();

        // If the goals have already been met, we need to look for a
        // new combination that also meets the goals
        if self.goals_met {
            // Remove the previous action used to satisfy the last
            // goal and start the loop from the last goal. This will
            // yield a new combination or recursively back track.
            self.goals_met = false;
            let goal_idx = goal_len - 1;
            self.accum.remove(&goal_idx);
            stack.push_front((goal_idx,));
        } else {
            stack.push_front((0,));
        }

        while let Some((goal_idx, )) = stack.pop_front() {
            let available_actions = if let Some(acts) = self.attempts.get(&goal_idx) {
                acts.to_owned()
            } else {
                let goal = &goals[goal_idx];
                debug!("Working on goal {:?}", goal);
                let mut available = BTreeSet::new();
                // Only actions that produce the goal and are not
                // mutex with any other actions and have not
                // already been attempted in combination with the
                // other attempted actions and are not mutex with
                // any other action
                for a in actions {
                    // Early continue since the later checks are
                    // more expensive
                    if !a.effects.contains(goal) {
                        continue
                    };

                    // Early break if we already know this action
                    // works for the goal from previous attempts
                    if self.accum.get(&goal_idx).map(|i| i == a).unwrap_or(false) {
                        available.insert(a.clone());
                        break
                    };

                    // Check if this action is mutex with any of
                    // the other accumulated actions
                    let acts = self.accum.clone();
                    debug!("pairs_from_sets {:?}, {:?}",
                             hashset!{a.clone()},
                             ActionCombination(acts.clone()).as_set());
                    let pairs = pairs_from_sets(
                        hashset!{a.clone()},
                        ActionCombination(acts).as_set()
                    );
                    debug!("Checking pairs: {:?} against mutexes: {:?}", pairs, &self.meta.mutexes);

                    if let Some(muxes) = &self.meta.mutexes {
                        if muxes.intersection(&pairs).collect::<Vec<_>>().is_empty() {
                            available.insert(a.clone());
                        }
                    };
                };
                available
            };

            if available_actions.is_empty() {
                if goal_idx == 0 {
                    // Complete fail
                    break;
                }
                debug!("Unable to find actions for goal {:?}. Going back to previous goal...", goal_idx);
                // Clear attempts for this goal so finding an action
                // can be retried with a new set of actions
                self.attempts.remove(&goal_idx);
                // Backtrack to the previous goal
                stack.push_front((goal_idx - 1,));
            } else {
                let next_action = available_actions.iter().next().unwrap();
                // TODO only add the action if the goal isn't met yet
                self.accum.insert(goal_idx, next_action.clone());

                // Add to previous attempts in case we need to backtrack
                let mut remaining_actions = available_actions.clone();
                remaining_actions.remove(&next_action);
                self.attempts.insert(goal_idx, remaining_actions);

                // TODO Implement minimal action sets i.e handle if
                // this action staisfies more than one
                // goal. Otherwise, the speed of finding a solution is
                // dependent on the ordering of goals
                // From the paper: no action can be
                // removed from A so that the add effects of the
                // actions remaining still contain G

                // Proceed to the next goal
                if goal_idx < goal_len - 1 {
                    stack.push_front((goal_idx + 1,));
                } else {
                    self.goals_met = true;
                }
            };
        };

        if self.goals_met {
            Some(ActionCombination(self.accum.clone()))
        } else {
            None
        }
    }
}


#[cfg(test)]
mod goal_set_action_generator_test {
    use super::*;

    #[test]
    fn single_goal() {
        let p1 = Proposition::from_str("coffee");
        let p2 = Proposition::from_str("caffeinated");
        let goals = vec![p2.clone()];
        let mut actions = BTreeSet::new();
        let a1 = Action::new(
            String::from("drink coffee"),
            hashset!{&p1},
            hashset!{&p2}
        );
        actions.insert(a1.clone());
        let mutexes = Some(MutexPairs::new());
        let expected = ActionCombination(hashmap!{0 => a1});
        let actual = GoalSetActionGenerator::new(goals, actions, mutexes)
            .into_iter()
            .next()
            .unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn multiple_goals() {
        let p1 = Proposition::from_str("coffee");
        let p2 = Proposition::from_str("caffeinated");
        let p3 = Proposition::from_str("breakfast");
        let p4 = Proposition::from_str("full");
        let goals = vec![p2.clone(), p4.clone()];
        let mut actions = BTreeSet::new();
        let a1 = Action::new(
            String::from("drink coffee"),
            hashset!{&p1},
            hashset!{&p2}
        );
        actions.insert(a1.clone());

        let a2 = Action::new(
            String::from("eat breakfast"),
            hashset!{&p3},
            hashset!{&p4}
        );
        actions.insert(a2.clone());

        let mutexes = Some(MutexPairs::new());
        let expected = ActionCombination(hashmap!{0 => a1.clone(), 1 => a2.clone()});
        let actual = GoalSetActionGenerator::new(goals, actions, mutexes)
            .into_iter()
            .next()
            .unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn yields_all() {
        let p1 = Proposition::from_str("tea");
        let p2 = Proposition::from_str("coffee");
        let p3 = Proposition::from_str("caffeinated");
        let p4 = Proposition::from_str("scone");
        let p5 = Proposition::from_str("muffin");
        let p6 = Proposition::from_str("full");
        let goals = vec![p3.clone(), p6.clone()];
        let mut actions = BTreeSet::new();

        let a1 = Action::new(
            String::from("drink coffee"),
            hashset!{&p2},
            hashset!{&p3}
        );
        actions.insert(a1.clone());

        let a2 = Action::new(
            String::from("drink tea"),
            hashset!{&p1},
            hashset!{&p3}
        );
        actions.insert(a2.clone());

        let a3 = Action::new(
            String::from("eat scone"),
            hashset!{&p4},
            hashset!{&p6}
        );
        actions.insert(a3.clone());

        let a4 = Action::new(
            String::from("eat muffin"),
            hashset!{&p5},
            hashset!{&p6}
        );
        actions.insert(a4.clone());

        let mutexes = Some(MutexPairs::new());
        let expected = vec![
            vec![a1.clone(), a4.clone()],
            vec![a1.clone(), a3.clone()],
            vec![a2.clone(), a4.clone()],
            vec![a2.clone(), a3.clone()],
        ];
        let generator = GoalSetActionGenerator::new(goals, actions, mutexes);
        let actual: Vec<Vec<Action>> = generator.into_iter()
            .map(|combo| {let mut i = combo.as_vec(); i.sort(); i})
            .collect();

        assert_eq!(expected, actual);
    }
}

impl GraphPlanSolver for SimpleSolver {
    fn search(&self, plangraph: &PlanGraph) -> Option<Solution> {
        let mut success = false;
        let mut plan = Solution::new();
        let mut failed_goals_memo: HashSet<(usize, Vec<Proposition>)> = HashSet::new();

        // Initialize the loop
        let mut stack: VecDeque<(usize, Vec<Proposition>, Option<ActionCombinationIterator>)> = VecDeque::new();
        let init_goals = Vec::from_iter(plangraph.goals.clone());
        let init_layer_idx = plangraph.layers.len() - 1;
        let init_action_gen = None;
        stack.push_front((init_layer_idx, init_goals, init_action_gen));

        while let Some((idx, goals, action_gen)) = stack.pop_front() {
            debug!("Working on layer {:?} with goals {:?}", idx, goals);
            // Check if the goal set is unsolvable at level idx
            if failed_goals_memo.contains(&(idx, goals.clone())) {
                // Continue to previous layer (the next element in the queue)
                continue;
            }

            // Note: This is a btreeset so ordering is guaranteed
            let actions = plangraph.actions_at_layer(idx - 1)
                .expect("Failed to get actions");
            let mutexes = plangraph.mutex_actions.get(&(idx - 1)).cloned();
            let mut gen = action_gen
                .or(Some(GoalSetActionGenerator::new(goals.clone(),
                                                     actions.clone(),
                                                     mutexes).into_iter()))
                .unwrap();

            if let Some(goal_actions) = gen.next() {
                debug!("Found actions {:?}", goal_actions);
                // If we are are on the second to last proposition
                // layer, we are done
                if (idx - 2) == 0 {
                    debug!("Actions: {:?}", goal_actions.as_set());
                    plan.push(goal_actions.as_set());
                    debug!("Found plan! {:?}", plan);
                    success = true;
                    break;
                } else {
                    debug!("Actions: {:?}", goal_actions.as_set());
                    plan.push(goal_actions.as_set());
                    let next_goals = goal_actions.as_set().into_iter()
                        .flat_map(|action| action.reqs)
                        .unique()
                        .collect();
                    // Add this layer back into the queue incase we need to backtrack
                    stack.push_front((idx, goals, Some(gen)));
                    stack.push_front((idx - 2, next_goals, None));
                };
            } else {
                debug!("Unable to find actions for goals {:?} from actions {:?}",
                       goals, actions);
                // Record the failed goals at level idx
                failed_goals_memo.insert((idx, goals.clone()));
                // Remove the last step in the plan from which this
                // set of goals comes from
                plan.pop();
                // Backtrack to previous layer and goalset or nothing
                // (the next element in the queue)
            }
        };

        if success {
            // Since this solver goes from the last layer to the
            // first, we need to reverse the plan
            plan.reverse();
            Some(plan)
        } else {
            None
        }
    }
}

#[cfg(test)]
mod simple_solver_test {
    use super::*;

    #[test]
    fn solver_works() {
        let p1 = Proposition::from_str("tired");
        let not_p1 = p1.negate();
        let p2 = Proposition::from_str("dog needs to pee");
        let not_p2 = p2.negate();
        let p3 = Proposition::from_str("caffeinated");

        let a1 = Action::new(
            String::from("coffee"),
            hashset!{&p1},
            hashset!{&p3, &not_p1}
        );

        let a2 = Action::new(
            String::from("walk dog"),
            hashset!{&p2, &p3},
            hashset!{&not_p2},
        );

        let goals = hashset!{&not_p1, &not_p2, &p3};

        let mut pg = PlanGraph::new(
            hashset!{&p1, &p2},
            goals,
            hashset!{&a1, &a2}
        );
        pg.extend();
        pg.extend();
        debug!("Plangraph: {:?}", pg);

        let solver = SimpleSolver::new();
        let expected = Some(vec![hashset!{a1.clone()}, hashset!{a2.clone()}]);
        let actual = PlanGraph::format_plan(solver.search(&pg));
        assert_eq!(expected, actual);
    }
}

#[cfg(test)]
/// Prove that BTreeSet preserves ordering
mod btreeset_test {
    use std::collections::BTreeSet;

    #[test]
    fn is_sorted () {
        let mut b = BTreeSet::new();
        b.insert(2);
        b.insert(3);
        b.insert(1);
        assert_eq!(b.into_iter().collect::<Vec<_>>(), vec![1, 2, 3]);

        let mut b = BTreeSet::new();
        b.insert(1);
        b.insert(2);
        b.insert(3);
        assert_eq!(b.into_iter().collect::<Vec<_>>(), vec![1, 2, 3]);
    }
}