Example #1
1
 public PathRecord(IVertex target, double weight, IList<IEdge> edgeTracks)
 {
     Target = target;
     Weight = weight;
     EdgeTracks = edgeTracks.ToArray();
     ParseVertexTracks(edgeTracks);
 }
 /// <summary>
 /// Returns a filtered enumerable collection of adjacent vertices
 /// </summary>
 /// <param name="v"></param>
 /// <returns></returns>
 public FilteredVertexEnumerable AdjacentVertices(IVertex v)
 {
     return new FilteredVertexEnumerable(
         AdjacencyGraph.AdjacentVertices(v),
         VertexPredicate
         );
 }
Example #3
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="u">reference vertex</param>
		/// <exception cref="ArgumentNullException">u is null</exception>
		public VertexEqualPredicate(IVertex u)
		{
			if (u == null)
				throw new ArgumentNullException("u");

			m_ReferenceVertex = u;
		}
Example #4
0
 /// <summary>
 /// 辺の両端の頂点を指定して初期化します。
 /// </summary>
 /// <param name="vtx1">第1端点</param>
 /// <param name="vtx2">第2端点</param>
 public Edge(Vertex vtx1, Vertex vtx2)
 {
     vertex1 = vtx1;
     vertex2 = vtx2;
     vertex1.AddNeighbor(vertex2);
     vertex2.AddNeighbor(vertex1);
 }
Example #5
0
 internal VertexRegister(IVertex currentVertex)
 {
     Vertex = currentVertex;
     Registed = false;
     TotalWeight = double.MaxValue;
     EdgeTracks = new List<IEdge>();
 }
Example #6
0
 internal RemoteSingleEdge(ServiceSingleEdgeInstance mySvcEdgeInstance, IServiceToken myServiceToken) : base(mySvcEdgeInstance, myServiceToken)
 {
     _EdgeTypeID = mySvcEdgeInstance.TypeID;
     _EdgePropertyID = mySvcEdgeInstance.EdgePropertyID;
     _SourceVertex = new RemoteVertex(mySvcEdgeInstance.SourceVertex, _ServiceToken);
     _TargetVertex = new RemoteVertex(mySvcEdgeInstance.TargetVertex, _ServiceToken);
 }
Example #7
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="source"></param>
 /// <param name="target"></param>
 /// <param name="g"></param>
 /// <returns></returns>
 public static ConnectsEdgePredicate Connects(
     IVertex source,
     IVertex target,
     IGraph g)
 {
     return new ConnectsEdgePredicate(source,target,g);
 }
		private static void Visit(IVertex node, ColorsSet colors,
								  TimestampSet discovery, TimestampSet finish, LinkedList<IVertex> list, ref int time)
		{
			colors.Set(node, VertexColor.Gray);

			discovery.Register(node, time++);

			foreach(IVertex child in node.Adjacencies)
			{
				if (colors.ColorOf(child) == VertexColor.White)
				{
					Visit(child, colors, discovery, finish, list, ref time);
				}
			}

			finish.Register(node, time++);

#if DEBUG
			Debug.Assert(discovery.TimeOf(node) < finish.TimeOf(node));
#endif

			list.AddFirst(node);

			colors.Set(node, VertexColor.Black);
		}
Example #9
0
		public ColorsSet(IVertex[] items)
		{
			foreach(IVertex item in items)
			{
				Set(item, VertexColor.White);
			}
		}
Example #10
0
        public FanMotif(IVertex headVertex,IVertex[] leafVertices)
        {
            m_oHeadVertex = headVertex;
            m_aoLeafVertices = leafVertices;
            m_dArcScale = 1.0;

        }
 internal void Augment(IVertex src, IVertex sink)
 {
     IEdge edge = null;
     IVertex vertex = null;
     double maxValue = double.MaxValue;
     edge = base.Predecessors.get_Item(sink);
     do
     {
         maxValue = Math.Min(maxValue, base.ResidualCapacities.get_Item(edge));
         vertex = edge.get_Source();
         edge = base.Predecessors.get_Item(vertex);
     }
     while (vertex != src);
     edge = base.Predecessors.get_Item(sink);
     do
     {
         EdgeDoubleDictionary dictionary;
         IEdge edge2;
         EdgeDoubleDictionary dictionary2;
         IEdge edge3;
         (dictionary = base.ResidualCapacities).set_Item(edge2 = edge, dictionary.get_Item(edge2) - maxValue);
         (dictionary2 = base.ResidualCapacities).set_Item(edge3 = base.ReversedEdges.get_Item(edge), dictionary2.get_Item(edge3) + maxValue);
         vertex = edge.get_Source();
         edge = base.Predecessors.get_Item(vertex);
     }
     while (vertex != src);
 }
Example #12
0
        // Kiem tra 1 diem co nam trong da giac khong
        public static bool CheckInnerPoint(IVertexCollection points, IVertex point)
        {
            IVertex currentPoint = point;
            //Ray-cast algorithm is here onward
            int k, j = points.Count - 1;
            var oddNodes = false; //to check whether number of intersections is odd

            for (k = 0; k < points.Count; k++)
            {
                //fetch adjucent points of the polygon
                IVertex polyK = points[k];
                IVertex polyJ = points[j];

                //check the intersections
                if (((polyK.Y > currentPoint.Y) != (polyJ.Y > currentPoint.Y)) &&
                 (currentPoint.X < (polyJ.X - polyK.X) * (currentPoint.Y - polyK.Y) / (polyJ.Y - polyK.Y) + polyK.X))
                    oddNodes = !oddNodes; //switch between odd and even
                j = k;
            }

            //if odd number of intersections
            if (oddNodes)
            {
                //mouse point is inside the polygon
                return true;
            }

            //if even number of intersections
            return false;
        }
Example #13
0
        /// <summary>
        /// Create a new triangle with 3 new edge 
        /// </summary>
        /// <param name="vert1"></param>
        /// <param name="vert2"></param>
        /// <param name="vert3"></param>
        /// <param name="he1"></param>
        /// <param name="he2"></param>
        /// <param name="he3"></param>
        public static void CreateTriangle( IVertex<float> vert1, IVertex<float> vert2, IVertex<float> vert3,
            out Half_Edge he1, out Half_Edge he2, out Half_Edge he3 )
        {
            // create the new triangle
            he1 = new Half_Edge();
            he2 = new Half_Edge();
            he3 = new Half_Edge();

            // CCW test
            if ( ( ( vert2.X - vert1.X ) * ( vert3.Y - vert1.Y ) - ( vert3.X - vert1.X ) * ( vert2.Y - vert1.Y ) ) > 0 ) {
                he1.NextEdge = he2;
                he2.NextEdge = he3;
                he3.NextEdge = he1;
            } else {
                he1.NextEdge = he3;
                he3.NextEdge = he2;
                he2.NextEdge = he1;
            }

            // set the vertex
            he1.StartVertex = vert1;
            he2.StartVertex = vert2;
            he3.StartVertex = vert3;

            // set null the twin edge
            he1.TwinEdge = null;
            he2.TwinEdge = null;
            he3.TwinEdge = null;
        }
Example #14
0
 public Quad()
 {
     Vertices = new IVertex[]
     {
             new Vertex
                 {
                     Position = new Vector3(-1f, -1f, 0f),
                     Color = Color.White,
                     Texcoords = new Texcoords(new Vector2(0f, 0f))
                 },
             new Vertex
                 {
                     Position = new Vector3(1f, -1f, 0f),
                     Color = Color.White,
                     Texcoords = new Texcoords(new Vector2(1f, 0f))
                 },
             new Vertex
                 {
                     Position = new Vector3(1f, 1f, 0f),
                     Color = Color.White,
                     Texcoords = new Texcoords(new Vector2(1f, 1f))
                 },
             new Vertex
                 {
                     Position = new Vector3(-1f, 1f, 0f),
                     Color = Color.White,
                     Texcoords = new Texcoords(new Vector2(0f, 1f))
                 },
     };
     Indices = new short[] { 0, 1, 2, 0, 2, 3 };
 }
