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
use std::collections::HashMap;

use crate::core::{EdgeId, NodeId, TransitEdge, TransitNode};
use geo::{Coord, CoordNum, EuclideanDistance};
use petgraph::{
    graph::EdgeIndex,
    graph::{NodeIndex, UnGraph},
};

/// Represents the physical layout of the transit network.
///
/// `PhysicalGraph` is an undirected graph where each node represents a transit node (a point in the transit network where a vehicle can stop) and each edge represents a transit edge (a path between two transit nodes).
/// The `PhysicalGraph` uses the `UnGraph` structure from the `petgraph` crate to internally represent this data. The `PhysicalGraph` maintains mappings between `NodeId`s and `NodeIndex`es (from `petgraph`), allowing for efficient conversion between the two.
///
/// # Examples
///
/// Creating a new `PhysicalGraph` and adding a `TransitNode`:
/// ```
/// use transit_grid::core::TransitNode;
/// use transit_grid::prelude::PhysicalGraph;
/// use geo::{coord, Coord};
///
/// let mut graph: PhysicalGraph<Coord, f64> = PhysicalGraph::new();
/// let node = TransitNode { id: 1, location: coord! { x:0.0, y:0.0 } };
/// graph.add_transit_node(node);
/// ```
///
/// Adding a `TransitEdge` to the `PhysicalGraph`:
/// ```
/// use transit_grid::core::{TransitNode, TransitEdge};
/// use transit_grid::prelude::PhysicalGraph;
/// use geo::{coord, Coord, LineString};
///
/// let mut graph: PhysicalGraph<Coord, f64> = PhysicalGraph::new();
/// let node1 = TransitNode { id: 1, location: coord! { x:0.0, y:0.0 } };
/// let node2 = TransitNode { id: 2, location: coord! { x:1.0, y:1.0 } };
/// let node1_id = graph.add_transit_node(node1);
/// let node2_id = graph.add_transit_node(node2);
/// let edge = TransitEdge {
///     id: 1,
///     source: 1,
///     target: 2,
///     length: 1.0,
///     path: LineString(vec![coord! { x:0.0, y:0.0 }, coord! { x:1.0, y:1.0 }]),
/// };
/// graph.add_transit_edge(edge);
/// ```
#[derive(Debug, Clone)]
pub struct PhysicalGraph<R, T: CoordNum> {
    /// Underlying undirected graph.
    pub graph: UnGraph<TransitNode<R>, TransitEdge<T>, u32>,

    /// Mapping of NodeId to petgraph's NodeIndex.
    id_to_index: HashMap<NodeId, NodeIndex>,

    /// Mapping of petgraph's NodeIndex to NodeId.
    index_to_id: HashMap<NodeIndex, NodeId>,
}

impl<R: Copy, T: CoordNum> PhysicalGraph<R, T> {
    /// Creates a new, empty `PhysicalGraph`.
    pub fn new() -> Self {
        PhysicalGraph {
            graph: UnGraph::<TransitNode<R>, TransitEdge<T>, u32>::new_undirected(),
            id_to_index: HashMap::new(),
            index_to_id: HashMap::new(),
        }
    }

    /// Converts a `NodeIndex` to a `NodeId`.
    ///
    /// This method provides a way to map from the petgraph's `NodeIndex` to
    /// the `NodeId` used in the `TransitNode`.
    ///
    /// # Arguments
    ///
    /// * `index` - The `NodeIndex` to be converted.
    ///
    /// # Returns
    ///
    /// * `NodeId` - The corresponding `NodeId` of the provided `NodeIndex`.
    ///
    /// # Example
    ///
    /// ```
    /// use transit_grid::prelude::PhysicalGraph;
    /// use transit_grid::core::TransitNode;
    /// use geo::{coord, Coord};
    ///
    /// let mut graph: PhysicalGraph<Coord, f64> = PhysicalGraph::new();
    /// let node = TransitNode { id: 1, location: coord! { x:0.0, y:0.0 } };
    /// let node_index = graph.add_transit_node(node);
    /// let node_id = graph.index_to_id(node_index);
    /// assert_eq!(node_id, Some(&1));
    /// ```
    pub fn index_to_id(&self, index: NodeIndex) -> Option<&NodeId> {
        self.index_to_id.get(&index)
    }

