Exemple #1
0
        public void SetRootVertex()
        {
            var graph     = new AdjacencyGraph <int, Edge <int> >();
            var algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0, vertex => 0.0);

            SetRootVertex_Test(algorithm);
        }
        public static bool ComputeDistanceBetween <TVertex, TEdge>(this AStarShortestPathAlgorithm <TVertex, TEdge> algo, TVertex start, TVertex end, out IEnumerable <TEdge> path)
            where TEdge : IEdge <TVertex>
        {
            var wrap = new AStarWrapper <TVertex, TEdge>(algo, start, end);

            return(wrap.Compute(out path));
        }
        public void TryGetDistance_Throws()
        {
            var graph     = new AdjacencyGraph <TestVertex, Edge <TestVertex> >();
            var algorithm = new AStarShortestPathAlgorithm <TestVertex, Edge <TestVertex> >(graph, edge => 1.0, vertex => 0.0);

            TryGetDistance_Throws_Test(algorithm);
        }
        public static TryFunc <TVertex, IEnumerable <TEdge> > ShortestPathsAStar <TVertex, TEdge>(
#if !NET20
            this
#endif
            IVertexAndEdgeListGraph <TVertex, TEdge> visitedGraph,
            Func <TEdge, double> edgeWeights,
            Func <TVertex, double> costHeuristic,
            TVertex source
            )
            where TEdge : IEdge <TVertex>
        {
            Contract.Requires(visitedGraph != null);
            Contract.Requires(edgeWeights != null);
            Contract.Requires(costHeuristic != null);
            Contract.Requires(source != null);

            var algorithm           = new AStarShortestPathAlgorithm <TVertex, TEdge>(visitedGraph, edgeWeights, costHeuristic);
            var predecessorRecorder = new VertexPredecessorRecorderObserver <TVertex, TEdge>();

            using (predecessorRecorder.Attach(algorithm))
                algorithm.Compute(source);

            var predecessors = predecessorRecorder.VertexPredecessors;

            return(delegate(TVertex v, out IEnumerable <TEdge> edges)
            {
                return EdgeExtensions.TryGetPath(predecessors, v, out edges);
            });
        }
        public void AStar_HeuristicCallCount()
        {
            var lineGraph = new AdjacencyGraph <int, Edge <int> >();

            lineGraph.AddVerticesAndEdgeRange(new[]
            {
                new Edge <int>(2, 3),
                new Edge <int>(3, 4),
                new Edge <int>(2, 1),
                new Edge <int>(1, 0)
            });

            const int root = 2;

            var heuristicCalls = new List <int>();
            var algorithm      = new AStarShortestPathAlgorithm <int, Edge <int> >(
                lineGraph,
                _ => 1.0,
                v =>
            {
                // Goal is 2, h(v) = v
                heuristicCalls.Add(v);
                return(v);
            });

            algorithm.Compute(root);

            // Heuristic function must be called at least 4 times
            Assert.GreaterOrEqual(4, heuristicCalls.Count);

            // 0 must be expanded before 4
            Assert.Contains(0, heuristicCalls);
            Assert.Contains(4, heuristicCalls);
            Assert.Less(heuristicCalls.IndexOf(0), heuristicCalls.IndexOf(4));
        }
        public void ClearRootVertex()
        {
            var graph     = new AdjacencyGraph <int, Edge <int> >();
            var algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(graph, _ => 1.0, _ => 0.0);

            ClearRootVertex_Test(algorithm);
        }
        public void SetRootVertex_Throws()
        {
            var graph     = new AdjacencyGraph <TestVertex, Edge <TestVertex> >();
            var algorithm = new AStarShortestPathAlgorithm <TestVertex, Edge <TestVertex> >(graph, _ => 1.0, _ => 0.0);

            SetRootVertex_Throws_Test(algorithm);
        }
        private PathResult CalculatePath(PathNode start, PathNode stop)
        {
            var result = new PathResult();
            var astar  = new AStarShortestPathAlgorithm <PathNode, PathEdge>(
                _graph,
                edge => edge.Weight,
                node => node.Coords.DistanceTo(stop.Coords)
                );

            astar.SetRootVertex(start);
            astar.FinishVertex += vertex =>
            {
                if (Equals(vertex, stop))
                {
                    astar.Abort();
                }
            };

            var recorderObserver = new VertexPredecessorRecorderObserver <PathNode, PathEdge>();

            recorderObserver.Attach(astar);
            astar.Compute();
            var predecessors = recorderObserver.VertexPredecessors;

            if (predecessors.TryGetPath(stop, out var edges))
            {
                result.Status = PathStatus.Success;
                result.Path   = new List <PathEdge>(edges as PathEdge[] ?? edges.ToArray());
                return(result);
            }

            result.Status  = PathStatus.NotFound;
            result.Message = $"No path found between {start.Id} and {stop.Id}";
            return(result);
        }
 public AStarWrapper(AStarShortestPathAlgorithm <TVertex, TEdge> innerAlgo, TVertex root, TVertex target)
 {
     innerAlgorithm = innerAlgo;
     this.innerAlgorithm.SetRootVertex(root);
     this.target = target;
     this.innerAlgorithm.FinishVertex += new VertexAction <TVertex>(innerAlgorithm_FinishVertex);
 }
        public void AStar_Throws()
        {
            var edge12 = new Edge <int>(1, 2);
            var edge23 = new Edge <int>(2, 3);
            var edge34 = new Edge <int>(3, 4);

            var negativeWeightGraph = new AdjacencyGraph <int, Edge <int> >();

            negativeWeightGraph.AddVerticesAndEdgeRange(new[]
            {
                edge12, edge23, edge34
            });

            var algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(
                negativeWeightGraph,
                e =>
            {
                if (e == edge12)
                {
                    return(12.0);
                }
                if (e == edge23)
                {
                    return(-23.0);
                }
                if (e == edge34)
                {
                    return(34.0);
                }
                return(1.0);
            },
                v => 0.0);

            Assert.Throws <NegativeWeightException>(() => algorithm.Compute(1));
        }
