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
use std::collections::{HashMap, HashSet, BTreeSet};
use log::{debug};
use crate::proposition::Proposition;
use crate::action::Action;
use crate::pairset::{pairs, PairSet};
use crate::solver::GraphPlanSolver;
use crate::layer::{Layer, MutexPairs};


type LayerNumber = usize;
type QueryActions = Result<BTreeSet<Action>, String>;
pub type Solution = Vec<HashSet<Action>>;

#[derive(Debug)]
pub struct PlanGraph {
    pub goals: HashSet<Proposition>,
    pub actions: HashSet<Action>,
    pub layers: Vec<Layer>,
    pub mutex_props: HashMap<LayerNumber, MutexPairs<Proposition>>,
    pub mutex_actions: HashMap<LayerNumber, MutexPairs<Action>>,
}

impl PlanGraph {
    pub fn new(initial_props: HashSet<&Proposition>,
               goals: HashSet<&Proposition>,
               actions: HashSet<&Action>) -> Self {
        let owned_init_props = initial_props.into_iter().cloned().collect();
        let init_layer = Layer::PropositionLayer(owned_init_props);
        PlanGraph {
            goals: goals.into_iter().cloned().collect(),
            actions: actions.into_iter().cloned().collect(),
            layers: vec![init_layer],
            mutex_props: HashMap::new(),
            mutex_actions: HashMap::new()
        }
    }

    pub fn push(&mut self, layer: Layer) {
        self.layers.push(layer)
    }

    /// Extends the plangraph to depth i+1
    /// Inserts another action layer and proposition layer
    pub fn extend(&mut self) {
        let length = self.layers.len();
        if let Some(layer) = self.layers.last() {
            match layer {
                Layer::ActionLayer(_) => {
                    panic!("Tried to extend a plangraph from an ActionLayer which is not allowed")
                },
                Layer::PropositionLayer(props) => {
                    let mutex_props = self.mutex_props.get(&(length - 1));
                    let actions_no_mutex_reqs = mutex_props
                        .map(|mp| {
                            self.actions.iter()
                                .filter(|action| {
                                    pairs(&action.reqs).intersection(&mp)
                                        .collect::<Vec<_>>()
                                        .is_empty()
                                })
                                .collect::<HashSet<&Action>>()
                        })
                        .unwrap_or(self.actions.iter().collect());

                    let p_layer = Layer::PropositionLayer(props.to_owned());
                    let action_layer = Layer::from_layer(
                        actions_no_mutex_reqs,
                        &p_layer
                    );
                    let action_layer_actions: HashSet<&Action> = match &action_layer {
                        Layer::ActionLayer(action_data) => action_data.iter().collect(),
                        _ => unreachable!("Tried to get actions from PropositionLayer")
                    };
                    let action_mutexes = Layer::action_mutexes(
                        &action_layer_actions,
                        mutex_props
                    );
                    self.mutex_actions.insert(
                        self.layers.len(),
                        action_mutexes.clone()
                            .into_iter()
                            .map(|i| {
                                let PairSet(a, b) = i;
                                PairSet(a.to_owned(), b.to_owned())
                            })
                            .collect()
                    );

                    let prop_layer = Layer::from_layer(
                        self.actions.iter().collect(),
                        &action_layer
                    );
                    let prop_layer_props = match &prop_layer {
                        Layer::PropositionLayer(prop_data) => Some(prop_data),
                        _ => unreachable!("Tried to get propositions from ActionLayerr")
                    };
                    let prop_mutexes = Layer::proposition_mutexes(
                        // This shouldn't fail
                        &prop_layer_props.unwrap(),
                        &action_layer_actions,
                        Some(&action_mutexes)
                    );
                    self.layers.push(action_layer);
                    self.layers.push(prop_layer);
                    self.mutex_props.insert(self.layers.len(), prop_mutexes.clone());
                }
            }
        } else {
            panic!("Tried to extend a plangraph that is not initialized. Please use PlanGraph::new instead of instantiating it as a struct.")
        }
    }

    /// Returns the depth of the planning graph
    pub fn depth(&self) -> usize {
        if self.layers.len() > 2 {
            (self.layers.len() - 1) / 2
        } else {
            0
        }
    }

    // Returns the actions at layer index as an ordered set
    pub fn actions_at_layer(&self, index: usize) -> QueryActions {
        self.layers.get(index).map_or(
            Err(format!("Layer {} does not exist", index)),
            |layer| {
                match layer {
                    Layer::ActionLayer(actions) => {
                        let acts = actions
                           .into_iter()
                           .cloned()
                           .collect::<BTreeSet<_>>();
                        Ok(acts)
                    },
                    Layer::PropositionLayer(_) => {
                        Err(format!("Tried to get actions from proposition layer {}",
                                    index))
                    }
                }
            }
        )
    }

    /// A solution is possible if all goals exist in the last
    /// proposition layer and are not mutex
    fn has_possible_solution(&self) -> bool {
        let goals = self.goals.clone();
        let last_layer_idx = self.layers.clone().len() - 1;

        if let Some(prop_layer) = self.layers.get(last_layer_idx) {
            match prop_layer {
                Layer::PropositionLayer(props) => {
                    let all_goals_present = &goals.is_subset(props);
                    let mutexes = self.mutex_props
                        .get(&last_layer_idx)
                        .unwrap_or(&MutexPairs::new())
                        .to_owned();
                    let goal_pairs = pairs(&goals);
                    let mutex_goals: HashSet<_> = mutexes
                        .intersection(&goal_pairs)
                        .collect();
                    *all_goals_present && mutex_goals.is_empty()
                },
                _ => panic!("Tried to check for a solution in a Layer::Action")
            }
        } else {
            false
        }
    }

    /// The graph is considered to have "leveled off" when proposition
    /// layer P and an adjacent proposition layer Q are equal
    fn has_leveled_off(&self) -> bool {
        let len = self.layers.len();
        if len > 2 as usize {
            let prop_layer = self.layers.get(len - 1).expect("Failed to get layer");
            let adjacent_prop_layer = self.layers.get(len - 3).expect("Failed to get adjacent layer");
            prop_layer == adjacent_prop_layer
        } else {
            false
        }
    }

    /// Searches the planning graph for a solution using the solver if
    /// there is no solution, extends the graph to depth i+1 and tries
    /// to solve again
    pub fn search_with<T>(&mut self, solver: &T) -> Option<Solution>
    where T: GraphPlanSolver {
        let mut tries = 0;
        let mut solution = None;
        let max_tries = self.actions.len() + 1;

        while tries < max_tries {
            // This doesn't provide early termination for _all_
            // cases that won't yield a solution.
            if self.has_leveled_off() {
                break;
            }
            if self.has_possible_solution() {
                if let Some(s) = solver.search(self) {
                    solution = Some(s);
                    break;
                } else {
                    debug!("No solution found at depth {}", self.depth());
                    self.extend();
                    tries += 1
                }
            } else {
                debug!("No solution exists at depth {}", self.depth());
                self.extend();
                tries += 1;
            }
        };
        solution
    }

    /// Takes a solution and filters out maintenance actions
    pub fn format_plan(solution: Option<Solution>) -> Option<Solution> {
        solution.map(|steps| steps.iter()
                     .map(|s| s.iter()
                          .filter(|i| !i.name.contains("[maintain]"))
                          .cloned()
                          .collect())
                     .collect()
        )
    }
}