Ejemplo n.º 1
0
        /// <summary>
        /// the recursive call
        /// </summary>
        /// <param name="nodeValue"></param>
        /// <param name="nodePath"></param>
        /// <param name="nodeStore"></param>
        /// <param name="traversalIndex"></param>
        private void BuildNode(object nodeValue, GraphPath nodePath)
        {
            //skip if indicated
            if (this.SkipFilter != null && this.SkipFilter(nodeValue, nodePath))
            {
                return;
            }

            //get the manager for this node value
            var manager = this.ChainOfResponsibility.FindHandlingValueManager(nodeValue, this);

            Condition.Requires(manager).IsNotNull();

            //using the manager, serialize node value, and build the node
            var val = manager.DehydrateValue(nodeValue, this);

            this.Counter.Increment();
            var node = GraphNode.New(nodePath, nodeValue, this.Counter.Current, manager.Id, val);

            //save the node
            this.NodeStore.SaveItem(node);

            var traverseList = manager.GetChildTraversalNodes(nodeValue, nodePath);

            traverseList.WithEach(tuple =>
            {
                BuildNode(tuple.Item1, tuple.Item2);
            });
        }
Ejemplo n.º 2
0
        static int Sum(int x, int y)
        {
            var xNode    = new InPoint(new IntColor(x));
            var yNode    = new InPoint(new IntColor(y));
            int res      = 0;
            var summator = new Summator();

            //connect x and y to summato
            xNode.ConnectTo(summator);
            yNode.ConnectTo(summator);

            //both x and y will recieve the same result in this text, so add just one of them
            graph.Add(xNode);
            graph.OnFinish += delegate(GraphResult result)
            {
                GraphPath path = result[xNode];
                if (path != null)
                {
                    var color = path.LastColor as IntColor;
                    if (color != null)
                    {
                        res = color.Value;
                    }
                    //sum is list of transitions of first value — result is the last one.
                }
            };

            graph.Start();
            return(res);
        }
Ejemplo n.º 3
0
    protected override void Awake()
    {
        base.Awake();
        _wires = GameObject.FindObjectsOfType <Wire>() as Wire[];

        _powerSource = GameObject.FindObjectOfType <PowerSource>() as PowerSource;
        if (_powerSource == null)
        {
            Debug.LogError("One and only one power source must be in the scene");
        }

        // scan the wires and powersource, generate graph(s)
        _wireGraph = GraphPath.Build(_wires);

        _electricCurrentGameObjectHolder = GameObject.Find("*ElectricCurrentHolder*");
        if (_electricCurrentGameObjectHolder == null)
        {
            _electricCurrentGameObjectHolder = new GameObject("*ElectricCurrentHolder*");
        }

        _dynamicObjectHolder = GameObject.Find("*DynamicObjectHolder*");
        if (_dynamicObjectHolder == null)
        {
            _dynamicObjectHolder = new GameObject("*DynamicObjectHolder*");
        }

        _backpackItemGameObjectHolder = GameObject.Find("*BackpackItemHolder");
        if (_backpackItemGameObjectHolder == null)
        {
            _backpackItemGameObjectHolder = new GameObject("*BackpackItemHolder");
        }

        _currentItemsInBackpack = SpawnBackpackDefaultItems(Application.loadedLevelName);
        _heroController         = FindObjectOfType <HeroController>() as HeroController;
    }
Ejemplo n.º 4
0
        public bool SearchPath(N startNode, N endNode, Heuristic <N> heuristic, GraphPath <Connection <N> > outPath)
        {
            if (startNode == null)
            {
                Debug.LogError("起点坐标不在寻路层中");
                return(false);
            }

            if (endNode == null)
            {
                Debug.LogError("终点坐标不在寻路层中");
                return(false);
            }

            // Perform AStar
            bool found = Search(startNode, endNode, heuristic);

            if (found)
            {
                // Create a path made of connections
                GeneratePath(startNode, outPath);
            }

            return(found);
        }