    /// Converts a `NodeId` to a `NodeIndex`.
    ///
    /// This method provides a way to map from a `NodeId` used in the `TransitNode` to
    /// the petgraph's `NodeIndex`.
    ///
    /// # Arguments
    ///
    /// * `id` - The `NodeId` to be converted.
    ///
    /// # Returns
    ///
    /// * `NodeIndex` - The corresponding `NodeIndex` of the provided `NodeId`.
    ///
    /// # Example
    ///
    /// ```
    /// use transit_grid::prelude::PhysicalGraph;
    /// use transit_grid::core::TransitNode;
    /// use geo::{coord, Coord};
    ///
    /// let mut graph: PhysicalGraph<Coord, f64> = PhysicalGraph::new();
    /// let node = TransitNode { id: 1, location: coord! { x:0.0, y:0.0 } };
    /// let node_index = graph.add_transit_node(node);
    /// let queried_index = graph.id_to_index(1);
    /// assert_eq!(Some(&node_index), queried_index);
    /// ```
    pub fn id_to_index(&self, id: NodeId) -> Option<&NodeIndex> {
        self.id_to_index.get(&id)
    }

    /// Adds a `TransitNode` to the `PhysicalGraph`.
    ///
    /// # Example
    /// ```
    /// use transit_grid::prelude::PhysicalGraph;
    /// use transit_grid::core::TransitNode;
    /// use geo::{coord, Coord};
    ///
    /// let mut graph: PhysicalGraph<Coord, f64> = PhysicalGraph::new();
    /// let node = TransitNode { id: 1, location: coord! { x:0.0, y:0.0 } };
    /// graph.add_transit_node(node);
    /// ```
    pub fn add_transit_node(&mut self, node: TransitNode<R>) -> NodeIndex {
        let index = self.graph.add_node(node);
        self.id_to_index.insert(node.id, index);
        self.index_to_id.insert(index, node.id);
        index
    }

    /// Adds a `TransitEdge` to the `PhysicalGraph`.
    ///
    /// # Example
    /// ```
    /// use transit_grid::prelude::PhysicalGraph;
    /// use transit_grid::core::{TransitNode, TransitEdge};
    /// use geo::{coord, Coord, LineString};
    /// use petgraph::csr::IndexType;
    ///
    /// let mut graph: PhysicalGraph<Coord, f64> = PhysicalGraph::new();
    /// let node1 = TransitNode { id: 1, location: coord! { x:0.0, y:0.0 } };
    /// let node2 = TransitNode { id: 2, location: coord! { x:1.0, y:1.0 } };
    ///
    /// let node1_id = graph.add_transit_node(node1);
    /// let node2_id = graph.add_transit_node(node2);
    ///
    /// let edge = TransitEdge {
    ///     id: 1,
    ///     source: 1,
    ///     target: 2,
    ///     length: 1.0,
    ///     path: LineString(vec![coord! { x:0.0, y:0.0 }, coord! { x:1.0, y:1.0 }]),
    /// };
    ///
    /// graph.add_transit_edge(edge);
    /// ```
    pub fn add_transit_edge(&mut self, edge: TransitEdge<T>) -> EdgeIndex {
        let from = self.id_to_index(edge.source);
        let to = self.id_to_index(edge.target);
        if let (Some(from), Some(to)) = (from, to) {
            self.graph.add_edge(*from, *to, edge)
        } else {
            panic!("Invalid node ID")
        }
    }

