Ejemplo n.º 1
0
    public List <INode> GetSuccessors(INode source)
    {
        List <INode> result = new List <INode>();

        var node  = AbstractGraph.GetNode(source.Id);
        var edges = node.Edges;

        foreach (var edge in edges.Values)
        {
            if (!IsValidEdgeForLevel(edge, m_curtLevel))
            {
                continue;
            }

            int targetAbsId   = edge.TargetNodeId;
            var targetAbsNode = AbstractGraph.GetNode(targetAbsId);
            if (!IsInCurtCluster(targetAbsNode.Pos))
            {
                continue;
            }

            result.Add(targetAbsNode);
        }

        return(result);
    }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the neighbours(successors) of the nodeId for the level set in the currentLevel
        /// </summary>
        public IEnumerable <Connection <AbstractNode> > GetConnections(Id <AbstractNode> nodeId)
        {
            var node   = AbstractGraph.GetNode(nodeId);
            var edges  = node.Edges;
            var result = new List <Connection <AbstractNode> >();

            foreach (var edge in edges.Values)
            {
                var edgeInfo = edge.Info;
                if (!IsValidEdgeForLevel(edgeInfo, currentLevel))
                {
                    continue;
                }

                var targetNodeId   = edge.TargetNodeId;
                var targetNodeInfo = AbstractGraph.GetNodeInfo(targetNodeId);

                if (!PositionInCurrentCluster(targetNodeInfo.Position))
                {
                    continue;
                }

                result.Add(new Connection <AbstractNode>(targetNodeId, edgeInfo.Cost));
            }

            return(result);
        }
    /// <summary>
    /// 恢复寻路新增节点导致的变化
    /// </summary>
    private void RestoreNodeBackup(HierarchicalMap map, int nodeId, NodeBackup backup)
    {
        AbstractGraph graph = map.AbstractGraph;
        AbstractNode  node  = graph.GetNode(nodeId);

        //恢复节点的级别
        node.Level = backup.Level;

        //恢复相关的边
        graph.RemoveEdgeFromAndToNode(nodeId);
        foreach (var edge in backup.Edges)
        {
            int targetNodeId = edge.TargetNodeId;
            var targetNode   = map.GetAbstractNode(targetNodeId);

            AbstractEdge abstractEdge = HPADemo.Instance.CreateEdge(node.Pos, targetNode.Pos, edge.Level, edge.IsInterEdge);
            abstractEdge.Init(targetNodeId, edge.Cost, edge.Level, edge.IsInterEdge);
            abstractEdge.SetInnerLowerLevelPath(edge.InnerLowerLevelPath);
            graph.AddEdge(nodeId, abstractEdge);

            edge.InnerLowerLevelPath?.Reverse();

            abstractEdge = HPADemo.Instance.CreateEdge(targetNode.Pos, node.Pos, edge.Level, edge.IsInterEdge);
            abstractEdge.Init(nodeId, edge.Cost, edge.Level, edge.IsInterEdge);
            abstractEdge.SetInnerLowerLevelPath(edge.InnerLowerLevelPath);
            graph.AddEdge(targetNodeId, abstractEdge);
        }

        m_backupDict.Remove(nodeId);
    }
Ejemplo n.º 4
0
        public static void PrintTestDirectedGraph()
        {
            TestGraph1 = new DirectedGraph("g1");
            Point x1 = new Point("x1");

            TestGraph1.AddPoint(x1);
            Point x2 = new Point("x2");

            TestGraph1.AddPoint(x2);
            Point x3 = new Point("x3");

            TestGraph1.AddPoint(x3);
            Point x4 = new Point("x4");

            TestGraph1.AddPoint(x4);
            //Point x5 = new Point("x5");
            //TestGrapch1.AddPoint(x5);

            TestGraph1.AddEdge(new Edge("a1", x1, x2));
            TestGraph1.AddEdge(new Edge("a2", x2, x3));
            TestGraph1.AddEdge(new Edge("a3", x2, x3));
            //TestGraph1.AddEdge(new Edge("a4", x2, x3));
            //TestGraph1.AddEdge(new Edge("a5", x3, x4));
            //TestGraph1.AddEdge(new Edge("a6", x3, x5));
            //TestGraph1.AddEdge(new Edge("a7", x5, x3));

            Console.WriteLine(notation.ConvertFromGrapch(TestGraph1));
        }