Example #15
0
 public WFVertexWrapper(IGraphWrapper graphWrapper,IVertex vertex)
 {
     this.graphWrapper = graphWrapper;
     vertexValue = vertex.Value;
     if ( graphWrapper.Graph != vertex.Graph )
         throw new Exception( "Invalid argument - vertex or graphWrapper. Method - WFVertexWrapper.constructor(IGraphWrapper,IVertex)" );
 }
        /// <summary>
        /// Gets an enumerable collection of child <see cref="IVertex"/>
        /// </summary>
        /// <param name="v">current <see cref="IVertex"/></param>
        /// <returns>An enumerable collection of adjacent vertices</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="v"/> is a null reference
        /// </exception>
        public IVertexEnumerable ChildVertices(IVertex v)
        {
            if (v==null)
                throw new ArgumentNullException("v");

            return new TargetVertexEnumerable(this.Wrapped.OutEdges(v));
        }
Example #17
0
        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        public static Dictionary<IVertex, double> WidestPath(this Graph graph, IVertex from, IVertex to)
        {
            var width = new Dictionary<IVertex, double>();
            var previous = new Dictionary<IVertex, IVertex>();
            foreach (var vertex in from DictionaryEntry dictEntry in graph.Vertices select (IVertex)dictEntry.Value)
            {
                width.Add(vertex, double.NegativeInfinity);
                previous.Add(vertex, null);
            }

            width[from] = double.PositiveInfinity;
            var q = (from DictionaryEntry dictEntry in graph.Vertices select (IVertex)dictEntry.Value).ToList();

            while (q.Count > 0)
            {
                var u = q.MaxBy(x => width[x]);
                q.Remove(u);

                if (double.IsNegativeInfinity(width[u]) || u == to)
                    break;

                foreach (var neighbor in graph.GetNeighbors(u))
                {
                    var alt = Math.Max(width[neighbor], Math.Min(width[u], graph.GetEdgeCost(u, neighbor)));

                    if (!(alt > width[neighbor])) continue;
                    width[neighbor] = alt;
                    previous[neighbor] = u;
                }
            }

            return width;
        }
        public void Test(IVertexAndEdgeListGraph g, IVertex root)
        {
            this.root = root;

            RandomWalkAlgorithm walker = new RandomWalkAlgorithm(g);
            walker.TreeEdge +=new EdgeEventHandler(walker_TreeEdge);
            walker.Generate(root,50);

            BidirectionalAdaptorGraph bg = new BidirectionalAdaptorGraph(g);
            ReversedBidirectionalGraph rg = new ReversedBidirectionalGraph(bg);
            CyclePoppingRandomTreeAlgorithm pop = new CyclePoppingRandomTreeAlgorithm(rg);

            pop.InitializeVertex +=new VertexEventHandler(this.InitializeVertex);
            pop.FinishVertex +=new VertexEventHandler(this.FinishVertex);
            pop.TreeEdge += new EdgeEventHandler(this.TreeEdge);

            pop.InitializeVertex +=new VertexEventHandler(vis.InitializeVertex);
            pop.TreeEdge += new EdgeEventHandler(vis.TreeEdge);
            pop.ClearTreeVertex += new VertexEventHandler(vis.ClearTreeVertex);

            pop.RandomTreeWithRoot(root);

            // plot tree...
            GraphvizAlgorithm gv = new GraphvizAlgorithm(g,".",GraphvizImageType.Svg);
            gv.FormatEdge +=new FormatEdgeEventHandler(this.FormatEdge);
            gv.FormatVertex +=new FormatVertexEventHandler(this.FormatVertex);

            gv.Write("randomtree");
        }
 public void ReducePathDistance(IVertexDistanceMatrix distances, IVertex source, IVertex target, IVertex intermediate)
 {
     if (distances.Distance(source, target) == 0.0)
     {
         distances.SetDistance(source, target, Convert.ToDouble((distances.Distance(source, intermediate) != 0.0) && (distances.Distance(intermediate, target) != 0.0)));
     }
 }
Example #20
0
 private static void PrintVertexTrack(IVertex[] vertex)
 {
     Console.WriteLine("Vertex tracks:");
     for (int i = 0; i < vertex.Count(); i++) {
         Console.WriteLine("{0}: {1}", i + 1, vertex[i]);
     }
 }
Example #21
0
        //*************************************************************************
        //  Method: AddVertices()
        //
        /// <summary>
        /// Adds a specified number of <see cref="Vertex" /> objects to a graph
        /// using the <see cref="IVertexCollection.Add(IVertex)" /> method.
        /// </summary>
        ///
        /// <param name="oGraph">
        /// Graph to add vertices to.
        /// </param>
        ///
        /// <param name="iVerticesToAdd">
        /// Number of vertices to add.
        /// </param>
        ///
        /// <returns>
        /// An array of the added vertices.
        /// </returns>
        //*************************************************************************
        public static IVertex[] AddVertices(
            IGraph oGraph,
            Int32 iVerticesToAdd
            )
        {
            Debug.Assert(oGraph != null);
            Debug.Assert(iVerticesToAdd >= 0);

            IVertex[] aoVertices = new IVertex[iVerticesToAdd];

            IVertexCollection oVertexCollection = oGraph.Vertices;

            // Add the vertices.

            for (Int32 i = 0; i < iVerticesToAdd; i++)
            {
            IVertex oVertex = aoVertices[i] = new Vertex();

            oVertex.Name = oVertex.ID.ToString();

            oVertexCollection.Add(oVertex);
            }

            return (aoVertices);
        }
 public virtual IEdge Successor(IImplicitGraph g, IVertex u)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     if (u == null)
     {
         throw new ArgumentNullException("u");
     }
     int num = g.OutDegree(u);
     double num2 = 0.0;
     IEdgeEnumerator enumerator = g.OutEdges(u).GetEnumerator();
     while (enumerator.MoveNext())
     {
         IEdge edge = enumerator.get_Current();
         num2 += this.weights.get_Item(edge);
     }
     double num3 = this.rnd.NextDouble() * num2;
     double num4 = 0.0;
     double num5 = 0.0;
     IEdgeEnumerator enumerator2 = g.OutEdges(u).GetEnumerator();
     while (enumerator2.MoveNext())
     {
         IEdge edge2 = enumerator2.get_Current();
         num5 = num4 + this.weights.get_Item(edge2);
         if ((num3 >= num4) && (num3 <= num5))
         {
             return edge2;
         }
         num4 = num5;
     }
     return null;
 }
Example #23
0
        public void Add(IVertex current_node, double current_distance, UInt64 current_depth)
        {
            var id = current_node.VertexID;
            _buffer.Add(Tuple.Create(current_distance, id), Tuple.Create(current_node, current_distance, current_depth));

            _count++;
        }
Example #24
0
        /// <summary>
        /// Executes the function on myCallingObject
        /// </summary>
        public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken, params FuncParameter[] myParams)
        {
            var currentInnerEdgeType = ((IOutgoingEdgeDefinition)myAttributeDefinition).InnerEdgeType;

            if (myCallingObject is IHyperEdge && currentInnerEdgeType.HasProperty("Weight"))
            {
                var hyperEdge = myCallingObject as IHyperEdge;

                if (currentInnerEdgeType.HasProperty("Weight"))
                {
                    var weightProperty = currentInnerEdgeType.GetPropertyDefinition("Weight");

                    var maxWeight = hyperEdge.InvokeHyperEdgeFunc<Double>(singleEdges =>
                    {
                        return Convert.ToDouble(
                            weightProperty.GetValue(
                            singleEdges
                            .OrderByDescending(edge => weightProperty.GetValue(edge))
                            .First()));
                    });

                    return new FuncParameter(maxWeight);

                }
            }

            throw new InvalidTypeException(myCallingObject.GetType().ToString(), "Weighted IHyperEdge");
        }
 /// <summary>
 /// Push a new vertex on the buffer.
 /// </summary>
 /// <param name="v">new vertex</param>
 public override void Push(IVertex v)
 {
     // add to queue
     base.Push(v);
     // sort queue
     Sort(m_Comparer);
 }
