| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | |
| | | 4 | | namespace Itinero.MapMatching.Model; |
| | | 5 | | |
| | | 6 | | public class GraphModel |
| | | 7 | | { |
| | 40 | 8 | | private readonly List<GraphNode> _nodes = new(); |
| | 40 | 9 | | private readonly Dictionary<int, List<GraphEdge>> _edges = new(); |
| | | 10 | | |
| | 40 | 11 | | public GraphModel(Track track) |
| | 40 | 12 | | { |
| | 40 | 13 | | this.Track = track; |
| | 40 | 14 | | } |
| | | 15 | | |
| | 0 | 16 | | public Track Track { get; } |
| | | 17 | | |
| | 88 | 18 | | public int Count => _nodes.Count; |
| | | 19 | | |
| | 28268 | 20 | | public int? FirstNode { get; private set; } |
| | | 21 | | |
| | 23243 | 22 | | public int? LastNode { get; private set; } |
| | | 23 | | |
| | | 24 | | public int AddNode(GraphNode node) |
| | 13045 | 25 | | { |
| | 13045 | 26 | | var id = _nodes.Count; |
| | 13045 | 27 | | _nodes.Add(node); |
| | | 28 | | |
| | 13045 | 29 | | this.FirstNode = this.FirstNode ?? id; |
| | 13045 | 30 | | this.LastNode = id; |
| | 13045 | 31 | | return id; |
| | 13045 | 32 | | } |
| | | 33 | | |
| | | 34 | | public void AddEdge(GraphEdge edge) |
| | 129109 | 35 | | { |
| | 129109 | 36 | | if (!_edges.TryGetValue(edge.Node1, out var edges)) |
| | 11160 | 37 | | { |
| | 11160 | 38 | | edges = new List<GraphEdge>(); |
| | 11160 | 39 | | _edges.Add(edge.Node1, edges); |
| | 11160 | 40 | | } |
| | 129109 | 41 | | edges.Add(edge); |
| | 129109 | 42 | | } |
| | | 43 | | |
| | | 44 | | public GraphNode GetNode(int node) |
| | 27660 | 45 | | { |
| | 27660 | 46 | | return _nodes[node]; |
| | 27660 | 47 | | } |
| | | 48 | | |
| | | 49 | | public IEnumerable<GraphEdge> GetNeighbours(int node) |
| | 10142 | 50 | | { |
| | 10142 | 51 | | if (!_edges.TryGetValue(node, out var neighbours)) |
| | 170 | 52 | | { |
| | 170 | 53 | | return ArraySegment<GraphEdge>.Empty; |
| | | 54 | | } |
| | | 55 | | |
| | 9972 | 56 | | return neighbours; |
| | 10142 | 57 | | } |
| | | 58 | | |
| | | 59 | | /// <summary> |
| | | 60 | | /// Gets the edge between two specific nodes, or null if not found. |
| | | 61 | | /// </summary> |
| | | 62 | | public GraphEdge? GetEdge(int node1, int node2) |
| | 2030 | 63 | | { |
| | 2030 | 64 | | if (!_edges.TryGetValue(node1, out var edges)) return null; |
| | | 65 | | |
| | 14284 | 66 | | foreach (var edge in edges) |
| | 5112 | 67 | | { |
| | 7142 | 68 | | if (edge.Node2 == node2) return edge; |
| | 3082 | 69 | | } |
| | | 70 | | |
| | 0 | 71 | | return null; |
| | 2030 | 72 | | } |
| | | 73 | | } |