Ejemplo n.º 5
0
    protected GraphSearchCommons.SearchValidationFlgas validateTheSearch(
        int sourceIndex, int targetIndex,
        AbstractGraph <NodeType, EdgeType> sourceGraph
        )
    {
        if (sourceIndex == NodeCommons.InvalidNodeId || targetIndex == NodeCommons.InvalidNodeId)
        {
            ErrorPrinter.PrintError(
                "GraphDFS", "validateTheSearch", "Has invalid indices for SOURCE: " +
                sourceIndex + " TARGET: " + targetIndex, "Cihan"
                );
            return(GraphSearchCommons.SearchValidationFlgas.invalidIndices);
        }

        if (sourceGraph.GetNode(sourceIndex) == null || sourceGraph.GetNode(targetIndex) == null)
        {
            ErrorPrinter.PrintError(
                "GraphDFS", "validateTheSearch", "Has invalid nodes in the grap! SOURCE: " +
                sourceIndex + " TARGET: " + targetIndex, "Cihan"
                );
            return(GraphSearchCommons.SearchValidationFlgas.invalidIndices);
        }

        if (sourceIndex == targetIndex)
        {
            return(GraphSearchCommons.SearchValidationFlgas.atTheTarget);
        }

        return(GraphSearchCommons.SearchValidationFlgas.valid);
    }
Ejemplo n.º 6
0
 public HierarchicalMap(ConcreteMap concreteMap, int clusterSize, int maxLevel)
 {
     AbstractGraph  = new AbstractGraph();
     Width          = concreteMap.Width;
     Height         = concreteMap.Height;
     MinClusterSize = clusterSize;
     MaxLevel       = maxLevel;
 }
Ejemplo n.º 7
0
        public static void TestSearchPathInGraph()
        {
            TestGraph1 = GraphUtils.GenerateRandomDirectedGraph("g1", 4, 10);

            Console.WriteLine(notation.ConvertFromGrapch(TestGraph1));
            Console.WriteLine("===");
            PrintAllEdgesForGraph(TestGraph1);
        }
Ejemplo n.º 8
0
        public void AddEdge(Id <AbstractNode> sourceNodeId, Id <AbstractNode> destNodeId, int cost, int level = 1, bool inter = false, List <Id <AbstractNode> > pathPathNodes = null)
        {
            var edgeInfo = new AbstractEdgeInfo(cost, level, inter);

            edgeInfo.InnerLowerLevelPath = pathPathNodes;

            AbstractGraph.AddEdge(sourceNodeId, destNodeId, edgeInfo);
        }
Ejemplo n.º 9
0
        public void Analyze(Function f)
        {
            // Build an abstract graph to analyze with
            var blockIDMap    = new Dictionary <BasicBlock, int>();
            var abstractNodes = new List <Node>();

            for (int i = 0; i < f.Blocks.Count; i++)
            {
                blockIDMap.Add(f.Blocks[i], i);
                var node = new Node {
                    OriginalBlock = f.Blocks[i]
                };
                if (i == f.Blocks.Count - 1)
                {
                    node.IsTerminal = true;
                }
                abstractNodes.Add(node);
            }
            foreach (var b in blockIDMap)
            {
                foreach (var pred in b.Key.Predecessors)
                {
                    abstractNodes[b.Value].Predecessors.Add(abstractNodes[blockIDMap[pred]]);
                }
                foreach (var succ in b.Key.Successors)
                {
                    abstractNodes[b.Value].Successors.Add(abstractNodes[blockIDMap[succ]]);
                }
            }

            // Calculate intervals and the graph sequence in preperation for loop detection
            var headGraph = new AbstractGraph();

            headGraph.StartNode = abstractNodes[blockIDMap[f.StartBlock]];
            headGraph.Nodes     = abstractNodes;
            headGraph.CalculateIntervals();
            headGraph.LabelReversePostorderNumbers();

            DetectLoopsForIntervalLevel(headGraph);

            foreach (var latch in headGraph.LoopLatches)
            {
                foreach (var head in latch.Value)
                {
                    var b = head.OriginalBlock;
                    b.IsLoopHead = true;
                    b.LoopLatches.Add(latch.Key.OriginalBlock);
                    b.LoopType = headGraph.LoopTypes[head];
                    if (headGraph.LoopFollows[head] == null)
                    {
                        continue;
                    }
                    b.LoopFollow = headGraph.LoopFollows[head].OriginalBlock;
                    latch.Key.OriginalBlock.IsLoopLatch = true;
                }
            }
        }