Example #26
0
		/// <summary>
		/// Adds the elements of an array to the end of this VertexCollection.
		/// </summary>
		/// <param name="items">
		/// The array whose elements are to be added to the end of this VertexCollection.
		/// </param>
		public  void AddRange(IVertex[] items)
		{
			foreach (IVertex item in items)
			{
				this.List.Add(item);
			}
		}
Example #27
0
        public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken, params FuncParameter[] myParams)
        {
            if (!(myCallingObject is String))
            {
                throw new FunctionParameterTypeMismatchException(typeof(String), myCallingObject.GetType());
            }

            var pos = Convert.ToInt32(myParams[0].Value);

            StringBuilder resString = new StringBuilder();
            bool dontInsert = false;

            if (pos > (myCallingObject as String).Length)
            {
                dontInsert = true;
                resString.Append((myCallingObject as String).ToString());
            }
            else
            {
                resString.Append((myCallingObject as String).ToString().Substring(0, pos));
            }

            foreach (FuncParameter fp in myParams.Skip(1))
            {
                resString.Append(fp.Value as String);
            }

            if(!dontInsert)
                resString.Append((myCallingObject as String).ToString().Substring(pos));

            return new FuncParameter(resString.ToString());
        }
Example #28
0
File: Board.cs Project: Corne/VOC
        public IEstablishment BuildEstablishment(IVertex vertex, IPlayer owner)
        {
            if (vertex == null)
                throw new ArgumentNullException(nameof(vertex));
            if (owner == null)
                throw new ArgumentNullException(nameof(owner));
            if (!Vertices.Contains(vertex))
                throw new ArgumentException("Did not find the passed vertex on the board");
            if (establishments.Any(e => e.Vertex == vertex))
                throw new ArgumentException("Invalid vertex, already an establishment here");

            var vertices = Vertices.Where(v => v.IsAdjacentTo(vertex));
            var tiles = Tiles.Where(t => t.IsAdjacentTo(vertex));
            if (establishments.Any(e => vertices.Contains(e.Vertex)))
                throw new ArgumentException("Invalid vertex, establishment can't be placed next to another establishment");
            if (tiles.All(t => t.Rawmaterial == MaterialType.Sea))
                throw new ArgumentException("Can't place an establishment on sea!");

            if (establishments.Count(e => e.Owner == owner) >= 2 &&
                roads.Where(r => r.Owner == owner).All(r => !r.Edge.IsAdjacentTo(vertex)))
                throw new InvalidOperationException("Each player can only build 2 houses without adjacent roads!");

            var establishment = new Establishment(owner, vertex);
            establishments.Add(establishment);


            logger.Info($"Establisment Build; Player {owner.Name}, {vertex.ToString()}");

            return establishment;
        }
 public void ReducePathDistance(IVertexDistanceMatrix distances, IVertex source, IVertex target, IVertex intermediate)
 {
     if ((source == target) && (distances.Distance(source, target) < 0.0))
     {
         throw new Exception("Negative cycle");
     }
 }
Example #30
0
 /// <summary>
 /// Creates a new instance of VertexType.
 /// </summary>
 /// <param name="myVertexTypeVertex">An IVertex that represents the vertex type.</param>
 internal VertexType(IVertex myVertexTypeVertex)
     : base(myVertexTypeVertex)
 {
     _hasOwnUniques = HasOutgoingEdge(AttributeDefinitions.VertexTypeDotUniquenessDefinitions);
     _hasOwnIndices = HasIncomingVertices(BaseTypes.Index, AttributeDefinitions.IndexDotDefiningVertexType);
     _hasChilds = HasIncomingVertices(BaseTypes.VertexType, AttributeDefinitions.VertexTypeDotParent);
 }
 public void ChangePrevios(IVertex <T> vertex)
 {
     _previos = vertex;
 }
Example #32
0
 public IEdge AddEdge(object id, string label, IVertex vertex)
 {
     return(IdInnerTinkerGrapĥ.AddEdge(id, this, vertex, label));
 }
Example #33
0
 /// <summary>
 /// Gets an enumerable collection of the v adjacent vertices
 /// </summary>
 /// <param name="v"></param>
 /// <returns></returns>
 public IVertexEnumerable AdjacentVertices(IVertex v)
 {
     return(new TargetVertexEnumerable(OutEdges(v)));
 }
Example #34
0
 /// <summary>
 /// Implentens IIncidenceGraph interface.
 /// </summary>
 /// <param name="v"></param>
 /// <returns></returns>
 IEdgeEnumerable IImplicitGraph.OutEdges(IVertex v)
 {
     return(this.OutEdges(v));
 }
Example #35
0
 /// <summary>
 /// Returns an iterable collection of the out edges of v
 /// </summary>
 public FilteredEdgeEnumerable OutEdges(IVertex v)
 {
     return(FilteredIncidenceGraph.OutEdges(v));
 }
Example #36
0
 /// <summary>
 /// Returns the number of out-degree edges of v
 /// </summary>
 /// <param name="v">vertex to test</param>
 /// <returns>out-degree</returns>
 public int OutDegree(IVertex v)
 {
     return(FilteredIncidenceGraph.OutDegree(v));
 }
Example #37
0
 /// <summary>
 /// Gets a value indicating if the set of out-edges is empty
 /// </summary>
 /// <remarks>
 /// <para>
 /// Usually faster that calling <see cref="OutDegree"/>.
 /// </para>
 /// </remarks>
 /// <value>
 /// true if the out-edge set is empty, false otherwise.
 /// </value>
 /// <exception cref="ArgumentNullException">v is a null reference</exception>
 public bool OutEdgesEmpty(IVertex v)
 {
     return(this.OutEdgesEmpty(v));
 }
 public double CalculateStepCost(IVertex neighbour, IVertex current)
 {
     return(Math.Abs(neighbour.Cost.CurrentCost - current.Cost.CurrentCost));
 }
Example #39
0
        private void SetAsVisitedLeft(Tuple <long, long> myTuple, ref Node myCurrentNode, ref Node myNextNode, IVertex myVertex)
        {
            //create a new node
            myNextNode = new Node(myTuple, myCurrentNode);

            //set currentNode
            myCurrentNode.addChild(myNextNode);

            //never seen before
            //mark the node as visited
            //_VisitedNodesLeft.Add(currentNodeLeft.Key, currentNodeLeft);
            _VisitedNodesLeft.Add(myNextNode.Key, myNextNode);

            //and put node into the queue
            _QueueLeft.Enqueue(myVertex);
        }
Example #40
0
        private void SetAsVisitedRight(Tuple <long, long> myTuple, ref Node myCurrentNode, ref Node myNextNode, IVertex myVertex)
        {
            //create a new node and set currentRight = child
            myNextNode = new Node(myTuple);
            myNextNode.addChild(myCurrentNode);

            //set currentNodeRight as parent of current Right
            myCurrentNode.addParent(myNextNode);

            //never seen before
            //mark the node as visited
            _VisitedNodesRight.Add(myNextNode.Key, myNextNode);

            //and look what comes on the next level of depth
            _QueueRight.Enqueue(myVertex);
        }
