Ejemplo n.º 1
0
        public static Adjacency?GetInverse(Adjacency adj)
        {
            switch (adj)
            {
            case Adjacency.NorthWest:
                return(Adjacency.SouthEast);

            case Adjacency.North:
                return(Adjacency.South);

            case Adjacency.NorthEast:
                return(Adjacency.SouthWest);

            case Adjacency.East:
                return(Adjacency.West);

            case Adjacency.SouthEast:
                return(Adjacency.NorthWest);

            case Adjacency.South:
                return(Adjacency.North);

            case Adjacency.SouthWest:
                return(Adjacency.NorthEast);

            case Adjacency.West:
                return(Adjacency.East);
            }
            return(null);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Move this node from its current position to a position adjacent to a specified node in the same tree.
        /// </summary>
        /// <param name="targetId">Target entity Id</param>
        /// <param name="adjacency">Specifies which side to place the node</param>
        public virtual void MoveToAdjacentPosition(TId targetId, Adjacency adjacency)
        {
            var targetNode = Root[targetId];

            if (targetNode.Equals(this))
            {
                // already here!
                return;
            }

            if (targetNode.IsRoot)
            {
                throw new InvalidOperationException("Cannot move to root level");
            }

            if (IsAncestorOf(targetNode))
            {
                throw new InvalidOperationException("Cannot move to a descendant");
            }

            if (IsSiblingOf(targetNode))
            {
                MoveToSiblingAdjacentPosition(targetNode, adjacency);
            }
            else
            {
                MoveToNonSiblingAdjacentPosition(targetNode, adjacency);
            }
        }
        /// <summary>
        /// Read the shortest path file of the specific brite file.
        /// </summary>
        /// <param name="fileName">Shortest path file name. EX:n1kd4_14.brite.ShortestPath</param>
        private void ReadShortestPathFile(string fileName)
        {
            DataUtility.Log("Reading shortest path file...");

            AdjacentMatrix = null;
            GC.Collect();
            // Create the space of adjacent matrix
            AdjacentMatrix = new Adjacency[Nodes.Count, Nodes.Count];

            using (BufferedStream bs = new BufferedStream(File.OpenRead(fileName)))
            {
                using (StreamReader reader = new StreamReader(bs))
                {
                    int i = 0;

                    while (!reader.EndOfStream)
                    {
                        string[] data = reader.ReadLine().Split(' ');

                        for (int j = 0; j < data.Length; j++)
                        {
                            if (!data[j].Equals("null"))
                            {
                                AdjacentMatrix[i, j] = new Adjacency(data[j]);
                            }
                        }

                        i++;
                    }
                }
            }

            DataUtility.Log("Done.\n", false);
        }
        public void GeometricMedianReturnsFermatPointOnAcuteTriangleTest()
        {
            // Create sample points that makes a Acute triangle
            var samplePoints = new List <Point>
            {
                Point.ByCoordinates(5, 5),
                Point.ByCoordinates(9.5, 4.2),
                Point.ByCoordinates(8, 3)
            };

            // Get the geometric median of the Acute triangles sample points
            // Also known as the Fermat Point
            Point fermatPoint = Adjacency.GeometricMedianOfPoints(samplePoints);

            // Create vectors from the fermat point to two arbitrary points in the sample points list.
            var vectors = new List <Vector>
            {
                Vector.ByTwoPoints(fermatPoint, samplePoints[0]),
                Vector.ByTwoPoints(fermatPoint, samplePoints[1]),
            };

            // Getting the angle between the two vectors just created.
            // This angle should always be 120 degrees in a Acute triangle.
            var testAngle = vectors[0].AngleWithVector(vectors[1]);

            // Checking if the angle is equal to 120 degrees.
            Assert.AreEqual(120.0, Math.Round(testAngle, 1));

            // Dispose unused geometry
            samplePoints.ForEach(p => p.Dispose());
            fermatPoint.Dispose();
            vectors.ForEach(p => p.Dispose());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// sets the adjacencies of the specified landblocks.  nulls are allowed in the use case of deleting
        /// or unloading a landblock.  Landblock2 is {adjacency} of Landblock1.  if autoLoad is true, and
        /// landblock2 is null, it will be auto loaded.
        ///
        /// NOTE: ASSUMES A LOCK ON landblockMutex
        /// </summary>
        /// <param name="landblock1">a landblock</param>
        /// <param name="landblock2">a landblock</param>
        /// <param name="adjacency">the adjacency of landblock2 relative to landblock1</param>
        /// <param name="autoLoad">Will load landBlock2 if it's not loaded already</param>
        private static void SetAdjacency(LandblockId landblock1, LandblockId landblock2, Adjacency adjacency, bool autoLoad = false)
        {
            // suppress adjacency logic for indoor areas
            if (landblock1.MapScope != Entity.Enum.MapScope.Outdoors || landblock2.MapScope != Entity.Enum.MapScope.Outdoors)
            {
                return;
            }

            Landblock lb1 = landblocks[landblock1.LandblockX, landblock1.LandblockY];
            Landblock lb2 = landblocks[landblock2.LandblockX, landblock2.LandblockY];

            if (autoLoad && lb2 == null)
            {
                lb2 = GetLandblock(landblock2, false);
            }

            lb1.SetAdjacency(adjacency, lb2);

            if (lb2 != null)
            {
                int       inverse          = (((int)adjacency) + 4) % 8; // go halfway around the horn (+4) and mod 8 to wrap around
                Adjacency inverseAdjacency = (Adjacency)Enum.ToObject(typeof(Adjacency), inverse);
                lb2.SetAdjacency(inverseAdjacency, lb1);
            }
        }
Ejemplo n.º 6
0
 void Start()
 {
     vSize = 2 * gameObject.GetComponent <Camera>().orthographicSize;
     hSize = vSize * gameObject.GetComponent <Camera>().aspect;
     tile  = Adjacency.TileOf(gameObject);
     transform.position = new Vector3(tile.transform.position.x, tile.transform.position.y, transform.position.z);
 }
        /// <summary>
        /// Adds a polygon that will be drawn on the next Draw() call.
        /// A polygon is a filled shape.
        /// </summary>
        /// <param name="pl">The polyline that defines the polygon's border. Must be closed</param>
        /// <param name="color">The filling color</param>
        public void AddCompletePolygon(Polyline pl, Color color)
        {
            List<Adjacency> pointList = new List<Adjacency>();
            List<Line> lineList = pl.lineList;

            if (lineList.Count > 2)
            {
                Adjacency prevAdjacency = new Adjacency();
                Adjacency newAdjacency;
                prevAdjacency.point = lineList[0].p1;
                //lineList.RemoveAt(0);
                foreach (Line l in lineList.GetRange(1, lineList.Count-1))
                {
                    newAdjacency = new Adjacency();
                    prevAdjacency.adj2 = newAdjacency;
                    pointList.Add(prevAdjacency);
                    newAdjacency.adj1 = prevAdjacency;
                    newAdjacency.point = l.p1;
                    prevAdjacency = newAdjacency;
                }
                // linking last point to first point
                prevAdjacency.adj2 = pointList[0];
                pointList.Add(prevAdjacency);
                pointList[0].adj1 = prevAdjacency;

                pointList.Sort(Adjacency.CompareX);

                AddPolygon(pointList, color);
            }
        }
Ejemplo n.º 8
0
 private List <GameObject> TilesReachableFrom(GameObject tile, int movement)
 {
     if (tile.layer != 8)
     {
         return(null);
     }
     else
     {
         List <GameObject> output = new List <GameObject>();
         output.Add(tile);
         if (Adjacency.TileUp(tile) != null && movement >= TileCost(Adjacency.TileUp(tile)))
         {
             output.AddRange(TilesReachableFrom(Adjacency.TileUp(tile), movement - TileCost(Adjacency.TileUp(tile))));
         }
         if (Adjacency.TileDown(tile) != null && movement >= TileCost(Adjacency.TileDown(tile)))
         {
             output.AddRange(TilesReachableFrom(Adjacency.TileDown(tile), movement - TileCost(Adjacency.TileDown(tile))));
         }
         if (Adjacency.TileLeft(tile) != null && movement >= TileCost(Adjacency.TileLeft(tile)))
         {
             output.AddRange(TilesReachableFrom(Adjacency.TileLeft(tile), movement - TileCost(Adjacency.TileLeft(tile))));
         }
         if (Adjacency.TileRight(tile) != null && movement >= TileCost(Adjacency.TileRight(tile)))
         {
             output.AddRange(TilesReachableFrom(Adjacency.TileRight(tile), movement - TileCost(Adjacency.TileRight(tile))));
         }
         return(output);
     }
 }
        public void GeometricMedianReturnsThePointInsideTriangleFormedByRemainingPointsOnConcaveQuadrilateralTest()
        {
            // Create sample points that makes a Concave Quadrilateral
            var samplePoints = new List <Point>
            {
                //Point inside triangle formed by remaining 3 points
                Point.ByCoordinates(7, 8),
                //Remaining point
                Point.ByCoordinates(9.5, 7.2),
                Point.ByCoordinates(8, 4.8),
                Point.ByCoordinates(6, 9)
            };

            // Get the geometric median of the Concave Quadrilateral sample points
            // which is the point inside the triangle formed by remaining 3 points
            Point geometricMedianPoint = Adjacency.GeometricMedianOfPoints(samplePoints);

            // Check if both X and Y of the geometric median is the same as X and Y of the
            // point inside the triangle formed by the remaining points (samplePoints[0]).
            Assert.AreEqual(samplePoints[0].X, geometricMedianPoint.X);
            Assert.AreEqual(samplePoints[0].Y, geometricMedianPoint.Y);

            // Dispose unused geometry.
            samplePoints.ForEach(p => p.Dispose());
            geometricMedianPoint.Dispose();
        }
Ejemplo n.º 10
0
    private static void test12()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    TEST12 tests TRIANGULATION_ORDER6_ADJ_SET
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    05 January 2007
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        int hole_num     = 0;
        int node_num     = 0;
        int triangle_num = 0;

        Console.WriteLine("");
        Console.WriteLine("TEST12");
        Console.WriteLine("  TRIANGULATION_ORDER6_ADJ_SET sets the (lower)");
        Console.WriteLine("  adjacencies defined by a triangulation.");

        Order6_Example.triangulation_order6_example2_size(ref node_num, ref triangle_num, ref hole_num);

        double[] node_xy           = new double[2 * node_num];
        int[]    triangle_node     = new int[6 * triangle_num];
        int[]    triangle_neighbor = new int[3 * triangle_num];

        Order6_Example.triangulation_order6_example2(node_num, triangle_num, ref node_xy,
                                                     ref triangle_node, ref triangle_neighbor);

        typeMethods.i4mat_transpose_print(6, triangle_num, triangle_node,
                                          "  TRIANGLE_NODE");

        int[] adj_row = new int[node_num + 1];

        int adj_num = Adjacency.triangulation_order6_adj_count(node_num, triangle_num, triangle_node,
                                                               ref triangle_neighbor, ref adj_row);

        int[] adj = new int [adj_num];

        adj = Adjacency.triangulation_order6_adj_set(node_num, triangle_num, triangle_node,
                                                     triangle_neighbor, adj_num, adj_row);

        AdjacencyMatrix.adj_print(node_num, adj_num, adj_row, adj, "  ADJ array:");

        int bandwidth = AdjacencyMatrix.adj_bandwidth(node_num, adj_num, adj_row, adj);

        Console.WriteLine("");
        Console.WriteLine("  ADJ bandwidth = " + bandwidth + "");
    }
Ejemplo n.º 11
0
        private static Adjacency GetAdjacency(int gridX, int gridY, TileType type)
        {
            Adjacency adj = new Adjacency();

            adj.N = (gridY > 0) && type == Map[gridX, gridY - 1].Type;
            adj.W = (gridX > 0) && type == Map[gridX - 1, gridY].Type;
            adj.E = (gridX < Map.GetUpperBound(0)) && type == Map[gridX + 1, gridY].Type;
            adj.S = (gridY < Map.GetUpperBound(1)) && type == Map[gridX, gridY + 1].Type;
            return(adj);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Returns an adjacent landblock ID for a landblock
        /// </summary>
        private static ulong?GetAdjacentID(ulong longLandblockId, Adjacency adjacency)
        {
            uint landblock = (uint)(longLandblockId & 0xFFFFFFFF);
            uint instance  = (uint)(longLandblockId >> 32);
            int  lbx       = (int)(landblock >> 24);
            int  lby       = (int)((landblock >> 16) & 0xFF);

            switch (adjacency)
            {
            case Adjacency.North:
                lby += 1;
                break;

            case Adjacency.South:
                lby -= 1;
                break;

            case Adjacency.West:
                lbx -= 1;
                break;

            case Adjacency.East:
                lbx += 1;
                break;

            case Adjacency.NorthWest:
                lby += 1;
                lbx -= 1;
                break;

            case Adjacency.NorthEast:
                lby += 1;
                lbx += 1;
                break;

            case Adjacency.SouthWest:
                lby -= 1;
                lbx -= 1;
                break;

            case Adjacency.SouthEast:
                lby -= 1;
                lbx += 1;
                break;
            }

            if (lbx < 0 || lbx > 254 || lby < 0 || lby > 254)
            {
                return(null);
            }

            landblock = (uint)(lbx << 24 | lby << 16 | 0xFFFF);
            return((((ulong)instance) << 32) | landblock);
        }
Ejemplo n.º 13
0
 public IEnumerable <IWeightedEdge <TV, TW> > GetEdgesOfVertex(IVertex <TV> vertex)
 {
     if (Adjacency.TryGetValue(vertex.Value, out HashSet <Edge <TV, TW> > edges))
     {
         return(edges);
     }
     else
     {
         throw new InvalidOperationException("The passed vertex is not a vertex of this graph.");
     }
 }
        private void MoveToNonSiblingAdjacentPosition(TNode targetNode, Adjacency adjacency)
        {
            OnNodeReparenting(targetNode);

            var targetIndex = targetNode.OrderIndex + (adjacency == Adjacency.Before ? 0 : 1);

            var newParent = targetNode.Parent;

            Detach();
            newParent.AttachChildOnMove(This, targetIndex);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Add new entity node as sibling adjacent to this node
        /// </summary>
        /// <param name="item">Entity to add</param>
        /// <param name="adjacency">Specifies which side to place the node</param>
        /// <returns></returns>
        public virtual TNode AddAtAdjacentPosition(TItem item, Adjacency adjacency)
        {
            if (IsRoot)
            {
                throw new InvalidOperationException("Cannot insert at root level");
            }

            var insertIndex = OrderIndex + (adjacency == Adjacency.Before ? 0 : 1);

            return(Parent.AddChild(item, insertIndex));
        }
        protected override void DoCommandAction()
        {
            Tile clb          = FPGA.FPGA.Instance.GetAllTiles().FirstOrDefault(t => IdentifierManager.Instance.IsMatch(t.Location, IdentifierManager.RegexTypes.CLB));
            Tile interconnect = FPGATypes.GetInterconnectTile(clb);

            List <string> lutInPorts = new List <string>();

            foreach (Port lutInPort in clb.SwitchMatrix.Ports.Where(p => Regex.IsMatch(p.Name, LUTInPortFilter)))
            {
                lutInPorts.Add(lutInPort.Name);
            }

            Adjacency adjacency = new Adjacency(lutInPorts, EndPortFilter, LUTOutPortFilter);

            // section 1
            foreach (Port endPort in interconnect.SwitchMatrix.Ports.Where(p => Regex.IsMatch(p.Name, EndPortFilter)).OrderBy(p => p.Name[p.Name.Length - 1]))
            {
                foreach (Port logicIn in interconnect.SwitchMatrix.GetDrivenPorts(endPort))
                {
                    // goto CLB
                    foreach (Location loc in Navigator.GetDestinations(interconnect, logicIn).Where(l => l.Tile.Location.Equals(clb.Location)))
                    {
                        foreach (Port lutInPort in clb.SwitchMatrix.GetDrivenPorts(loc.Pip).Where(l => Regex.IsMatch(l.Name, LUTInPortFilter)))
                        {
                            adjacency.AddConnection(endPort.Name, lutInPort.Name);
                        }
                    }
                }
            }

            // section 2
            foreach (Port lutOutPort in clb.SwitchMatrix.Ports.Where(p => Regex.IsMatch(p.Name, LUTOutPortFilter)))
            {
                foreach (Port logicOut in clb.SwitchMatrix.GetDrivenPorts(lutOutPort))
                {
                    // goto int
                    foreach (Location locInt in Navigator.GetDestinations(clb, logicOut).Where(l => l.Tile.Location.Equals(interconnect.Location)))
                    {
                        foreach (Port logicIn in interconnect.SwitchMatrix.GetDrivenPorts(locInt.Pip))
                        {
                            foreach (Location locClb in Navigator.GetDestinations(interconnect, logicIn).Where(l => l.Tile.Location.Equals(clb.Location)))
                            {
                                foreach (Port lutInPort in clb.SwitchMatrix.GetDrivenPorts(locClb.Pip).Where(l => Regex.IsMatch(l.Name, LUTInPortFilter)))
                                {
                                    adjacency.AddConnection(lutOutPort.Name, lutInPort.Name);
                                }
                            }
                        }
                    }
                }
            }
            OutputManager.WriteOutput(adjacency.ToString());
        }
Ejemplo n.º 17
0
 private void Update()
 {
     currentTile = Adjacency.TileOf(gameObject);
     if (HasActed())
     {
         GetComponent <SpriteRenderer>().material.color = Color.grey;
     }
     else
     {
         GetComponent <SpriteRenderer>().material.color = Color.white;
     }
 }
        public int GetShortestPathCount(int SourceNodeId, int DestinationNodeId)
        {
            Adjacency adjacency = AdjacentMatrix[NodeID2Index(SourceNodeId), NodeID2Index(DestinationNodeId)];

            if (adjacency == null)
            {
                return(0);
            }
            else
            {
                return(adjacency.PathCount);
            }
        }
Ejemplo n.º 19
0
        protected static void addDoubleConnection3D(int x1, int y1, int z1, int x2, int y2, int z2, Real d, Position3D_Connected[, ,] map)
        {
            IAdjacency a1 = new Adjacency(map[x1, y1, z1], d);

            map[x2, y2, z2].GetAdjacencyOut().Add(a1);

            IAdjacency a2 = new Adjacency(map[x2, y2, z2], d);

            map[x1, y1, z1].GetAdjacencyOut().Add(a2);

            map[x2, y2, z2].GetAdjacencyIn().Add(a1);
            map[x1, y1, z1].GetAdjacencyIn().Add(a2);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Returns an adjacent landblock ID for a landblock
        /// </summary>
        private static LandblockId?GetAdjacentID(LandblockId landblock, Adjacency adjacency)
        {
            int lbx = landblock.LandblockX;
            int lby = landblock.LandblockY;

            switch (adjacency)
            {
            case Adjacency.North:
                lby += 1;
                break;

            case Adjacency.South:
                lby -= 1;
                break;

            case Adjacency.West:
                lbx -= 1;
                break;

            case Adjacency.East:
                lbx += 1;
                break;

            case Adjacency.NorthWest:
                lby += 1;
                lbx -= 1;
                break;

            case Adjacency.NorthEast:
                lby += 1;
                lbx += 1;
                break;

            case Adjacency.SouthWest:
                lby -= 1;
                lbx -= 1;
                break;

            case Adjacency.SouthEast:
                lby -= 1;
                lbx += 1;
                break;
            }

            if (lbx < 0 || lbx > 254 || lby < 0 || lby > 254)
            {
                return(null);
            }

            return(new LandblockId((byte)lbx, (byte)lby));
        }
Ejemplo n.º 21
0
        private static void UpdateAdjacency(int gridX, int gridY)
        {
            if (!PointIsInMap(gridX, gridY))
            {
                return;
            }

            if (Map[gridX, gridY].Type == TileType.Grass)
            {
                Adjacency adj     = GetAdjacency(gridX, gridY, TileType.Grass);
                Adjacency dirtAdj = GetAdjacency(gridX, gridY, TileType.Dirt);
                adj.N |= dirtAdj.N;
                adj.W |= dirtAdj.W;
                adj.E |= dirtAdj.E;
                adj.S |= dirtAdj.S;
                Map[gridX, gridY].fgRect = Sprites.TileRects[TileType.Grass][adj];

                Map[gridX, gridY].drawBg = !(adj.N && adj.E && adj.W && adj.S);
                if (Map[gridX, gridY].drawBg)
                {
                    adj = GetAdjacency(gridX, gridY, TileType.Water);
                    if (adj.N || adj.E || adj.W || adj.S)
                    {
                        Map[gridX, gridY].bgRect = new Rectangle(51, 17, size, size); //water
                    }
                    else
                    {
                        Map[gridX, gridY].bgRect = new Rectangle(136, 170, size, size); //dirt
                    }
                }
            }
            else if (Map[gridX, gridY].Type == TileType.Dirt)
            {
                Adjacency adj = GetAdjacency(gridX, gridY, TileType.Dirt);
                Map[gridX, gridY].fgRect = Sprites.TileRects[TileType.Dirt][adj];

                Map[gridX, gridY].drawBg = !(adj.N && adj.E && adj.W && adj.S);
                if (Map[gridX, gridY].drawBg)
                {
                    adj = GetAdjacency(gridX, gridY, TileType.Water);
                    if (adj.N || adj.E || adj.W || adj.S)
                    {
                        Map[gridX, gridY].bgRect = new Rectangle(51, 17, size, size); //water
                    }
                    else
                    {
                        Map[gridX, gridY].bgRect = new Rectangle(136, 272, size, size); //grass
                    }
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Checks for the initial placement of a WaterFlow at a point on the map, and places it.
        /// </summary>
        /// <param name="gridX">The grid x.</param>
        /// <param name="gridY">The grid y.</param>
        private static void CheckWaterFlow(int gridX, int gridY)
        {
            if (Map[gridX, gridY].type != TileType.Dirt)
            {
                return;
            }

            Adjacency adj = GetAdjacency(gridX, gridY, TileType.Water);

            if (adj.N || adj.W || adj.E || adj.S)
            {
                new WaterFlow(gridX, gridY);
            }
        }
Ejemplo n.º 23
0
    private static void test08()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    TEST08 tests TRIANGULATION_ORDER3_ADJ_COUNT
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    04 January 2007
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        int hole_num     = 0;
        int node_num     = 0;
        int triangle_num = 0;

        Console.WriteLine("");
        Console.WriteLine("TEST08");
        Console.WriteLine("  TRIANGULATION_ORDER3_ADJ_COUNT counts the (lower)");
        Console.WriteLine("  adjacencies defined by a triangulation.");

        Order3_Example.triangulation_order3_example2_size(ref node_num, ref triangle_num, ref hole_num);

        double[] node_xy           = new double[2 * node_num];
        int[]    triangle_node     = new int[3 * triangle_num];
        int[]    triangle_neighbor = new int[3 * triangle_num];

        Order3_Example.triangulation_order3_example2(node_num, triangle_num, ref node_xy,
                                                     ref triangle_node, ref triangle_neighbor);

        typeMethods.i4mat_transpose_print(3, triangle_num, triangle_node,
                                          "  TRIANGLE_NODE");

        int[] adj_row = new int[node_num + 1];

        Adjacency.triangulation_order3_adj_count(node_num, triangle_num,
                                                 triangle_node, triangle_neighbor, adj_row);

        typeMethods.i4vec_print(node_num + 1, adj_row, "  ADJ_ROW");
    }
Ejemplo n.º 24
0
        public HashSet <VariableDescriptor> DependsOn(VariableDescriptor v)
        {
            if (DependsOnSCCsDAG == null)
            {
                if (CommandLineOptions.Clo.Trace)
                {
                    Console.WriteLine("Variable dependence: computing SCCs");
                }

                Adjacency <VariableDescriptor> next = new Adjacency <VariableDescriptor>(dependsOnNonTransitive.Successors);
                Adjacency <VariableDescriptor> prev = new Adjacency <VariableDescriptor>(dependsOnNonTransitive.Predecessors);
                StronglyConnectedComponents <VariableDescriptor> DependsOnSCCs =
                    new StronglyConnectedComponents <VariableDescriptor>(
                        dependsOnNonTransitive.Nodes, next, prev);
                DependsOnSCCs.Compute();

                VariableDescriptorToSCC = new Dictionary <VariableDescriptor, SCC <VariableDescriptor> >();
                foreach (var scc in DependsOnSCCs)
                {
                    foreach (var s in scc)
                    {
                        VariableDescriptorToSCC[s] = scc;
                    }
                }

                DependsOnSCCsDAG = new Graph <SCC <VariableDescriptor> >();
                foreach (var edge in dependsOnNonTransitive.Edges)
                {
                    if (VariableDescriptorToSCC[edge.Item1] != VariableDescriptorToSCC[edge.Item2])
                    {
                        DependsOnSCCsDAG.AddEdge(VariableDescriptorToSCC[edge.Item1], VariableDescriptorToSCC[edge.Item2]);
                    }
                }

                SCC <VariableDescriptor> dummy = new SCC <VariableDescriptor>();
                foreach (var n in dependsOnNonTransitive.Nodes)
                {
                    DependsOnSCCsDAG.AddEdge(VariableDescriptorToSCC[n], dummy);
                }

                if (CommandLineOptions.Clo.Trace)
                {
                    Console.WriteLine("Variable dependence: SCCs computed!");
                }
            }

            return(DependsOn(VariableDescriptorToSCC[v]));
        }
Ejemplo n.º 25
0
        public bool MayReach(Block src, Block dst)
        {
            if (ReachabilityGraphSCCsDAG == null)
            {
                if (CommandLineOptions.Clo.Trace)
                {
                    Console.WriteLine("Interprocedural reachability: computing SCCs");
                }

                Adjacency <Block> next = new Adjacency <Block>(reachabilityGraph.Successors);
                Adjacency <Block> prev = new Adjacency <Block>(reachabilityGraph.Predecessors);
                StronglyConnectedComponents <Block> ReachabilitySCCs = new StronglyConnectedComponents <Block>(
                    reachabilityGraph.Nodes, next, prev);
                ReachabilitySCCs.Compute();

                BlockToSCC = new Dictionary <Block, SCC <Block> >();
                foreach (var scc in ReachabilitySCCs)
                {
                    foreach (var s in scc)
                    {
                        BlockToSCC[s] = scc;
                    }
                }

                ReachabilityGraphSCCsDAG = new Graph <SCC <Block> >();
                foreach (var edge in reachabilityGraph.Edges)
                {
                    if (BlockToSCC[edge.Item1] != BlockToSCC[edge.Item2])
                    {
                        ReachabilityGraphSCCsDAG.AddEdge(BlockToSCC[edge.Item1], BlockToSCC[edge.Item2]);
                    }
                }

                SCC <Block> dummy = new SCC <Block>();
                foreach (var n in reachabilityGraph.Nodes)
                {
                    ReachabilityGraphSCCsDAG.AddEdge(BlockToSCC[n], dummy);
                }

                if (CommandLineOptions.Clo.Trace)
                {
                    Console.WriteLine("Interprocedural reachability: SCCs computed!");
                }
            }

            return(ReachableFrom(BlockToSCC[src]).Contains(dst));
        }
Ejemplo n.º 26
0
    void InsertEdge(int startIndex, int endIndex, double weight)
    {
        Adjacency node1 = new Adjacency();
        Adjacency node2 = new Adjacency();

        node1.bigNodeIndex = endIndex;
        node1.weight       = weight;
        node1.link         = adjacencies[startIndex];

        adjacencies[startIndex] = node1;

        node2.bigNodeIndex = startIndex;
        node2.weight       = weight;
        node2.link         = adjacencies[endIndex];

        adjacencies[endIndex] = node2;
    }
        private void ConstructStagesDAG()
        {
            if (CommandLineOptions.Clo.Trace)
            {
                Console.WriteLine("Annotation dependence analysis: Computing SCCs");
            }

            Adjacency <string> next = new Adjacency <string>(AnnotationDependences.Successors);
            Adjacency <string> prev = new Adjacency <string>(AnnotationDependences.Predecessors);

            SCCs = new StronglyConnectedComponents <string>(
                AnnotationDependences.Nodes, next, prev);
            SCCs.Compute();

            if (CommandLineOptions.Clo.Trace)
            {
                Console.WriteLine("Annotation dependence analysis: Building stages DAG");
            }

            Dictionary <string, SCC <string> > rep = new Dictionary <string, SCC <string> >();

            foreach (var scc in SCCs)
            {
                foreach (var s in scc)
                {
                    rep[s] = scc;
                }
            }

            StagesDAG = new Graph <SCC <string> >();

            foreach (var edge in AnnotationDependences.Edges)
            {
                if (rep[edge.Item1] != rep[edge.Item2])
                {
                    StagesDAG.AddEdge(rep[edge.Item1], rep[edge.Item2]);
                }
            }

            SCC <string> dummy = new SCC <string>();

            foreach (var scc in SCCs)
            {
                StagesDAG.AddEdge(scc, dummy);
            }
        }
Ejemplo n.º 28
0
    public static void TestAssignment()
    {
        StopWatch t1   = new StopWatch("dynamic set");
        StopWatch t2   = new StopWatch("compile set");
        Adjacency edge = new Adjacency(3, 4);

        Console.WriteLine(edge.ToDescriptionString());
        t1.tic();
        Tag.SetProperty(edge, "SpringConstant", "200");
        t1.toc();
        Console.WriteLine(edge.ToDescriptionString());
        t2.tic();
        edge.SpringConstant = 203;
        t2.toc();
        Console.WriteLine(edge.ToDescriptionString());
        Console.WriteLine(t1.Result());
        Console.WriteLine(t2.Result());
    }
Ejemplo n.º 29
0
        private Vector3 get_force(ModelNode x, int node_index)
        {
            List <int> indices     = x.AdjacencyIndices;
            Vector3    total_force = Vector3.Zero;

            for (int i = 0; i < x.EdgeCount; i++)
            {
                Adjacency current_edge   = currentstate.GetEdge(indices[i]);
                int       relevant_index = current_edge.GetRelevantIndex(node_index);
                ModelNode y               = currentstate.GetNode(relevant_index);
                Vector3   direction       = new Vector3(x.CurrentLocation, y.CurrentLocation);
                double    eff_length      = direction.Norm - current_edge.EquilibriumLength;
                double    total_magnitude = current_edge.SpringConstant * eff_length;
                Vector3   current_force   = (total_magnitude / direction.Norm) * direction;
                //Vector3 current_force = direction;
                total_force = total_force + current_force;
            }
            return(total_force - x.DampingCoefficient * x.CurrentVelocity);
        }
Ejemplo n.º 30
0
    private void ConstructStagesDAG()
    {
      if (CommandLineOptions.Clo.Trace)
      {
        Console.WriteLine("Annotation dependence analysis: Computing SCCs");
      }

      Adjacency<string> next = new Adjacency<string>(AnnotationDependences.Successors);
      Adjacency<string> prev = new Adjacency<string>(AnnotationDependences.Predecessors);
      SCCs = new StronglyConnectedComponents<string>(
        AnnotationDependences.Nodes, next, prev);
      SCCs.Compute();

      if (CommandLineOptions.Clo.Trace)
      {
        Console.WriteLine("Annotation dependence analysis: Building stages DAG");
      }

      Dictionary<string, SCC<string>> rep = new Dictionary<string, SCC<string>>();
      foreach (var scc in SCCs)
      {
        foreach (var s in scc)
        {
          rep[s] = scc;
        }
      }

      StagesDAG = new Graph<SCC<string>>();

      foreach (var edge in AnnotationDependences.Edges)
      {
        if (rep[edge.Item1] != rep[edge.Item2])
        {
          StagesDAG.AddEdge(rep[edge.Item1], rep[edge.Item2]);
        }
      }

      SCC<string> dummy = new SCC<string>();
      foreach (var scc in SCCs)
      {
        StagesDAG.AddEdge(scc, dummy);
      }
    }
Ejemplo n.º 31
0
 public IEnumerable <IVertex <TV> > GetAdjacentVerteces(TV vertexValue)
 {
     if (ContainsVertex(vertexValue))
     {
         Adjacency.TryGetValue(vertexValue, out HashSet <Edge <TV, TW> > edges);
         IEnumerable <IVertex <TV> > targetVerteces = null;
         if (IsDirected)
         {
             targetVerteces = edges.Select(e => e.TargetVertex);
         }
         else
         {
             targetVerteces = edges.Select(e => e.ConnectedVertex(vertexValue));
         }
         return(targetVerteces);
     }
     else
     {
         throw new InvalidOperationException("The passed vertex is not a vertex of this graph.");
     }
 }
Ejemplo n.º 32
0
            public List <Ll> Run()
            {
                var rt = new List <Ll>();

                Size.REP(_ => rt.Add(new Ll()));

                Size.REP(i => Size.REP(k => rt[i].Add(i == k ? 0 : Inf)));

                Adjacency.ForeachWith((i, item) => {
                    foreach (var k in item)
                    {
                        rt[i][k.To] = k.Cost;
                    }
                });

                Size.REP(i => Size.REP(j => Size.REP(k => {
                    rt[j][k] = Min(rt[j][k], rt[j][i] + rt[i][k]);
                })));

                return(rt);
            }
        private void splitPolygon(List<Adjacency> insidePoints, List<Adjacency> pointList, Color color)
        {
            Adjacency a1 = insidePoints[0];
            Adjacency a2 = pointList[0];

            List<Adjacency> polygon1 = new List<Adjacency>();
            List<Adjacency> polygon2 = new List<Adjacency>();

            bool firstPolygon = true;
            Adjacency a = pointList[0];
            for( int i = 0; i < pointList.Count; i++)
            {
                if (firstPolygon)
                {
                    if (a != insidePoints[0])
                    {
                        polygon1.Add(a);
                        // running through the polygon
                        a = a.adj2;
                    }
                    else
                    {
                        // running through the polygon first to avoid the following modifications to the adjacencies
                        // to mess up with the run
                        a = a.adj2;

                        // copying the two scission points
                        Adjacency a1Copy = new Adjacency();
                        Adjacency a2Copy = new Adjacency();
                        a1Copy.point = a1.point;
                        a1Copy.adj2 = a1.adj2;
                        a2Copy.point = a2.point;
                        a2Copy.adj1 = a2.adj1;

                        // isolating first polygon
                        a1.adj2 = a2;
                        a2.adj1 = a1;
                        polygon1.Add(a1);

                        // isolating second polygon
                        a1Copy.adj1 = a2Copy;
                        a2Copy.adj2 = a1Copy;
                        polygon2.Add(a2Copy);
                        polygon2.Add(a1Copy);
                        firstPolygon = false;
                    }
                }
                else
                {
                    polygon2.Add(a);
                    // running through the polygon
                    a = a.adj2;
                }
            }
            AddPolygon(polygon1, color);
            AddPolygon(polygon2, color);
        }
 public static int CompareX(Adjacency a1, Adjacency a2)
 {
     if (a1.point.x == a2.point.x)
     {
         return 0;
     }
     if (a1.point.x > a2.point.x)
     {
         return 1;
     }
     return -1;
 }
        public HashSet<VariableDescriptor> DependsOn(VariableDescriptor v)
        {
            if (DependsOnSCCsDAG == null) {
            if (CommandLineOptions.Clo.Trace) {
              Console.WriteLine("Variable dependence: computing SCCs");
            }
            Adjacency<VariableDescriptor> next = new Adjacency<VariableDescriptor>(dependsOnNonTransitive.Successors);
            Adjacency<VariableDescriptor> prev = new Adjacency<VariableDescriptor>(dependsOnNonTransitive.Predecessors);
            StronglyConnectedComponents<VariableDescriptor> DependsOnSCCs = new StronglyConnectedComponents<VariableDescriptor>(
              dependsOnNonTransitive.Nodes, next, prev);
            DependsOnSCCs.Compute();

            VariableDescriptorToSCC = new Dictionary<VariableDescriptor, SCC<VariableDescriptor>>();
            foreach (var scc in DependsOnSCCs) {
              foreach (var s in scc) {
            VariableDescriptorToSCC[s] = scc;
              }
            }

            DependsOnSCCsDAG = new Graph<SCC<VariableDescriptor>>();
            foreach (var edge in dependsOnNonTransitive.Edges) {
              if (VariableDescriptorToSCC[edge.Item1] != VariableDescriptorToSCC[edge.Item2]) {
            DependsOnSCCsDAG.AddEdge(VariableDescriptorToSCC[edge.Item1], VariableDescriptorToSCC[edge.Item2]);
              }
            }

            SCC<VariableDescriptor> dummy = new SCC<VariableDescriptor>();
            foreach (var n in dependsOnNonTransitive.Nodes) {
              DependsOnSCCsDAG.AddEdge(VariableDescriptorToSCC[n], dummy);
            }

            if (CommandLineOptions.Clo.Trace) {
              Console.WriteLine("Variable dependence: SCCs computed!");
            }
              }
              return DependsOn(VariableDescriptorToSCC[v]);
        }
Ejemplo n.º 36
0
    /// <summary>
    /// Compute the strongly connected compontents of the blocks in the implementation.
    /// As a side effect, it also computes the "predecessor" relation for the block in the implementation
    /// </summary>
    override public void ComputeStronglyConnectedComponents() {
      if (!this.BlockPredecessorsComputed)
        ComputePredecessorsForBlocks();

      Adjacency<Block/*!*/> next = new Adjacency<Block/*!*/>(Successors);
      Adjacency<Block/*!*/> prev = new Adjacency<Block/*!*/>(Predecessors);

      this.scc = new StronglyConnectedComponents<Block/*!*/>(this.Blocks, next, prev);
      scc.Compute();


      foreach (Block/*!*/ block in this.Blocks) {
        Contract.Assert(block != null);
        block.Predecessors = new List<Block>();
      }

    }
Ejemplo n.º 37
0
        public override void GenerateGraphShape()
        {
            ClearAll();

            Node[,] nodeMatrix = new Node[ rowCount, colCount ];

            // Create all the nodes.
            for( int row = 0; row < rowCount; row++ )
            {
                float y = ( float )( rowCount - row - 1 );

                for( int col = 0; col < colCount; col++ )
                {
                    float x = ( float )col;

                    Node.Point location = new Node.Point( x, y );
                    Node node = CreateNode( location );
                    Insert( node );
                    nodeMatrix[ row, col ] = node;
                }
            }

            // Create all the adjacencies between the nodes.
            for( int row = 0; row < rowCount; row++ )
            {
                for( int col = 0; col < colCount; col++ )
                {
                    if( row < rowCount - 1 )
                    {
                        Adjacency adjacency = new Adjacency( nodeMatrix[ row, col ], nodeMatrix[ row + 1, col ] );
                        Insert( adjacency );
                    }

                    if( col < colCount - 1 )
                    {
                        Adjacency adjacency = new Adjacency( nodeMatrix[ row, col ], nodeMatrix[ row, col + 1 ] );
                        Insert( adjacency );
                    }
                }
            }

            mazeStart = nodeMatrix[ 0, 0 ];
            mazeFinish = nodeMatrix[ rowCount - 1, colCount - 1 ];
        }
Ejemplo n.º 38
0
        public override void GenerateGraphShape()
        {
            ClearAll();

            Node[][] nodeRingArray = new Node[ concentricCircleCount ][];

            int nodesPerRing = 7;
            float radiusDelta = 0.5f;
            float radius = 0.5f;

            for( int ringIndex = 0; ringIndex < concentricCircleCount; ringIndex++ )
            {
                Node[] nodeRing = new Node[ nodesPerRing ];
                nodeRingArray[ ringIndex ] = nodeRing;

                for( int index = 0; index < nodesPerRing; index++ )
                {
                    float angle = ( float )index / ( float )nodesPerRing * 2.0f * ( float )Math.PI;
                    float x = radius * ( float )Math.Cos( angle );
                    float y = radius * ( float )Math.Sin( angle );

                    Node.Point location = new Node.Point( x, y );
                    Node node = CreateNode( location );
                    nodeRing[ index ] = node;
                    Insert( node );
                }

                radius += radiusDelta;

                if( ringIndex < concentricCircleCount - 1 )
                {
                    float angle = ( 1.0f / ( float )nodesPerRing ) * 2.0f * ( float )Math.PI;
                    float arcLength = radius * angle;
                    if( arcLength > 1.0f )
                        nodesPerRing *= 2;
                }
            }

            Node centerNode = CreateNode( new Node.Point( 0.0f, 0.0f ) );
            Insert( centerNode );
            mazeStart = centerNode;
            mazeFinish = nodeRingArray[ concentricCircleCount - 1 ][0];

            Adjacency adjacency = new Adjacency( centerNode, nodeRingArray[0][0] );
            Insert( adjacency );

            for( int ringIndex = 0; ringIndex < concentricCircleCount; ringIndex++ )
            {
                Node[] nodeRing = nodeRingArray[ ringIndex ];
                Node[] nextNodeRing = null;
                int indexScalar = 1;
                if( ringIndex < concentricCircleCount - 1 )
                {
                    nextNodeRing = nodeRingArray[ ringIndex + 1 ];
                    if( nextNodeRing.Length > nodeRing.Length )
                        indexScalar = 2;
                }

                for( int index = 0; index < nodeRing.Length; index++ )
                {
                    int nextIndex = ( index + 1 ) % nodeRing.Length;
                    Node nodeA = nodeRing[ index ];
                    Node nodeB = nodeRing[ nextIndex ];
                    adjacency = new Adjacency( nodeA, nodeB );
                    Insert( adjacency );

                    if( nextNodeRing != null )
                    {
                        nodeA = nodeRing[ index ];
                        nodeB = nextNodeRing[ index * indexScalar ];
                        adjacency = new Adjacency( nodeA, nodeB );
                        Insert( adjacency );
                    }
                }
            }
        }
Ejemplo n.º 39
0
 public void Remove( Adjacency adjacency )
 {
     setOfAdjacencies.Remove( adjacency );
 }
Ejemplo n.º 40
0
 // We assume here that the nodes associated with the given adjacency are
 // both members of this graph.
 public void Insert( Adjacency adjacency )
 {
     setOfAdjacencies.Add( adjacency );
 }
        public bool MayReach(Block src, Block dst)
        {
            if (ReachabilityGraphSCCsDAG == null) {
            if (CommandLineOptions.Clo.Trace) {
              Console.WriteLine("Interprocedural reachability: computing SCCs");
            }
            Adjacency<Block> next = new Adjacency<Block>(reachabilityGraph.Successors);
            Adjacency<Block> prev = new Adjacency<Block>(reachabilityGraph.Predecessors);
            StronglyConnectedComponents<Block> ReachabilitySCCs = new StronglyConnectedComponents<Block>(
              reachabilityGraph.Nodes, next, prev);
            ReachabilitySCCs.Compute();

            BlockToSCC = new Dictionary<Block, SCC<Block>>();
            foreach (var scc in ReachabilitySCCs) {
              foreach (var s in scc) {
            BlockToSCC[s] = scc;
              }
            }

            ReachabilityGraphSCCsDAG = new Graph<SCC<Block>>();
            foreach (var edge in reachabilityGraph.Edges) {
              if (BlockToSCC[edge.Item1] != BlockToSCC[edge.Item2]) {
            ReachabilityGraphSCCsDAG.AddEdge(BlockToSCC[edge.Item1], BlockToSCC[edge.Item2]);
              }
            }

            SCC<Block> dummy = new SCC<Block>();
            foreach (var n in reachabilityGraph.Nodes) {
              ReachabilityGraphSCCsDAG.AddEdge(BlockToSCC[n], dummy);
            }

            if (CommandLineOptions.Clo.Trace) {
              Console.WriteLine("Interprocedural reachability: SCCs computed!");
            }
              }
              return ReachableFrom(BlockToSCC[src]).Contains(dst);
        }