decoupled-search 0.3.0

Decoupled (star-topology) search for factored SAS+ planning: star factorings, cost-optimal and greedy search, dominance pruning and decoupled heuristics
Documentation
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
//! Compiles a [`Task`] against a [`Factoring`] into a [`DecoupledTask`].
//!
//! ```mermaid
//! graph LR
//!     check[validate task] --> owners[owner of every variable]
//!     owners --> derived[attach derived variables to center or one leaf]
//!     derived --> leaves[rank leaves, split goal]
//!     leaves --> ops[split every operator: leaf action or global action]
//! ```

use alloc::vec;
use alloc::vec::Vec;

use sas_plus::{Effect, Fact, OpId, Operator, Task, VarId};

use super::axioms::Axioms;
use super::leaf::LeafEffect;
use super::{
    CenterEffect, DecoupledTask, GlobalAction, Leaf, LeafAction, LeafFact, LeafPart, Price, widen,
};
use crate::heuristic::fact_offsets;
use crate::{Error, Factoring};

/// Where a task variable lives in the decoupled task.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Owner {
    /// Center slot.
    Center(usize),
    /// Leaf index and slot within the leaf.
    Leaf(usize, usize),
}

impl Owner {
    /// The leaf index, `None` for the center.
    fn leaf(self) -> Option<usize> {
        match self {
            Self::Center(_) => None,
            Self::Leaf(leaf, _) => Some(leaf),
        }
    }
}

/// A list of facts split by owner.
#[derive(Debug)]
struct Split {
    /// Facts on center variables; `var` is the center slot.
    center: Vec<Fact>,
    /// Facts on each leaf, indexed by leaf.
    leaves: Vec<Vec<LeafFact>>,
}

/// The effects of one operator split by owner.
#[derive(Debug)]
struct SplitEffects {
    /// Effects on center variables.
    center: Vec<CenterEffect>,
    /// Effects on each leaf, indexed by leaf.
    leaves: Vec<Vec<LeafEffect>>,
    /// The leaves the effect conditions read, indexed by leaf.
    reads: Vec<bool>,
}

/// The ownership of every task variable.
struct Ownership {
    /// The owner of every task variable.
    owners: Vec<Owner>,
    /// The task variable of each center slot.
    center_vars: Vec<VarId>,
    /// The derived center variables.
    center_derived: Vec<VarId>,
    /// The derived variables attached to each leaf.
    leaf_derived: Vec<Vec<VarId>>,
}