Example #41
0
        /// <summary>
        /// Checks if the search should be aborted.
        /// </summary>
        /// <param name="myTuple">the Tuple of the current Vertex.</param>
        /// <param name="myCurrentNode">The current Node.</param>
        /// <param name="myNextNode">The next Node.</param>
        /// <param name="myVertex">The actual Vertex.</param>
        /// <returns>True, if the target is found AND the BFS could be finished. False, if the BFS should be continued.</returns>
        private bool TargetFoundCheckAbort(Tuple <long, long> myTuple, ref Node myCurrentNode, ref Node myNextNode, IVertex myVertex)
        {
            if (myTuple.Equals(_Target.Key))
            {
                //set currentLeft as parent of _Target
                _Target.addParent(myCurrentNode);

                #region check if already visited
                if (_VisitedNodesLeft.ContainsKey(myTuple))
                {
                    //set currentLeft as parent
                    _VisitedNodesLeft[myTuple].addParent(myCurrentNode);

                    //set currentNodeLeft as child
                    myCurrentNode.addChild(_VisitedNodesLeft[myTuple]);
                }
                else
                {
                    //create a new node and set currentLeft = parent
                    myNextNode = new Node(myTuple, myCurrentNode);

                    //set currentNodeLeft as child of currentLeft
                    myCurrentNode.addChild(myNextNode);

                    //never seen before
                    //mark the node as visited
                    _VisitedNodesLeft.Add(myNextNode.Key, myNextNode);

                    //and put node into the queue
                    _QueueLeft.Enqueue(myVertex);
                }

                #endregion

                #region check how much parents are searched

                if (_ShortestOnly && !_FindAll)
                {
                    if ((_DepthLeft + _DepthRight + 1) > _MaxPathLength)
                    {
                        _ShortestPathLength = _MaxPathLength;
                    }
                    else
                    {
                        _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight + 1);
                    }

                    return(true);
                }
                //if find all shortest paths
                else if (_ShortestOnly && _FindAll)
                {
                    //set maxDepth to actual depth
                    _MaxDepthLeft  = _DepthLeft;
                    _MaxDepthRight = _DepthRight;

                    if ((_DepthLeft + _DepthRight) > _MaxPathLength)
                    {
                        _ShortestPathLength = _MaxPathLength;
                    }
                    else
                    {
                        _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight);
                    }
                }

                #endregion
            }

            return(false);
        }
Example #42
0
        private bool RootFoundCheckAbort(Tuple <long, long> myTuple, ref Node myCurrentNode, ref Node myNextNode, IVertex myVertex)
        {
            #region check if already visited
            //mark node as visited
            if (_VisitedNodesRight.ContainsKey(myTuple))
            {
                //set found children
                _VisitedNodesRight[myTuple].addChild(myCurrentNode);

                myCurrentNode.addParent(_VisitedNodesRight[myTuple]);
            }
            else
            {
                //create a new node and set currentRight = child
                myNextNode = new Node(myTuple);
                myNextNode.addChild(myCurrentNode);

                //set currentNodeRight as parent of current Right
                myCurrentNode.addParent(myNextNode);

                //never seen before
                //mark the node as visited
                _VisitedNodesRight.Add(myNextNode.Key, myNextNode);

                //and look what comes on the next level of depth
                _QueueRight.Enqueue(myVertex);
            }

            #endregion check if already visited
            #region check how much paths are searched

            if (_ShortestOnly && !_FindAll)
            {
                if ((_DepthLeft + _DepthRight + 1) > _MaxPathLength)
                {
                    _ShortestPathLength = _MaxPathLength;
                }
                else
                {
                    _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight + 1);
                }

                return(true);
            }
            //if find all shortest paths
            else if (_ShortestOnly && _FindAll)
            {
                //set maxDepth to actual depth
                _MaxDepthLeft  = _DepthLeft;
                _MaxDepthRight = _DepthRight;

                if ((_DepthLeft + _DepthRight) > _MaxPathLength)
                {
                    _ShortestPathLength = _MaxPathLength;
                }
                else
                {
                    _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight);
                }
            }
            #endregion check how much paths are searched

            return(false);
        }
Example #43
0
 public bool Equals(IVertex <T> other)
 {
     return(Value.Equals(other.Value));
 }