    /// Returns a reference to the `TransitEdge` connecting the two nodes specified by `node1` and `node2`.
    ///
    /// # Arguments
    ///
    /// * `node1` - The `NodeId` of the first node.
    /// * `node2` - The `NodeId` of the second node.
    ///
    /// # Returns
    ///
    /// A reference to the `TransitEdge` connecting `node1` and `node2`. This function will panic if there is no edge between the nodes.
    ///
    /// # Panics
    ///
    /// This function will panic in the following cases:
    ///
    /// * If `node1` or `node2` are not valid node IDs in the graph.
    /// * If there is no edge between `node1` and `node2`.
    pub fn get_transit_edge(&self, node1: NodeId, node2: NodeId) -> Option<&TransitEdge<T>> {
        let node1_index = self.id_to_index(node1);
        let node2_index = self.id_to_index(node2);
        if let (Some(node1_index), Some(node2_index)) = (node1_index, node2_index) {
            if let Some(edge_index) = self.graph.find_edge(*node1_index, *node2_index) {
                self.graph.edge_weight(edge_index)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Returns a reference to the `TransitEdge` with the specified `EdgeId`.
    pub fn get_transit_edge_by_id(&self, edge_id: EdgeId) -> Option<&TransitEdge<T>> {
        self.graph
            .edge_references()
            .find(|edge| edge.weight().id == edge_id)
            .map(|edge| edge.weight())
    }

    /// Repairs a physical edge in the `PhysicalGraph` based on its nodes' locations.
    ///
    /// # Arguments
    ///
    /// * `edge` - The `TransitEdge` to be repaired.
    ///
    /// # Example
    ///
    /// ```
    /// use transit_grid::prelude::PhysicalGraph;
    /// use transit_grid::core::{TransitNode, TransitEdge};
    /// use geo::{coord, Coord, LineString};
    ///
    /// let mut graph: PhysicalGraph<Coord, f64> = PhysicalGraph::new();
    /// let node1 = TransitNode { id: 1, location: coord! { x:0.0, y:0.0 } };
    /// let node2 = TransitNode { id: 2, location: coord! { x:1.0, y:1.0 } };
    ///
    /// let node1_id = graph.add_transit_node(node1);
    /// let node2_id = graph.add_transit_node(node2);
    ///
    /// let mut edge = TransitEdge {
    ///     id: 1,
    ///     source: 1,
    ///     target: 2,
    ///     length: 1.0,
    ///     path: LineString(vec![coord! { x:1.0, y:1.0 }, coord! { x:0.0, y:0.0 }]),  // Note that the direction is initially reversed
    /// };
    ///
    /// graph.add_transit_edge(edge.clone());
    /// graph.repair_edge(1, 2);
    /// let edge = graph.get_transit_edge(1, 2).unwrap();
    /// assert_eq!(
    ///    edge.path,
    ///    LineString(vec![Coord { x: 0.0, y: 0.0 }, Coord { x: 1.0, y: 1.0 }])
    /// );
    ///
    /// // After repair, the edge path should be from 0,0 to 1,1
    /// //assert_eq!(edge.path.0.first().unwrap(), &coord! { x:0.0, y:0.0 });
    /// //assert_eq!(edge.path.0.last().unwrap(), &coord! { x:1.0, y:1.0 });
    /// ```
    pub fn repair_edge(&mut self, node1: NodeId, node2: NodeId)
    where
        R: EuclideanDistance<T, Coord<T>>,
    {
        let node1_index = self.id_to_index(node1);
        let node2_index = self.id_to_index(node2);
        if let (Some(node1_index), Some(node2_index)) = (node1_index, node2_index) {
            let from_node_location = {
                let from_node: &TransitNode<R> = self.graph.node_weight(*node1_index).unwrap();
                from_node.location
            };

            let edge_index = self.graph.find_edge(*node1_index, *node2_index).unwrap();
            let edge = self.graph.edge_weight_mut(edge_index).unwrap();

            let first_point = edge.path.0.first().unwrap();
            let last_point = edge.path.0.last().unwrap();

            let dist_to_first = from_node_location.euclidean_distance(first_point);
            let dist_to_last = from_node_location.euclidean_distance(last_point);

            if dist_to_first > dist_to_last {
                edge.path.0.reverse();
            }
        }
    }
}

impl<R: Copy, T: CoordNum> Default for PhysicalGraph<R, T> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use geo::{coord, Coord, LineString};

    #[test]
    fn test_graph() {
        let mut graph = PhysicalGraph::new();

        let node1 = TransitNode {
            id: 1,
            location: coord! { x:0.0, y:0.0 },
        };

        let node2 = TransitNode {
            id: 2,
            location: coord! { x:1.0, y:1.0 },
        };

        let node3 = TransitNode {
            id: 3,
            location: coord! { x:1.0, y:1.0 },
        };

        let _node1_id = graph.add_transit_node(node1);
        let _node2_id = graph.add_transit_node(node2);
        let _node3_id = graph.add_transit_node(node3);

        let edge = TransitEdge {
            id: 1,
            source: 1,
            target: 2,
            length: 1.0,
            path: LineString(vec![coord! { x:0.0, y:0.0 }, coord! { x:1.0, y:1.0 }]),
        };

        let _ = graph.add_transit_edge(edge);

        assert_eq!(graph.graph.node_count(), 3);
        assert_eq!(graph.graph.edge_count(), 1);

        assert!(graph.get_transit_edge(1, 2).is_some());
        assert!(graph.get_transit_edge(1, 3).is_none());
    }

    #[test]
    fn test_index_to_id() {
        let mut graph = PhysicalGraph::<Coord, f64>::new();

        let node1 = TransitNode {
            id: 1,
            location: coord! { x:0.0, y:0.0 },
        };

        let node2 = TransitNode {
            id: 2,
            location: coord! { x:1.0, y:1.0 },
        };

        let node1_index = graph.add_transit_node(node1);
        let node2_index = graph.add_transit_node(node2);

        let node1_id = graph.index_to_id(node1_index);
        let node2_id = graph.index_to_id(node2_index);

        assert_eq!(node1_id, Some(&1));
        assert_eq!(node2_id, Some(&2));
    }

    #[test]
    fn test_id_to_index() {
        let mut graph = PhysicalGraph::<Coord, f64>::new();

        let node1 = TransitNode {
            id: 1,
            location: coord! { x:0.0, y:0.0 },
        };

        let node2 = TransitNode {
            id: 2,
            location: coord! { x:1.0, y:1.0 },
        };

        let node1_index = graph.add_transit_node(node1);
        let node2_index = graph.add_transit_node(node2);

        let queried_node1_index = graph.id_to_index(1);
        let queried_node2_index = graph.id_to_index(2);

        assert_eq!(Some(&node1_index), queried_node1_index);
        assert_eq!(Some(&node2_index), queried_node2_index);
    }

    #[test]
    fn test_default() {
        let graph: PhysicalGraph<u32, f64> = PhysicalGraph::default();

        assert_eq!(graph.graph.node_count(), 0);
        assert_eq!(graph.graph.edge_count(), 0);
    }

    #[test]
    fn test_repair_physical() {
        let mut graph = PhysicalGraph::<Coord, f64>::new();
        let node1 = TransitNode {
            id: 1,
            location: Coord { x: 0.0, y: 0.0 },
        };
        let node2 = TransitNode {
            id: 2,
            location: Coord { x: 1.0, y: 1.0 },
        };

        graph.add_transit_node(node1);
        graph.add_transit_node(node2);

        let edge = TransitEdge {
            id: 1,
            source: 1,
            target: 2,
            length: 1.0,
            path: LineString(vec![Coord { x: 1.0, y: 1.0 }, Coord { x: 0.0, y: 0.0 }]),
        };

        graph.add_transit_edge(edge.clone());

        graph.repair_edge(1, 2);

        let edge = graph.get_transit_edge(1, 2).unwrap();

        assert_eq!(
            edge.path,
            LineString(vec![Coord { x: 0.0, y: 0.0 }, Coord { x: 1.0, y: 1.0 }])
        );
    }
}