/// Compiles `task` against `factoring`.
///
/// # Errors
///
/// See [`DecoupledTask::new`].
pub(super) fn compile(task: &Task, factoring: &Factoring) -> Result<DecoupledTask, Error> {
    task.validate().map_err(Error::InvalidTask)?;
    let ownership = ownership(task, factoring)?;
    let axioms = Axioms::new(task, ownership.center_vars.clone());
    let leaf_count = factoring.leaves().len();

    let mut leaves = factoring
        .leaves()
        .iter()
        .zip(&ownership.leaf_derived)
        .enumerate()
        .map(|(index, (vars, derived))| {
            compile_leaf(task, vars, index, axioms.scope(derived.clone()))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let goal = split(&ownership.owners, leaf_count, &task.goal);
    for (leaf, facts) in leaves.iter_mut().zip(goal.leaves) {
        leaf.goal = facts;
    }

    let mut globals = Vec::new();
    for (op, operator) in task.operators.iter().enumerate() {
        let pre = split(&ownership.owners, leaf_count, &operator.pre);
        let eff = split_effects(&ownership.owners, leaf_count, op, &operator.eff)?;
        let cost = Price::from(operator.cost);
        match leaf_action_owner(&pre, &eff) {
            Some(leaf) => leaves[leaf]
                .actions
                .push(leaf_action(op, cost, pre, eff, leaf)),
            None => globals.push(global_action(op, cost, pre, eff)),
        }
    }

    for leaf in &mut leaves {
        leaf.index_center_reads();
    }

    let initial = task.initial_state();
    Ok(DecoupledTask {
        initial_center: ownership
            .center_vars
            .iter()
            .map(|&v| initial.0[v])
            .collect(),
        center_derived: axioms.scope(ownership.center_derived),
        center_vars: ownership.center_vars,
        axioms,
        fact_offsets: fact_offsets(task),
        leaf_of: ownership.owners.iter().map(|o| o.leaf()).collect(),
        center_goal: goal.center,
        leaves,
        globals,
        reachability_only: false,
    })
}

/// Per leaf of `factoring`, whether it has at least one leaf action (is
/// *mobile*), classifying operators as [`compile`] does but without
/// compiling the leaves.
///
/// Whenever [`compile`] accepts `factoring`, this says which of its leaves
/// have actions. Operators that [`compile`] would reject (effect
/// conditions across factors) are classified by their facts alone.
///
/// # Errors
///
/// As [`ownership`].
pub(crate) fn mobile_leaves(task: &Task, factoring: &Factoring) -> Result<Vec<bool>, Error> {
    let owners = ownership(task, factoring)?.owners;
    let mut mobile = vec![false; factoring.leaves().len()];
    for operator in &task.operators {
        if let Some(leaf) = leaf_action_of(|v| owners[v].leaf(), operator) {
            mobile[leaf] = true;
        }
    }

    Ok(mobile)
}

/// The leaf `operator` is a leaf action of, given the leaf of every task
/// variable (`None` for the center), as [`leaf_action_owner`] decides on
/// split facts: it sets something and nothing in the center, and every
/// variable it reads or writes lies in the center or in one leaf.
pub(crate) fn leaf_action_of(
    leaf_of: impl Fn(VarId) -> Option<usize>,
    operator: &Operator,
) -> Option<usize> {
    if operator.eff.is_empty() || operator.eff.iter().any(|e| leaf_of(e.fact.var).is_none()) {
        return None;
    }

    let conditions = operator.eff.iter().flat_map(|e| &e.conditions);
    let facts = operator.pre.iter().chain(conditions);
    let vars = facts
        .map(|f| f.var)
        .chain(operator.eff.iter().map(|e| e.fact.var));
    let mut leaf = None;
    for owner in vars.filter_map(&leaf_of) {
        if *leaf.get_or_insert(owner) != owner {
            return None;
        }
    }

    leaf
}

/// The owner of every task variable: the factoring's leaves own their
/// variables; a derived variable joins the one leaf it depends on, if any,
/// and the center otherwise.
///
/// # Errors
///
/// [`Error::FactoringMismatch`] if the factoring does not partition the
/// task's variables, [`Error::DerivedInLeaf`] if a leaf names a derived
/// variable, and [`Error::AxiomAcrossLeaves`] if a derived variable depends
/// on two leaves.
fn ownership(task: &Task, factoring: &Factoring) -> Result<Ownership, Error> {
    let leaf_of = factoring.leaf_of(task)?;
    if let Some(var) =
        (0..task.num_variables()).find(|&v| leaf_of[v].is_some() && task.variables[v].is_derived())
    {
        return Err(Error::DerivedInLeaf { var });
    }

    let axioms = Axioms::new(task, Vec::new());
    let mut out = Ownership {
        owners: vec![Owner::Center(0); task.num_variables()],
        center_vars: Vec::new(),
        center_derived: Vec::new(),
        leaf_derived: vec![Vec::new(); factoring.leaves().len()],
    };
    for (leaf, vars) in factoring.leaves().iter().enumerate() {
        for (slot, &var) in vars.iter().enumerate() {
            out.owners[var] = Owner::Leaf(leaf, slot);
        }
    }

    for &var in factoring.center() {
        if !task.variables[var].is_derived() {
            out.owners[var] = Owner::Center(out.center_vars.len());
            out.center_vars.push(var);
            continue;
        }

        if let Some(leaf) = derived_leaf(task, &axioms, &leaf_of, var)? {
            let slot = factoring.leaves()[leaf].len() + out.leaf_derived[leaf].len();
            out.owners[var] = Owner::Leaf(leaf, slot);
            out.leaf_derived[leaf].push(var);
        } else {
            out.owners[var] = Owner::Center(out.center_vars.len());
            out.center_vars.push(var);
            out.center_derived.push(var);
        }
    }

    Ok(out)
}

/// The one leaf whose state variables derived variable `var` depends on,
/// directly or through other derived variables; `None` if it depends only
/// on the center.
///
/// # Errors
///
/// [`Error::AxiomAcrossLeaves`] if it depends on two leaves.
fn derived_leaf(
    task: &Task,
    axioms: &Axioms,
    leaf_of: &[Option<usize>],
    var: VarId,
) -> Result<Option<usize>, Error> {
    let mut seen = vec![false; task.num_variables()];
    let mut stack = vec![var];
    seen[var] = true;
    let mut found = None;
    while let Some(v) = stack.pop() {
        for dep in axioms.dependencies(v) {
            if core::mem::replace(&mut seen[dep], true) {
                continue;
            }

            if task.variables[dep].is_derived() {
                stack.push(dep);
                continue;
            }

            let Some(leaf) = leaf_of[dep] else {
                continue;
            };

            match found {
                None => found = Some(leaf),
                Some(other) if other != leaf => {
                    return Err(Error::AxiomAcrossLeaves {
                        var,
                        leaves: (other.min(leaf), other.max(leaf)),
                    });
                }
                Some(_) => {}
            }
        }
    }

    Ok(found)
}

/// Compiles the ranking and initial state of leaf `index` over `vars`, with
/// the attached derived variables of `derived`; goal and actions are filled
/// in later.
///
/// # Errors
///
/// [`Error::LeafTooLarge`] if the leaf has more than
/// [`crate::MAX_LEAF_STATES`] states.
fn compile_leaf(
    task: &Task,
    vars: &[VarId],
    index: usize,
    derived: super::Scope,
) -> Result<Leaf, Error> {
    let domains = vars
        .iter()
        .map(|&v| widen(task.variables[v].domain_size))
        .collect();
    let initial: Vec<usize> = vars.iter().map(|&v| widen(task.initial.0[v])).collect();
    let mut leaf =
        Leaf::new(vars.to_vec(), domains, &initial).ok_or(Error::LeafTooLarge { leaf: index })?;
    leaf.derived = derived;
    Ok(leaf)
}

/// Splits `facts` into center facts and per-leaf facts.
fn split(owners: &[Owner], leaf_count: usize, facts: &[Fact]) -> Split {
    let mut out = Split {
        center: Vec::new(),
        leaves: vec![Vec::new(); leaf_count],
    };
    for f in facts {
        match owners[f.var] {
            Owner::Center(slot) => out.center.push(Fact::new(slot, f.value)),
            Owner::Leaf(leaf, slot) => out.leaves[leaf].push(LeafFact {
                slot,
                value: widen(f.value),
            }),
        }
    }

    out.center.sort_unstable_by_key(|f| (f.var, f.value));
    out
}

/// Splits the effects of operator `op` by owner.
///
/// # Errors
///
/// [`Error::CenterEffectReadsLeaf`] if an effect on the center is
/// conditioned on a leaf, and [`Error::EffectConditionAcrossLeaves`] if an
/// effect on one leaf is conditioned on another.
fn split_effects(
    owners: &[Owner],
    leaf_count: usize,
    op: OpId,
    effects: &[Effect],
) -> Result<SplitEffects, Error> {
    let mut out = SplitEffects {
        center: Vec::new(),
        leaves: vec![Vec::new(); leaf_count],
        reads: vec![false; leaf_count],
    };
    for (effect, e) in effects.iter().enumerate() {
        let cond = split(owners, leaf_count, &e.conditions);
        let read: Vec<usize> = (0..leaf_count)
            .filter(|&l| !cond.leaves[l].is_empty())
            .collect();
        for &l in &read {
            out.reads[l] = true;
        }

        match owners[e.fact.var] {
            Owner::Center(slot) => {
                if !read.is_empty() {
                    return Err(Error::CenterEffectReadsLeaf { op, effect });
                }

                out.center.push(CenterEffect {
                    cond: cond.center,
                    fact: Fact::new(slot, e.fact.value),
                });
            }
            Owner::Leaf(leaf, slot) => {
                if read.iter().any(|&l| l != leaf) {
                    return Err(Error::EffectConditionAcrossLeaves { op, effect });
                }

                out.leaves[leaf].push(LeafEffect {
                    center_cond: cond.center,
                    cond: cond.leaves.into_iter().nth(leaf).unwrap_or_default(),
                    fact: LeafFact {
                        slot,
                        value: widen(e.fact.value),
                    },
                });
            }
        }
    }

    Ok(out)
}

/// The leaf an operator is a leaf action of, given its split preconditions
/// and effects: the only leaf it touches, provided it sets no center
/// variable and sets something in that leaf.
fn leaf_action_owner(pre: &Split, eff: &SplitEffects) -> Option<usize> {
    if !eff.center.is_empty() {
        return None;
    }

    let mut touched = (0..eff.leaves.len()).filter(|&l| touches(pre, eff, l));
    let leaf = touched.next()?;
    (touched.next().is_none() && !eff.leaves[leaf].is_empty()).then_some(leaf)
}

/// Whether an operator reads or writes leaf `leaf`.
fn touches(pre: &Split, eff: &SplitEffects, leaf: usize) -> bool {
    !pre.leaves[leaf].is_empty() || !eff.leaves[leaf].is_empty() || eff.reads[leaf]
}

/// Builds the leaf action of leaf `leaf` from split preconditions and effects.
fn leaf_action(op: OpId, cost: Price, pre: Split, eff: SplitEffects, leaf: usize) -> LeafAction {
    LeafAction {
        op,
        cost,
        center_pre: pre.center,
        part: LeafPart {
            pre: pre.leaves.into_iter().nth(leaf).unwrap_or_default(),
            eff: eff.leaves.into_iter().nth(leaf).unwrap_or_default(),
        },
    }
}

/// Builds a global action from split preconditions and effects.
fn global_action(op: OpId, cost: Price, pre: Split, eff: SplitEffects) -> GlobalAction {
    let parts = pre
        .leaves
        .into_iter()
        .zip(eff.leaves)
        .zip(eff.reads)
        .map(|((pre, leaf_eff), reads)| {
            (!pre.is_empty() || !leaf_eff.is_empty() || reads)
                .then_some(LeafPart { pre, eff: leaf_eff })
        })
        .collect();

    GlobalAction {
        op,
        cost,
        center_pre: pre.center,
        center_eff: eff.center,
        parts,
    }
}