Example #44
0
        /// <summary>
        /// Please look at the class documentation for detailed description how this algorithm works.
        /// </summary>
        /// <param name="myTypeAttribute">The Attribute representing the edge to follow (p.e. "Friends")</param>
        /// <param name="myVertexType">The type of the start node.</param>
        /// <param name="myStart">The start node</param>
        /// <param name="myEnd">The end node</param>
        /// <param name="shortestOnly">true, if only shortest path shall be found</param>
        /// <param name="findAll">if true and shortestOnly is true, all shortest paths will be found.
        /// If true, and shortest only is false, all paths will be searched</param>
        /// <param name="myMaxDepth">The maximum depth to search</param>
        /// <param name="myMaxPathLength">The maximum path length which shall be analyzed</param>
        /// <returns>A HashSet which contains all found paths. Every path is represented by a List of ObjectUUIDs</returns>m>
        public HashSet <List <Tuple <long, long> > > Find(IAttributeDefinition myTypeAttribute,
                                                          IVertexType myVertexType,
                                                          IVertex myStart,
                                                          IVertex myEnd,
                                                          bool shortestOnly,
                                                          bool findAll,
                                                          UInt64 myMaxDepth,
                                                          UInt64 myMaxPathLength)
        {
            #region declarations

            //set current depth
            _DepthLeft  = 1;
            _DepthRight = 1;

            //maximum depth
            _MaxDepthLeft  = 0;
            _MaxDepthRight = 0;

            _MaxPathLength = myMaxPathLength;

            #region initialize maxDepths

            //if the maxDepth is greater then maxPathLength, then set maxDepth to maxPathLength
            if (myMaxDepth > _MaxPathLength)
            {
                myMaxDepth = _MaxPathLength;
            }
            else if (_MaxPathLength > myMaxDepth)
            {
                _MaxPathLength = myMaxDepth;
            }

            //set depth for left side
            _MaxDepthLeft = Convert.ToUInt64(myMaxDepth / 2 + 1);

            //if myMaxDepth is 1 _MaxDepthRight keeps 0, just one side is searching
            if (myMaxDepth > 1)
            {
                //both sides have the same depth
                _MaxDepthRight = _MaxDepthLeft;
            }

            //if myMaxDepth is even, one side has to search in a greater depth
            if ((myMaxDepth % 2) == 0)
            {
                _MaxDepthRight = Convert.ToUInt64(_MaxDepthLeft - 1);
            }

            #endregion

            //shortest path length
            _ShortestPathLength = 0;

            //_Target node, the _Target of the select
            _Target = new Node(myEnd.VertexTypeID, myEnd.VertexID);
            _Root   = new Node(myStart.VertexTypeID, myStart.VertexID);

            //the attribute (edge) which is used for the search
            _AttributeDefinition = myTypeAttribute;

            //search the type on which the attribute is defined
            IVertexType        current  = myVertexType;
            List <IVertexType> tempList = new List <IVertexType>();
            tempList.Add(current);

            bool foundDefinedType = false;

            while (current.HasParentType && !foundDefinedType)
            {
                if (current.ParentVertexType.HasAttribute(_AttributeDefinition.Name))
                {
                    foundDefinedType = true;
                }

                current = current.ParentVertexType;
                tempList.Add(current);
            }

            if (foundDefinedType)
            {
                _Types = tempList;
            }
            else
            {
                _Types.Add(myVertexType);
            }

            //dummy node to check in which level the BFS is
            _DummyLeft  = null;
            _DummyRight = null;

            _FindAll      = findAll;
            _ShortestOnly = shortestOnly;

            #endregion

            #region BidirectionalBFS
            //check if the EdgeType is ASetReferenceEdgeType

            #region initialize variables

            //enqueue start node to start from left side
            _QueueLeft.Enqueue(myStart);
            //enqueue _DummyLeft to analyze the depth of the left side
            _QueueLeft.Enqueue(_DummyLeft);

            //enqueue _Target node to start from right side
            _QueueRight.Enqueue(myEnd);
            //enqueue _DummyRight to analyze the depth of the right side
            _QueueRight.Enqueue(_DummyRight);

            //add _Root and _Target to visitedNodes
            _VisitedNodesLeft.Add(_Root.Key, _Root);
            _VisitedNodesRight.Add(_Target.Key, _Target);

            #endregion

            #region check if start has outgoing and _Target has incoming edge

            //check that the start node has the outgoing edge and the target has incoming vertices
            if (!myStart.HasOutgoingEdge(_AttributeDefinition.ID) && !HasIncomingVertices(myEnd))
            {
                return(null);
            }

            #endregion

            //if there is more than one object in the queue and the actual depth is less than MaxDepth
            while (((_QueueLeft.Count > 0) && (_QueueRight.Count > 0)) &&
                   ((_DepthLeft <= _MaxDepthLeft) || (_DepthRight <= _MaxDepthRight)))
            {
                #region both queues contain objects and both depths are not reached
                if (((_QueueLeft.Count > 0) && (_QueueRight.Count > 0)) &&
                    ((_DepthLeft <= _MaxDepthLeft) && (_DepthRight <= _MaxDepthRight)))
                {
                    #region check if a level is completely searched

                    if (LeftLevelCompleted())
                    {
                        continue;
                    }

                    if (RightLevelCompleted())
                    {
                        continue;
                    }

                    #endregion check if there is a dummyNode at the beginning of a queue

                    #region get first nodes of the queues

                    //hold the actual element of the queues
                    Node currentNodeLeft;
                    Node currentNodeRight;

                    IVertex currentVertexLeft;
                    IVertex currentVertexRight;

                    Tuple <long, long> currentLeft;
                    Tuple <long, long> currentRight;

                    //get the first Object of the queue
                    currentVertexLeft = _QueueLeft.Dequeue();
                    currentLeft       = new Tuple <long, long>(currentVertexLeft.VertexTypeID,
                                                               currentVertexLeft.VertexID);

                    if (_VisitedNodesLeft.ContainsKey(currentLeft))
                    {
                        currentNodeLeft = _VisitedNodesLeft[currentLeft];
                    }
                    else
                    {
                        currentNodeLeft = new Node(currentLeft);
                    }

                    //get the first Object of the queue
                    currentVertexRight = _QueueRight.Dequeue();
                    currentRight       = new Tuple <long, long>(currentVertexRight.VertexTypeID,
                                                                currentVertexRight.VertexID);

                    if (_VisitedNodesRight.ContainsKey(currentRight))
                    {
                        currentNodeRight = _VisitedNodesRight[currentRight];
                    }
                    else
                    {
                        currentNodeRight = new Node(currentRight);
                    }

                    #endregion

                    #region the edge and the backwardedge are existing
                    if (currentVertexLeft.HasOutgoingEdge(_AttributeDefinition.ID) &&
                        HasIncomingVertices(currentVertexRight))
                    {
                        //get all referenced ObjectUUIDs using the given Edge
                        var leftVertices = currentVertexLeft.GetOutgoingEdge(_AttributeDefinition.ID).GetTargetVertices();

                        #region check left friends
                        foreach (var nextLeftVertex in leftVertices)
                        {
                            Node nextLeftNode           = null;
                            Tuple <long, long> nextLeft = new Tuple <long, long>(nextLeftVertex.VertexTypeID, nextLeftVertex.VertexID);

                            #region if the child is the _Target
                            if (nextLeft.Equals(_Target.Key))
                            {
                                if (TargetFoundCheckAbort(nextLeft, ref currentNodeLeft, ref nextLeftNode, nextLeftVertex))
                                {
                                    return(new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths());
                                }
                            }
                            #endregion
                            #region already visited
                            else if (_VisitedNodesLeft.ContainsKey(nextLeft))
                            {
                                UpdateVisitedLeft(nextLeft, ref currentNodeLeft);
                            }
                            #endregion already visited
                            #region set as visited
                            else
                            {
                                SetAsVisitedLeft(nextLeft, ref currentNodeLeft, ref nextLeftNode, nextLeftVertex);
                            }
                            #endregion set as visited
                        }
                        #endregion check left friends

                        //get all referenced ObjectUUIDs using the given Edge
                        var rightVertices = GetIncomingVertices(currentVertexRight);

                        #region check right friends
                        foreach (var nextRightVertex in rightVertices)
                        {
                            Node nextRightNode           = null;
                            Tuple <long, long> nextRight = new Tuple <long, long>(nextRightVertex.VertexTypeID, nextRightVertex.VertexID);

                            #region if the child is the _Target
                            if (_Root.Key.Equals(nextRight))
                            {
                                if (RootFoundCheckAbort(nextRight, ref currentNodeRight, ref nextRightNode, nextRightVertex))
                                {
                                    return(new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths());
                                }
                            }
                            #endregion if the child is the _Target
                            #region already visited
                            else if (_VisitedNodesRight.ContainsKey(nextRight))
                            {
                                UpdateVisitedRight(nextRight, ref currentNodeRight);
                            }
                            #endregion already visited
                            #region set as visited
                            else
                            {
                                SetAsVisitedRight(nextRight, ref currentNodeRight, ref nextRightNode, nextRightVertex);
                            }
                            #endregion set as visited
                        }
                        #endregion check right friends

                        #region build intersection of _VisitedNodesLeft and _VisitedNodesRight
                        //marks if intersection nodes are existing
                        bool foundIntersect = false;

                        foreach (var node in _VisitedNodesLeft)
                        {
                            if (_VisitedNodesRight.ContainsKey(node.Key))
                            {
                                //set nodes children and parents
                                node.Value.addChildren(_VisitedNodesRight[node.Key].Children);
                                node.Value.addParents(_VisitedNodesRight[node.Key].Parents);

                                //set nodes children and parents
                                _VisitedNodesRight[node.Key].addChildren(node.Value.Children);
                                _VisitedNodesRight[node.Key].addParents(node.Value.Parents);

                                _IntersectNodes.Add(_VisitedNodesRight[node.Key]);

                                foundIntersect = true;
                            }
                        }
                        #endregion build intersection of _VisitedNodesLeft and _VisitedNodesRight

                        #region analyze intersection
                        //if intersection nodes existing
                        if (foundIntersect)
                        {
                            //only shortest path
                            if (_ShortestOnly && !_FindAll)
                            {
                                if ((_DepthLeft + _DepthRight + 1) > _MaxPathLength)
                                {
                                    _ShortestPathLength = _MaxPathLength;
                                }
                                else
                                {
                                    _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight + 1);
                                }

                                //return new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths();
                                return(new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll)
                                       .GetShortestPath(_IntersectNodes));
                            }
                            //if find all shortest paths
                            else if (_ShortestOnly && _FindAll)
                            {
                                //set maxDepth to actual depth
                                _MaxDepthLeft  = _DepthLeft;
                                _MaxDepthRight = _DepthRight;

                                if ((_DepthLeft + _DepthRight + 1) > _MaxPathLength)
                                {
                                    _ShortestPathLength = _MaxPathLength;
                                }
                                else if (_ShortestPathLength == 0)
                                {
                                    _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight + 1);
                                }
                            }
                        }
                        #endregion analyze intersection
                    }
                    #endregion the edge and the backwardedge are existing
                    #region only the edge exists
                    else if (currentVertexLeft.HasOutgoingEdge(_AttributeDefinition.ID))
                    {
                        var result = CheckNextVerticesOfLeftSide(ref currentVertexLeft, ref currentNodeLeft);

                        if (result != null)
                        {
                            return(result);
                        }
                    }
                    #endregion only the edge exists
                    #region only the backwardedge exists
                    else if (HasIncomingVertices(currentVertexRight))
                    {
                        var result = CheckNextVerticesOfRightSide(ref currentVertexRight, ref currentNodeRight);

                        if (result != null)
                        {
                            return(result);
                        }
                    }
                    #endregion only the backwardedge exists
                }
                #endregion  both queues contain objects and both depths are not reached
                #region only left queue contain objects
                else if ((_QueueLeft.Count > 0) && (_DepthLeft <= _MaxDepthLeft))
                {
                    #region check if first element of queue is a dummy

                    if (LeftLevelCompleted())
                    {
                        continue;
                    }

                    #endregion check if first element of queue is a dummy

                    #region get first nodes of the queues

                    //hold the actual element of the queues
                    Node    currentNodeLeft;
                    IVertex currentVertexLeft;

                    //get the first Object of the queue
                    currentVertexLeft = _QueueLeft.Dequeue();
                    Tuple <long, long> currentLeft = new Tuple <long, long>(currentVertexLeft.VertexTypeID, currentVertexLeft.VertexID);

                    if (_VisitedNodesLeft.ContainsKey(currentLeft))
                    {
                        continue;
                    }

                    if (_VisitedNodesLeft.ContainsKey(currentLeft))
                    {
                        currentNodeLeft = _VisitedNodesLeft[currentLeft];
                    }
                    else
                    {
                        currentNodeLeft = new Node(currentLeft);
                    }

                    #endregion

                    #region check next vertices

                    if (currentVertexLeft.HasOutgoingEdge(_AttributeDefinition.ID))
                    {
                        var result = CheckNextVerticesOfLeftSide(ref currentVertexLeft, ref currentNodeLeft);

                        if (result != null)
                        {
                            return(result);
                        }
                    }

                    #endregion
                }
                #endregion only left queue contain objects
                #region only right queue contain objects
                else if ((_QueueRight.Count > 0) && (_DepthRight <= _MaxDepthRight))
                {
                    #region check if first element of the queue is a dummy

                    if (RightLevelCompleted())
                    {
                        continue;
                    }

                    #endregion check if first element of the queue is a dummy

                    #region get first nodes of the queues

                    //hold the actual element of the queues
                    Node    currentNodeRight;
                    IVertex currentVertexRight;

                    //get the first Object of the queue
                    currentVertexRight = _QueueRight.Dequeue();
                    Tuple <long, long> currentRight = new Tuple <long, long>(currentVertexRight.VertexTypeID, currentVertexRight.VertexID);

                    if (_VisitedNodesRight.ContainsKey(currentRight))
                    {
                        continue;
                    }

                    if (_VisitedNodesRight.ContainsKey(currentRight))
                    {
                        currentNodeRight = _VisitedNodesRight[currentRight];
                    }
                    else
                    {
                        currentNodeRight = new Node(currentRight);
                    }

                    #endregion

                    #region check next vertices

                    if (HasIncomingVertices(currentVertexRight))
                    {
                        var result = CheckNextVerticesOfRightSide(ref currentVertexRight, ref currentNodeRight);

                        if (result != null)
                        {
                            return(result);
                        }
                    }

                    #endregion
                }
                #endregion only right queue contain objects
                #region abort loop

                else
                {
                    break;
                }

                #endregion abort loop
            }

            #region nothing found
            if (_ShortestOnly && !_FindAll)
            {
                return(null);
            }
            #endregion

            //get result paths
            #region start TargetAnalyzer
            if (_ShortestOnly && _FindAll)
            {
                if (_ShortestPathLength > _MaxPathLength)
                {
                    _ShortestPathLength = _MaxPathLength;
                }

                return(new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths());
            }
            else
            {
                return(new TargetAnalyzer(_Root, _Target, _MaxPathLength, _ShortestOnly, _FindAll).GetPaths());
            }
            #endregion start TargetAnalyzer

            #endregion BidirectionalBFS
        }