Ejemplo n.º 10
0
 public void AddLinks(AbstractGraph graph, Coords characterPostition, params Coords[] potentialPos)
 {
     foreach (Coords coords in potentialPos)
     {
         graph[characterPostition.y, characterPostition.x].Edges.Add(coords);
         coords.IsTemporary = true;
         graph[coords.y, coords.x].Edges.Add(characterPostition);
         characterPostition.IsTemporary = true;
     }
 }
Ejemplo n.º 11
0
    /// <summary>
    /// 把指定节点涉及的边加到所有层级中
    /// </summary>
    public void AddHierarchicalEdgesForAbstractNode(int abstractId)
    {
        var absNode  = AbstractGraph.GetNode(abstractId);
        int oldLevel = absNode.Level;

        absNode.Level = MaxLevel;
        for (int level = oldLevel + 1; level <= MaxLevel; level++)
        {
            AddEdgesToOtherEntrancesInCluster(absNode, level);
        }
    }
Ejemplo n.º 12
0
        public int GetHeuristic(Id <AbstractNode> startNodeId, Id <AbstractNode> targetNodeId)
        {
            var startPos  = AbstractGraph.GetNodeInfo(startNodeId).Position;
            var targetPos = AbstractGraph.GetNodeInfo(targetNodeId).Position;
            var diffY     = Math.Abs(startPos.Y - targetPos.Y);
            var diffX     = Math.Abs(startPos.X - targetPos.X);

            // Manhattan distance, after testing a bit for hierarchical searches we do not need
            // the level of precision of Diagonal distance or euclidean distance
            return((diffY + diffX) * Constants.COST_ONE);
        }
Ejemplo n.º 13
0
    // Finds and returns the path between source and target indices
    // and the spanning tree of the search.
    //
    // Returns true if a path exists, returns false otherwise.
    //
    // TODO Replace ref with in if one day Unity supports C# 7+
    protected override bool FindPath(
        int sourceIndex, int targetIndex,
        AbstractGraph <NodeType, EdgeType> sourceGraph,
        ref List <int> path,
        ref List <HelperEdge> spanningTree
        )
    {
        HelperEdge startEdge = new HelperEdge(sourceIndex, sourceIndex, EdgeCommons.DefaultEdgeCost);

        searchQueue.Enqueue(startEdge);
        visitingList[sourceIndex] = GraphSearchCommons.SearchFlags.visited;

        // Search
        while (searchQueue.Count > 0)
        {
            // Get the next element in the queue
            HelperEdge next = searchQueue.Dequeue();

            // Mark for the route
            route[next.ToNode] = next.FromNode;

            // Add into the spanning tree
            if (next != startEdge)
            {
                spanningTree.Add(next);
            }

            // The target has found
            if (next.ToNode == targetIndex)
            {
                GetTargetPath(sourceIndex, targetIndex, ref path);
                return(true);
            }

            List <HelperEdge> edgeList = sourceGraph.GetLeadingEdges(next.ToNode);
            if (edgeList.Count > 0)
            {
                foreach (HelperEdge edge in edgeList)
                {
                    // Push each path leading to an unvisited node
                    if (visitingList[edge.ToNode] == GraphSearchCommons.SearchFlags.unvisited)
                    {
                        // Push each path leading to an unvisited node
                        searchQueue.Enqueue(edge);
                        // And mark it as visited
                        visitingList[edge.ToNode] = GraphSearchCommons.SearchFlags.visited;
                    }
                }
            }
        }   // End of while

        // No path to the target
        return(false);
    }