Exemple #11
0
        public void Constructor()
        {
            Func <int, double>        Heuristic = v => 1.0;
            Func <Edge <int>, double> Weights   = e => 1.0;

            var graph     = new AdjacencyGraph <int, Edge <int> >();
            var algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(graph, Weights, Heuristic);

            AssertAlgorithmProperties(algorithm, graph, Heuristic, Weights);

            algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(graph, Weights, Heuristic, DistanceRelaxers.CriticalDistance);
            AssertAlgorithmProperties(algorithm, graph, Heuristic, Weights, DistanceRelaxers.CriticalDistance);

            algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(null, graph, Weights, Heuristic, DistanceRelaxers.CriticalDistance);
            AssertAlgorithmProperties(algorithm, graph, Heuristic, Weights, DistanceRelaxers.CriticalDistance);

            #region Local function

            void AssertAlgorithmProperties <TVertex, TEdge>(
                AStarShortestPathAlgorithm <TVertex, TEdge> algo,
                IVertexListGraph <TVertex, TEdge> g,
                Func <TVertex, double> heuristic = null,
                Func <TEdge, double> eWeights    = null,
                IDistanceRelaxer relaxer         = null)
                where TEdge : IEdge <TVertex>
            {
                AssertAlgorithmState(algo, g);
                Assert.IsNull(algo.VerticesColors);
                if (heuristic is null)
                {
                    Assert.IsNotNull(algo.CostHeuristic);
                }
                else
                {
                    Assert.AreSame(heuristic, algo.CostHeuristic);
                }
                if (eWeights is null)
                {
                    Assert.IsNotNull(algo.Weights);
                }
                else
                {
                    Assert.AreSame(eWeights, algo.Weights);
                }
                Assert.IsNull(algo.Distances);
                if (relaxer is null)
                {
                    Assert.IsNotNull(algo.DistanceRelaxer);
                }
                else
                {
                    Assert.AreSame(relaxer, algo.DistanceRelaxer);
                }
            }

            #endregion
        }
Exemple #12
0
        public void ComputeWithRoot()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVertex(0);
            var algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0, vertex => 0.0);

            ComputeWithRoot_Test(algorithm);
        }