Example #45
0
 /// <summary>
 /// DepthFirstSearch constructor with starting vertex.
 /// </summary>
 /// <param name="vertex">starting vertex</param>
 public DepthFirstSearch(IVertex vertex)
 {
     Origin        = vertex;
     _visitedStack = new Stack <IVertex>();
 }
Example #46
0
        PopulateGraph()
        {
            IGraph            oGraph    = m_oNodeXLControl.Graph;
            IVertexCollection oVertices = oGraph.Vertices;
            IEdgeCollection   oEdges    = oGraph.Edges;
            Double            dWidth    = this.Width;
            Double            dHeight   = this.Height;
            Random            oRandom   = new Random();

            // m_oNodeXLControl.Layout.Margin = 0;

            {
        #if false  // Two shapes only.
                IVertex oVertex1 = oVertices.Add();

                oVertex1.SetValue(ReservedMetadataKeys.PerVertexShape,
                                  VertexShape.Circle);

                oVertex1.SetValue(ReservedMetadataKeys.PerVertexRadius, 5.0F);
                oVertex1.SetValue(ReservedMetadataKeys.LockVertexLocation, true);
                oVertex1.Location = new System.Drawing.PointF(300, 300);

                oVertex1.SetValue(ReservedMetadataKeys.PerVertexLabel,
                                  "This is A: " + oVertex1.Location);

                IVertex oVertex2 = oVertices.Add();

                oVertex2.SetValue(ReservedMetadataKeys.PerVertexShape,
                                  VertexShape.Circle);

                oVertex2.SetValue(ReservedMetadataKeys.PerVertexRadius, 5.0F);
                oVertex2.SetValue(ReservedMetadataKeys.LockVertexLocation, true);
                oVertex2.Location = new System.Drawing.PointF(500, 300);

                oVertex2.SetValue(ReservedMetadataKeys.PerVertexLabel,
                                  "This is B: " + oVertex2.Location);

                IEdge oEdge = oEdges.Add(oVertex1, oVertex2, true);

                // oEdge.SetValue(ReservedMetadataKeys.PerEdgeWidth, 20F);

                m_oNodeXLControl.DrawGraph(true);

                return;
        #endif
            }

            {
        #if false  // Two labels only.
                IVertex oVertex1 = oVertices.Add();

                oVertex1.SetValue(ReservedMetadataKeys.PerVertexShape,
                                  VertexShape.Label);

                oVertex1.SetValue(ReservedMetadataKeys.PerVertexLabel,
                                  "This is a label.");

                oVertex1.SetValue(ReservedMetadataKeys.LockVertexLocation, true);
                oVertex1.Location = new System.Drawing.PointF(300, 300);

                IVertex oVertex2 = oVertices.Add();

                oVertex2.SetValue(ReservedMetadataKeys.PerVertexShape,
                                  VertexShape.Label);

                oVertex2.SetValue(ReservedMetadataKeys.PerVertexLabel,
                                  "This is another label.");

                oVertex2.SetValue(ReservedMetadataKeys.LockVertexLocation, true);
                oVertex2.Location = new System.Drawing.PointF(500, 100);

                oEdges.Add(oVertex1, oVertex2, true);

                m_oNodeXLControl.DrawGraph(true);

                return;
        #endif
            }

            Microsoft.NodeXL.Visualization.Wpf.VertexShape[] aeShapes
                = (Microsoft.NodeXL.Visualization.Wpf.VertexShape[])
                  Enum.GetValues(typeof(Microsoft.NodeXL.Visualization.Wpf.
                                        VertexShape));

            Int32 iShapes = aeShapes.Length;

            Int32 Vertices = 100;

            IVertex oFirstVertex = oVertices.Add();

            oFirstVertex.SetValue(ReservedMetadataKeys.PerVertexRadius, 4.0F);

            IVertex oPreviousVertex = oFirstVertex;

            for (Int32 i = 1; i < Vertices; i++)
            {
                IVertex     oVertex = oVertices.Add();
                VertexShape eShape  = aeShapes[oRandom.Next(iShapes)];
                oVertex.SetValue(ReservedMetadataKeys.PerVertexShape, eShape);

            #if false  // Hard-coded vertex shape.
                oVertex.SetValue(ReservedMetadataKeys.PerVertexShape,
                                 VertexDrawer.VertexShape.Diamond);
            #endif

            #if true  // Vertex color.
                oVertex.SetValue(ReservedMetadataKeys.PerColor,
                                 System.Windows.Media.Color.FromArgb(255,
                                                                     (Byte)oRandom.Next(256),
                                                                     (Byte)oRandom.Next(256),
                                                                     (Byte)oRandom.Next(256))
                                 );
            #endif

            #if true  // Vertex radius.
                Single fRadius = (Single)(
                    Microsoft.NodeXL.Visualization.Wpf.VertexDrawer.MinimumRadius +
                    (0.1 *
                     Microsoft.NodeXL.Visualization.Wpf.VertexDrawer.MaximumRadius
                     - Microsoft.NodeXL.Visualization.Wpf.VertexDrawer.MinimumRadius)
                    * oRandom.NextDouble());

                oVertex.SetValue(ReservedMetadataKeys.PerVertexRadius, fRadius);
            #endif

                if (true && oRandom.Next(20) == 0) // Image
                {
                    oVertex.SetValue(ReservedMetadataKeys.PerVertexShape,
                                     VertexShape.Image);

                    oVertex.SetValue(ReservedMetadataKeys.PerVertexImage,
                                     new System.Windows.Media.Imaging.BitmapImage(
                                         new Uri(oRandom.Next(2) == 1 ?
                                                 "..\\..\\Images\\TestImage1.gif" :
                                                 "..\\..\\Images\\TestImage2.jpg",
                                                 UriKind.Relative)));
                }

                if (eShape == VertexShape.Label)
                {
                    String sLabel = "This is a label";

                    if (oRandom.Next(2) == 0)
                    {
                        sLabel = LongLabel;
                    }

                    oVertex.SetValue(ReservedMetadataKeys.PerVertexLabel, sLabel);

                    /*
                     * oVertex.SetValue( ReservedMetadataKeys.PerColor,
                     *  System.Windows.Media.Color.FromArgb(255, 0, 0, 0) );
                     *
                     * oVertex.SetValue(
                     *
                     *  ReservedMetadataKeys.PerVertexLabelFillColor,
                     *      System.Windows.Media.Color.FromArgb(255, 200, 200,
                     *          200) );
                     *
                     * oVertex.SetValue(ReservedMetadataKeys.PerAlpha, (Single)128);
                     */
                }
                else
                {
                    String sAnnotation = "This is an annotation.";

                    oVertex.SetValue(ReservedMetadataKeys.PerVertexLabel,
                                     sAnnotation);
                }

                if (true && oRandom.Next(1) == 1) // Vertex visibility.
                {
                    oVertex.SetValue(ReservedMetadataKeys.Visibility,
                                     VisibilityKeyValue.Filtered);
                }

            #if false  // Vertex alpha.
                oVertex.SetValue(
                    ReservedMetadataKeys.PerAlpha, (Single)oRandom.Next(256));
            #endif

            #if false  // Vertex IsSelected.
                oVertex.SetValue(ReservedMetadataKeys.IsSelected, null);
            #endif

                oVertex.Location = new System.Drawing.PointF(
                    (Single)(dWidth * oRandom.NextDouble()),
                    (Single)(dHeight * oRandom.NextDouble())
                    );


                IEdge oEdge = oEdges.Add(oFirstVertex, oVertex, true);

                oEdge.SetValue(ReservedMetadataKeys.PerEdgeLabel,
                               "This is an edge label");


            #if false  // Edge color.
                oEdge.SetValue(ReservedMetadataKeys.PerColor,
                               System.Windows.Media.Color.FromArgb(255,
                                                                   (Byte)oRandom.Next(256),
                                                                   (Byte)oRandom.Next(256),
                                                                   (Byte)oRandom.Next(256))
                               );
            #endif

            #if false  // Edge width.
                Double dEdgeWidth = EdgeDrawer.MinimumWidth +
                                    (EdgeDrawer.MaximumWidth - EdgeDrawer.MinimumWidth)
                                    * oRandom.NextDouble();

                oEdge.SetValue(ReservedMetadataKeys.PerEdgeWidth, dEdgeWidth);
            #endif

            #if true  // Edge visibility.
                oEdge.SetValue(ReservedMetadataKeys.Visibility,
                               VisibilityKeyValue.Visible);
            #endif

            #if true  // Edge alpha.
                oEdge.SetValue(ReservedMetadataKeys.PerAlpha,
                               (Single)oRandom.Next(256));
            #endif

            #if false  // Edge IsSelected.
                oEdge.SetValue(ReservedMetadataKeys.IsSelected, null);
            #endif


            #if true
                if (oRandom.Next(1) == 0)
                {
                    IEdge oRandomEdge = oEdges.Add(oPreviousVertex, oVertex, true);

                #if true  // Edge label.
                    oRandomEdge.SetValue(ReservedMetadataKeys.PerEdgeLabel,
                                         "This is a random edge label");
                #endif
                }
            #endif

                oPreviousVertex = oVertex;
            }

            AddToolTipsToVertices();
            SetBackgroundImage();

            m_oNodeXLControl.DrawGraph(true);
        }