Ejemplo n.º 5
0
        public static IGraphPath Convert(ReportQueryItemResult queryItem, int columnNumber)
        {
            IGraphPath outputPath = new GraphPath();

            outputPath.DirectFlow = new List <GraphItem>();

            for (int i = 0; i < queryItem.Paths.Count; i++)
            {
                if (i == 0 || i == queryItem.Paths.Count - 1)
                {
                    ReportQueryItemPathResult item = queryItem.Paths[i];

                    GraphItem graphItem = (GraphItem)Convert(item, columnNumber, i == 0 ? 0 : 1);
                    graphItem.Parent = outputPath;

                    outputPath.DirectFlow.Add(graphItem);
                }
            }

            // To show two nodes in graph view if only one available
            if (outputPath.DirectFlow.Count == 1)
            {
                GraphItem graphItem = (GraphItem)Convert(queryItem.Paths[0], columnNumber, 1);
                graphItem.Parent = outputPath;

                outputPath.DirectFlow.Add(graphItem);
            }

            return(outputPath);
        }
        public void AStarPathFindServiceUnitTests_ShouldFindOptimalPath_From00To04()
        {
            // Arrange
            var start   = new Vector2Int(0, 0);
            var end     = new Vector2Int(0, 4);
            var options = new PathFindingOptions()
            {
                Start = start,
                End   = end
            };

            var graph           = new MatrixFullGraph(5, 5, 0);
            var neighborService = new GraphGridNeighborsService(1);
            var astar_finder    = new AStarPathFindService(neighborService);

            // Act
            var result = astar_finder.Find(graph, options);

            // Assert
            var expected = new GraphPath()
            {
                Path = new List <Vector2Int>()
                {
                    start,
                    new Vector2Int(0, 1),
                    new Vector2Int(0, 2),
                    new Vector2Int(0, 3),
                    end
                }
            };

            Assert.True(Enumerable.SequenceEqual(expected.Path, result.Path));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates a specific graph which has some obvious cycles and lets the graph analysis highlight them, thus confirming the cycles
        /// which can be easily found manually. The analysis goes of course beyond what the human eye can see and would find cycles in an arbitrary graph.
        /// </summary>
        /// <param name="diagram">The diagram.</param>
        /// <param name="specs">The specs.</param>
        private void Cycles(RadDiagram diagram, GraphGenerationSpecifications specs)
        {
            diagram.Clear();
            Dictionary <Node, RadDiagramShape>      nodeMap;
            Dictionary <Edge, RadDiagramConnection> edgeMap;
            var g = diagram.CreateDiagram(new List <string> {
                "1,2", "3,1", "2,4", "4,3", "4,5", "10,11", "11,12", "12,10"
            }, out nodeMap,
                                          out edgeMap, specs.CreateShape, specs.RandomShapeSize);
            var cycles = g.FindCycles();

            if (cycles.Count > 0)
            {
                foreach (var cycle in cycles)
                {
                    var path = new GraphPath <Node, Edge>();
                    cycle.ToList().ForEach(path.AddNode);
                    this.Highlight(path, nodeMap, edgeMap, specs.HighlightBrush);
                }
            }
            diagram.Layout(LayoutType.Tree, new TreeLayoutSettings
            {
                TreeLayoutType       = TreeLayoutType.TreeRight,
                VerticalSeparation   = 50d,
                HorizontalSeparation = 80d
            });
        }
Ejemplo n.º 8
0
        public void DirectedGraph_With_BackCrossSelfEdges_WithCycles_1()
        {
            var graph = new Graph <string, string>();

            graph.AddEdges(new List <VertexLink <string, string> >
            {
                new VertexLink <string, string>("A", "B"),
                new VertexLink <string, string>("A", "C"),
                new VertexLink <string, string>("A", "E"),
                new VertexLink <string, string>("C", "B"),
                new VertexLink <string, string>("B", "D"),
                new VertexLink <string, string>("C", "D"),
                new VertexLink <string, string>("D", "A"),
                new VertexLink <string, string>("D", "E"),
                new VertexLink <string, string>("E", "E")
            });
            var cycleTraverser = new CycleDetector <string, string>();
            var cycles         = cycleTraverser.FindAllCycles(graph, "A").ToList();

            for (int i = 0; i < cycles.Count; i++)
            {
                Console.WriteLine("FoundPath{0}: {1}", i, cycles[i]);
            }
            Assert.AreEqual(4, cycles.Count, "Cycles count does not match");

            var vertexA       = graph.Vertices.Single(v => v.Equals("A"));
            var vertexB       = graph.Vertices.Single(v => v.Equals("B"));
            var vertexC       = graph.Vertices.Single(v => v.Equals("C"));
            var vertexD       = graph.Vertices.Single(v => v.Equals("D"));
            var vertexE       = graph.Vertices.Single(v => v.Equals("E"));
            var expectedPath1 = new GraphPath <string, string>(CreateCycleEdges(graph, new List <string> {
                vertexA, vertexB, vertexD
            }));
            var expectedPath2 = new GraphPath <string, string>(CreateCycleEdges(graph, new List <string> {
                vertexA, vertexC, vertexD
            }));
            var expectedPath3 = new GraphPath <string, string>(CreateCycleEdges(graph, new List <string> {
                vertexA, vertexC, vertexB, vertexD
            }));
            var expectedPath4 = new GraphPath <string, string>(CreateCycleEdges(graph, new List <string> {
                vertexE
            }));

            Console.WriteLine("ExpectedPath1: {0}", expectedPath1);
            Console.WriteLine("ExpectedPath2: {0}", expectedPath2);
            Console.WriteLine("ExpectedPath3: {0}", expectedPath3);
            Console.WriteLine("ExpectedPath4: {0}", expectedPath4);

            Assert.IsTrue(expectedPath1.Equals(cycles[0]) || expectedPath1.Equals(cycles[1]) ||
                          expectedPath1.Equals(cycles[2]) || expectedPath1.Equals(cycles[3]), "Path A->B->D not found");

            Assert.IsTrue(expectedPath2.Equals(cycles[0]) || expectedPath2.Equals(cycles[1]) ||
                          expectedPath2.Equals(cycles[2]) || expectedPath2.Equals(cycles[3]), "Path A->C->D not found");

            Assert.IsTrue(expectedPath3.Equals(cycles[0]) || expectedPath3.Equals(cycles[1]) ||
                          expectedPath3.Equals(cycles[2]) || expectedPath3.Equals(cycles[3]), "Path A->C->B->D not found");

            Assert.IsTrue(expectedPath4.Equals(cycles[0]) || expectedPath4.Equals(cycles[1]) ||
                          expectedPath4.Equals(cycles[2]) || expectedPath4.Equals(cycles[3]), "Path E not found");
        }
Ejemplo n.º 9
0
        public void DirectedGraph_WithBackEdge_WithCycles()
        {
            var graph = new Graph <string, string>();

            graph.AddEdges(new List <VertexLink <string, string> >
            {
                new VertexLink <string, string>("A", "B"),
                new VertexLink <string, string>("A", "C"),
                new VertexLink <string, string>("B", "D"),
                new VertexLink <string, string>("D", "A"),
            });

            var cycleTraverser = new CycleDetector <string, string>();
            var cycles         = cycleTraverser.FindAllCycles(graph, "A").ToList();

            Assert.AreEqual(1, cycles.Count, "Cycles count does not match");

            var vertexA      = graph.Vertices.Single(v => v.Equals("A"));
            var vertexB      = graph.Vertices.Single(v => v.Equals("B"));
            var vertexD      = graph.Vertices.Single(v => v.Equals("D"));
            var expectedPath = new GraphPath <string, string>(CreateCycleEdges(graph, new List <string> {
                vertexA, vertexB, vertexD
            }));

            Console.WriteLine("ExpectedPath: {0}", expectedPath);
            Console.WriteLine("FoundPath: {0}", cycles[0]);

            Assert.IsTrue(expectedPath.Equals(cycles[0]), "Path A->B->D not found");
        }
Ejemplo n.º 10
0
        public void DirectedGraph_WithSelfEdges_WithCycles()
        {
            var graph = new Graph <string, string>();

            graph.AddEdges(new List <VertexLink <string, string> >
            {
                new VertexLink <string, string>("A", "B"),
                new VertexLink <string, string>("A", "C"),
                new VertexLink <string, string>("B", "D"),
                new VertexLink <string, string>("C", "D"),
                new VertexLink <string, string>("A", "A"),
                new VertexLink <string, string>("B", "B"),
                new VertexLink <string, string>("C", "C"),
                new VertexLink <string, string>("D", "D"),
            });

            var cycleTraverser = new CycleDetector <string, string>();
            var cycles         = cycleTraverser.FindAllCycles(graph, "A").ToList();

            Assert.AreEqual(4, cycles.Count, "Cycles count does not match");

            var vertexA       = graph.Vertices.Single(v => v.Equals("A"));
            var vertexB       = graph.Vertices.Single(v => v.Equals("B"));
            var vertexC       = graph.Vertices.Single(v => v.Equals("C"));
            var vertexD       = graph.Vertices.Single(v => v.Equals("D"));
            var expectedPathA = new GraphPath <string, string>(CreateCycleEdges(graph, new List <string> {
                vertexA
            }));
            var expectedPathB = new GraphPath <string, string>(CreateCycleEdges(graph, new List <string> {
                vertexB
            }));
            var expectedPathC = new GraphPath <string, string>(CreateCycleEdges(graph, new List <string> {
                vertexC
            }));
            var expectedPathD = new GraphPath <string, string>(CreateCycleEdges(graph, new List <string> {
                vertexD
            }));

            Console.WriteLine("ExpectedPathA: {0}", expectedPathA);
            Console.WriteLine("ExpectedPathB: {0}", expectedPathB);
            Console.WriteLine("ExpectedPathC: {0}", expectedPathC);
            Console.WriteLine("ExpectedPathD: {0}", expectedPathD);
            for (int i = 0; i < cycles.Count; i++)
            {
                Console.WriteLine("FoundPath{0}: {1}", i, cycles[i]);
            }

            Assert.IsTrue(expectedPathA.Equals(cycles[0]) || expectedPathA.Equals(cycles[1]) ||
                          expectedPathA.Equals(cycles[2]) || expectedPathA.Equals(cycles[3]), "Path A not found");

            Assert.IsTrue(expectedPathB.Equals(cycles[0]) || expectedPathB.Equals(cycles[1]) ||
                          expectedPathB.Equals(cycles[2]) || expectedPathB.Equals(cycles[3]), "Path B not found");

            Assert.IsTrue(expectedPathC.Equals(cycles[0]) || expectedPathC.Equals(cycles[1]) ||
                          expectedPathC.Equals(cycles[2]) || expectedPathC.Equals(cycles[3]), "Path C not found");

            Assert.IsTrue(expectedPathD.Equals(cycles[0]) || expectedPathD.Equals(cycles[1]) ||
                          expectedPathD.Equals(cycles[2]) || expectedPathD.Equals(cycles[3]), "Path D not found");
        }
Ejemplo n.º 11
0
        public void Paint(GraphPath figure, Graphics g, int time)
        {
            Brush brush1 = null;

            brush1 = BrushManager.GetGDIBrushFromPatten(this.pattern, figure.GetBounds());

            g.FillPath(brush1, figure.GPath);
        }
        private void Draw(GraphPath <Token, Token> path)
        {
            Graph graph = new Graph("Graph");

            for (int i = 0; i < graphToken.Nodes.Count; i++)
            {
                string str = "Root";
                if (graphToken.Nodes[i].Info != null)
                {
                    str = graphToken.Nodes[i].Info.ToString() + " - " + graphToken.Nodes[i].Id.ToString();
                }

                Node no = graph.AddNode(graphToken.Nodes[i].Name);
                no.Attr.Shape = Shape.Circle;
                no.LabelText  = str;
                if (graphToken.Nodes[i].Info != null && graphToken.Nodes[i].Info.RecToken != null)
                {
                    var color = graphToken.Nodes[i].Info.RecToken.Color;
                    no.Attr.FillColor = new Microsoft.Msagl.Drawing.Color((byte)color.R, (byte)color.G, (byte)color.B);
                }

                foreach (var transition in graphToken.Nodes[i].Edges)
                {
                    Edge arco = graph.AddEdge(graphToken.Nodes[i].Name, transition.Cost.ToString("n2"), transition.Destiny.Name);
                    System.Drawing.Color c = Utils.GetColor(transition.Cost);
                    var color = new Microsoft.Msagl.Drawing.Color((byte)c.R, (byte)c.G, (byte)c.B);

                    if (path != null)
                    {
                        if (path.Nodes.Contains(transition.Destiny) && path.Nodes.Contains(graphToken.Nodes[i]))
                        {
                            arco.Attr.Color = color;
                        }
                        else
                        {
                            arco.Attr.Color = Microsoft.Msagl.Drawing.Color.Gray;
                        }
                    }
                    else
                    {
                        arco.Attr.Color = color;
                    }

                    arco.Attr.AddStyle(Style.Bold);
                    arco.Attr.LineWidth = 5;
                }
            }

            GViewer viewer = new GViewer();

            viewer.NavigationVisible = false;
            viewer.OutsideAreaBrush  = Brushes.White;
            viewer.ToolBarIsVisible  = false;
            viewer.Graph             = graph;
            viewer.Dock = System.Windows.Forms.DockStyle.Fill;
            pnlGraph.Controls.Clear();
            pnlGraph.Controls.Add(viewer);
        }
Ejemplo n.º 13
0
        public void AStarPathFindServiceUnitTests_ShouldFindOptimalPath()
        {
            // Arrange
            var start   = new Vector2Int(0, 0);
            var end     = new Vector2Int(1, 1);
            var options = new PathFindingOptions()
            {
                Start = start,
                End   = end
            };

            var graphMock = new Mock <IGraph>();

            graphMock.Setup(g => g.GetTransition(end, start)).Returns(1);
            graphMock.Setup(g => g.GetTransition(end, new Vector2Int(1, 0))).Returns(1);
            graphMock.Setup(g => g.GetTransition(end, new Vector2Int(0, 1))).Returns(0);
            graphMock.Setup(g => g.GetTransition(new Vector2Int(0, 1), start)).Returns(0);
            graphMock.Setup(g => g.GetTransition(new Vector2Int(1, 0), start)).Returns(1);

            var neighborService = new Mock <IGraphNeighborsService>();

            neighborService.Setup(n => n.GetNeighbors(graphMock.Object, end, It.IsAny <IList <Vector2Int> >()))
            .Callback((IGraph _g, Vector2Int _v, IList <Vector2Int> res) =>
            {
                res.Clear();
                res.Add(new Vector2Int(1, 0));
                res.Add(new Vector2Int(0, 1));
                res.Add(new Vector2Int(0, 0));
            });

            neighborService.Setup(n => n.GetNeighbors(graphMock.Object, new Vector2Int(0, 1), It.IsAny <IList <Vector2Int> >()))
            .Callback((IGraph _g, Vector2Int _v, IList <Vector2Int> res) =>
            {
                res.Clear();
                res.Add(new Vector2Int(1, 1));
                res.Add(new Vector2Int(1, 0));
                res.Add(new Vector2Int(0, 0));
            });

            var astar_finder = new AStarPathFindService(neighborService.Object);

            // Act
            var result = astar_finder.Find(graphMock.Object, options);

            // Assert
            var expected = new GraphPath()
            {
                Path = new List <Vector2Int>()
                {
                    start, new Vector2Int(0, 1), end
                }
            };

            Assert.True(Enumerable.SequenceEqual(expected.Path, result.Path));
            neighborService.Verify(
                n => n.GetNeighbors(It.IsAny <IGraph>(), It.IsAny <Vector2Int>(), It.IsAny <IList <Vector2Int> >()),
                Times.Exactly(2));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// given a path and a nodestore, tries to locate a node
        /// </summary>
        /// <param name="path"></param>
        /// <param name="nodeStore"></param>
        /// <returns></returns>
        public static GraphNode GetNode(this IStoreOf <GraphNode> nodeStore, GraphPath path)
        {
            Condition.Requires(path).IsNotNull();
            Condition.Requires(nodeStore).IsNotNull();

            var node = nodeStore.Get <GraphNode>(path.Path);

            return(node);
        }
Ejemplo n.º 15
0
            GraphTraversalEvaluatorResult ITraversalVisitor.Visit(GraphPath path)
            {
                if (_pathEvaluator == null)
                {
                    return(GraphTraversalEvaluatorResult.IncludeAndContinue);
                }

                return(_pathEvaluator(path));
            }
Ejemplo n.º 16
0
 public static bool Dijkstra <V, E>(
     this Graph <V, E> graph,
     int from,
     int to,
     WeightCalculator <E> calculator,
     out GraphPath <V, E> path,
     ExplorationCallbacks <V, E> callbacks = default
     )
 {
     return(graph.AStar(from, to, ZeroHeuristics, calculator, out path, callbacks));
 }
Ejemplo n.º 17
0
        public void Given_DistanceTable_When_DestinationIsReachable_Then_ReturnPath(string startingVertex,
                                                                                    string destinationVertex, IDictionary <string, DistanceInfo <string> > distances,
                                                                                    GraphPath <string> expectedPath)
        {
            // Arrange
            // Act
            GraphPath <string> result = Sut.FindPath(startingVertex, destinationVertex, distances);

            // Assert
            Assert.Equal(expectedPath, result);
        }
 private bool HasOverrideLink(GraphPath mainPath, GraphPath savedMainPath)
 {
     foreach (string link in mainPath.Path)
     {
         if (savedMainPath.Path.FirstOrDefault(r => r == link) != null)
         {
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 19
0
        public static int GetCost(this Graph graph, GraphPath path)
        {
            var sum = 0;

            for (int i = 1; i < path.Vertices.Count; i++)
            {
                var key = graph.AdjacencyTable.GetRelation(path.Vertices[i - 1].Index, path.Vertices[i].Index);
                sum += graph.AdjacencyTable[key];
            }

            return(sum);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// for a given node returns all the child nodes
        /// </summary>
        /// <param name="nodeValue"></param>
        /// <param name="parentNodePath"></param>
        /// <returns></returns>
        public static List <Tuple <object, GraphPath> > GetChildTraversalNodes(object nodeValue, GraphPath parentNodePath,
                                                                               Func <object, GraphPath, bool> doNotTraverseFilter = null)
        {
            List <Tuple <object, GraphPath> > rv = new List <Tuple <object, GraphPath> >();

            //if the node is IEnumerable, recurse here
            if (nodeValue is IEnumerable && (nodeValue is string) == false)
            {
                IEnumerable objEnumerable = nodeValue as IEnumerable;

                int index = 0;
                foreach (var each in objEnumerable)
                {
                    //build the path
                    var path = GraphPath.New(parentNodePath);
                    path.AddSegment(EnumeratedItemSegment.New(index));

                    if (doNotTraverseFilter != null &&
                        doNotTraverseFilter(each, path))
                    {
                        continue;
                    }

                    rv.Add(new Tuple <object, GraphPath>(each, path));
                    index++;
                }
            }
            else
            {
                //recurse the fields
                var fields = GraphingUtil.GetNestingNotatedFieldInfos(nodeValue.GetType());

                foreach (var field in fields)
                {
                    //get field value
                    var obj = field.Item2.GetValue(nodeValue);

                    var path = GraphPath.New(parentNodePath);
                    path.AddSegment(GraphSegment.New(field.Item1));

                    if (doNotTraverseFilter != null &&
                        doNotTraverseFilter(obj, path))
                    {
                        continue;
                    }

                    //build the node and recurse
                    rv.Add(new Tuple <object, GraphPath>(obj, path));
                }
            }
            return(rv);
        }
        /**
         * {@inheritDoc}
         */
        public double getPathWeight(V source, V sink)
        {
            GraphPath <V, E> p = getPath(source, sink);

            if (p == null)
            {
                return(Double.PositiveInfinity);
            }
            else
            {
                return(p.getWeight());
            }
        }
Ejemplo n.º 22
0
        public bool SearchNodePath(N startNode, N endNode, Heuristic <N> heuristic, GraphPath <N> outPath)
        {
            // Perform AStar
            bool found = Search(startNode, endNode, heuristic);

            if (found)
            {
                // Create a path made of nodes
                GenerateNodePath(startNode, outPath);
            }

            return(found);
        }
Ejemplo n.º 23
0
        public void Given_Graph_When_DestinationIsReachable_Then_ReturnPath(int startingVertex,
                                                                            int destinationVertex, EdgeDescriptor <int>[] edges, GraphPath <int> expectedPath)
        {
            // Arrange
            Sut.AddToGraph(edges);

            // Act
            GraphPath <int> result =
                Sut.FindShortestPath(startingVertex, destinationVertex, o => o.UseUnweightedGraph());

            // Assert
            Assert.Equal(expectedPath, result);
        }
Ejemplo n.º 24
0
        protected void GeneratePath(N startNode, GraphPath <Connection <N> > outPath)
        {
            // Work back along the path, accumulating connections
            // outPath.clear();
            while (!_current.node.Equals(startNode))
            {
                outPath.Add(_current.connection);
                _current = _nodeRecords[_graph.GetIndex(_current.connection.GetFromNode())];
            }

            // Reverse the path
            outPath.reverse();
        }
Ejemplo n.º 25
0
        public void Path_ValidParentVertices_ReturnsFullPath()
        {
            int       expectedPathLength = expectedPraphPathCoordinates.Length - 1;
            const int expectedPathCost   = 25;
            var       graphPath          = new GraphPath(parentVertices, endPoints, graph);

            double pathCost        = graphPath.PathCost;
            int    pathLength      = graphPath.PathLength;
            var    pathCoordinates = graphPath.Path.Select(Coordinate).Reverse();

            Assert.AreEqual(expectedPathLength, pathLength);
            Assert.AreEqual(expectedPathCost, pathCost);
            Assert.IsTrue(pathCoordinates.Match(expectedPraphPathCoordinates, AreEqual));
        }
Ejemplo n.º 26
0
        public void Paint(GraphPath figure, Graphics g, int time)
        {
            SolidBrush brush1 = null;

            if (this.color.IsEmpty)
            {
                brush1 = new SolidBrush(System.Drawing.Color.Empty);
            }
            else
            {
                brush1 = new SolidBrush(System.Drawing.Color.FromArgb((int)(255f * this.opacity), this.color.R, this.color.G, this.color.B));
            }
            g.FillPath(brush1, figure.GPath);
        }
Ejemplo n.º 27
0
        private GraphNode(GraphPath path, object nodeValue, int traversalIndex, string valueMgrId, string serializedNodeValue)
            : base()
        {
            Condition.Requires(path).IsNotNull();
            Condition.Requires(traversalIndex).IsGreaterThan(-1);

            //validate the serialized value doesn't have reserved characters
            this.TraversalIndex = traversalIndex;
            this.ValueManagerId = valueMgrId;
            this.Id             = path.Path;
            this.Context        = serializedNodeValue;
            //set placeholder
            this.NodeValue = nodeValue;
        }
Ejemplo n.º 28
0
        protected virtual List <AvailableSlot> GetAvailableTableSlots(Graph graph, GraphPath path, RSATable table)
        {
            List <AvailableSlot> availableSlots = new List <AvailableSlot>();
            List <GraphLink>     pathLinks      = path.ToLinks(graph.Links);

            foreach (GraphLink link in pathLinks)
            {
                AvailableSlot element = new AvailableSlot();
                element.Link       = link;
                element.Availables = new List <int>(table.Table[link.GetLinkId()].Where(r => r.Value.Values.Count == 0).Select(r => r.Key).ToList());
                availableSlots.Add(element);
            }

            return(availableSlots);
        }
Ejemplo n.º 29
0
        protected void GenerateNodePath(N startNode, GraphPath <N> outPath)
        {
            // Work back along the path, accumulating nodes
            // outPath.clear();
            while (_current.connection != null)
            {
                outPath.Add(_current.node);
                _current = _nodeRecords[_graph.GetIndex(_current.connection.GetFromNode())];
            }

            outPath.Add(startNode);

            // Reverse the path
            outPath.reverse();
        }
Ejemplo n.º 30
0
        public void Given_DistanceTable_When_Source_And_Destination_AreSame_ButNotRoot_Then_ReturnOneStepPath()
        {
            // Arrange
            var distances = new Dictionary <string, DistanceInfo <string> >
            {
                { "A", new DistanceInfo <string>(0, 0, "A") },
                { "B", new DistanceInfo <string>(1, 1, "A") },
                { "C", new DistanceInfo <string>(1, 1, "A") }
            };

            // Act
            GraphPath <string> result = Sut.FindPath("C", "C", distances);

            // Assert
            Assert.Equal(new GraphPath <string>(new [] { "C" }, 0, Comparer), result);
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Highlights the specified path.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <param name="nodeMap">The node map.</param>
 /// <param name="edgeMap">The edge map.</param>
 /// <param name="brush">The brush for highlighting.</param>
 private void Highlight(GraphPath<Node, Edge> path, IDictionary<Node, RadDiagramShape> nodeMap, IDictionary<Edge, RadDiagramConnection> edgeMap, Brush brush)
 {
     if (path == null) return;
     foreach (var node in path.Nodes) nodeMap[node].Background = brush;
     foreach (var link in path.Links)
     {
         edgeMap[link].Background = brush;
         edgeMap[link].Stroke = brush;
         edgeMap[link].StrokeThickness = 2d;
     }
 }
Ejemplo n.º 32
0
    IEnumerator getPath()
    {
        GraphPath graph = new GraphPath(nodeValues, nodeEdges, decisionLevels);

        path = bfsOrDfs ? graph.getRouteBFS() : graph.getRouteDFS();
        yield return null;
    }
Ejemplo n.º 33
0
 /// <summary>
 /// Creates a specific graph which has some obvious cycles and lets the graph analysis highlight them, thus confirming the cycles
 /// which can be easily found manually. The analysis goes of course beyond what the human eye can see and would find cycles in an arbitrary graph.
 /// </summary>
 /// <param name="diagram">The diagram.</param>
 /// <param name="specs">The specs.</param>
 private void Cycles(RadDiagram diagram, GraphGenerationSpecifications specs)
 {
     diagram.Clear();
     Dictionary<Node, RadDiagramShape> nodeMap;
     Dictionary<Edge, RadDiagramConnection> edgeMap;
     var g = diagram.CreateDiagram(new List<string> { "1,2", "3,1", "2,4", "4,3", "4,5", "10,11", "11,12", "12,10" }, out nodeMap,
         out edgeMap, specs.CreateShape, specs.RandomShapeSize);
     var cycles = g.FindCycles();
     if (cycles.Count > 0)
     {
         foreach (var cycle in cycles)
         {
             var path = new GraphPath<Node, Edge>();
             cycle.ToList().ForEach(path.AddNode);
             this.Highlight(path, nodeMap, edgeMap, specs.HighlightBrush);
         }
     }
     diagram.Layout(LayoutType.Tree, new TreeLayoutSettings
                                         {
                                             TreeLayoutType = TreeLayoutType.TreeRight,
                                             VerticalSeparation = 50d,
                                             HorizontalSeparation = 80d
                                         });
 }
Ejemplo n.º 34
0
 public ArmyOrder(int armyID, GraphPath<int> path)
 {
     ArmyID = armyID;
     Path = path;
     PathIndex = 0;
 }
        public List<Symbol> GetSymbols(GraphPath<Token, Token> path)
        {
            List<Symbol> symbols = new List<Symbol>();
            foreach (var item in path.Nodes.Skip(1))
            {
                var terminal = Syn.Grammar.Terminals.FirstOrDefault(t =>
                        t.Name == item.Info.RecToken.Name);

                if (terminal != null)
                {
                    var symbol = new Symbol(terminal.Id, terminal.Name, true, terminal.Value);
                    symbol.SetCustomValue("Token", item.Info);
                    symbols.Add(symbol);
                }
            }

            return symbols;
        }