Example #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DelegateBidirectionalIncidenceGraph{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="tryGetOutEdges">Getter of out-edges.</param>
 /// <param name="tryGetInEdges">Getter of in-edges.</param>
 /// <param name="allowParallelEdges">
 /// Indicates if parallel edges are allowed.
 /// Note that get of edges is delegated so you may have bugs related
 /// to parallel edges due to the delegated implementation.
 /// </param>
 /// <exception cref="T:System.ArgumentNullException"><paramref name="tryGetOutEdges"/> is <see langword="null"/>.</exception>
 /// <exception cref="T:System.ArgumentNullException"><paramref name="tryGetInEdges"/> is <see langword="null"/>.</exception>
 public DelegateBidirectionalIncidenceGraph(
     [NotNull] TryFunc <TVertex, IEnumerable <TEdge> > tryGetOutEdges,
     [NotNull] TryFunc <TVertex, IEnumerable <TEdge> > tryGetInEdges,
     bool allowParallelEdges = true)
     : base(tryGetOutEdges, allowParallelEdges)
 {
     _tryGetInEdgesFunc = tryGetInEdges ?? throw new ArgumentNullException(nameof(tryGetInEdges));
 }
Example #2
0
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="getter"></param>
 /// <param name="threadSafe"></param>
 public DemandDictionary(TryFunc <TKey, TValue> getter, bool threadSafe)
     : this(getter, threadSafe ? (IDictionary <TKey, TValue>) new ConcurrentDictionary <TKey, TValue>() : new Dictionary <TKey, TValue>())
 {
     if (getter == null)
     {
         throw new ArgumentNullException(nameof(getter));
     }
 }
Example #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DelegateUndirectedGraph{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="vertices">Graph vertices.</param>
 /// <param name="tryGetAdjacentEdges">Getter of adjacent edges.</param>
 /// <param name="allowParallelEdges">
 /// Indicates if parallel edges are allowed.
 /// Note that get of edges is delegated so you may have bugs related
 /// to parallel edges due to the delegated implementation.
 /// </param>
 public DelegateUndirectedGraph(
     IEnumerable <TVertex> vertices,
     TryFunc <TVertex, IEnumerable <TEdge> > tryGetAdjacentEdges,
     bool allowParallelEdges = true)
     : base(tryGetAdjacentEdges, allowParallelEdges)
 {
     _vertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
 }