Example #47
0
        internal bool IsVisited(IVertex vertex)
        {
            ThrowIfVertexIsNull(vertex);

            return(_visits[vertex.Num].IsVisited);
        }
        IncidentEdgeShouldBeCounted
        (
            IEdge oIncidentEdge,
            IVertex oVertexInGroup1,
            Int32 iGroup1Index,
            Dictionary <Int32, Int32> oGroupIndexDictionary,
            Boolean bUseDirectedness,
            Boolean bGraphIsDirected,
            out Int32 iGroup2Index
        )
        {
            Debug.Assert(oIncidentEdge != null);
            Debug.Assert(oVertexInGroup1 != null);
            Debug.Assert(iGroup1Index >= 0);
            Debug.Assert(oGroupIndexDictionary != null);
            AssertValid();

            IVertex oVertex2 = oIncidentEdge.GetAdjacentVertex(oVertexInGroup1);

            if (!oGroupIndexDictionary.TryGetValue(
                    oVertex2.ID, out iGroup2Index))
            {
                // The edge's second vertex is not in a group.

                return(false);
            }

            Boolean bEdgesFirstVertexIsVertexInGroup1 =
                (oIncidentEdge.Vertex1 == oVertexInGroup1);

            if (iGroup1Index == iGroup2Index)
            {
                // The edge's vertices are in the same group.  Count the edge only
                // if its first vertex is oVertexInGroup1.  That way, when the same
                // edge is passed to this method again as an incident edge of the
                // edge's second vertex, it won't be counted again.

                return(bEdgesFirstVertexIsVertexInGroup1);
            }
            else if (!bUseDirectedness || !bGraphIsDirected)
            {
                // All edges between group 1 and group 2 should be counted in a
                // single IntergroupEdgeInfo object.  Count the edge only if its
                // second vertex is in a group whose index is greater than or equal
                // to the group index of its first vertex.  (The equal case handles
                // edges whose vertices are within the same group, including
                // self-loops.)  That way, when the same edge is passed to this
                // method again as an incident edge of the edge's second vertex, it
                // won't be counted again.

                return(iGroup2Index >= iGroup1Index);
            }
            else
            {
                // Edges from group 1 to group 2 should be returned in one object,
                // and edges from group 2 to group 1 should be returned in another
                // IntergroupEdgeInfo object.  Count the edge only if its first
                // vertex is in group 1.  That way, when the same edge is passed to
                // this method again as an incident edge of the edge's second
                // vertex, it won't be counted again.

                return(bEdgesFirstVertexIsVertexInGroup1);
            }
        }
Example #49
0
 /// <summary>
 /// Add an edge from this Vertex to inVertex of edge type looked up from label, if edge type does not yet exist it is created.
 /// </summary>
 /// <param name="label">The type of edge to create</param>
 /// <param name="inVertex">The head of the new edge</param>
 /// <returns>the new edge</returns>
 public IEdge AddEdge(string label, IVertex inVertex)
 {
     return(AddEdge(null, label, inVertex));
 }