Ejemplo n.º 14
0
        public void AddHierarchicalEdgesForAbstractNode(Id <AbstractNode> abstractNodeId)
        {
            var abstractNodeInfo = AbstractGraph.GetNodeInfo(abstractNodeId);
            var oldLevel         = abstractNodeInfo.Level;

            abstractNodeInfo.Level = MaxLevel;
            for (var level = oldLevel + 1; level <= MaxLevel; level++)
            {
                AddEdgesToOtherEntrancesInCluster(abstractNodeInfo, level);
            }
        }
Ejemplo n.º 15
0
        public void RemoveAbstractNode(Id <AbstractNode> abstractNodeId)
        {
            var abstractNodeInfo = AbstractGraph.GetNodeInfo(abstractNodeId);

            var cluster = Clusters[abstractNodeInfo.ClusterId.IdValue];

            cluster.RemoveLastEntranceRecord();

            ConcreteNodeIdToAbstractNodeIdMap.Remove(abstractNodeInfo.ConcreteNodeId);
            AbstractGraph.RemoveEdgesFromAndToNode(abstractNodeId);
            AbstractGraph.RemoveLastNode();
        }
Ejemplo n.º 16
0
        public HierarchicalMap(ConcreteMap concreteMap, int clusterSize, int maxLevel)
        {
            ClusterSize = clusterSize;
            MaxLevel    = maxLevel;

            SetType(concreteMap.TileType);
            this.Height = concreteMap.Height;
            this.Width  = concreteMap.Width;
            ConcreteNodeIdToAbstractNodeIdMap = new Dictionary <Id <ConcreteNode>, Id <AbstractNode> >();

            Clusters      = new List <Cluster>();
            AbstractGraph = new AbstractGraph();
        }
Ejemplo n.º 17
0
    public void RemoveAbstractNode(int abstractId)
    {
        //移除cluster里的点
        var absNode = AbstractGraph.GetNode(abstractId);
        var cluster = m_clusters[absNode.ClusterId];

        cluster.RemoveEntrancePoint(abstractId);

        //移除graph里的点
        AbstractGraph.RemoveEdgeFromAndToNode(abstractId);
        AbstractGraph.RemoveLastNode(abstractId);

        m_abstractNodeDict.Remove(absNode.Id);
        m_pos2AbstractNode.Remove(absNode.Pos);
    }
Ejemplo n.º 18
0
    // Finds and returns the path between source and target indices.
    //
    // Returns true if a path exists, returns false otherwise.
    //
    // TODO Replace ref with in if one day Unity supports C# 7+
    protected override bool FindPath(
        int sourceIndex, int targetIndex,
        AbstractGraph <NodeType, EdgeType> sourceGraph,
        ref List <int> path
        )
    {
        HelperEdge startEdge = new HelperEdge(sourceIndex, sourceIndex, EdgeCommons.DefaultEdgeCost);

        searchStack.Push(startEdge);

        // Search
        while (searchStack.Count > 0)
        {
            // Get the top element of the stack
            //EdgeType next = searchStack.Peek();
            HelperEdge next = searchStack.Peek();
            searchStack.Pop();

            // Mark for the route
            route[next.ToNode] = next.FromNode;

            // And mark as visited
            visitingList[next.ToNode] = GraphSearchCommons.SearchFlags.visited;

            // The target has found
            if (next.ToNode == targetIndex)
            {
                GetTargetPath(sourceIndex, targetIndex, ref path);
                return(true);
            }

            List <HelperEdge> edgeList = sourceGraph.GetLeadingEdges(next.ToNode);
            if (edgeList.Count > 0)
            {
                foreach (HelperEdge edge in edgeList)
                {
                    // Push each path leading to an unvisited node
                    if (visitingList[edge.ToNode] == GraphSearchCommons.SearchFlags.unvisited)
                    {
                        searchStack.Push(edge);
                    }
                }
            }
        }   // End of while()

        // No path to the target
        return(false);
    }