Exemple #13
0
        public void TryGetDistance()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVertex(1);
            var algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0, vertex => 0.0);

            TryGetDistance_Test(algorithm);
        }
        public static IDictionary <int, double> Get(AdjacencyGraph <int, Edge <int> > graph, int root)
        {
            Func <int, double>        Heuristic = v => 1.0;
            Func <Edge <int>, double> Weights   = e => 1.0;

            var algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(graph, Weights, Heuristic);

            algorithm.Compute(root);
            return(algorithm.Distances);
        }
        public static IDictionary <string, double> Get(AdjacencyGraph <string, TaggedEdge <string, string> > graph, string root)
        {
            Func <string, double> Heuristic = v => 1.0;
            Func <TaggedEdge <string, string>, double> Weights = e => double.Parse(e.Tag);

            var algorithm = new AStarShortestPathAlgorithm <string, TaggedEdge <string, string> >(graph, Weights, Heuristic);

            algorithm.Compute(root);
            return(algorithm.Distances);
        }
Exemple #16
0
        public bool CreateCustomRoute(CustomRouteRequest route, out IList <RouteResponse> result)
        {
            var routes = _context.GradedRoutesWithIncludedRelatedData();
            var places = FindPlacesFromRoutes(routes);

            PlaceResponse start = route.Start;
            PlaceResponse end   = route.End;

            double distanceFromStart = FindClosestPlace(start, places, out Miejsce closestToStart);
            double distanceFromEnd   = FindClosestPlace(end, places, out Miejsce closestToEnd);

            if (distanceFromStart <= MAXIMUM_DISTANCE && distanceFromEnd <= MAXIMUM_DISTANCE)
            {
                var mountainGroup     = FindMountainGroup(closestToStart);
                var mountainGroupName = _context.GrupaGorska.First(m => m.Id == mountainGroup).Nazwa;
                routes = routes.Where(r => r.GrupaGorskaId == mountainGroup).ToList();
                places = FindPlacesFromRoutes(routes);

                //create graph from locations in a mountain group
                var graph = new BidirectionalGraph <PlaceVertex, Edge <PlaceVertex> >();
                var edgeCostDictionary = new Dictionary <Edge <PlaceVertex>, int>();
                PopulateGraph(graph, edgeCostDictionary, places, routes);

                //find path between start location and end location using A* Algorithm
                AStarShortestPathAlgorithm <PlaceVertex, Edge <PlaceVertex> > astar = new AStarShortestPathAlgorithm <PlaceVertex, Edge <PlaceVertex> >(graph, x => edgeCostDictionary[x], x => 0);
                var startVertex = new PlaceVertex(closestToStart.Id);
                var endVertex   = new PlaceVertex(closestToEnd.Id);

                if (astar.ComputeDistanceBetween(startVertex, endVertex, out var path))
                {
                    result = new List <RouteResponse>();
                    if (distanceFromStart >= MINIMUM_DISTANCE)
                    {
                        result.Add(RouteResponse.CreateCustomRoute(start, PlaceResponse.BuildFromModel(closestToStart), mountainGroupName, distanceFromStart));
                    }
                    result = result.Concat(CreateResponseListFromPath(path)).ToList();
                    if (distanceFromEnd >= MINIMUM_DISTANCE)
                    {
                        result.Add(RouteResponse.CreateCustomRoute(PlaceResponse.BuildFromModel(closestToEnd), end, mountainGroupName, distanceFromEnd));
                    }
                    return(true);
                }
                else
                {
                    result = new List <RouteResponse>();
                    return(false);
                }
            }
            else
            {
                result = new List <RouteResponse>();
                return(false);
            }
        }
Exemple #17
0
        public void GetVertexColor_Throws()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVertex(0);
            var algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0, vertex => 0.0);

            algorithm.Compute(0);

            // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
            Assert.Throws <VertexNotFoundException>(() => algorithm.GetVertexColor(1));
        }
Exemple #18
0
        public void GetVertexColor()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVerticesAndEdge(new Edge <int>(1, 2));

            var algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0, vertex => 0.0);

            algorithm.Compute(1);

            Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(1));
            Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(2));
        }