Example #50
0
 public void RemoveVertex(IVertex vertex)
 {
     GraphContract.ValidateRemoveVertex(vertex);
     VerifyNativeElement(vertex);
     _baseGraph.RemoveVertex(((IdVertex)vertex).GetBaseVertex());
 }
 public static List <IVertex> Search(IGraph myGraph, IVertex mySource, IVertex myTarget, Func <IVertex, bool> myMatchingFunc = null)
 {
     return(Search(myGraph, mySource, myTarget, false, myMatchingFunc));
 }
        /// <summary>
        /// BFS for st-connectivity
        /// </summary>
        /// <param name="myGraph"></param>
        /// <param name="mySource"></param>
        /// <param name="myTarget"></param>
        /// <param name="myMatchingFunc"></param>
        /// <returns></returns>
        public static List <IVertex> Search(IGraph myGraph, IVertex mySource, IVertex myTarget, bool myInitGraph, Func <IVertex, bool> myMatchingFunc = null)
        {
            #region Init

            if (myInitGraph)
            {
                InitGraph(myGraph);
            }
            mySource[COLOR_ATTRIBUTE_KEY]       = Color.RED;
            mySource[PREDECESSOR_ATTRIBUTE_KEY] = null;
            myTarget[COLOR_ATTRIBUTE_KEY]       = Color.GREEN;
            myTarget[PREDECESSOR_ATTRIBUTE_KEY] = null;

            var doMatching = myMatchingFunc != null;

            // used to indicate that the target node has been found
            var done = false;

            // use Concurrent Queue for parallel access
            var from    = new List <IVertex>();
            var to      = new List <IVertex>();
            var lockObj = new Object();
            OrderablePartitioner <Tuple <int, int> > partitioner;

            #endregion

            #region BFS

            // enqueue the source vertex
            from.Add(mySource);

            while (from.Count > 0 && !done)
            {
                to          = new List <IVertex>();
                partitioner = Partitioner.Create(0, from.Count);

                // process queue in parallel
                Parallel.ForEach(
                    // the values to be aggregated
                    partitioner,
                    // local initial partial result
                    () => new List <IVertex>(),
                    // loop body
                    (range, loopState, partialResult) =>
                {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        IVertex u = from[i];
                        //Parallel.ForEach<IEdge>(u.OutgoingEdges, outEdge =>
                        foreach (var outEdge in u.OutgoingEdges)
                        {
                            // neighbour node
                            var v = outEdge.Target;
                            // get the color of that neighbour
                            var color = (Color)v[COLOR_ATTRIBUTE_KEY];

                            if (color == Color.WHITE)     // not the target
                            {
                                // set as visited (Color.RED)
                                v[COLOR_ATTRIBUTE_KEY] = Color.RED;
                                // set the predecessor
                                v[PREDECESSOR_ATTRIBUTE_KEY] = u;
                                // and enqueue that node (if matching condition == true)
                                if (doMatching)
                                {
                                    // matches condition?
                                    if (myMatchingFunc(v))
                                    {
                                        // matches, add to local set
                                        partialResult.Add(v);
                                    }
                                    // do nothing
                                }
                                else
                                {
                                    // no matching necessary, add to local set
                                    partialResult.Add(v);
                                }
                            }
                            else if (color == Color.GREEN)     // done
                            {
                                // finished
                                done = true;
                                // set the predecessor
                                v[PREDECESSOR_ATTRIBUTE_KEY] = u;
                            }
                            //});
                        }
                        u[COLOR_ATTRIBUTE_KEY] = Color.RED;
                    }

                    return(partialResult);
                },
                    //the final step of each local context
                    (localPartialSet) =>
                {
                    lock (lockObj)
                    {
                        // sloooooow
                        //to = to.Union<IVertex>(localPartialSet).ToList();
                        to.AddRange(localPartialSet);
                    }
                });

                from = to;
            }

            #endregion


            if (done)
            {
                return(PathConcatenation.ConcatPath(myTarget, PREDECESSOR_ATTRIBUTE_KEY));
            }

            return(null);
        }
Example #53
0
 /// <summary>
 /// Updates vertex
 /// </summary>
 /// <param name="v"></param>
 void IVertexProvider.UpdateVertex(IVertex v)
 {
     this.UpdateVertex((CustomVertex)v);
 }
Example #54
0
 /// <summary>
 /// Constructs a new named edge
 /// </summary>
 /// <param name="id"></param>
 /// <param name="source"></param>
 /// <param name="target"></param>
 public NamedEdge(int id, IVertex source, IVertex target)
     : base(id, source, target)
 {
 }
Example #55
0
        public static void Benchmark(String myExampleGraph,
                                     Int32 myRuns,
                                     Int32 myInnerRuns,
                                     List <Func <IGraph, IVertex, IVertex, Func <IVertex, bool>, List <IVertex> > > myBFSAlgos,
                                     bool myStore = false,
                                     Func <IVertex, bool> myMatchingFunc = null,
                                     Action <IGraph> myBeforeRunAction   = null,
                                     Action <IGraph> myAfterRunAction    = null)
        {
            IGraph g         = null;
            var    isGraphML = false;

            #region init graph

            g = InitGraph(myExampleGraph);

            if (g == null)
            {
                return;
            }

            // hack :/
            isGraphML = myExampleGraph.EndsWith(".xml");

            Console.WriteLine("Graph successfully loaded .. |V|={0}, |E|={1}", g.VertexCount, g.EdgeCount);

            #endregion

            #region runs

            // store the single results
            var runs      = new long[myBFSAlgos.Count, myRuns];
            var innerRuns = new long[myInnerRuns];

            var sw  = new Stopwatch();
            var sum = 0L;

            IVertex        source = null;
            IVertex        target = null;
            List <IVertex> path   = null;
            List <IVertex> path2  = null;

            for (int i = 0; i < myRuns; i++)
            {
                #region init source and target

                while (path == null)
                {
                    source = GetRandomNode(g, isGraphML);
                    target = GetRandomNode(g, isGraphML);

                    if (myBeforeRunAction != null)
                    {
                        myBeforeRunAction(g);
                    }

                    path = myBFSAlgos[0](g, source, target, myMatchingFunc);

                    if (path == null)
                    {
                        Console.WriteLine("random source and target are not connected, trying new ones");
                    }
                }

                Console.WriteLine("got a working path from {0} to {1} with length {2}...starting benchmark", source.UUID, target.UUID, path.Count);

                // k, got a connected source and target


                #endregion

                #region bench

                for (int j = 0; j < myBFSAlgos.Count; j++)
                {
                    for (int k = 0; k < myInnerRuns; k++)
                    {
                        #region before run init

                        if (myBeforeRunAction != null)
                        {
                            myBeforeRunAction(g);
                        }

                        #endregion

                        sw.Start();
                        path2 = myBFSAlgos[j](g, source, target, myMatchingFunc);
                        path2.LongCount();
                        sw.Stop();
                        innerRuns[k] = sw.ElapsedMilliseconds;



                        sw.Reset();

                        #region after run action

                        if (myAfterRunAction != null)
                        {
                            myAfterRunAction(g);
                        }

                        #endregion
                    }
                    runs[j, i] = innerRuns.Aggregate((a, b) => a + b) / myInnerRuns;

                    Console.WriteLine("Algorithm {0} took {1} ms (avg of {2} runs)", j, runs[j, i], myInnerRuns);
                }

                #endregion

                path = null;
            }

            #region calc avg time

            var res = CalculateResult(runs, myBFSAlgos.Count, myRuns);

            #endregion

            #endregion
        }
 public DistanceModel(IVertex <T> current, int distance, IVertex <T> previos)
 {
     _current = current;
     _dist    = distance;
     _previos = previos;
 }
 public IEdge AddEdge(object id, IVertex outVertex, IVertex inVertex, string label)
 {
     throw new InvalidOperationException(ReadOnlyTokens.MutateErrorMessage);
 }
 public void RemoveVertex(IVertex vertex)
 {
     GraphContract.ValidateRemoveVertex(vertex);
     throw new InvalidOperationException(ReadOnlyTokens.MutateErrorMessage);
 }
Example #59
0
 /// <summary>
 /// Gets a value indicating if the set of edges connected to v is empty
 /// </summary>
 /// <remarks>
 /// <para>
 /// Usually faster that calling <see cref="Degree"/>.
 /// </para>
 /// </remarks>
 /// <value>
 /// true if the adjacent edge set is empty, false otherwise.
 /// </value>
 /// <exception cref="ArgumentNullException">v is a null reference</exception>
 public bool AdjacentEdgesEmpty(IVertex v)
 {
     return(this.OutEdgesEmpty(v) && this.InEdgesEmpty(v));
 }
 public void ChangeCurrent(IVertex <T> vertex)
 {
     _current = vertex;
 }