Example #4
0
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="getter"></param>
 public DemandDictionary(TryFunc <TKey, TValue> getter)
     : this(getter, false)
 {
     if (getter == null)
     {
         throw new ArgumentNullException(nameof(getter));
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DelegateVertexAndEdgeListGraph{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="vertices">Graph vertices.</param>
 /// <param name="tryGetOutEdges">Getter of out-edges.</param>
 /// <param name="allowParallelEdges">
 /// Indicates if parallel edges are allowed.
 /// Note that get of edges is delegated so you may have bugs related
 /// to parallel edges due to the delegated implementation.
 /// </param>
 public DelegateVertexAndEdgeListGraph(
     [NotNull, ItemNotNull] IEnumerable <TVertex> vertices,
     [NotNull] TryFunc <TVertex, IEnumerable <TEdge> > tryGetOutEdges,
     bool allowParallelEdges = true)
     : base(tryGetOutEdges, allowParallelEdges)
 {
     _vertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
 }
Example #6
0
        public DelegateBidirectionalIncidenceGraph(
            TryFunc <TVertex, IEnumerable <TEdge> > tryGetOutEdges,
            TryFunc <TVertex, IEnumerable <TEdge> > tryGetInEdges)
            : base(tryGetOutEdges)
        {
            //Contract.Requires(tryGetInEdges != null);

            this.tryGetInEdges = tryGetInEdges;
        }
Example #7
0
        public bool IsRoutePossible(IPlatformModule sourceModule, IPlatformModule targetModule)
        {
            Func <ModuleGraphEdge, double> edgeCost = x => 1;
            TryFunc <IPlatformModule, IEnumerable <ModuleGraphEdge> > tryGetPaths = Graph.ShortestPathsDijkstra(edgeCost, sourceModule);

            IEnumerable <ModuleGraphEdge> path;

            return(tryGetPaths(targetModule, out path));
        }
        public void TestPDFCreator()
        {
            TryFunc <int, IEnumerable <Edge <int> > > tryGetPath = this.graph.ShortestPathsDijkstra(this.edgeCost, 0);
            DotGenerator <int, Edge <int> >           generator  = new DotGenerator <int, Edge <int> >(graph, tryGetPath);

            (new PDFGenerator(generator.GetDotCode(), "test.pdf")).GeneratePDF();
            FileAssert.Exists("test.pdf");
            File.Delete("test.pdf");
        }
        public DelegateImplicitUndirectedGraph(
            TryFunc <TVertex, IEnumerable <TEdge> > tryGetAdjacenyEdges,
            bool allowParallelEdges)
        {
            Contract.Requires(tryGetAdjacenyEdges != null);

            this.tryGetAdjacentEdges = tryGetAdjacenyEdges;
            this.allowParallelEdges  = allowParallelEdges;
        }
Example #10
0
        public IEnumerable <IBranch> GetShortestPath(INode source, INode target, Func <IBranch, double> weights)
        {
            TryFunc <INode, IEnumerable <IBranch> > result = this.ShortestPathsDijkstra(b => b.Length, source);
            IEnumerable <IBranch> path;

            result(target, out path);

            return(path);
        }
Example #11
0
        private static void CompareAlgorithms <TVertex, TEdge, TGraph>(
            [NotNull] AdjacencyGraph <TVertex, TEdge> graph,
            [NotNull, InstantHandle] Func <TEdge, double> getDistances,
            [NotNull, InstantHandle] Func <AdjacencyGraph <TVertex, TEdge>, Func <TEdge, double>, ShortestPathAlgorithmBase <TVertex, TEdge, TGraph> > shortestPathAlgorithmFactory)
            where TEdge : IEdge <TVertex>
            where TGraph : IVertexSet <TVertex>
        {
            // Compute all paths
            var algorithm = new FloydWarshallAllShortestPathAlgorithm <TVertex, TEdge>(graph, getDistances);

            algorithm.Compute();

            TVertex[] vertices = graph.Vertices.ToArray();
            foreach (TVertex source in vertices)
            {
                ShortestPathAlgorithmBase <TVertex, TEdge, TGraph> otherAlgorithm = shortestPathAlgorithmFactory(graph, getDistances);
                var predecessors = new VertexPredecessorRecorderObserver <TVertex, TEdge>();
                using (predecessors.Attach(otherAlgorithm))
                    otherAlgorithm.Compute(source);

                TryFunc <TVertex, IEnumerable <TEdge> > otherPaths = predecessors.TryGetPath;
                foreach (TVertex target in vertices)
                {
                    if (source.Equals(target))
                    {
                        continue;
                    }

                    bool pathExists = algorithm.TryGetPath(source, target, out IEnumerable <TEdge> floydPath);
                    Assert.AreEqual(pathExists, otherPaths(target, out IEnumerable <TEdge> otherPath));

                    if (pathExists)
                    {
                        TEdge[] floydEdges = floydPath.ToArray();
                        CheckPath(source, target, floydEdges);

                        TEdge[] otherEdges = otherPath.ToArray();
                        CheckPath(source, target, otherEdges);

                        // All distances are usually 1 in this test, so it should at least
                        // be the same number
                        if (otherEdges.Length != floydEdges.Length)
                        {
                            Assert.Fail("Path do not have the same length.");
                        }

                        // Check path length are the same
                        double floydLength = floydEdges.Sum(getDistances);
                        double otherLength = otherEdges.Sum(getDistances);
                        if (Math.Abs(floydLength - otherLength) > double.Epsilon)
                        {
                            Assert.Fail("Path do not have the same length.");
                        }
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        /// Creates an instance of DelegateIncidenceGraph.
        /// </summary>
        /// <typeparam name="TVertex">type of the vertices</typeparam>
        /// <typeparam name="TEdge">type of the edges</typeparam>
        /// <param name="tryGetOutEdges"></param>
        /// <returns></returns>
        public static DelegateIncidenceGraph <TVertex, TEdge> ToDelegateIncidenceGraph <TVertex, TEdge>(
#if !NET20
            this
#endif
            TryFunc <TVertex, IEnumerable <TEdge> > tryGetOutEdges)
            where TEdge : IEdge <TVertex>, IEquatable <TEdge>
        {
            Contract.Requires(tryGetOutEdges != null);
            return(new DelegateIncidenceGraph <TVertex, TEdge>(tryGetOutEdges));
        }
        public void TestShortestPaths()
        {
            TryFunc <int, IEnumerable <Edge <int> > > tryGetPath = this.graph.ShortestPathsDijkstra(this.edgeCost, 0);
            IEnumerable <Edge <int> > path;

            Assert.IsFalse(tryGetPath(0, out path));
            tryGetPath(2, out path);
            int[] pattern = new int[] { 4, 2 };
            Assert.IsTrue(this.checkPath(path, pattern));
        }
Example #14
0
        /// <summary>
        /// Creates an instance of DelegateIncidenceGraph.
        /// </summary>
        /// <typeparam name="TVertex">type of the vertices</typeparam>
        /// <typeparam name="TEdge">type of the edges</typeparam>
        /// <param name="tryGetOutEdges"></param>
        /// <param name="tryGetInEdges"></param>
        /// <returns></returns>
        public static DelegateBidirectionalIncidenceGraph <TVertex, TEdge> ToDelegateBidirectionalIncidenceGraph <TVertex, TEdge>
            (this TryFunc <TVertex, IEnumerable <TEdge> > tryGetOutEdges,
            TryFunc <TVertex, IEnumerable <TEdge> > tryGetInEdges)
            where TEdge : IEdge <TVertex>, IEquatable <TEdge>
        {
            Contract.Requires(tryGetOutEdges != null);
            Contract.Requires(tryGetInEdges != null);

            return(new DelegateBidirectionalIncidenceGraph <TVertex, TEdge>(tryGetOutEdges, tryGetInEdges));
        }
        private IEnumerable <Conversion> ComputeShortestPath(Unit start, Unit end)
        {
            // Find a path from the source to the target
            Func <Conversion, double> edgeCost = e => 1;

            TryFunc <Unit, IEnumerable <Conversion> > tryGetPaths = this.ShortestPathsDijkstra(edgeCost, start);

            IEnumerable <Conversion> path;

            return(tryGetPaths(end, out path) ? path : null);
        }
Example #16
0
 public static IEnumerable <TResult> Execute <TInput, TResult>(this TryFunc <TInput, IEnumerable <TResult> > tryFunc, TInput input)
 {
     if (tryFunc(input, out var result))
     {
         return(result);
     }
     else
     {
         return(Enumerable.Empty <TResult>());
     }
 }
 public DictionaryAdapter(
     TryFunc <TKey, TValue> getCallback,
     Func <IEnumerable <TKey> > keyEnumerable,
     Action <TKey, TValue> addOrSetCallback,
     Predicate <TKey> removeCallback)
 {
     this.GetCallback      = getCallback;
     this.AddOrSetCallback = addOrSetCallback;
     this.RemoveCallback   = removeCallback;
     this.KeyEnumerable    = keyEnumerable;
 }
        public void TestGraphWithOneVertex()
        {
            Matrix matrix = new Matrix(
                new int[][] {
                new int[] { -1 }
            });
            TryFunc <int, IEnumerable <Edge <int> > > tryGetPath = this.createTryGetPath(matrix);
            IEnumerable <Edge <int> > edges;

            Assert.IsFalse(tryGetPath(0, out edges));
        }
Example #19
0
 public static IEnumerable <TResult> SelectTry <TSource, TResult>(
     this IEnumerable <TSource> source, TryFunc <TSource, TResult> selector)
 {
     foreach (TSource item in source)
     {
         TResult result;
         if (selector(item, out result))
         {
             yield return(result);
         }
     }
 }
Example #20
0
        public static bool TryRetryFail(int retries, TryFunc thisFunction)
        {
            bool actionSucceeded = false;
            int  tryCounter      = 0;

            while ((actionSucceeded == false) && (tryCounter < retries))
            {
                actionSucceeded = thisFunction();
                tryCounter++;
            }

            return(actionSucceeded);
        }
Example #21
0
 ///  <summary>
 ///
 ///  </summary>
 ///  <typeparam name="TSource"></typeparam>
 ///  <typeparam name="TResult"></typeparam>
 /// <typeparam name="TValue"></typeparam>
 /// <param name="source"></param>
 ///  <param name="selector"></param>
 /// <param name="executor"></param>
 /// <returns></returns>
 public static IEnumerable <TResult> SelectTry <TSource, TValue, TResult>(
     this IEnumerable <TSource> source,
     Func <TSource, TValue> selector,
     TryFunc <TValue, TResult> executor)
 {
     foreach (TSource s in source)
     {
         if (executor(selector(s), out TResult r))
         {
             yield return(r);
         }
     }
 }
Example #22
0
 public DelegateVertexAndEdgeListGraph(
     IEnumerable <TVertex> vertices,
     TryFunc <TVertex, IEnumerable <TEdge> > tryGetOutEdges)
     : base(tryGetOutEdges)
 {
     Contract.Requires(vertices != null);
     Contract.Requires(Enumerable.All(vertices, v =>
     {
         IEnumerable <TEdge> edges;
         return(tryGetOutEdges(v, out edges));
     }));
     this.vertices = vertices;
 }
 public DelegateUndirectedGraph(
     IEnumerable <TVertex> vertices,
     TryFunc <TVertex, IEnumerable <TEdge> > tryGetAdjacentEdges,
     bool allowParallelEdges)
     : base(tryGetAdjacentEdges, allowParallelEdges)
 {
     Contract.Requires(vertices != null);
     Contract.Requires(Enumerable.All(vertices, v =>
     {
         IEnumerable <TEdge> edges;
         return(tryGetAdjacentEdges(v, out edges));
     }));
     this.vertices = vertices;
 }
        private readonly Func <TEdge, double> _edgeCost = e => 1; // constant cost

        public IEnumerable <TEdge> Find(TGraph dataGraph)

        {
            IEnumerable <DataVertex> vertices = dataGraph.Vertices;

            DataVertex root   = GetVertexBySymbol(vertices, new Start().Symbol);
            DataVertex target = GetVertexBySymbol(vertices, new Quit().Symbol);

            // compute shortest paths
            TryFunc <DataVertex, IEnumerable <TEdge> > tryGetPaths = dataGraph.ShortestPathsDijkstra(_edgeCost, root);

            tryGetPaths(target, out IEnumerable <TEdge> path);
            return(path);
        }
Example #25
0
        protected override void InternalCompute()
        {
            var visibilityGraph = new VisibilityGraph();

            foreach (TVertex vertex in VisitedGraph.Vertices)
            {
                Point pos  = _vertexPositions[vertex];
                Size  sz   = _vertexSizes[vertex];
                var   rect = new Rect(new Point(pos.X - (sz.Width / 2), pos.Y - (sz.Height / 2)), sz);
                rect.Inflate(_parameters.VertexMargin, _parameters.VertexMargin);
                visibilityGraph.Obstacles.Add(new Obstacle(rect.TopLeft, rect.TopRight, rect.BottomRight, rect.BottomLeft));
            }

            foreach (TEdge edge in VisitedGraph.Edges)
            {
                visibilityGraph.SinglePoints.Add(_vertexPositions[edge.Source]);
                visibilityGraph.SinglePoints.Add(_vertexPositions[edge.Target]);
            }

            var vertexPoints = new HashSet <PointVertex>(_vertexPositions.Select(kvp => new PointVertex(kvp.Value)));

            visibilityGraph.Compute();
            IUndirectedGraph <PointVertex, Edge <PointVertex> > graph = visibilityGraph.Graph;
            var usedEdges = new HashSet <Edge <PointVertex> >();

            foreach (TEdge edge in VisitedGraph.Edges)
            {
                var pos1 = new PointVertex(_vertexPositions[edge.Source]);
                var pos2 = new PointVertex(_vertexPositions[edge.Target]);
                TryFunc <PointVertex, IEnumerable <Edge <PointVertex> > > paths = graph.ShortestPathsDijkstra(e => GetWeight(vertexPoints, usedEdges, pos1, pos2, e), pos1);
                IEnumerable <Edge <PointVertex> > path;
                if (paths(pos2, out path))
                {
                    var         edgeRoute = new List <Point>();
                    bool        first     = true;
                    PointVertex point     = pos1;
                    foreach (Edge <PointVertex> e in path)
                    {
                        if (!first)
                        {
                            edgeRoute.Add(point.Point);
                        }
                        usedEdges.Add(e);
                        point = e.GetOtherVertex(point);
                        first = false;
                    }
                    _edgeRoutes[edge] = edgeRoute.ToArray();
                }
            }
        }
Example #26
0
        public virtual IEnumerable <IBranch> GetShortestPath(INode source, INode target, Func <IBranch, double> weights)
        {
            if (source == null || target == null)
            {
                return(new List <IBranch>());
            }

            TryFunc <INode, IEnumerable <IBranch> > result = this.ShortestPathsDijkstra(b => b.Length, source);
            IEnumerable <IBranch> path;

            result(target, out path);

            return(path ?? new List <IBranch>());
        }
Example #27
0
 /// <summary>
 /// 使用委托 封装try--catch---finally
 /// </summary>
 /// <param name="tryFunc"></param>
 /// <param name="errorFunc"></param>
 /// <param name="finallyFunc"></param>
 public static void TryCatchFuc(TryFunc tryFunc, ErrorFunc errorFunc, FinallyFunc finallyFunc)
 {
     try
     {
         tryFunc.Invoke();
     }
     catch (Exception ex)
     {
         errorFunc?.Invoke(ex);
     }
     finally
     {
         finallyFunc();
     }
 }
 static void Main(String[] args)
 {
     try {
         String path = args[0];
         (IVertexAndEdgeListGraph <int, Edge <int> > graph,
          Func <Edge <int>, double> edgeCost) = new GraphCreator(MatrixReader.ReadMatrix(path)).GetResult();
         TryFunc <int, IEnumerable <Edge <int> > > tryGetPath = graph.ShortestPathsDijkstra(edgeCost, 0);
         DotGenerator <int, Edge <int> >           generator  = new DotGenerator <int, Edge <int> >(graph, tryGetPath);
         (new PDFGenerator(generator.GetDotCode(), args[1])).GeneratePDF();
     } catch (IndexOutOfRangeException exn) {
         Console.Error.WriteLine("Path to adjacency matrix should be given.");
     } catch (Exception exn) {
         Console.Error.WriteLine(exn.Message);
     }
 }
Example #29
0
 static void Main(string[] args)
 {
     try
     {
         String path = args[0];
         (IVertexAndEdgeListGraph <int, Edge <int> > graph,
          Func <Edge <int>, double> edgeCost) = GraphCreator.Create(MatrixReader.Read(path));
         TryFunc <int, IEnumerable <Edge <int> > > tryGetPath = graph.ShortestPathsDijkstra(edgeCost, 0);
         PdfGenerator.Generate(DotGenerator <int, Edge <int> > .GetDotCode(graph, tryGetPath), args[1]);
     }
     catch (IndexOutOfRangeException)
     {
         Console.Error.WriteLine("Path to graph matrix must be given");
     }
 }
Example #30
0
        /// <summary>
        /// Creates an instance of DelegateIncidenceGraph.
        /// </summary>
        /// <param name="vertices"></param>
        /// <typeparam name="TVertex">type of the vertices</typeparam>
        /// <typeparam name="TEdge">type of the edges</typeparam>
        /// <param name="tryGetAdjacentEdges"></param>
        /// <returns></returns>
        public static DelegateUndirectedGraph <TVertex, TEdge> ToDelegateUndirectedGraph <TVertex, TEdge>
            (this IEnumerable <TVertex> vertices,
            TryFunc <TVertex, IEnumerable <TEdge> > tryGetAdjacentEdges)
            where TEdge : IEdge <TVertex>, IEquatable <TEdge>
        {
            Contract.Requires(vertices != null);
            Contract.Requires(tryGetAdjacentEdges != null);
            Contract.Requires(Enumerable.All(vertices, v =>
            {
                IEnumerable <TEdge> edges;
                return(tryGetAdjacentEdges(v, out edges));
            }));

            return(new DelegateUndirectedGraph <TVertex, TEdge>(vertices, tryGetAdjacentEdges, true));
        }
Example #31
0
        private List<int> PathToItem(List<int> finalPath,int from,int to)
        {
            this.tryPath = this.graph.ShortestPathsDijkstra(edgeWeights, from);
            IEnumerable<SEquatableEdge<int>> path;

            if (this.tryPath(to, out path))
            {
                foreach (var node in path)
                {
                    finalPath.Add(node.Target);
                    locations[node.Target] = 0;
                }
            }
            return finalPath;
        }