Exemplo n.º 1
0
 public int Add(GraphEdge newItem)
 {
     GraphEdge edgeToAdd = newItem;
     edgeToAdd.Next = Head;
     Head = edgeToAdd;
     return size++;
 }
    public void AddNode(Vector3 neighborPoint, ref GraphNode currentNode, ref Queue<GraphNode> q )
    {
        RaycastHit hitInfo;
        Vector3 rayDirection = Vector3.zero;
        #if USE_XZ
        rayDirection = new Vector3(0, -1, 0);
        #else
        rayDirection = new Vector3(0, 0, 1);
        #endif //USE_XZ
        int layerMask = 1 << 8;
        layerMask = ~layerMask;
        if ( Physics.Raycast(neighborPoint, rayDirection, out hitInfo, Mathf.Infinity, layerMask) )
        {
            if (hitInfo.transform.tag == "Ground")
            {
                GraphNode newNode = new GraphNode(mNumOfNodes, hitInfo.point); // make a new node for this point
                GraphEdge newEdge = new GraphEdge(currentNode.GetIndex(), newNode.GetIndex()); // creat a new edge

                int index = 0;
                bool nodeFound = false;
                while ( !nodeFound && index <= mNumOfNodes )
                {
                    //Debug.Log (index + " out of " + NavigationGraph.Length + " thinks there's only" + mNumOfNodes);
                    nodeFound = ( NavigationGraph[index] == hitInfo.point );

                    ++index;
                }

                if ( !nodeFound ) // if we have not found this node before, add it
                {
                    Nodes.Add(newNode);
                    NavigationGraph[mNumOfNodes] = hitInfo.point;
                    ++mNumOfNodes;

                    q.Enqueue(newNode);
                }
                else
                {
                    newEdge.SetToIndex(index-1);
                }

                // If the raycast hit then we will always want to add the edge, since we want edges
                // in both directions and there won't ever be duplicates.

                // check if there is a clear path to add an edge
                Vector3 heightOffset = Vector3.zero;
        #if USE_XZ
                heightOffset = new Vector3(0, 0.5f, 0);
        #else
                heightOffset = new Vector3(0, 0, -0.5f);
        #endif // USE_XZ
                if ( !Physics.Linecast(currentNode.GetPosition() + heightOffset, newNode.GetPosition() + heightOffset, out hitInfo, layerMask) )
                {
                    Edges.Add(newEdge);
                    currentNode.AddEdge(newEdge);
                }
            }
        }
    }
Exemplo n.º 3
0
 public ObstacleDebugInfo(GraphEdge edge, Vector2?intersection, float dot, Vector2 avoidStrength, Vector2 translation)
 {
     Point1        = edge.Point1 + translation;
     Point2        = edge.Point2 + translation;
     Intersection  = intersection;
     Dot           = dot;
     AvoidStrength = avoidStrength;
 }
Exemplo n.º 4
0
        public async Task <GraphGetRp> GetGraphExperience(int productId, DatePeriodValue period)
        {
            GraphGetRp result  = new GraphGetRp();
            var        product = await this._dbContext.FullLoadProductWithSourceItems(productId, period.Start, period.End);

            result.Name   = product.Name;
            result.Id     = product.Id.Value;
            result.Avatar = product.Avatar;
            foreach (var journey in product.Journeys)
            {
                var measure = journey.Measure();
                var snode   = new GraphNode
                {
                    Id     = string.Format("journey_{0}", journey.Id),
                    Avatar = journey.Avatar,
                    Name   = string.Format("{0} [ {1} | {2} ]", journey.Name,
                                           Math.Round(journey.ExperienceSlo, 2),
                                           Math.Round(measure.Experience, 2)),
                    Value  = measure.Experience,
                    Group  = "journeys",
                    Slo    = journey.ExperienceSlo,
                    Budget = measure.ExperienceErrorBudget
                };

                result.Nodes.Add(snode);

                foreach (var map in journey.FeatureMap)
                {
                    var featureMeasure = map.Feature.Measure();
                    var Id             = string.Format("feature_{0}", map.Feature.Id);
                    var fnode          = result.Nodes.SingleOrDefault(c => c.Id == Id);
                    if (fnode == null)
                    {
                        fnode = new GraphNode
                        {
                            Id     = Id,
                            Avatar = map.Feature.Avatar,
                            Name   = map.Feature.Name,
                            Value  = featureMeasure.Experience,
                            Group  = "features"
                        };
                        result.Nodes.Add(fnode);
                    }
                    var fedge = new GraphEdge()
                    {
                        From  = snode.Id,
                        To    = fnode.Id,
                        Value = QualityUtils.MeasureBudget(fnode.Value, journey.ExperienceSlo),
                        Tags  = new Dictionary <string, object>()
                        {
                            { "Latency", fnode.Value }
                        }
                    };
                    result.Edges.Add(fedge);
                }
            }
            return(result);
        }
Exemplo n.º 5
0
            public List <int> CalculateBFS(int sourceNode, int targetNode)
            {
                //@Depth first search, unlikely to find best path
                List <int> m_path = new List <int>();

                for (int y = 0; y < 64; y++)
                {
                    for (int x = 0; x < 64; x++)
                    {
                        m_path.Add(-1);//= null value
                    }
                }
                List <bool> m_visited = new List <bool>();

                for (int y = 0; y < 64; y++)
                {
                    for (int x = 0; x < 64; x++)
                    {
                        m_visited.Add(false);
                    }
                }
                Queue <GraphEdge> m_graphEdges = new Queue <GraphEdge>();

                //Add all adjacent to the source node and mark as visited
                m_visited[sourceNode] = true;
                foreach (GraphEdge edge in m_nodes[sourceNode].m_edges)
                {
                    m_graphEdges.Enqueue(edge);
                }

                uint iteration = 0;

                //While there are elements in our stack
                while (m_graphEdges.Count > 0)
                {
                    iteration++;
                    GraphEdge edge = m_graphEdges.Dequeue();
                    m_path[edge.m_to]    = edge.m_from;
                    m_visited[edge.m_to] = true;
                    if (edge.m_to == targetNode)
                    {
                        return(m_path);
                    }
                    else
                    {
                        //Add all new adjacent edges to the stack
                        foreach (GraphEdge edges in m_nodes[edge.m_to].m_edges)
                        {
                            if ((m_visited[edges.m_to] == false) && !m_graphEdges.Contains(edges))
                            {
                                m_graphEdges.Enqueue(edges);
                            }
                        }
                    }
                }
                //If we got here, there is no path;
                return(null);
            }
Exemplo n.º 6
0
    public bool Check(NavGraph graph, int sourceNode, int targetNode)
    {
        graphNodes            = graph.Nodes;
        nodeCosts[sourceNode] = 0f;
        GetAdjacentEdges(sourceNode, graphNodes, graphNodes[targetNode]);

        while (edgeQueue.Count() != 0)
        {
            GraphEdge tempEdge = edgeQueue.Dequeue();
            traversedEdges.Add(tempEdge);
            if (nodeCosts[tempEdge.To] > nodeCosts[tempEdge.From] + tempEdge.GetCost())
            {
                nodeRoute[tempEdge.To] = tempEdge.From;
                nodeCosts[tempEdge.To] = nodeCosts[tempEdge.From] + tempEdge.GetCost() + manhattanDist(graphNodes[tempEdge.To], graphNodes[tempEdge.From]);

                if (tempEdge.To == targetNode)
                {
                    targetNodeFound = true;
                    continue;
                }
            }



            for (int i = 0; i < graphNodes[tempEdge.To].adjacencyList.Count; i++)
            {
                bool canAdd = true;
                if (traversedEdges.Contains(graphNodes[tempEdge.To].adjacencyList[i]))
                {
                    canAdd = false;
                }
                else if (edgeQueue.data.Contains(graphNodes[tempEdge.To].adjacencyList[i]))
                {
                    canAdd = false;
                }
                if (canAdd == true)
                {
                    float priority = manhattanDist(graphNodes[tempEdge.To], graphNodes[targetNode]); //should set the value to be based off of the manhattan distance
                    graphNodes[tempEdge.To].adjacencyList[i].edgeCost = priority;
                    nodeCosts[tempEdge.To] = nodeCosts[tempEdge.From] + tempEdge.GetCost();
                    edgeQueue.Enqueue(graphNodes[tempEdge.To].adjacencyList[i]);
                }
            }
        }

        if (targetNodeFound == true)
        {
            int currentNode = targetNode;
            Path.Add(currentNode);
            while (currentNode != sourceNode)
            {
                currentNode = nodeRoute[currentNode];
                Path.Add(currentNode);
            }
            return(true);
        }
        return(false);
    }