Exemple #19
0
        public RiskResult CalculateMinimalRisk(IVertexAndEdgeListGraph<Station, StationPath> graph, Station from, Station to)
        {
            Func<StationPath, double> calcWeight = visiting => visiting.Risk;
            Func<Station, double> calcHeuristic = visiting => visiting.CalculateRisk(to);

            var algorithm = new AStarShortestPathAlgorithm<Station, StationPath>(graph, calcWeight, calcHeuristic);
            var pathRecorder = new VertexPredecessorRecorderObserver<Station, StationPath>();
            using (pathRecorder.Attach(algorithm))
            {
                algorithm.Compute(from);
                IEnumerable<StationPath> path;
                pathRecorder.TryGetPath(to, out path);

                return new RiskResult(path, from.RadianLocation.Radius);
            }
        }
        public static IEnumerable <Edge <GraphVertex> > ShortestWayAstarAlgorithm(List <GraphVertex> listVertex, List <GraphEdge> listEdge, GraphVertex start, GraphVertex end)
        {
            AdjacencyGraph <GraphVertex, Edge <GraphVertex> > graph = new AdjacencyGraph <GraphVertex, Edge <GraphVertex> >();

            foreach (var vert in listVertex)
            {
                graph.AddVertex(vert);
            }
            foreach (var edge in listEdge)
            {
                graph.AddEdge(new Edge <GraphVertex>(edge.StartVertex, edge.EndVertex));
            }
            Dictionary <Edge <GraphVertex>, double> edgeCost = new Dictionary <Edge <GraphVertex>, double>();
            int i = 0;

            foreach (var edge in graph.Edges)
            {
                double eCost = EdgeCostSearching(edge.Source, edge.Target, listEdge);
                edgeCost.Add(edge, eCost);
                i++;
            }


            Func <Edge <GraphVertex>, double> getW = edge => edgeCost[edge];

            //---------------------------------
            IEnumerable <Edge <GraphVertex> > edgessAstar;
            AStarShortestPathAlgorithm <GraphVertex, Edge <GraphVertex> >     astar    = new AStarShortestPathAlgorithm <GraphVertex, Edge <GraphVertex> >(graph, getW, x => 0.0);
            VertexDistanceRecorderObserver <GraphVertex, Edge <GraphVertex> > distObsA = new VertexDistanceRecorderObserver <GraphVertex, Edge <GraphVertex> >(getW);

            using (distObsA.Attach(astar))
            {
                VertexPredecessorRecorderObserver <GraphVertex, Edge <GraphVertex> > predObs = new VertexPredecessorRecorderObserver <GraphVertex, Edge <GraphVertex> >();
                using (predObs.Attach(astar))
                {
                    astar.Compute(start);
                    if (predObs.TryGetPath(end, out edgessAstar))
                    {
                        return(edgessAstar);
                    }
                }
            }
            return(null);
        }
        public static AStarShortestPathAlgorithm <T, Edge <T> > CreateAlgorithmAndMaybeDoComputation <T>(
            [NotNull] ContractScenario <T> scenario)
        {
            var graph = new AdjacencyGraph <T, Edge <T> >();

            graph.AddVerticesAndEdgeRange(scenario.EdgesInGraph.Select(e => new Edge <T>(e.Source, e.Target)));
            graph.AddVertexRange(scenario.SingleVerticesInGraph);

            double Heuristic(T v) => 1.0;
            double Weights(Edge <T> e) => 1.0;

            var algorithm = new AStarShortestPathAlgorithm <T, Edge <T> >(graph, Weights, Heuristic);

            if (scenario.DoComputation)
            {
                algorithm.Compute(scenario.Root);
            }
            return(algorithm);
        }
