mapf 0.3.0

Base traits and utilities for multi-agent planning
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/*
 * Copyright (C) 2023 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

use crate::{
    domain::{
        Activity, Backtrack, Domain, IncrementalExtrapolator, Keyed, KeyedSpace, Keyring,
        PartialKeyed, Reversible, SelfKey,
    },
    error::StdError,
    graph::{Edge, Graph},
    motion::{MaybeTimed, TimePoint, Timed},
    templates::graph_motion::{GraphMotionError, GraphMotionReversalError},
};
use std::{borrow::Borrow, fmt::Debug};

/// `IncrementalGraphMotion` defines a domain and activity that moves over a
/// spatial graph as thoroughly as possible. This is generally used for motion
/// planning problems that cache their search results.
///
/// The activity of `IncrementalGraphMotion` is meant to thoroughly cover every
/// state that the search is passing through. This leads to more search
/// iterations for the algorithm operating on this activity, but it also allows
/// more thorough caching of search results which may be desirable or even
/// necessary for some algorithms, like the Dijkstra algorithms.
///
/// For a more efficient activity representation, use [`super::GraphMotion`].
#[derive(Debug, Clone)]
pub struct IncrementalGraphMotion<S, G, E> {
    pub space: S,
    pub graph: G,
    pub extrapolator: E,
}

impl<S, G, E> IncrementalGraphMotion<S, G, E> {
    fn update_state_waypoint(
        &self,
        waypoint: S::Waypoint,
        original_state: &IncrementalState<S::State, G>,
    ) -> IncrementalState<S::State, G>
    where
        S: KeyedSpace<G::Key>,
        G: Graph,
        G::Key: Clone,
        G::EdgeAttributes: Clone,
    {
        let vertex = self
            .space
            .vertex_of(self.space.key_for(&original_state.base_state).borrow())
            .clone();
        IncrementalState {
            target: original_state.target.clone(),
            base_state: self.space.make_keyed_state(vertex, waypoint),
        }
    }
}

impl<S, G, E> Domain for IncrementalGraphMotion<S, G, E>
where
    S: KeyedSpace<G::Key>,
    G: Graph,
    E: IncrementalExtrapolator<S::Waypoint, G::Vertex, G::EdgeAttributes, G::Key>,
{
    type State = IncrementalState<S::State, G>;
    type Error = GraphMotionError<G::Key, E::IncrementalExtrapolationError>;
}

impl<S, G, E> Activity<IncrementalState<S::State, G>> for IncrementalGraphMotion<S, G, E>
where
    S: KeyedSpace<G::Key>,
    S::Key: Borrow<G::Key>,
    S::State: Clone,
    G: Graph,
    G::Key: Clone,
    G::EdgeAttributes: Clone,
    E: IncrementalExtrapolator<S::Waypoint, G::Vertex, G::EdgeAttributes, G::Key>,
    E::IncrementalExtrapolationError: StdError,
{
    type Action = E::IncrementalExtrapolation;
    type ActivityError = GraphMotionError<G::Key, E::IncrementalExtrapolationError>;
    type Choices<'a>
        = IncrementalGraphMotionChoices<'a, S, G, E>
    where
        Self: 'a,
        Self::Action: 'a,
        Self::ActivityError: 'a,
        S::State: 'a,
        G::EdgeAttributes: 'a;

    fn choices<'a>(&'a self, from_state: IncrementalState<S::State, G>) -> Self::Choices<'a>
    where
        Self: 'a,
        Self::Action: 'a,
        Self::ActivityError: 'a,
        IncrementalState<S::State, G>: 'a,
    {
        if let Some(target) = from_state.target {
            // Just keep moving this state towards its target.
            IncrementalGraphMotionChoices {
                current_iter: None,
                next_target: Some(target),
                edges_from_vertex: None,
                motion: &self,
                from_base_state: from_state.base_state,
            }
        } else {
            // No specific target, so we want to expand in every direction from
            // this vertex.
            let edges_from_vertex = self
                .graph
                .edges_from_vertex(self.space.key_for(&from_state.base_state).borrow().borrow())
                .into_iter();

            IncrementalGraphMotionChoices {
                current_iter: None,
                next_target: None,
                edges_from_vertex: Some(edges_from_vertex),
                motion: &self,
                from_base_state: from_state.base_state,
            }
        }
    }
}

impl<S, G, E> Keyed for IncrementalGraphMotion<S, G, E>
where
    S: Keyed,
{
    type Key = S::Key;
}

impl<S, G, E> PartialKeyed for IncrementalGraphMotion<S, G, E>
where
    S: PartialKeyed,
{
    type PartialKey = S::PartialKey;
}

impl<S, G, E> Keyring<IncrementalState<S::State, G>> for IncrementalGraphMotion<S, G, E>
where
    S: KeyedSpace<G::Key>,
    G: Graph,
{
    type KeyRef<'a>
        = S::KeyRef<'a>
    where
        Self: 'a,
        S::State: 'a;

    fn key_for<'a>(&'a self, state: &'a IncrementalState<S::State, G>) -> Self::KeyRef<'a>
    where
        Self: 'a,
        IncrementalState<S::State, G>: 'a,
    {
        self.space.key_for(&state.base_state)
    }
}

impl<S, G, E> Reversible for IncrementalGraphMotion<S, G, E>
where
    S: Reversible,
    G: Reversible,
    E: Reversible,
{
    type ReversalError =
        GraphMotionReversalError<S::ReversalError, G::ReversalError, E::ReversalError>;
    fn reversed(&self) -> Result<Self, Self::ReversalError> {
        Ok(IncrementalGraphMotion {
            space: self
                .space
                .reversed()
                .map_err(GraphMotionReversalError::Space)?,
            graph: self
                .graph
                .reversed()
                .map_err(GraphMotionReversalError::Graph)?,
            extrapolator: self
                .extrapolator
                .reversed()
                .map_err(GraphMotionReversalError::Extrapolator)?,
        })
    }
}

impl<S, G, E> Backtrack<IncrementalState<S::State, G>, E::IncrementalExtrapolation>
    for IncrementalGraphMotion<S, G, E>
where
    S: KeyedSpace<G::Key>,
    G: Graph,
    G::Key: Clone,
    G::EdgeAttributes: Clone,
    E: IncrementalExtrapolator<S::Waypoint, G::Vertex, G::EdgeAttributes, G::Key>
        + Backtrack<S::Waypoint, E::IncrementalExtrapolation>,
{
    type BacktrackError = E::BacktrackError;
    fn flip_endpoints(
        &self,
        initial_reverse_state: &IncrementalState<S::State, G>,
        final_reverse_state: &IncrementalState<S::State, G>,
    ) -> Result<(IncrementalState<S::State, G>, IncrementalState<S::State, G>), Self::BacktrackError>
    {
        self.extrapolator
            .flip_endpoints(
                self.space
                    .waypoint(&initial_reverse_state.base_state)
                    .borrow(),
                self.space
                    .waypoint(&final_reverse_state.base_state)
                    .borrow(),
            )
            .map(|(initial_forward_waypoint, final_forward_waypoint)| {
                (
                    self.update_state_waypoint(initial_forward_waypoint, final_reverse_state),
                    self.update_state_waypoint(final_forward_waypoint, initial_reverse_state),
                )
            })
    }

    fn backtrack(
        &self,
        parent_forward_state: &IncrementalState<S::State, G>,
        parent_reverse_state: &IncrementalState<S::State, G>,
        reverse_action: &E::IncrementalExtrapolation,
        child_reverse_state: &IncrementalState<S::State, G>,
    ) -> Result<(E::IncrementalExtrapolation, IncrementalState<S::State, G>), Self::BacktrackError>
    {
        self.extrapolator
            .backtrack(
                self.space
                    .waypoint(&parent_forward_state.base_state)
                    .borrow(),
                self.space
                    .waypoint(&parent_reverse_state.base_state)
                    .borrow(),
                reverse_action,
                self.space
                    .waypoint(&child_reverse_state.base_state)
                    .borrow(),
            )
            .map(|(action, waypoint)| {
                let state = self.update_state_waypoint(waypoint, child_reverse_state);
                (action, state)
            })
    }
}

pub struct IncrementalGraphMotionChoices<'a, S, G, E>
where
    S: KeyedSpace<G::Key>,
    G: Graph,
    E: IncrementalExtrapolator<S::Waypoint, G::Vertex, G::EdgeAttributes, G::Key>,
{
    current_iter: Option<
        Extrapolations<
            G::Key,
            G::EdgeAttributes,
            <E::IncrementalExtrapolationIter<'a> as IntoIterator>::IntoIter,
        >,
    >,
    next_target: Option<(G::Key, G::EdgeAttributes)>,
    edges_from_vertex: Option<<G::EdgeIter<'a> as IntoIterator>::IntoIter>,
    motion: &'a IncrementalGraphMotion<S, G, E>,
    from_base_state: S::State,
}

impl<'a, S, G, E> Iterator for IncrementalGraphMotionChoices<'a, S, G, E>
where
    S: KeyedSpace<G::Key>,
    S::Key: Borrow<G::Key>,
    S::State: Clone,
    G: Graph,
    G::Key: Clone,
    G::EdgeAttributes: Clone,
    E: IncrementalExtrapolator<S::Waypoint, G::Vertex, G::EdgeAttributes, G::Key>,
    E::IncrementalExtrapolationError: StdError,
{
    type Item = Result<
        (E::IncrementalExtrapolation, IncrementalState<S::State, G>),
        GraphMotionError<G::Key, E::IncrementalExtrapolationError>,
    >;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(current_iter) = self.current_iter.as_mut() {
                if let Some(result) = current_iter.extrapolations.next() {
                    match result {
                        Ok((action, waypoint, progress)) => {
                            let target = &current_iter.target;
                            if progress.incomplete() {
                                let key = self
                                    .motion
                                    .space
                                    .key_for(&self.from_base_state)
                                    .borrow()
                                    .borrow()
                                    .clone();
                                let state = IncrementalState {
                                    target: Some(current_iter.target.clone()),
                                    base_state: self.motion.space.make_keyed_state(key, waypoint),
                                };
                                return Some(Ok((action, state)));
                            } else {
                                let key = target.0.clone();
                                let state = IncrementalState {
                                    target: None,
                                    base_state: self.motion.space.make_keyed_state(key, waypoint),
                                };
                                return Some(Ok((action, state)));
                            }
                        }
                        Err(err) => {
                            return Some(Err(GraphMotionError::Extrapolator(err)));
                        }
                    }
                }
            }
            self.current_iter = None;

            if let Some((to_key, with_guidance)) = Option::take(&mut self.next_target) {
                let Some(to_v_ref) = self.motion.graph.vertex(&to_key) else {
                    return Some(Err(GraphMotionError::MissingVertex(to_key)));
                };

                let from_waypoint_ref = self.motion.space.waypoint(&self.from_base_state);
                let from_waypoint = from_waypoint_ref.borrow();
                let extrapolations = self.motion.extrapolator.incremental_extrapolate(
                    from_waypoint,
                    to_v_ref.borrow(),
                    &with_guidance,
                    (
                        Some(
                            self.motion
                                .space
                                .key_for(&self.from_base_state)
                                .borrow()
                                .borrow(),
                        ),
                        Some(&to_key),
                    ),
                );

                self.current_iter = Some(Extrapolations {
                    target: (to_key, with_guidance),
                    extrapolations: extrapolations.into_iter(),
                });
                // Return to the start of the loop to begin pulling items out
                // of the extrapolation iterator.
                continue;
            }

            if let Some(edges_from_vertex) = self.edges_from_vertex.as_mut() {
                if let Some(edge) = edges_from_vertex.next() {
                    let to_vertex = edge.to_vertex().clone();
                    let with_guidance = edge.attributes().clone();
                    self.next_target = Some((to_vertex, with_guidance));
                    // Return to the start of the loop to extrapolate toward
                    // this new target.
                    continue;
                }
            }

            return None;
        }
    }
}

struct Extrapolations<Key, Guidance, E> {
    target: (Key, Guidance),
    extrapolations: E,
}

pub struct IncrementalState<BaseState, G: Graph> {
    target: Option<(G::Key, G::EdgeAttributes)>,
    base_state: BaseState,
}

impl<BaseState, G: Graph> Debug for IncrementalState<BaseState, G>
where
    BaseState: Debug,
    G::Key: Debug,
    G::EdgeAttributes: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IncrementalState")
            .field("target", &self.target)
            .field("base_state", &self.base_state)
            .finish()
    }
}

impl<BaseState: Clone, G: Graph> Clone for IncrementalState<BaseState, G>
where
    G::Key: Clone,
    G::EdgeAttributes: Clone,
{
    fn clone(&self) -> Self {
        Self {
            target: self.target.clone(),
            base_state: self.base_state.clone(),
        }
    }
}

impl<BaseState, G: Graph> From<BaseState> for IncrementalState<BaseState, G> {
    fn from(base_state: BaseState) -> Self {
        IncrementalState {
            target: None,
            base_state,
        }
    }
}

impl<BaseState, G: Graph> Borrow<BaseState> for IncrementalState<BaseState, G> {
    fn borrow(&self) -> &BaseState {
        &self.base_state
    }
}

impl<BaseState: Keyed, G: Graph> Keyed for IncrementalState<BaseState, G> {
    type Key = BaseState::Key;
}

impl<BaseState: SelfKey, G: Graph> SelfKey for IncrementalState<BaseState, G> {
    type KeyRef<'a>
        = BaseState::KeyRef<'a>
    where
        BaseState: 'a,
        G: 'a;
    fn key<'a>(&'a self) -> Self::KeyRef<'a>
    where
        Self: 'a,
    {
        self.base_state.key()
    }
}

impl<BaseState: Timed, G: Graph> Timed for IncrementalState<BaseState, G> {
    fn set_time(&mut self, new_time: TimePoint) {
        self.base_state.set_time(new_time)
    }

    fn time(&self) -> TimePoint {
        self.base_state.time()
    }
}

impl<BaseState: Timed, G: Graph> MaybeTimed for IncrementalState<BaseState, G> {
    fn maybe_time(&self) -> Option<TimePoint> {
        Some(self.base_state.time())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        domain::Initializable,
        graph::SimpleGraph,
        motion::se2::{Point, StarburstSE2, StateSE2},
    };

    #[test]
    fn test_incremental_initialization() {
        /*
         *      5
         *      |
         *      |
         * 0----1----2
         *     / \
         *   /     \
         * 3         4
         *
         */

        let graph = SimpleGraph::from_iters(
            [
                Point::new(-1.0, 0.0),  // 0
                Point::new(0.0, 0.0),   // 1
                Point::new(1.0, 0.0),   // 2
                Point::new(-1.0, -1.0), // 3
                Point::new(1.0, -1.0),  // 4
                Point::new(0.0, 1.0),   // 5
            ],
            [
                (0, 1, ()),
                (1, 0, ()),
                (2, 1, ()),
                (1, 2, ()),
                (3, 1, ()),
                (1, 3, ()),
                (4, 1, ()),
                (1, 4, ()),
                (5, 1, ()),
                (1, 5, ()),
            ],
        );

        const R: u32 = 100;
        let init = StarburstSE2::for_start(graph);
        let states: Result<Vec<IncrementalState<StateSE2<usize, R>, SimpleGraph<Point, ()>>>, _> =
            init.initialize(1, &4).collect();
        let states = states.unwrap();
        assert!(states.len() == 5);
    }
}