Exemplo n.º 7
0
        private string GenHtmlString(string istrSchemaName)
        {
            var node           = new GraphNode();
            var edge           = new GraphEdge();
            var returnGraphDot = "";

            returnGraphDot += GraphStart;
            returnGraphDot += node.istrGraphNode;
            returnGraphDot += edge.istrGraphEdge;
            var clusterIncrement = 0;

            if (istrSchemaName.IsNullOrEmpty())
            {
                TablesAndColumns.Select(x => x.istrSchemaName).DistinctBy(x => x).ToList().ForEach(x1 =>
                {
                    TablesAndColumns.Select(x => x.istrSchemaName).DistinctBy(x => x).ToList().ForEach(SchemaName =>
                    {
                        returnGraphDot += "subgraph cluster_" + clusterIncrement + " {\t label=" + SchemaName +
                                          ";\t";
                        returnGraphDot += "bgcolor=" + "\"" + RandomColor() + "\";";
                        TablesAndColumns.Where(x => x.istrSchemaName.Equals(SchemaName)).ForEach(x =>
                        {
                            x.keyValuePairs.ForEach(x2 =>
                            {
                                returnGraphDot += new TableSvg(x2.Key, x2.Value).GetTableHtml();
                            });
                        });
                        returnGraphDot += "\t}\t";
                        clusterIncrement++;
                    });
                });
            }
            else
            {
                TablesAndColumns.Select(x => x.istrSchemaName.Equals(istrSchemaName)).DistinctBy(x => x).ToList()
                .ForEach(x1 =>
                {
                    TablesAndColumns.Select(x => x.istrSchemaName).DistinctBy(x => x).ToList().ForEach(
                        SchemaName =>
                    {
                        returnGraphDot += "subgraph cluster_" + clusterIncrement + " {\t label=" +
                                          SchemaName + ";\t";
                        returnGraphDot += "bgcolor=" + "\"" + RandomColor() + "\";";
                        TablesAndColumns.Where(x => x.istrSchemaName.Equals(SchemaName)).ForEach(x =>
                        {
                            x.keyValuePairs.ForEach(x2 =>
                            {
                                returnGraphDot += new TableSvg(x2.Key, x2.Value).GetTableHtml();
                            });
                        });
                        returnGraphDot += "\t}\t";
                        clusterIncrement++;
                    });
                });
            }
            return(returnGraphDot);
        }
Exemplo n.º 8
0
            public static void RemoveEdge(GraphEdge edge)
            {
                GraphNode source = Graph.GetNode(edge.source);

                source.RemoveEdge(edge.target);
                GraphNode target = Graph.GetNode(edge.target);

                target.RemoveEdge(edge.source);
            }
Exemplo n.º 9
0
            public void DeleteEdge(GraphEdge edge)
            {
                GraphNode source = GetNode(edge.source);

                source.DeleteEdge(edge.target);
                GraphNode target = GetNode(edge.target);

                target.DeleteEdge(edge.source);
            }
        /// <summary>
        /// Gets the node importance.
        /// </summary>
        /// <param name="currentNodeId">The current node identifier.</param>
        /// <param name="graphEdge">The graph edge.</param>
        /// <returns></returns>
        private double GetNodeImportance(int currentNodeId, GraphEdge <int> graphEdge)
        {
            var pheromoneAmount = GetPheromoneAmount(currentNodeId, graphEdge.DestinationId);

            var pheromone = Math.Pow(pheromoneAmount, PheromoneInfluence);
            var edgeCost  = Math.Pow(graphEdge.Cost, EdgeCostInfluence);

            return(pheromone * edgeCost);
        }
Exemplo n.º 11
0
        public bool RemoveEdge(Graph <T> graph, GraphEdge <T> edge)
        {
            if (edge == null)
            {
                return(false);
            }

            return(graph.Edges.Remove(edge));
        }
 private void InitializeGraph(int V, int E)
 {
     InitializeGraph(V);
     Edges = new GraphEdge[E];
     for (int i = 0; i < E; i++)
     {
         Edges[i] = new GraphEdge();
     }
 }
Exemplo n.º 13
0
            public SpawnPosition(GraphEdge graphEdge, Vector2 normal, LevelObjectPrefab.SpawnPosType spawnPosType, Alignment alignment)
            {
                GraphEdge    = graphEdge;
                Normal       = normal;
                SpawnPosType = spawnPosType;
                Alignment    = alignment;

                Length = Vector2.Distance(graphEdge.Point1, graphEdge.Point2);
            }
Exemplo n.º 14
0
    public GraphEdge CreateEdge(int fromId, int toId)
    {
        GameObject node = nodesAvailable[fromId].gameObject;
        GameObject e    = Instantiate(edgePrefab, node.transform.position, Quaternion.identity);
        GraphEdge  edge = e.GetComponent <GraphEdge>();

        edge.SetEdge(nodesAvailable[fromId], nodesAvailable[toId], true);
        return(edge);
    }
Exemplo n.º 15
0
        // http://math.stackexchange.com/questions/142112/how-to-construct-a-k-regular-graph
        // k-regular graph on n vertices.
        public static void Graph()
        {
            HashSet <GraphEdge> edges = new HashSet <GraphEdge>();

            int k = 24, n = 350;

            //int k = 7, n = 24;

            if (k % 2 == 0)
            {
                int increment = n / (k + 1);
                increment = 1;

                for (int i = 0; i < n; i++)
                {
                    for (int j = 1; j <= k / 2; j++)
                    {
                        int t1 = Clamp(i + j * increment, n);
                        int t2 = Clamp(i - j * increment, n);

                        GraphEdge e1 = new GraphEdge(i, t1);
                        GraphEdge e2 = new GraphEdge(i, t2);
                        edges.Add(e1);
                        edges.Add(e2);
                    }
                }
            }
            else
            {
                int m = k / 2;
                for (int i = 0; i < n; i++)
                {
                    for (int j = 1; j <= m; j++)
                    {
                        int t1 = Clamp(i + j, n);
                        int t2 = Clamp(i - j, n);

                        GraphEdge e1 = new GraphEdge(i, t1);
                        GraphEdge e2 = new GraphEdge(i, t2);
                        edges.Add(e1);
                        edges.Add(e2);
                    }

                    int t3 = Clamp(i + n / 2, n);
                    edges.Add(new GraphEdge(i, t3));
                }
            }

            using (StreamWriter sw = File.CreateText("733.csv"))
            {
                foreach (GraphEdge e in edges)
                {
                    sw.WriteLine(string.Format("master{0};master{1}", e.V1, e.V2));
                }
            }
        }
Exemplo n.º 16
0
    private void Search()
    {
        var pq = new Heap <GraphNode>(m_Graph.NumNodes(), Compare);

        pq.Add(m_Graph.GetNode(m_iSource));
        m_CostToThisNode[m_iSource] = 0;
        m_SearchFrontier[m_iSource] = new GraphEdge();
        while (pq.Count > 0)
        {
            //get the lowest cost node from the queue. Don't forget, the return value
            //is a *node index*, not the node itself. This node is the node not already
            //on the SPT that is the closest to the source node
            int nextClosestNode = pq.RemoveFirst().Index;

            //move this edge from the search frontier to the shortest path tree
            m_ShortestPathTree[nextClosestNode] = m_SearchFrontier[nextClosestNode];

            if (nextClosestNode == m_iTarget)
            {
                m_bFound = true;
                return;
            }
            //now to relax the edges. For each edge connected to the next closest node
            var edgeList = m_Graph.GetEdgesAt(nextClosestNode);
            var edgeNode = edgeList.First;

            while (edgeNode != null)
            {
                var   edgeNodeVal = edgeNode.Value;
                float newCost     = m_CostToThisNode[nextClosestNode] + edgeNodeVal.Cost;
                //if this edge has never been on the frontier make a note of the cost
                //to reach the node it points to, then add the edge to the frontier
                //and the destination node to the PQ.
                if (m_SearchFrontier[edgeNodeVal.To] == null)
                {
                    m_CostToThisNode[edgeNodeVal.To] = newCost;
                    pq.Add(m_Graph.GetNode(edgeNodeVal.To));
                    m_SearchFrontier[edgeNodeVal.To] = edgeNodeVal;
                }
                //else test to see if the cost to reach the destination node via the
                //current node is cheaper than the cheapest cost found so far. If
                //this path is cheaper we assign the new cost to the destination
                //node, update its entry in the PQ to reflect the change, and add the
                //edge to the frontier
                else if (newCost < m_CostToThisNode[edgeNodeVal.To] && m_ShortestPathTree[edgeNodeVal.To] == null)
                {
                    m_CostToThisNode[edgeNodeVal.To] = newCost;
                    //because the cost is less than it was previously, the PQ must be
                    //resorted to account for this
                    pq.UpdateItem(m_Graph.GetNode(edgeNodeVal.To));
                    m_SearchFrontier[edgeNodeVal.To] = edgeNodeVal;
                }
                edgeNode = edgeNode.Next;
            }
        }
    }
Exemplo n.º 17
0
        public void FindEdgeNodeTest()
        {
            Graph <object, object>     g  = new Graph <object, object>();
            GraphEdge <object, object> ge = g.FindGraphEdge(new object());

            Assert.IsNull(ge);

            ge = g.FindGraphEdge(null);
            Assert.IsNull(ge);
        }
Exemplo n.º 18
0
            public List <int> CalculateDFS(int sourceNode, int targetNode)
            {
                //@Breadth first search, inefficient to search
                List <int> m_path = new List <int>();

                for (int y = 0; y < 64; y++)
                {
                    for (int x = 0; x < 64; x++)
                    {
                        m_path.Add(-1);//= null value
                    }
                }
                List <bool> m_visited = new List <bool>();

                for (int y = 0; y < 64; y++)
                {
                    for (int x = 0; x < 64; x++)
                    {
                        m_visited.Add(false);
                    }
                }
                Stack <GraphEdge> m_graphEdges = new Stack <GraphEdge>();

                //Add all adjacent to the source node and mark as visited
                m_visited[sourceNode] = true;
                foreach (GraphEdge edge in m_nodes[sourceNode].m_edges)
                {
                    m_graphEdges.Push(edge);
                }

                //While there are elements in our stack
                while (m_graphEdges.Count > 0)
                {
                    GraphEdge edge = m_graphEdges.Pop();
                    m_path[edge.m_to]    = edge.m_from;
                    m_visited[edge.m_to] = true;
                    if (edge.m_to == targetNode)
                    {
                        return(m_path);
                    }
                    else
                    {
                        //Add all new adjacent edges to the stack
                        foreach (GraphEdge edges in m_nodes[edge.m_to].m_edges)
                        {
                            if (m_visited[edges.m_to] == false)
                            {
                                m_graphEdges.Push(edges);
                            }
                        }
                    }
                }
                //If we got here, there is no path;
                return(null);
            }