Exemple #22
0
        private static void RunAStarAndCheck <TVertex, TEdge>(
            [NotNull] IVertexAndEdgeListGraph <TVertex, TEdge> graph,
            [NotNull] TVertex root)
            where TEdge : IEdge <TVertex>
        {
            var distances = new Dictionary <TEdge, double>();

            foreach (TEdge edge in graph.Edges)
            {
                distances[edge] = graph.OutDegree(edge.Source) + 1;
            }

            var algorithm = new AStarShortestPathAlgorithm <TVertex, TEdge>(
                graph,
                e => distances[e],
                v => 0.0);

            algorithm.InitializeVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.White, algorithm.VerticesColors[vertex]);
            };

            algorithm.DiscoverVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.Gray, algorithm.VerticesColors[vertex]);
            };

            algorithm.FinishVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.Black, algorithm.VerticesColors[vertex]);
            };

            var predecessors = new VertexPredecessorRecorderObserver <TVertex, TEdge>();

            using (predecessors.Attach(algorithm))
                algorithm.Compute(root);

            Assert.IsNotNull(algorithm.Distances);
            Assert.AreEqual(graph.VertexCount, algorithm.Distances.Count);

            Verify(algorithm, predecessors);
        }
        public void RunAStarAndCheck <TVertex, TEdge>([NotNull] IVertexAndEdgeListGraph <TVertex, TEdge> graph, [NotNull] TVertex root)
            where TEdge : IEdge <TVertex>
        {
            var distances = new Dictionary <TEdge, double>();

            foreach (TEdge edge in graph.Edges)
            {
                distances[edge] = graph.OutDegree(edge.Source) + 1;
            }

            var algorithm = new AStarShortestPathAlgorithm <TVertex, TEdge>(
                graph,
                e => distances[e],
                v => 0);
            var predecessors = new VertexPredecessorRecorderObserver <TVertex, TEdge>();

            using (predecessors.Attach(algorithm))
                algorithm.Compute(root);

            Verify(algorithm, predecessors);
        }
 private static void Verify <TVertex, TEdge>(
     [NotNull] AStarShortestPathAlgorithm <TVertex, TEdge> algorithm,
     [NotNull] VertexPredecessorRecorderObserver <TVertex, TEdge> predecessors)
     where TEdge : IEdge <TVertex>
 {
     // Verify the result
     foreach (TVertex vertex in algorithm.VisitedGraph.Vertices)
     {
         if (!predecessors.VertexPredecessors.TryGetValue(vertex, out TEdge predecessor))
         {
             continue;
         }
         if (predecessor.Source.Equals(vertex))
         {
             continue;
         }
         Assert.AreEqual(
             algorithm.TryGetDistance(vertex, out _),
             algorithm.TryGetDistance(predecessor.Source, out _));
     }
 }
        public void AStar_HeuristicCalls()
        {
            var edge01 = new Edge <int>(0, 1);
            var edge02 = new Edge <int>(0, 2);
            var edge03 = new Edge <int>(0, 3);
            var edge14 = new Edge <int>(1, 4);
            var edge23 = new Edge <int>(2, 3);
            var edge34 = new Edge <int>(3, 4);

            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVerticesAndEdgeRange(new[]
            {
                edge01,
                edge02,
                edge03,
                edge23,
                edge14,
                edge34
            });

            const int root = 0;

            var colorUpdates = new HashSet <GraphColor>
            {
                GraphColor.White, GraphColor.Gray, GraphColor.Black
            };

            int heuristicCalls = 0;
            AStarShortestPathAlgorithm <int, Edge <int> > algorithm = null;
            Func <int, double> heuristic = v =>
            {
                // ReSharper disable once PossibleNullReferenceException
                // ReSharper disable once AccessToModifiedClosure
                colorUpdates.Remove(algorithm.GetVertexColor(v));
                ++heuristicCalls;
                return(10.0 / heuristicCalls);
            };

            algorithm = new AStarShortestPathAlgorithm <int, Edge <int> >(
                graph,
                e =>
            {
                if (e == edge01)
                {
                    return(8.0);
                }
                if (e == edge02)
                {
                    return(6.0);
                }
                if (e == edge03)
                {
                    return(20.0);
                }
                if (e == edge34)
                {
                    return(5.0);
                }
                return(1.0);
            },
                heuristic);

            algorithm.Compute(root);

            CollectionAssert.IsEmpty(colorUpdates);
        }
 public JobSchedulerAlgorithm()
 {
     var astart = new AStarShortestPathAlgorithm<IJob, IEdge<IJob>>(new AdjacencyGraph<IJob, IEdge<IJob>>(false, 1000), Weights, CostHeuristic);
 }
Exemple #27
0
 public JobSchedulerAlgorithm()
 {
     var astart = new AStarShortestPathAlgorithm <IJob, IEdge <IJob> >(new AdjacencyGraph <IJob, IEdge <IJob> >(false, 1000), Weights, CostHeuristic);
 }