Ejemplo n.º 19
0
        public void CreateHierarchicalEdges()
        {
            // Starting from level 2 denotes a serious mess on design, because lvl 1 is
            // used by the clusters.
            for (var level = 2; level <= MaxLevel; level++)
            {
                SetCurrentLevelForSearches(level - 1);

                int n = 1 << (level - 1);
                // Group clusters by their level. Each subsequent level doubles the amount of clusters in each group
                var clusterGroups = Clusters.GroupBy(cl => $"{cl.ClusterX / n}_{cl.ClusterY / n}");

                foreach (var clusterGroup in clusterGroups)
                {
                    var entrancesInClusterGroup = clusterGroup
                                                  .SelectMany(cl => cl.EntrancePoints)
                                                  .Where(entrance => GetEntrancePointLevel(entrance) >= level)
                                                  .ToList();

                    var firstEntrance = entrancesInClusterGroup.FirstOrDefault();

                    if (firstEntrance == null)
                    {
                        continue;
                    }

                    var entrancePosition = AbstractGraph.GetNode(firstEntrance.AbstractNodeId).Info.Position;

                    SetCurrentClusterByPositionAndLevel(
                        entrancePosition,
                        level);

                    foreach (var entrance1 in entrancesInClusterGroup)
                    {
                        foreach (var entrance2 in entrancesInClusterGroup)
                        {
                            if (entrance1 == entrance2 || !IsValidAbstractNodeForLevel(entrance1.AbstractNodeId, level) || !IsValidAbstractNodeForLevel(entrance2.AbstractNodeId, level))
                            {
                                continue;
                            }

                            AddEdgesBetweenAbstractNodes(entrance1.AbstractNodeId, entrance2.AbstractNodeId, level);
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public static void BuildGrapgAndTestIt()
        {
            while (!stop)
            {
                TestGraph1 = GraphUtils.GenerateRandomDirectedGraph("g1", 4, 3);

                Console.WriteLine(notation.ConvertFromGrapch(TestGraph1));

                PrintTransitiveClosureForAllPoints(TestGraph1);
                PrintOneSidedComp(TestGraph1);

                if (Console.ReadLine() == "stop")
                {
                    stop = true;
                }
            }
        }
Ejemplo n.º 21
0
    /// <summary>
    /// 构建上层的边
    /// </summary>
    public void CreateHierarchicalEdges()
    {
        for (int level = 2; level <= MaxLevel; level++)
        {
            SetCurrentLevelForSearch(level - 1);

            int n             = 1 << (level - 1);
            var clusterGroups = m_clusters.GroupBy(c => $"{c.Pos.x / n}_{c.Pos.y / n}"); //按等级划分

            foreach (var clusterGroup in clusterGroups)
            {
                var entrancesInClusterGroup = clusterGroup
                                              .SelectMany(c => c.EntrancePoints)
                                              .Where(entrance => GetEntrancePointLevel(entrance) >= level)
                                              .ToList();

                var firstEntrance = entrancesInClusterGroup.FirstOrDefault();
                if (firstEntrance == null)
                {
                    continue;
                }

                var entrancePos = AbstractGraph.GetNode(firstEntrance.AbstractId).Pos;
                SetCurrentClusterAndLevel(entrancePos, level);

                foreach (var entrance1 in entrancesInClusterGroup)
                {
                    foreach (var entrance2 in entrancesInClusterGroup)
                    {
                        int absId1 = entrance1.AbstractId;
                        int absId2 = entrance2.AbstractId;
                        if (entrance1 == entrance2 ||
                            !IsValidAbstractNodeForLevel(absId1, level) ||
                            !IsValidAbstractNodeForLevel(absId2, level) ||
                            AbstractGraph.IsContainsEdge(absId1, absId2))
                        {
                            continue;
                        }

                        AddEdgesBetweenAbstractNodes(entrance1.AbstractId, entrance2.AbstractId, level);
                    }
                }
            }
        }
    }
Ejemplo n.º 22
0
    // Search interface for the client
    // TODO Replace ref with in if one day Unity supports C# 7+
    public bool Search(int sourceIndex, int targetIndex, AbstractGraph <NodeType, EdgeType> sourceGraph)
    {
        // TODO Update with a better approach in the future
        var validation = validateTheSearch(sourceIndex, targetIndex, sourceGraph);

        if (validation == GraphSearchCommons.SearchValidationFlgas.invalidIndices)
        {
            return(false);
        }
        else if (validation == GraphSearchCommons.SearchValidationFlgas.atTheTarget)
        {
            return(true);
        }

        // Preparation for the search
        Reset();
        return(FindPath(sourceIndex, targetIndex, sourceGraph));
    }
        private void AddEdge(AbstractGraph <int, int> graph, int source, int dest, int weight)
        {
            var add = true;

            if (IgnoreDuplicateEdges)
            {
                if (graph.GetNodes().Contains(source))
                {
                    if (graph.GetNeighbours(source).Contains(dest))
                    {
                        add = false;
                    }
                }
            }
            if (add)
            {
                graph.AddEdge(source, dest, weight);
            }
        }
Ejemplo n.º 24
0
        public Task <PlacementGraph> Analyze(AbstractGraph abstractGraph, GraphConfig config)
        {
            _abstractGraph = abstractGraph ?? throw new ArgumentNullException(nameof(abstractGraph));
            _config        = config ?? throw new ArgumentNullException(nameof(config));

            if (abstractGraph.Roots.Count == 0)
            {
                return(Task.FromResult(new PlacementGraph()));
            }

            _nextGraphRow = 0;
            _graph        = new PlacementGraph();
            _placedTasks  = new HashSet <Todo>();

            foreach (var root in _abstractGraph.Roots)
            {
                AddGraph(root);
            }

            return(Task.FromResult(_graph));
        }
Ejemplo n.º 25
0
        public bool BelongToSameCluster(Id <AbstractNode> node1Id, Id <AbstractNode> node2Id, int level)
        {
            var node1Pos    = AbstractGraph.GetNodeInfo(node1Id).Position;
            var node2Pos    = AbstractGraph.GetNodeInfo(node2Id).Position;
            var offset      = GetOffset(level);
            var currentRow1 = node1Pos.Y - (node1Pos.Y % offset);
            var currentRow2 = node2Pos.Y - (node2Pos.Y % offset);
            var currentCol1 = node1Pos.X - (node1Pos.X % offset);
            var currentCol2 = node2Pos.X - (node2Pos.X % offset);

            if (currentRow1 != currentRow2)
            {
                return(false);
            }

            if (currentCol1 != currentCol2)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 26
0
    /// <summary>
    /// 构建指定层级节点间的边
    /// </summary>
    private void AddEdgesBetweenAbstractNodes(int absId1, int absId2, int level)
    {
        var node1 = AbstractGraph.GetNode(absId1);
        var node2 = AbstractGraph.GetNode(absId2);

        var planner = new PathPlanner(this, null);
        var path    = planner.Search(node1, node2);

        if (path != null && path.Nodes.Count > 0)
        {
            AbstractEdge edge = HPADemo.Instance.CreateEdge(node1.Pos, node2.Pos, level, false);
            edge.Init(absId2, path.Cost, level, false);
            edge.SetInnerLowerLevelPath(path.Nodes);
            AbstractGraph.AddEdge(absId1, edge);

            path.Nodes.Reverse();

            edge = HPADemo.Instance.CreateEdge(node2.Pos, node1.Pos, level, false);
            edge.Init(absId1, path.Cost, level, false);
            edge.SetInnerLowerLevelPath(path.Nodes);
            AbstractGraph.AddEdge(absId2, edge);
        }
    }
Ejemplo n.º 27
0
 public void RemoveLinks(AbstractGraph graph, params (Coords, Coords)[] linkedCoords)
Ejemplo n.º 28
0
 public abstract void Generate(AbstractGraph abstractGraph);
Ejemplo n.º 29
0
 // Finds and returns the path between source and target indices
 // and the spanning tree of the search.
 //
 // Returns true if a path exists, returns false otherwise.
 //
 // TODO Replace ref with in if one day Unity supports C# 7+
 protected abstract bool FindPath(
     int sourceIndex, int targetIndex,
     AbstractGraph <NodeType, EdgeType> sourceGraph,
     ref List <int> path,
     ref List <HelperEdge> spanningTree
     );
Ejemplo n.º 30
0
 // Finds and returns the path between source and target indices.
 //
 // Returns true if a path exists, returns false otherwise.
 //
 // TODO Replace ref with in if one day Unity supports C# 7+
 protected abstract bool FindPath(
     int sourceIndex, int targetIndex,
     AbstractGraph <NodeType, EdgeType> sourceGraph,
     ref List <int> path
     );