Exemplo n.º 19
0
 void BuildEdges(GraphNode me, ArrayList others)
 {
     foreach (GraphNode gn in others)
     {
         GraphEdge ge = Instantiate(edge) as GraphEdge;
         ge.ShowColor(false);
         ge.SetPositions(me.transform.position, gn.transform.position);
         me.edges.Add(ge);
         gn.edges.Add(ge);
     }
 }
Exemplo n.º 20
0
    public bool Equals(GraphEdge p)
    {
        // If parameter is null return false:
        if ((object)p == null)
        {
            return(false);
        }

        // Return true if the fields match:
        return((m_iFrom == p.m_iFrom) && (m_iTo == p.m_iTo));
    }
Exemplo n.º 21
0
    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return(false);
        }

        GraphEdge edge = (GraphEdge)obj;

        return(this == edge);
    }
Exemplo n.º 22
0
        private bool AddEdge(GraphEdge newEdge, List <GraphEdge> edges)
        {
            if (newEdge == null)
            {
                return(false);
            }

            edges.Add(newEdge);

            return(true);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Add edge to the graph
 /// </summary>
 public void AddEdge(GraphEdge edge)
 {
     if (GetEdge(edge.from.index, edge.to.index) == null)
     {
         edges.Add(edge);
     }
     else
     {
         Debug.LogWarning("Edge " + edge.from.index + " - " + edge.to.index + " has already been added.");
     }
 }
Exemplo n.º 24
0
    static void SetTargetEdge()
    {
        GraphEdge edge = GetSelectedGraphEdge();

        if (edge == null)
        {
            Debug.LogError("[jxd] Edge isn't selected!");
            return;
        }
        s_TargetEdge = edge;
    }
Exemplo n.º 25
0
 // Add an edge (but don't add duplicate edges)
 public void AddIncidentEdge(GraphEdge e)
 {
     foreach (GraphEdge edge in incidentEdges)
     {
         if (edge.ToString() == e.ToString())
         {
             return;
         }
     }
     incidentEdges.Add(e);
 }
        public Graph GetTree()
        {
            // initialize the graph that will hold the MST
            Graph mst = new KevinGraph();

            // initialize the priority queue that will hold the vertices outside the MST
            PriorityQueue remainingVertices = new KevinPriorityQueue();

            foreach (GraphVertex v in weightedGraph.GetAllVertices())
            {
                remainingVertices.Enqueue(new MSTPriorityQueueNode(data: v, priority: int.MaxValue));
            }

            Dictionary <string, GraphEdge> lowestCostEdgeForVertex = new Dictionary <string, GraphEdge>();

            while (remainingVertices.Count() > 0)
            {
                // Get the vertex with the lowest code to add to the MST
                // The first vertex is chosen arbitrarily because all vertices start with max cost.
                PriorityQueueNode currentNode   = remainingVertices.Dequeue();
                GraphVertex       currentVertex = currentNode.Data as GraphVertex;

                // Add the vertex and its lowest cost edge (if any) to the MST
                mst.AddVertex(currentVertex.UniqueKey);
                if (lowestCostEdgeForVertex.ContainsKey(currentVertex.UniqueKey))
                {
                    GraphEdge lowestCostEdge = lowestCostEdgeForVertex[currentVertex.UniqueKey];
                    // TO-DO: why?
                    mst.AddEdge(lowestCostEdge.SourceVertexUniqueKey, lowestCostEdge.TargetVertexUniqueKey, lowestCostEdge.Weight);
                    mst.AddEdge(lowestCostEdge.TargetVertexUniqueKey, lowestCostEdge.SourceVertexUniqueKey, lowestCostEdge.Weight);
                }

                // update the minimum cost for each adjacent vertex, and the associated edge
                foreach (GraphEdge edge in currentVertex.GetIncidentEdges())
                {
                    GraphVertex edgeTarget = weightedGraph.GetVertexByUniqueKey(edge.TargetVertexUniqueKey);

                    if (!remainingVertices.Contains(edgeTarget.UniqueKey))
                    {
                        continue;
                    }

                    int newCost = edge.Weight;
                    PriorityQueueNode targetNode = remainingVertices.Peek(edgeTarget.UniqueKey);
                    if (newCost < targetNode.Priority)
                    {
                        remainingVertices.ChangePriority(targetNode.Data.UniqueKey, newCost);
                        lowestCostEdgeForVertex[edgeTarget.UniqueKey] = edge;
                    }
                }
            }

            return(mst);
        }
Exemplo n.º 27
0
        public async Task FindLibraryEntryAsync_LogsOnlyPackages(LibraryDependencyTarget libraryDependencyTarget)
        {
            // Arrange
            const string packageX = "x", version = "1.0.0-beta.1", source = "source";
            var          range          = new LibraryRange(packageX, VersionRange.Parse(version), libraryDependencyTarget);
            var          cacheContext   = new SourceCacheContext();
            var          testLogger     = new TestLogger();
            var          framework      = NuGetFramework.Parse("net45");
            var          token          = CancellationToken.None;
            var          edge           = new GraphEdge <RemoteResolveResult>(null, null, null);
            var          actualIdentity = new LibraryIdentity(packageX, NuGetVersion.Parse(version), LibraryType.Package);
            var          dependencies   = new[] { new LibraryDependency()
                                                  {
                                                      LibraryRange = new LibraryRange("y", VersionRange.All, LibraryDependencyTarget.Package)
                                                  } };
            var dependencyInfo = LibraryDependencyInfo.Create(actualIdentity, framework, dependencies);

            //package source mapping configuration
            Dictionary <string, IReadOnlyList <string> > patterns = new();

            patterns.Add(source, new List <string>()
            {
                packageX
            });
            PackageSourceMapping sourceMappingConfiguration = new(patterns);
            var context = new RemoteWalkContext(cacheContext, sourceMappingConfiguration, testLogger);

            var remoteProvider = new Mock <IRemoteDependencyProvider>();

            remoteProvider.Setup(e => e.FindLibraryAsync(range, It.IsAny <NuGetFramework>(), It.IsAny <SourceCacheContext>(), testLogger, token))
            .ReturnsAsync(actualIdentity);
            remoteProvider.SetupGet(e => e.IsHttp).Returns(true);
            remoteProvider.SetupGet(e => e.Source).Returns(new PackageSource(source));
            remoteProvider.Setup(e => e.GetDependenciesAsync(It.IsAny <LibraryIdentity>(), It.IsAny <NuGetFramework>(), It.IsAny <SourceCacheContext>(), testLogger, token))
            .ReturnsAsync(dependencyInfo);
            context.RemoteLibraryProviders.Add(remoteProvider.Object);

            // Act
            var result = await ResolverUtility.FindLibraryEntryAsync(range, framework, null, context, token);

            // Assert
            Assert.Equal(0, testLogger.Errors);
            testLogger.DebugMessages.TryPeek(out string message);
            if (libraryDependencyTarget == LibraryDependencyTarget.Package)
            {
                Assert.Equal($"Package source mapping matches found for package ID '{packageX}' are: '{source}'.", message);
                Assert.Equal(version, result.Key.Version.ToString());
                Assert.Equal(source, result.Data.Match.Provider.Source.Name);
            }
            else
            {
                Assert.Equal(message, null);
            }
        }
Exemplo n.º 28
0
        // AddEdge adds the edge, creating endpoint nodes if necessary.
        // Edge is added to adjacency list of from edges.
        public void AddEdge(string name1, string name2, string relationship)
        {
            AddNode(name1);                     // create the node if it doesn't already exist
            GraphNode n1 = nodeDict[name1];     // now fetch a reference to the node

            AddNode(name2);
            GraphNode n2 = nodeDict[name2];
            GraphEdge e  = new GraphEdge(n1, n2, relationship);

            n1.AddIncidentEdge(e);
        }
Exemplo n.º 29
0
 public override bool Equals(object obj)
 {
     if (obj is GraphEdge)
     {
         GraphEdge e = (GraphEdge)obj;
         return(e.cost == this.cost && e.from == this.from && e.to == this.to);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 30
0
        public async Task FindPackage_VerifyFloatingPackageIsRequiredOnlyFromASingleSource()
        {
            // Arrange
            var range          = new LibraryRange("x", VersionRange.Parse("1.0.0-*"), LibraryDependencyTarget.Package);
            var cacheContext   = new SourceCacheContext();
            var testLogger     = new TestLogger();
            var framework      = NuGetFramework.Parse("net45");
            var context        = new RemoteWalkContext(cacheContext, testLogger);
            var token          = CancellationToken.None;
            var edge           = new GraphEdge <RemoteResolveResult>(null, null, null);
            var actualIdentity = new LibraryIdentity("x", NuGetVersion.Parse("1.0.0-beta.1"), LibraryType.Package);
            var higherIdentity = new LibraryIdentity("x", NuGetVersion.Parse("1.0.0-beta.2"), LibraryType.Package);
            var dependencies   = new[] { new LibraryDependency()
                                         {
                                             LibraryRange = new LibraryRange("y", VersionRange.All, LibraryDependencyTarget.Package)
                                         } };
            var dependencyInfo  = LibraryDependencyInfo.Create(actualIdentity, framework, dependencies);
            var dependencyInfo2 = LibraryDependencyInfo.Create(higherIdentity, framework, dependencies);

            var downloadCount = 0;

            // Source1 returns 1.0.0-beta.1
            var remoteProvider = new Mock <IRemoteDependencyProvider>();

            remoteProvider.Setup(e => e.FindLibraryAsync(range, It.IsAny <NuGetFramework>(), It.IsAny <SourceCacheContext>(), testLogger, token))
            .ReturnsAsync(actualIdentity);
            remoteProvider.SetupGet(e => e.IsHttp).Returns(true);
            remoteProvider.SetupGet(e => e.Source).Returns(new PackageSource("test"));
            remoteProvider.Setup(e => e.GetDependenciesAsync(It.IsAny <LibraryIdentity>(), It.IsAny <NuGetFramework>(), It.IsAny <SourceCacheContext>(), testLogger, token))
            .ReturnsAsync(dependencyInfo)
            .Callback(() => ++ downloadCount);
            context.RemoteLibraryProviders.Add(remoteProvider.Object);

            // Source2 returns 1.0.0-beta.2
            var remoteProvider2 = new Mock <IRemoteDependencyProvider>();

            remoteProvider2.Setup(e => e.FindLibraryAsync(range, It.IsAny <NuGetFramework>(), It.IsAny <SourceCacheContext>(), testLogger, token))
            .ReturnsAsync(higherIdentity);
            remoteProvider2.SetupGet(e => e.IsHttp).Returns(true);
            remoteProvider2.SetupGet(e => e.Source).Returns(new PackageSource("test"));
            remoteProvider2.Setup(e => e.GetDependenciesAsync(It.IsAny <LibraryIdentity>(), It.IsAny <NuGetFramework>(), It.IsAny <SourceCacheContext>(), testLogger, token))
            .ReturnsAsync(dependencyInfo2)
            .Callback(() => ++ downloadCount);
            context.RemoteLibraryProviders.Add(remoteProvider2.Object);

            // Act
            var result = await ResolverUtility.FindLibraryEntryAsync(range, framework, null, edge, context, token);

            // Assert
            // Verify only one download happened
            Assert.Equal(1, downloadCount);
            Assert.Equal("1.0.0-beta.2", result.Key.Version.ToString());
        }
Exemplo n.º 31
0
    //this method performs the DFS search
    private bool Search()
    {
        //create a std stack of edges
        Stack <GraphEdge> stack = new Stack <GraphEdge>();

        //create a dummy edge and put on the stack
        GraphEdge Dummy = new GraphEdge(m_iSource, m_iSource, 0);

        stack.Push(Dummy);

        //while there are edges in the stack keep searching
        while (0 != stack.Count)
        {
            //grab the next edge
            GraphEdge Next = stack.Peek();
            //Debug.Log(Next); //chamto test

            //remove the edge from the stack
            stack.Pop();

            //make a note of the parent of the node this edge points to
            m_Route[Next.To()] = Next.From();

            //put it on the tree. (making sure the dummy edge is not placed on the tree)
            if (Next != Dummy)
            {
                m_SpanningTree.Add(Next);
            }

            //and mark it visited
            m_Visited[Next.To()] = (int)Aid.visited;

            //if the target has been found the method can return success
            if (Next.To() == m_iTarget)
            {
                return(true);
            }

            //push the edges leading from the node this edge points to onto
            //the stack (provided the edge does not point to a previously
            //visited node)
            foreach (GraphEdge pE in m_Graph.GetEdges(Next.To()))
            {
                if (m_Visited[pE.To()] == (int)Aid.unvisited)
                {
                    stack.Push(pE);
                }
            }
        }

        //no path to target
        return(false);
    }
Exemplo n.º 32
0
            public SpawnPosition(GraphEdge graphEdge, Vector2 normal, LevelObjectPrefab.SpawnPosType spawnPosType, Alignment alignment)
            {
                GraphEdge    = graphEdge;
                Normal       = normal;
                SpawnPosType = spawnPosType;
                Alignment    = alignment;

                Length = Vector2.Distance(graphEdge.Point1, graphEdge.Point2);

                noiseVal =
                    (float)(PerlinNoise.CalculatePerlin(GraphEdge.Point1.X / 10000.0f, GraphEdge.Point1.Y / 10000.0f, 0.5f) +
                            PerlinNoise.CalculatePerlin(GraphEdge.Point1.X / 20000.0f, GraphEdge.Point1.Y / 20000.0f, 0.5f));
            }
    public void Add(GraphEdge newObj)
    {
        if ( mSize >= mArray.Length )
        {
            GraphEdge[] temp = new GraphEdge[mCapacity << 1];

            for ( int i = 0; i < (mCapacity << 1); ++i )
            {
                temp[i] = mArray[i];
            }
            mCapacity = mCapacity << 1;
            mArray = new GraphEdge[mCapacity];
            mArray = temp;
        }

        mArray[mSize] = newObj;
        ++mSize;
    }
Exemplo n.º 34
0
 public bool Intersects(GraphEdge edge)
     {
     return LineSegmentGeometryD.Intersects(new LineSegmentGeometryD(this.A.Location, this.B.Location), new LineSegmentGeometryD(edge.A.Location, edge.B.Location));
     }
Exemplo n.º 35
0
    /// <summary>
    /// Creates a hallway on the given edge. Gets coordinates of the nodes in the edge,
    /// translates into world coordinates, and places the properly stretched hallway
    /// between those coordinates
    /// </summary>
    /// <param name="edge"></param>
    private void CreateHallway(GraphEdge edge) {
        MazeHallway newHallway = Instantiate(hallwayPrefab) as MazeHallway;

        IntVector2 cellCoord1 = MazeGrid.GetNodeCoords(edge.node1);
        IntVector2 cellCoord2 = MazeGrid.GetNodeCoords(edge.node2);

        Vector3 hallwayPosition = GetHallwayPosition(edge);

        newHallway.transform.parent = transform;
        newHallway.transform.localPosition = hallwayPosition;
        

        //decide which way the hallway should be rotated
        if (cellCoord1.z != cellCoord2.z) {
            newHallway.RotateHallway();
        }

        newHallway.StretchHallway(GetHallwayScale());

        //add the hallway to the list
        hallways[edge] = newHallway;
    }
Exemplo n.º 36
0
        /// <summary>
        /// Adds an outgoing edge.
        /// </summary>
        /// <param name="edge">The edge.</param>
        protected internal void AddOutgoingEdge(GraphEdge edge)
        {
            Contract.Requires(edge != null);

            this.outgoingEdges.Add(edge);
            this.AddConnectedNode(edge.To);
            this.AddConnectedEdge(edge);
        }
Exemplo n.º 37
0
    private void CreateAllNeighboursToGridNode(int row, int col, int totalrow, int totalcolumn)
    {
        int noderow = 0;
        int nodecol = 0;
        for (int i=-1; i<2; ++i)
        {
            for (int j=-1; j<2; ++j)
            {
                noderow =  row + i;
                nodecol = col + j;
                //Skip if equal to this node
                if((i == 0) && (j == 0))
                {
                    continue;
                }

                //Check to see if this is a valid neighbour
                if(ValidNeighbour(noderow, nodecol, totalrow, totalcolumn))
                {
                    Vector3 posnode = mNavGraph.Nodes[row * totalcolumn + col].Position;
                    Vector3 posneighbour = mNavGraph.Nodes[noderow * totalcolumn + nodecol].Position;

                    float dist = Vector3.Distance(posnode, posneighbour);
                    float fromnodeweight = mNavGraph.Nodes[row * totalcolumn + col].Weight;
                    float tonodeweight = mNavGraph.Nodes[noderow * totalcolumn + nodecol].Weight;
                    dist = dist + fromnodeweight + tonodeweight;

                    GraphEdge newedge = new GraphEdge(row * totalcolumn + col, noderow * totalcolumn + nodecol, dist);
                    mNavGraph.AddEdge(newedge);
                }
            }
        }
    }
Exemplo n.º 38
0
        private void pushGraphEdge( Site leftSite, Site rightSite, double x1, double y1, double x2, double y2 )
        {
            GraphEdge newEdge = new GraphEdge ();
            allEdges.Add ( newEdge );
            newEdge.x1 = x1;
            newEdge.y1 = y1;
            newEdge.x2 = x2;
            newEdge.y2 = y2;

            newEdge.site1 = leftSite.sitenbr;
            newEdge.site2 = rightSite.sitenbr;
        }
Exemplo n.º 39
0
 GraphEdge EdgeFromDomain(GraphComponent component, Domain d, bool fMustExist=false)
 // Return the edge for the indicated domain along its strand. We create this 
 // edge if it doesn't already exist. The returned edge has edge.A on the 5'
 // side of d and edge.B on the 3' side.
     {
     GraphEdge edge;
     if (!this.mpDomainEdge.TryGetValue(d, out edge))
         {
         Debug.Assert(!fMustExist);
         //
         // If there's another domain 5' of this one, and he already has
         // an edge, then we use the B vertex from that guy; otherwise,
         // we make one fresh anew.
         //
         GraphVertex to5 = null;
         if (d.CircularNextTo5 != null)
             {
             GraphEdge edgeTo5;
             if (this.mpDomainEdge.TryGetValue(d.CircularNextTo5, out edgeTo5))
                 {
                 to5 = edgeTo5.B;
                 }
             }
         if (null == to5)
             {
             to5 = new GraphVertex(component, "[" + d.DisplayName + ">", d);
             }
         //  
         // Ditto, but in the 3' direction
         //
         GraphVertex to3 = null;
         if (d.CircularNextTo3 != null)
             {
             GraphEdge edgeTo3;
             if (this.mpDomainEdge.TryGetValue(d.CircularNextTo3, out edgeTo3))
                 {
                 to3 = edgeTo3.A;
                 }
             }
         if (null == to3)
             {
             to3 = new GraphVertex(component, "<" + d.DisplayName + "]", d);
             }
         //
         // Make the new edge
         //
         double length = this.DomainRenderingLength(d);
         edge = new GraphEdge(component, to5, to3, length, Constants.StyleLineDomain);
         //
         // Apply appropriate forces to the edge
         // 
         SpringForce.CreateSymmetricalSpringForces(component, edge.A, edge.B, Constants.SpringConstantDomain, length);
         IntersectionForce.Create(component, edge, Constants.IntersectionForceStrength);
         //
         // Remember this edge
         //
         edge.Domain = d;
         this.mpDomainEdge[d] = edge;
         }
     return edge;
     }
Exemplo n.º 40
0
        /// <summary>
        /// Saves the action graph (and include dependency network) to a graph gile
        /// </summary>
        /// <param name="Filename">File name to emit</param>
        /// <param name="Description">Description to be stored in graph metadata</param>
        /// <param name="VisualizationType">Type of graph to create</param>
        /// <param name="Actions">All actions</param>
        /// <param name="IncludeCompileActions">True if we should include compile actions.  If disabled, only the static link actions will be shown, which is useful to see module relationships</param>
        public static void SaveActionGraphVisualization(STBuildTarget Target, string Filename, string Description, ActionGraphVisualizationType VisualizationType, List<Action> Actions, bool IncludeCompileActions = true)
        {
            // True if we should include individual files in the graph network, or false to include only the build actions
            var IncludeFiles = VisualizationType != ActionGraphVisualizationType.OnlyActions;
            var OnlyIncludeCPlusPlusFiles = VisualizationType == ActionGraphVisualizationType.OnlyCPlusPlusFilesAndHeaders;

            // True if want to show actions in the graph, otherwise we're only showing files
            var IncludeActions = VisualizationType != ActionGraphVisualizationType.OnlyFilesAndHeaders && VisualizationType != ActionGraphVisualizationType.OnlyCPlusPlusFilesAndHeaders;

            // True if C++ header dependencies should be expanded into the graph, or false to only have .cpp files
            var ExpandCPPHeaderDependencies = IncludeFiles && (VisualizationType == ActionGraphVisualizationType.ActionsWithFilesAndHeaders || VisualizationType == ActionGraphVisualizationType.OnlyFilesAndHeaders || VisualizationType == ActionGraphVisualizationType.OnlyCPlusPlusFilesAndHeaders);

            var TimerStartTime = DateTime.UtcNow;

            var GraphNodes = new List<GraphNode>();

            var FileToGraphNodeMap = new Dictionary<FileItem, GraphNode>();

            // Filter our list of actions
            var FilteredActions = new List<Action>();
            {
                for (var ActionIndex = 0; ActionIndex < Actions.Count; ++ActionIndex)
                {
                    var Action = Actions[ActionIndex];

                    if (!IncludeActions || IncludeCompileActions || (Action.ActionType != ActionType.Compile))
                    {
                        FilteredActions.Add(Action);
                    }
                }
            }

            var FilesToCreateNodesFor = new HashSet<FileItem>();
            for (var ActionIndex = 0; ActionIndex < FilteredActions.Count; ++ActionIndex)
            {
                var Action = FilteredActions[ActionIndex];

                if (IncludeActions)
                {
                    var GraphNode = new GraphNode()
                    {
                        Id = GraphNodes.Count,

                        // Don't bother including "Link" text if we're excluding compile actions
                        Label = IncludeCompileActions ? (Action.ActionType.ToString() + " " + Action.StatusDescription) : Action.StatusDescription
                    };

                    switch (Action.ActionType)
                    {
                        case ActionType.BuildProject:
                            GraphNode.Color = new GraphColor() { R = 0.3f, G = 1.0f, B = 1.0f, A = 1.0f };
                            GraphNode.Size = 1.1f;
                            break;

                        case ActionType.Compile:
                            GraphNode.Color = new GraphColor() { R = 0.3f, G = 1.0f, B = 0.3f, A = 1.0f };
                            break;

                        case ActionType.Link:
                            GraphNode.Color = new GraphColor() { R = 0.3f, G = 0.3f, B = 1.0f, A = 1.0f };
                            GraphNode.Size = 1.2f;
                            break;
                    }

                    GraphNodes.Add(GraphNode);
                }

                if (IncludeFiles)
                {
                    foreach (var ProducedFileItem in Action.ProducedItems)
                    {
                        if (!OnlyIncludeCPlusPlusFiles || IsCPPFile(ProducedFileItem))
                        {
                            FilesToCreateNodesFor.Add(ProducedFileItem);
                        }
                    }

                    foreach (var PrerequisiteFileItem in Action.PrerequisiteItems)
                    {
                        if (!OnlyIncludeCPlusPlusFiles || IsCPPFile(PrerequisiteFileItem))
                        {
                            FilesToCreateNodesFor.Add(PrerequisiteFileItem);
                        }
                    }
                }
            }

            var OverriddenPrerequisites = new Dictionary<FileItem, List<FileItem>>();

            // Determine the average size of all of the C++ source files
            Int64 AverageCPPFileSize;
            {
                Int64 TotalFileSize = 0;
                int CPPFileCount = 0;
                foreach (var FileItem in FilesToCreateNodesFor)
                {
                    if (IsCPPFile(FileItem))
                    {
                        ++CPPFileCount;
                        TotalFileSize += new FileInfo(FileItem.AbsolutePath).Length;
                    }
                }

                if (CPPFileCount > 0)
                {
                    AverageCPPFileSize = TotalFileSize / CPPFileCount;
                }
                else
                {
                    AverageCPPFileSize = 1;
                }
            }

            var BuildPlatform = STBuildPlatform.GetBuildPlatform(STTargetPlatform.Win64);

            foreach (var FileItem in FilesToCreateNodesFor)
            {
                var FileGraphNode = new GraphNode()
                {
                    Id = GraphNodes.Count,
                    Label = Path.GetFileName(FileItem.AbsolutePath)
                };

                if (FileItem.AbsolutePath.EndsWith(".h", StringComparison.InvariantCultureIgnoreCase) ||
                    FileItem.AbsolutePath.EndsWith(".inl", StringComparison.InvariantCultureIgnoreCase))
                {
                    // Header file
                    FileGraphNode.Color = new GraphColor() { R = 0.9f, G = 0.2f, B = 0.9f, A = 1.0f };
                }
                else if (FileItem.AbsolutePath.EndsWith(".cpp", StringComparison.InvariantCultureIgnoreCase) ||
                         FileItem.AbsolutePath.EndsWith(".c", StringComparison.InvariantCultureIgnoreCase) ||
                         FileItem.AbsolutePath.EndsWith(".mm", StringComparison.InvariantCultureIgnoreCase))
                {
                    // C++ file
                    FileGraphNode.Color = new GraphColor() { R = 1.0f, G = 1.0f, B = 0.3f, A = 1.0f };
                }
                else
                {
                    // Other file
                    FileGraphNode.Color = new GraphColor() { R = 0.4f, G = 0.4f, B = 0.1f, A = 1.0f };
                }

                // Set the size of the file node based on the size of the file on disk
                var bIsCPPFile = IsCPPFile(FileItem);
                if (bIsCPPFile)
                {
                    var MinNodeSize = 0.25f;
                    var MaxNodeSize = 2.0f;
                    var FileSize = new FileInfo(FileItem.AbsolutePath).Length;
                    float FileSizeScale = (float)((double)FileSize / (double)AverageCPPFileSize);

                    var SourceFileSizeScaleFactor = 0.1f;		// How much to make nodes for files bigger or larger based on their difference from the average file's size
                    FileGraphNode.Size = Math.Min(Math.Max(1.0f + SourceFileSizeScaleFactor * FileSizeScale, MinNodeSize), MaxNodeSize);
                }

                //@todo: Testing out attribute support.  Replace with an attribute that is actually useful!
                //if( FileItem.PrecompiledHeaderIncludeFilename != null )
                //{
                //FileGraphNode.Attributes[ "PCHFile" ] = Path.GetFileNameWithoutExtension( FileItem.PrecompiledHeaderIncludeFilename );
                //}

                FileToGraphNodeMap[FileItem] = FileGraphNode;
                GraphNodes.Add(FileGraphNode);

                if (ExpandCPPHeaderDependencies && bIsCPPFile)
                {
                    bool HasUObjects;
                    List<DependencyInclude> DirectlyIncludedFilenames = CPPEnvironment.GetDirectIncludeDependencies(Target, FileItem, BuildPlatform, bOnlyCachedDependencies: false, HasUObjects: out HasUObjects);

                    // Resolve the included file name to an actual file.
                    var DirectlyIncludedFiles =
                        DirectlyIncludedFilenames
                        .Where(DirectlyIncludedFilename => !string.IsNullOrEmpty(DirectlyIncludedFilename.IncludeResolvedName))
                        .Select(DirectlyIncludedFilename => DirectlyIncludedFilename.IncludeResolvedName)
                        // Skip same include over and over (.inl files)
                        .Distinct()
                        .Select(FileItem.GetItemByFullPath)
                        .ToList();

                    OverriddenPrerequisites[FileItem] = DirectlyIncludedFiles;
                }
            }

            // Connect everything together
            var GraphEdges = new List<GraphEdge>();

            if (IncludeActions)
            {
                for (var ActionIndex = 0; ActionIndex < FilteredActions.Count; ++ActionIndex)
                {
                    var Action = FilteredActions[ActionIndex];
                    var ActionGraphNode = GraphNodes[ActionIndex];

                    List<FileItem> ActualPrerequisiteItems = Action.PrerequisiteItems;
                    if (IncludeFiles && ExpandCPPHeaderDependencies && Action.ActionType == ActionType.Compile)
                    {
                        // The first prerequisite is always the .cpp file to compile
                        var CPPFile = Action.PrerequisiteItems[0];
                        if (!IsCPPFile(CPPFile))
                        {
                            throw new BuildException("Was expecting a C++ file as the first prerequisite for a Compile action");
                        }

                        ActualPrerequisiteItems = new List<FileItem>();
                        ActualPrerequisiteItems.Add(CPPFile);
                    }

                    foreach (var PrerequisiteFileItem in ActualPrerequisiteItems)
                    {
                        if (IncludeFiles)
                        {
                            GraphNode PrerequisiteFileGraphNode;
                            if (FileToGraphNodeMap.TryGetValue(PrerequisiteFileItem, out PrerequisiteFileGraphNode))
                            {
                                // Connect a file our action is dependent on, to our action itself
                                var GraphEdge = new GraphEdge()
                                {
                                    Id = GraphEdges.Count,
                                    Source = PrerequisiteFileGraphNode,
                                    Target = ActionGraphNode,
                                };

                                GraphEdges.Add(GraphEdge);
                            }
                            else
                            {
                                // Not a file we were tracking
                                // Console.WriteLine( "Unknown file: " + PrerequisiteFileItem.AbsolutePath );
                            }
                        }
                        else if (PrerequisiteFileItem.ProducingAction != null)
                        {
                            // Not showing files, so connect the actions together
                            var ProducingActionIndex = FilteredActions.IndexOf(PrerequisiteFileItem.ProducingAction);
                            if (ProducingActionIndex != -1)
                            {
                                var SourceGraphNode = GraphNodes[ProducingActionIndex];

                                var GraphEdge = new GraphEdge()
                                {
                                    Id = GraphEdges.Count,
                                    Source = SourceGraphNode,
                                    Target = ActionGraphNode,
                                };

                                GraphEdges.Add(GraphEdge);
                            }
                            else
                            {
                                // Our producer action was filtered out
                            }
                        }
                    }

                    foreach (var ProducedFileItem in Action.ProducedItems)
                    {
                        if (IncludeFiles)
                        {
                            if (!OnlyIncludeCPlusPlusFiles || IsCPPFile(ProducedFileItem))
                            {
                                var ProducedFileGraphNode = FileToGraphNodeMap[ProducedFileItem];

                                var GraphEdge = new GraphEdge()
                                {
                                    Id = GraphEdges.Count,
                                    Source = ActionGraphNode,
                                    Target = ProducedFileGraphNode,
                                };

                                GraphEdges.Add(GraphEdge);
                            }
                        }
                    }
                }
            }

            if (IncludeFiles && ExpandCPPHeaderDependencies)
            {
                // Fill in overridden prerequisites
                foreach (var FileAndPrerequisites in OverriddenPrerequisites)
                {
                    var FileItem = FileAndPrerequisites.Key;
                    var FilePrerequisites = FileAndPrerequisites.Value;

                    var FileGraphNode = FileToGraphNodeMap[FileItem];
                    foreach (var PrerequisiteFileItem in FilePrerequisites)
                    {
                        GraphNode PrerequisiteFileGraphNode;
                        if (FileToGraphNodeMap.TryGetValue(PrerequisiteFileItem, out PrerequisiteFileGraphNode))
                        {
                            var GraphEdge = new GraphEdge()
                            {
                                Id = GraphEdges.Count,
                                Source = PrerequisiteFileGraphNode,
                                Target = FileGraphNode,
                            };

                            GraphEdges.Add(GraphEdge);
                        }
                        else
                        {
                            // Some other header that we don't track directly
                            //Console.WriteLine( "File not known: " + PrerequisiteFileItem.AbsolutePath );
                        }
                    }
                }
            }

            GraphVisualization.WriteGraphFile(Filename, Description, GraphNodes, GraphEdges);

            if (BuildConfiguration.bPrintPerformanceInfo)
            {
                var TimerDuration = DateTime.UtcNow - TimerStartTime;
                Log.TraceInformation("Generating and saving ActionGraph took " + TimerDuration.TotalSeconds + "s");
            }
        }
Exemplo n.º 41
0
 /// <summary>
 /// Add an edge to the graph.
 /// </summary>
 /// <param name="edge">Edge to add.</param>
 public void Add(GraphEdge edge)
 {
     this.edges.Add(edge);
 }
Exemplo n.º 42
0
 public static void Create(GraphComponent component, GraphEdge eNew, double strength)
     {
     if (strength != 0)
         {
         foreach (GraphEdge eExist in component.Edges)
             {
             if (eExist != eNew && !eExist.IncidentTo(eNew))
                 {
                 new IntersectionForce(component, eExist.A, strength, eExist, eNew, eNew.A);
                 new IntersectionForce(component, eNew.A,   strength, eExist, eNew, eExist.A);
                 //
                 new IntersectionForce(component, eExist.B, strength, eExist, eNew, eNew.B);
                 new IntersectionForce(component, eNew.B,   strength, eExist, eNew, eExist.B);
                 }
             }
         }
     }
Exemplo n.º 43
0
    private Vector3 GetHallwayPosition(GraphEdge edge) {
        IntVector2 cellCoord1 = MazeGrid.GetNodeCoords(edge.node1);
        IntVector2 cellCoord2 = MazeGrid.GetNodeCoords(edge.node2);

        Vector3 cellPosition1 = GetCellLocalPosition(cellCoord1.x, cellCoord1.z);
        Vector3 cellPosition2 = GetCellLocalPosition(cellCoord2.x, cellCoord2.z);
        Vector3 hallwayPosition = (cellPosition1 + cellPosition2) / 2.0f;
        hallwayPosition.y += 0.3f;

        return hallwayPosition;
    }
Exemplo n.º 44
0
    void WireHydrogenBond(GraphComponent component, Domain d, GraphVertex from, GraphVertex to, GraphVertex fromAux, GraphVertex toAux)
        {
        if (!WiredHydrogenBondsOf(from).Contains(to))
            {
            Debug.Assert(!WiredHydrogenBondsOf(to).Contains(from));
            WiredHydrogenBondsOf(from).Add(to);
            WiredHydrogenBondsOf(to).Add(from);

            double length = this.HydrogenBondLength(d, d.Connection);
            GraphEdge edge = new GraphEdge(component, from, to, length, Constants.StyleLineHydrogenBond);
            // edge.Visualization.Shaft = VisualGraphEdge.SHAFT.Full;   // we don't show the end line of domains as we now shade the double stranded region entirely

            SpringForce.CreateSymmetricalSpringForces(component, edge.A, edge.B, Constants.SpringConstantHydrogenBond, length);
            IntersectionForce.Create(component, edge, Constants.IntersectionForceStrength);

            new RightAngleForce(component, fromAux, from, to,   Constants.RightAngleStrength);
            new RightAngleForce(component, toAux,   to,   from, Constants.RightAngleStrength); 
            }
        }
    public List<GraphEdge> AStar(Vector3 start, Vector3 end)
    {
        List<float> gCosts = new List<float>();
        List<float> fCosts = new List<float>();

        List<GraphEdge> spt = new List<GraphEdge>(); // shortest path tree
        List<GraphEdge> searchFrontier = new List<GraphEdge>();

        for (int i = 0; i < Nodes.Count; ++i)
        {
            gCosts.Add(9999);
            fCosts.Add(9999);
            searchFrontier.Add(new GraphEdge(-1, -1));
        }

        BinaryHeap pq = new BinaryHeap();

        int index = 0;
        while (pq.Count() == 0 && index < Nodes.Count)
        {
            // check if we've found the node we want to start at
        #if USE_XZ
            if (Nodes[index].GetPosition().x == start.x && Nodes[index].GetPosition().z == start.z)
        #else // USE_ZY
            if (Nodes[index].GetPosition().x == start.x && Nodes[index].GetPosition().y == start.y)
        #endif //USE_XZ
            {
                pq.Add(0, index); // add it to our pq
                gCosts[index] = 0; // set its g cost
                fCosts[index] = 0; // set its f cost
                searchFrontier[index] = new GraphEdge(index, index); // add it to frontier
            }
            ++index;
        }

        Vector2 endPosV2;
        #if USE_XZ
        endPosV2 = new Vector2(end.x, end.z);
        #else //USE_XY
        endPosV2 = new Vector2(end.x, end.y);
        #endif
        while (pq.Count() > 0)
        {
            int closestNode = pq.Values(0);
            pq.RemoveAt(0);

            if (!spt.Contains(searchFrontier[closestNode]))
                spt.Add(searchFrontier[closestNode]); // if I use insert here, then later I can index it instead of searching for it

            Vector2 curPositionV2 = new Vector2(Nodes[closestNode].GetPosition().x,
        #if USE_XZ
            Nodes[closestNode].GetPosition().z);
        #else
            Nodes[closestNode].GetPosition().y);
        #endif
            if (curPositionV2 == endPosV2)
            {
                return spt;
            }

            GraphNode curNode = Nodes[closestNode];

            for (int i = 0; i < curNode.mEdges.GetSize(); ++i)
            {
                // index of the node that this edge is pointing to
                int edgeToIndex = curNode.mEdges.Loc(i).GetToIndex();

                float g = gCosts[curNode.GetIndex()] + (curNode.GetPosition() - Nodes[edgeToIndex].GetPosition()).sqrMagnitude;
                float h = (end - Nodes[edgeToIndex].GetPosition()).sqrMagnitude;
                float f = g + h;

                // this is where I would index for the edge
                //if (searchFrontier[edgeToIndex].GetToIndex() == -1 &&
                 //   searchFrontier[edgeToIndex].GetFromIndex() == -1)
                bool onFrontier = false;
                for (int j = 0; j < searchFrontier.Count; +++j)
                {
                    if (searchFrontier[j].GetToIndex() == edgeToIndex)
                    {
                        onFrontier = true;
                        break;
                    }
                }

                if (!onFrontier)
                {
                    searchFrontier[edgeToIndex] = curNode.mEdges.Loc(i);

                    gCosts[edgeToIndex] = g;
                    fCosts[edgeToIndex] = f;

                    if (pq.ContainsValue(edgeToIndex))
                    {
                        int pqIndex = pq.IndexOfValue(edgeToIndex);

                        float oldFCost = pq.Keys(pqIndex);

                        if (f < oldFCost) // if path is shorter
                        {
                            pq.RemoveAt(pqIndex);
                            pq.Add(f, edgeToIndex);
                        }
                    }
                    else
                    {
                        pq.Add(f, edgeToIndex);
                    }
                }
                else
                {
                    int indexOfEdgeToIndex = pq.IndexOfValue(edgeToIndex);

                    if (indexOfEdgeToIndex >= 0 && f < pq.Keys(indexOfEdgeToIndex))
                    {
                        pq.RemoveAt(indexOfEdgeToIndex);
                        pq.Add(f, edgeToIndex);
                    }
                }
            }

        }

        //Debug.LogWarning("Path to destination not found");
        spt = new List<GraphEdge>(); // clear the list to represent no path found
        return spt;
    }
Exemplo n.º 46
0
    public void SaveGraphVisualization(List<string> Nodes)
    {
        var TimerStartTime = DateTime.UtcNow;

        var GraphNodes = new List<GraphNode>();

        var NodeToGraphNodeMap = new Dictionary<string, GraphNode>();

        for (var NodeIndex = 0; NodeIndex < Nodes.Count; ++NodeIndex)
        {
            var Node = Nodes[NodeIndex];

            var GraphNode = new GraphNode()
            {
                Id = GraphNodes.Count,
                Label = Node
            };
            GraphNodes.Add(GraphNode);
            NodeToGraphNodeMap.Add(Node, GraphNode);
        }

        // Connect everything together
        var GraphEdges = new List<GraphEdge>();

        for (var NodeIndex = 0; NodeIndex < Nodes.Count; ++NodeIndex)
        {
            var Node = Nodes[NodeIndex];
            GraphNode NodeGraphNode = NodeToGraphNodeMap[Node];

            foreach (var Dep in GUBPNodes[Node].FullNamesOfDependencies)
            {
                GraphNode PrerequisiteFileGraphNode;
                if (NodeToGraphNodeMap.TryGetValue(Dep, out PrerequisiteFileGraphNode))
                {
                    // Connect a file our action is dependent on, to our action itself
                    var NewGraphEdge = new GraphEdge()
                    {
                        Id = GraphEdges.Count,
                        Source = PrerequisiteFileGraphNode,
                        Target = NodeGraphNode,
                        Color = new GraphColor() { R = 0.0f, G = 0.0f, B = 0.0f, A = 0.75f }
                    };

                    GraphEdges.Add(NewGraphEdge);
                }

            }
            foreach (var Dep in GUBPNodes[Node].FullNamesOfPseudosependencies)
            {
                GraphNode PrerequisiteFileGraphNode;
                if (NodeToGraphNodeMap.TryGetValue(Dep, out PrerequisiteFileGraphNode))
                {
                    // Connect a file our action is dependent on, to our action itself
                    var NewGraphEdge = new GraphEdge()
                    {
                        Id = GraphEdges.Count,
                        Source = PrerequisiteFileGraphNode,
                        Target = NodeGraphNode,
                        Color = new GraphColor() { R = 0.0f, G = 0.0f, B = 0.0f, A = 0.25f }
                    };

                    GraphEdges.Add(NewGraphEdge);
                }

            }
        }

        string Filename = CommandUtils.CombinePaths(CommandUtils.CmdEnv.LogFolder, "GubpGraph.gexf");
        Log("Writing graph to {0}", Filename);
        GraphVisualization.WriteGraphFile(Filename, "GUBP Nodes", GraphNodes, GraphEdges);
        Log("Wrote graph to {0}", Filename);
    }
Exemplo n.º 47
0
 public IntersectionForce(GraphComponent component, IPhysicalObject target, double strength, GraphEdge a, GraphEdge b, IPhysicalObject reference) : base(component,target,strength)
     {
     this.a = a;
     this.b = b;
     this.reference = reference;
     }
Exemplo n.º 48
0
    public void UpdateNodeEdgesInfo(int index,float value)
    {
        Assert.IsTrue (index >= 0 && index < mNavGraph.NextFreeNodeIndex);
        //Update Nodes weight first
        mNavGraph.Nodes [index].Weight += value;

        //Update edge info that starts from Node[index]
        GraphEdge e;
        for (int i = 0; i < mNavGraph.mEdgesList[index].Count; i++) {
            e =  mNavGraph.mEdgesList[index][i];
            e.Cost += value;
        }
        //Update edge info that ends with Node[index]
        int fromindex = 0;
        GraphEdge edge = new GraphEdge ();
        for (int i = -1; i <= 1; i++) {
            for(int j = -1; j <= 1; j++)
            {
                fromindex = index + j + i * mColumn;
                if(IsValidIndex(fromindex) && fromindex != index)
                {
                    edge = mNavGraph.mEdgesList[fromindex].Find( x => x.To == index);
                    if(edge != null)
                    {
                        edge.Cost += value;
                    }
                }
            }
        }
    }
Exemplo n.º 49
0
 public void ToString_success()
 {
     var edge = new GraphEdge<int>(new GraphNode<int>(1), new GraphNode<int>(2));
     var toString = edge.ToString();
     Assert.AreEqual("{1} -> {2}", toString);
 }
Exemplo n.º 50
0
        /// <summary>
        /// Adds an incoming edge.
        /// </summary>
        /// <param name="edge">The edge.</param>
        protected internal void AddIncomingEdge(GraphEdge edge)
        {
            Contract.Requires(edge != null);

            this.incomingEdges.Add(edge);
            this.AddConnectedNode(edge.From);
            this.AddConnectedEdge(edge);
        }
 public void AddEdge(GraphEdge edge)
 {
     mEdges.Add(edge);
     //fastEdges.Add(edge);
 }
 public DynArray(GraphEdge type)
 {
     mArray = new GraphEdge[8];
     mCapacity = 8;
     mSize = 0;
 }
Exemplo n.º 53
0
 public GraphEdge(GraphEdge e)
 {
     mFrom = e.From;
     mTo = e.To;
     mCost = e.Cost;
 }
Exemplo n.º 54
0
    /// <summary>
    /// Exports the build graph as a GEXF file, for visualization in an external tool (eg. Gephi).
    /// </summary>
    /// <param name="Nodes">The nodes in the graph</param>
    static void SaveGraphVisualization(IEnumerable<BuildNode> Nodes)
    {
        // Create a graph node for each GUBP node in the graph
        List<GraphNode> GraphNodes = new List<GraphNode>();
        Dictionary<BuildNode, GraphNode> NodeToGraphNodeMap = new Dictionary<BuildNode, GraphNode>();
        foreach(BuildNode Node in Nodes)
        {
            GraphNode GraphNode = new GraphNode();
            GraphNode.Id = NodeToGraphNodeMap.Count;
            GraphNode.Label = Node.Name;

            NodeToGraphNodeMap.Add(Node, GraphNode);
            GraphNodes.Add(GraphNode);
        }

        // Connect everything together
        List<GraphEdge> GraphEdges = new List<GraphEdge>();
        foreach(KeyValuePair<BuildNode, GraphNode> NodeToGraphNodePair in NodeToGraphNodeMap)
        {
            foreach (BuildNode Dependency in NodeToGraphNodePair.Key.Dependencies)
            {
                GraphNode PrerequisiteFileGraphNode;
                if (NodeToGraphNodeMap.TryGetValue(Dependency, out PrerequisiteFileGraphNode))
                {
                    // Connect a file our action is dependent on, to our action itself
                    GraphEdge NewGraphEdge = new GraphEdge();

                    NewGraphEdge.Id = GraphEdges.Count;
                    NewGraphEdge.Source = PrerequisiteFileGraphNode;
                    NewGraphEdge.Target = NodeToGraphNodePair.Value;
                    NewGraphEdge.Color = new GraphColor() { R = 0.0f, G = 0.0f, B = 0.0f, A = 0.75f };

                    GraphEdges.Add(NewGraphEdge);
                }

            }
            foreach (BuildNode Dependency in NodeToGraphNodePair.Key.PseudoDependencies)
            {
                GraphNode PrerequisiteFileGraphNode;
                if (NodeToGraphNodeMap.TryGetValue(Dependency, out PrerequisiteFileGraphNode))
                {
                    // Connect a file our action is dependent on, to our action itself
                    GraphEdge NewGraphEdge = new GraphEdge();

                    NewGraphEdge.Id = GraphEdges.Count;
                    NewGraphEdge.Source = PrerequisiteFileGraphNode;
                    NewGraphEdge.Target = NodeToGraphNodePair.Value;
                    NewGraphEdge.Color = new GraphColor() { R = 0.0f, G = 0.0f, B = 0.0f, A = 0.25f };

                    GraphEdges.Add(NewGraphEdge);
                }

            }
        }

        // Export the graph definition
        string Filename = CommandUtils.CombinePaths(CommandUtils.CmdEnv.LogFolder, "GubpGraph.gexf");
        Log("Writing graph to {0}", Filename);
        GraphVisualization.WriteGraphFile(Filename, "GUBP Nodes", NodeToGraphNodeMap.Values.ToList(), GraphEdges);
        Log("Wrote graph to {0}", Filename);
    }
        protected override int ExecuteTest()
        {
            var edges = new GraphEdge[SearchSpaceSize];
            var removedNodes = 0;
            for (var i = 0; i < SearchSpaceSize; i++)
            {
                // This test only checks non-terminals.
                if (NodeStates.IsTarget(i)) continue;

                // Nodes with less than 3 neighbors are covered by DegreeTest
                // Nodes are limited to 7 neighbors because this test is exponential in the neighbor count.
                var neighbors = EdgeSet.NeighborsOf(i);
                if (neighbors.Count < 3 || neighbors.Count > 7) continue;
                
                // Cache the edges. They might be removed from EdgeSet when we need them.
                foreach (var neighbor in neighbors)
                {
                    edges[neighbor] = EdgeSet[i, neighbor];
                }

                // Check whether each subset satisfies the condition.
                var canBeRemoved = true;
                foreach (var subset in GetAllSubsets(neighbors))
                {
                    // Only subsets of at least size 3 are relevant.
                    if (subset.Count < 3) continue;

                    // Sum up the weights of all edges between the nodes of the subsets and i.
                    var edgeSum = subset.Sum(j => edges[j].Weight);
                    // Build the MST of the fully connected graph of the nodes in the subset with the bottleneck
                    // Steiner distances as edge weights.
                    var mst = new MinimalSpanningTree(subset, SMatrix);
                    mst.Span(subset[0]);
                    // Sum up the edge weights of the MST.
                    var mstSum = mst.SpanningEdges.Sum(e => e.Priority);
                    // The condition is only satisfied if edgeSum >= mstSum.
                    if (edgeSum < mstSum)
                    {
                        canBeRemoved = false;
                        break;
                    }
                }

                if (!canBeRemoved) continue;

                // Remove i and replace its edges.
                foreach (var neighbor in neighbors)
                {
                    // Remove the old edges between i and its neighbors.
                    var edge = edges[neighbor];
                    EdgeSet.Remove(edge);
                    // For each pair of neighbors create a new edge.
                    foreach (var neighbor2 in neighbors)
                    {
                        if (neighbor >= neighbor2) continue;
                        // The weight of the new edge between the two neighbors is the sum of their edge weights to i.
                        var edge2 = edges[neighbor2];
                        var newEdgeWeight = edge.Weight + edge2.Weight;
                        // Only add this edge if it wouldn't be removed by the Paths with many terminals test.
                        if (newEdgeWeight <= SMatrix[neighbor, neighbor2])
                        {
                            EdgeSet.Add(neighbor, neighbor2, newEdgeWeight);
                        }
                    }
                }

                NodeStates.MarkNodeAsRemoved(i);
                removedNodes++;
            }
            return removedNodes;
        }
Exemplo n.º 56
0
 public void ValueCopy(GraphEdge edge)
 {
     mFrom = edge.From;
     mTo = edge.To;
     mCost = edge.Cost;
 }
Exemplo n.º 57
0
    //The A* search algorithm with strickdistance with wall consideration
    private void Search(float strickdistance, bool isignorewall)
    {
        float currentnodetotargetdistance = Mathf.Infinity;

        mPQ.Clear();

        mPQ.Push(mFCosts[mISource]);

        //mSearchFrontier [mISource] = new GraphEdge (mISource, mISource, 0.0f);
        mSearchFrontier[mISource].From = mISource;
        mSearchFrontier[mISource].To = mISource;
        mSearchFrontier[mISource].Cost = 0.0f;
        GraphEdge edge = new GraphEdge();
        int nextclosestnode = -1;

        while (!mPQ.Empty())
        {
            //Get lowest cost node from the queue
            nextclosestnode = mPQ.Pop().Key;

            mAStarPathInfo.NodesSearched++;

            //move this node from the frontier to the spanning tree
            if (mSearchFrontier[nextclosestnode] != null && mSearchFrontier[nextclosestnode].IsValidEdge())
            {
                mShortestPathTree[nextclosestnode] = mSearchFrontier[nextclosestnode];
            }

            currentnodetotargetdistance = Heuristic_Euclid.Calculate(mGraph, mITarget, nextclosestnode);

            if (nextclosestnode == mITarget || (currentnodetotargetdistance <= strickdistance && !mGraph.Nodes[nextclosestnode].IsWall))
            {
                mITarget = nextclosestnode;
                return;
            }

            //Now to test all the edges attached to this node
            List<GraphEdge> edgelist = mGraph.EdgesList[nextclosestnode];
            for (int i = 0; i < edgelist.Count; i++)
            {
                //Avoid pass refrence
                edge.Reset();
                edge.From = edgelist[i].From;
                edge.To = edgelist[i].To;
                edge.Cost = edgelist[i].Cost;
                //calculate the heuristic cost from this node to the target (H)
                float hcost = Heuristic_Euclid.Calculate(mGraph, mITarget, edge.To) * mHCostPercentage;

                //calculate the 'real' cost to this node from the source (G)
                float gcost = 0.0f;
                if (isignorewall)
                {
                    gcost = mGCosts[nextclosestnode] + edge.Cost;

                    if (mGraph.Nodes[edge.From].IsWall)
                    {
                        gcost -= mGraph.Nodes[edge.From].Weight;
                    }
                    if (mGraph.Nodes[edge.To].IsWall)
                    {
                        gcost -= mGraph.Nodes[edge.To].Weight;
                    }
                }
                else
                {
                    gcost = mGCosts[nextclosestnode] + edge.Cost;
                    if (mGraph.Nodes[edge.From].IsJumpable)
                    {
                        gcost -= mGraph.Nodes[edge.From].Weight;
                    }
                    if (mGraph.Nodes[edge.To].IsJumpable)
                    {
                        gcost -= mGraph.Nodes[edge.To].Weight;
                    }
                }

                //if the node has not been added to the frontier, add it and update the G and F costs
                if (mSearchFrontier[edge.To] != null && !mSearchFrontier[edge.To].IsValidEdge())
                {
                    mFCosts[edge.To].Value = gcost + hcost;
                    mGCosts[edge.To] = gcost;

                    mPQ.Push(mFCosts[edge.To]);

                    mSearchFrontier[edge.To].ValueCopy(edge);

                    mAStarPathInfo.EdgesSearched++;

                    if (mBDrawExplorePath)
                    {
                        Debug.DrawLine(mGraph.Nodes[edge.From].Position, mGraph.Nodes[edge.To].Position, Color.yellow, mExplorePathRemainTime);
                    }
                }

                //if this node is already on the frontier but the cost to get here
                //is cheaper than has been found previously, update the node
                //cost and frontier accordingly
                else if (gcost < mGCosts[edge.To])
                {
                    mFCosts[edge.To].Value = gcost + hcost;
                    mGCosts[edge.To] = gcost;

                    //Due to some node's f cost has been changed
                    //we should reoder the priority queue to make sure we pop up the lowest fcost node first
                    //compare the fcost will make sure we search the path in the right direction
                    //h cost is the key to search in the right direction
                    mPQ.ChangePriority(edge.To);

                    mSearchFrontier[edge.To].ValueCopy(edge);

                    mAStarPathInfo.EdgesSearched++;
                }
            }
        }
    }
Exemplo n.º 58
0
    //----------------------------------------------------------------------------------------
    // Operations
    //----------------------------------------------------------------------------------------

    public bool IncidentTo(GraphEdge him)
        {
        return this.IncidentTo(him.A) || this.IncidentTo(him.B);
        }
Exemplo n.º 59
0
 private void DestroyHallway(GraphEdge edge) {
     Destroy(hallways[edge].gameObject);
 }