private void add_edges(DataRowCollection edge_rows, IVertexCollection oVertices, IEdgeCollection oEdges)
        {
            String from;
            String to;

            foreach (DataRow row in edge_rows)
            {
                //Notice: "EdgeFromid" and "EdgeToid" should be edited
                from = row["FromID"].ToString();
                to = row["ToID"].ToString();

                // Add an edge
                IVertex oFrom = null;
                IVertex oTo = null;

                foreach (IVertex oVertex in oVertices)
                {
                    if (oVertex.Tag.ToString() == from)
                    {
                        oFrom = oVertex;
                    }

                    if (oVertex.Tag.ToString() == to)
                    {
                        oTo = oVertex;
                    }
                }
                IEdge oEdge1 = oEdges.Add(oFrom, oTo, true);
            }
        }
 //*************************************************************************
 //  Constructor: ConnectedComponentCalculatorTest()
 //
 /// <summary>
 /// Initializes a new instance of the <see
 /// cref="ConnectedComponentCalculatorTest" /> class.
 /// </summary>
 //*************************************************************************
 public ConnectedComponentCalculatorTest()
 {
     m_oConnectedComponentCalculator = null;
     m_oGraph = null;
     m_oVertices = null;
     m_oEdges = null;
 }
 public void SetUp()
 {
     m_oConnectedComponentCalculator = new ConnectedComponentCalculator();
     m_oGraph = new Graph();
     m_oVertices = m_oGraph.Vertices;
     m_oEdges = m_oGraph.Edges;
 }
        TestGraphContainsDuplicateEdges12()
        {
            // Undirected graph, duplicate null name, C.

            m_oDuplicateEdgeDetector =
                new DuplicateEdgeDetector(m_oUndirectedGraph);

            IEdgeCollection oEdges = m_oUndirectedGraph.Edges;

            oEdges.Add(m_oUndirectedVertexA, m_oUndirectedVertexB, false);
            oEdges.Add(m_oUndirectedVertexA, m_oUndirectedVertexA, false);
            oEdges.Add(m_oUndirectedVertexB, m_oUndirectedVertexB, false);
            oEdges.Add(m_oUndirectedVertexC, m_oUndirectedVertexD, false);
            oEdges.Add(m_oUndirectedVertexC, m_oUndirectedVertexWithNullName,
                       false);

            oEdges.Add(m_oUndirectedVertexWithNullName, m_oUndirectedVertexC,
                       false);

            Assert.IsFalse(m_oDuplicateEdgeDetector.GraphContainsDuplicateEdges);
            Assert.AreEqual(4, m_oDuplicateEdgeDetector.UniqueEdges);
            Assert.AreEqual(0, m_oDuplicateEdgeDetector.EdgesWithDuplicates);

            Assert.AreEqual(2, m_oDuplicateEdgeDetector.
                            TotalEdgesAfterMergingDuplicatesNoSelfLoops);
        }
Example #5
0
        AddEdgeToGraph
        (
            PajekEdgeData oEdgeData,
            IEdgeCollection oEdges,
            IVertex [] aoVertices,
            Boolean bDirected
        )
        {
            Debug.Assert(oEdges != null);
            Debug.Assert(aoVertices != null);

            Int32 iVertices = aoVertices.Length;

            Int32 iFirstVertexNumber  = oEdgeData.FirstVertexNumber;
            Int32 iSecondVertexNumber = oEdgeData.SecondVertexNumber;

            Debug.Assert(iFirstVertexNumber >= 1);
            Debug.Assert(iFirstVertexNumber <= iVertices);
            Debug.Assert(aoVertices[iFirstVertexNumber - 1] != null);

            Debug.Assert(iSecondVertexNumber >= 1);
            Debug.Assert(iSecondVertexNumber <= iVertices);
            Debug.Assert(aoVertices[iSecondVertexNumber - 1] != null);

            IEdge oEdge = oEdges.Add(aoVertices[iFirstVertexNumber - 1],
                                     aoVertices[iSecondVertexNumber - 1], bDirected);

            oEdge.SetValue(ReservedMetadataKeys.EdgeWeight, oEdgeData.Weight);
        }
Example #6
0
        TestGraphContainsDuplicateEdges13()
        {
            // Undirected graph, many duplicates.

            m_oDuplicateEdgeDetector =
                new DuplicateEdgeDetector(m_oUndirectedGraph);

            IEdgeCollection oEdges = m_oUndirectedGraph.Edges;

            oEdges.Add(m_oUndirectedVertexB, m_oUndirectedVertexA, false);
            oEdges.Add(m_oUndirectedVertexC, m_oUndirectedVertexD, false);
            oEdges.Add(m_oUndirectedVertexA, m_oUndirectedVertexA, false);
            oEdges.Add(m_oUndirectedVertexB, m_oUndirectedVertexB, false);
            oEdges.Add(m_oUndirectedVertexC, m_oUndirectedVertexD, false);
            oEdges.Add(m_oUndirectedVertexA, m_oUndirectedVertexB, false);
            oEdges.Add(m_oUndirectedVertexA, m_oUndirectedVertexB, false);
            oEdges.Add(m_oUndirectedVertexB, m_oUndirectedVertexA, false);
            oEdges.Add(m_oUndirectedVertexC, m_oUndirectedVertexD, false);

            Assert.IsTrue(m_oDuplicateEdgeDetector.GraphContainsDuplicateEdges);
            Assert.AreEqual(2, m_oDuplicateEdgeDetector.UniqueEdges);
            Assert.AreEqual(7, m_oDuplicateEdgeDetector.EdgesWithDuplicates);

            Assert.AreEqual(2, m_oDuplicateEdgeDetector.
                            TotalEdgesAfterMergingDuplicatesNoSelfLoops);
        }
Example #7
0
        TestIsParallelTo
        (
            GraphDirectedness eDirectedness,
            Int32 iEdge1Vertex1,
            Int32 iEdge1Vertex2,
            Boolean bEdge1IsDirected,
            Int32 iEdge2Vertex1,
            Int32 iEdge2Vertex2,
            Boolean bEdge2IsDirected,
            Boolean bExpectedEdge1IsParallelToEdge2
        )
        {
            const Int32 Vertices = 100;

            CreateGraph(eDirectedness, Vertices);

            IVertex oEdge1Vertex1 = m_aoVertices[iEdge1Vertex1];
            IVertex oEdge1Vertex2 = m_aoVertices[iEdge1Vertex2];

            IVertex oEdge2Vertex1 = m_aoVertices[iEdge2Vertex1];
            IVertex oEdge2Vertex2 = m_aoVertices[iEdge2Vertex2];

            IEdge oEdge1 =
                CreateEdge(oEdge1Vertex1, oEdge1Vertex2, bEdge1IsDirected);

            IEdge oEdge2 =
                CreateEdge(oEdge2Vertex1, oEdge2Vertex2, bEdge2IsDirected);

            IEdgeCollection oEdgeCollection = m_oGraph.Edges;

            oEdgeCollection.Add(oEdge1);
            oEdgeCollection.Add(oEdge2);

            Boolean bActualEdge1IsParallelToEdge2 = oEdge1.IsParallelTo(oEdge2);

            Assert.AreEqual(
                bExpectedEdge1IsParallelToEdge2, bActualEdge1IsParallelToEdge2);

            Boolean bActualEdge2IsParallelToEdge1 = oEdge2.IsParallelTo(oEdge1);

            Assert.AreEqual(
                bExpectedEdge1IsParallelToEdge2, bActualEdge2IsParallelToEdge1);

            Boolean bActualEdge1IsAntiparallelToEdge2 =
                oEdge1.IsAntiparallelTo(oEdge2);

            Assert.AreEqual(
                !bExpectedEdge1IsParallelToEdge2,
                bActualEdge1IsAntiparallelToEdge2
                );

            Boolean bActualEdge2IsAntiparallelToEdge1 =
                oEdge2.IsAntiparallelTo(oEdge1);

            Assert.AreEqual(
                !bExpectedEdge1IsParallelToEdge2,
                bActualEdge2IsAntiparallelToEdge1
                );
        }
Example #8
0
    public NavGraph(INodeCollection para_vertices,
	                IEdgeCollection para_edges,
	                INavAlgorithm para_navAlg)
    {
        vertices = para_vertices;
        edges = para_edges;
        navAlgorithm = para_navAlg;
    }
Example #9
0
        ParseEdges
        (
            IGraph oGraph,
            XmlNode oGraphXmlNode,
            XmlNamespaceManager oXmlNamespaceManager,
            Dictionary <String, IVertex> oVertexDictionary,
            Dictionary <String, GraphMLAttribute> oGraphMLAttributeDictionary
        )
        {
            Debug.Assert(oGraph != null);
            Debug.Assert(oGraphXmlNode != null);
            Debug.Assert(oXmlNamespaceManager != null);
            Debug.Assert(oVertexDictionary != null);
            Debug.Assert(oGraphMLAttributeDictionary != null);
            AssertValid();

            IEdgeCollection oEdges = oGraph.Edges;

            Boolean bGraphIsDirected =
                (oGraph.Directedness == GraphDirectedness.Directed);

            foreach (XmlNode oEdgeXmlNode in oGraphXmlNode.SelectNodes(
                         GraphMLPrefix + ":edge", oXmlNamespaceManager))
            {
                IVertex oVertex1, oVertex2;

                if (
                    !TryGraphMLNodeIDToVertex(oEdgeXmlNode, "source",
                                              oVertexDictionary, out oVertex1)
                    ||
                    !TryGraphMLNodeIDToVertex(oEdgeXmlNode, "target",
                                              oVertexDictionary, out oVertex2)
                    )
                {
                    // From the GraphML Primer:
                    //
                    // For applications which can not handle nested graphs the
                    // fall-back behaviour is to ignore nodes which are not
                    // contained in the top-level graph and to ignore edges which
                    // have do not have both endpoints in the top-level graph.

                    continue;
                }

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

                String sID;

                if (XmlUtil2.TrySelectSingleNodeAsString(oEdgeXmlNode, "@id",
                                                         null, out sID))
                {
                    oEdge.Name = sID;
                }

                ParseGraphMLAttributeValues(oEdgeXmlNode, oXmlNamespaceManager,
                                            oEdge, false, oGraphMLAttributeDictionary);
            }
        }
Example #10
0
        /**
         * Constructs a graph instance.
         *
         * @param edges  An instance of IEdgeCollection interface
         *               that will store edges for this graph.
         * @param graph  A graph from which to copy the vertices.
         */
        protected GraphBase(IEdgeCollection edges, GraphBase <VertexT, EdgeT> graph)
        {
            Debug.Assert(edges != null);

            Vertices = new VertexT[graph.Vertices.Length];
            graph.Vertices.CopyTo(Vertices, 0);
            Edges = edges;
            Size  = graph.Size;
        }
Example #11
0
        TryCalculateGraphMetrics
        (
            IGraph graph,
            BackgroundWorker backgroundWorker,
            out Dictionary <Int32, Boolean> graphMetrics
        )
        {
            Debug.Assert(graph != null);
            AssertValid();

            IEdgeCollection oEdges = graph.Edges;

            // The key is an IEdge.ID and the value is a Boolean that indicates
            // whether the edge is reciprocated.

            Dictionary <Int32, Boolean> oReciprocationFlags =
                new Dictionary <Int32, Boolean>(oEdges.Count);

            graphMetrics = oReciprocationFlags;

            // The key is the combined IDs of the edge's vertices.

            HashSet <Int64> oVertexIDPairs = new HashSet <Int64>();

            if (graph.Directedness == GraphDirectedness.Directed)
            {
                foreach (IEdge oEdge in oEdges)
                {
                    oVertexIDPairs.Add(GetDictionaryKey(
                                           oEdge.Vertex1, oEdge.Vertex2));
                }

                if (!ReportProgressAndCheckCancellationPending(
                        1, 2, backgroundWorker))
                {
                    return(false);
                }

                foreach (IEdge oEdge in oEdges)
                {
                    Boolean bEdgeIsReciprocated = false;

                    if (!oEdge.IsSelfLoop)
                    {
                        Int64 i64ReversedVerticesKey = GetDictionaryKey(
                            oEdge.Vertex2, oEdge.Vertex1);

                        bEdgeIsReciprocated =
                            oVertexIDPairs.Contains(i64ReversedVerticesKey);
                    }

                    oReciprocationFlags.Add(oEdge.ID, bEdgeIsReciprocated);
                }
            }

            return(true);
        }
 public EdgeList(IEdgeCollection edges, bool isDirected, bool allowParallelEdges)
 {
     if (edges == null)
     {
         throw new ArgumentNullException("edge collection");
     }
     this.edges = edges;
     this.isDirected = isDirected;
     this.allowParallelEdges = allowParallelEdges;
 }
Example #13
0
 /// <summary>
 /// Collects edge data from all edges in the specified collection.
 /// Used by the <see cref="BundleAllEdges"/> method.
 /// </summary>
 ///
 /// <param name="edges">
 /// Collection of edges whose data should be collected
 /// </param>
 private void AddDataForAllEdges(IEdgeCollection edges)
 {
     foreach (IEdge e in edges)
     {
         if (!e.IsSelfLoop)
         {
             AddEdgeData(e);
         }
     }
 }
Example #14
0
        CreateGraph
        (
            IVertex [] aoVertices,
            List <PajekEdgeData> oUndirectedEdgeData,
            List <PajekEdgeData> oDirectedEdgeData
        )
        {
            Debug.Assert(oUndirectedEdgeData != null);
            Debug.Assert(oDirectedEdgeData != null);

            GraphDirectedness eDirectedness = GraphDirectedness.Undirected;

            Int32 iVertices        = 0;
            Int32 iUndirectedEdges = oUndirectedEdgeData.Count;
            Int32 iDirectedEdges   = oDirectedEdgeData.Count;

            if (iUndirectedEdges > 0 && iDirectedEdges > 0)
            {
                eDirectedness = GraphDirectedness.Mixed;
            }
            else if (iDirectedEdges > 0)
            {
                eDirectedness = GraphDirectedness.Directed;
            }

            IGraph            oGraph    = new Graph(eDirectedness);
            IVertexCollection oVertices = oGraph.Vertices;
            IEdgeCollection   oEdges    = oGraph.Edges;

            if (aoVertices != null)
            {
                // Populate the vertex collection.

                foreach (IVertex oVertex in aoVertices)
                {
                    oVertices.Add(oVertex);
                }

                iVertices = aoVertices.Length;
            }

            // Populate the edges collection.

            foreach (PajekEdgeData oEdgeData in oUndirectedEdgeData)
            {
                AddEdgeToGraph(oEdgeData, oEdges, aoVertices, false);
            }

            foreach (PajekEdgeData oEdgeData in oDirectedEdgeData)
            {
                AddEdgeToGraph(oEdgeData, oEdges, aoVertices, true);
            }

            return(oGraph);
        }
Example #15
0
 /// <summary>
 /// Collects edge data from all edges in the specified collection.
 /// Used for edges that already have control points metadata.
 /// </summary>
 ///
 /// <param name="edges">
 /// Collection of edges whose data should be collected
 /// </param>
 private void AddAllExistingData(IEdgeCollection edges)
 {
     subdivisionPoints = 0;
     foreach (IEdge e in edges)
     {
         if (!e.IsSelfLoop)
         {
             AddExistingData(e);
         }
     }
 }
Example #16
0
        //*************************************************************************
        //  Constructor: EdgeCollectionTest()
        //
        /// <summary>
        /// Initializes a new instance of the <see cref="EdgeCollectionTest" />
        /// class.
        /// </summary>
        //*************************************************************************
        public EdgeCollectionTest()
        {
            m_oEdgeCollection = null;
            m_oGraph = null;

            m_bEdgeAdded = false;
            m_oAddedEdge = null;

            m_bEdgeRemoved = false;
            m_oRemovedEdge = null;
        }
Example #17
0
        /**
         * Constructs a graph instance.
         *
         * @param edges             An instance of IEdgeCollection interface
         *                          that will store edges for this graph.
         * @param initial_capacity  Determines how much memory to reserve at
         *                          construction time. The larger this value
         *                          the fewer time the underlying collections
         *                          will have to be resized as the graph grows.
         *
         * @throws ArgumentException if initial_capacity is negative or zero.
         */
        protected GraphBase(IEdgeCollection edges, int initial_capacity = 10)
        {
            Debug.Assert(edges != null);

            if (initial_capacity <= 0)
            {
                throw new ArgumentException("initial_capacity must be positive");
            }

            Vertices = new VertexT[initial_capacity];
            Edges    = edges;
            Size     = 0;
        }
Example #18
0
        /// <summary>
        /// Builds an EdgeListGraph out of a edges collection
        /// </summary>
        /// <param name="edges"></param>
        /// <param name="isDirected"></param>
        /// <param name="allowParallelEdges"></param>
        public EdgeList(
            IEdgeCollection edges,
            bool isDirected,
            bool allowParallelEdges
            )
        {
            if (edges == null)
            {
                throw new ArgumentNullException("edge collection");
            }

            this.edges              = edges;
            this.isDirected         = isDirected;
            this.allowParallelEdges = allowParallelEdges;
        }
 /// <summary>
 /// Construct an edge that filters out edge in circuit
 /// and temporary circuit
 /// </summary>
 /// <param name="circuit"></param>
 /// <param name="temporaryCircuit"></param>
 public NotInCircuitEdgePredicate(
     IEdgeCollection circuit,
     IEdgeCollection temporaryCircuit
     )
 {
     if (circuit == null)
     {
         throw new ArgumentNullException("circuit");
     }
     if (temporaryCircuit == null)
     {
         throw new ArgumentNullException("temporaryCircuit");
     }
     this.circuit          = circuit;
     this.temporaryCircuit = temporaryCircuit;
 }
Example #20
0
        TestGetVertexIDPair6()
        {
            // Undirected graph, useDirectedness = false.

            IGraph            oUndirectedGraph    = new Graph(GraphDirectedness.Undirected);
            IVertexCollection oUndirectedVertices = oUndirectedGraph.Vertices;

            IVertex oUndirectedVertexA = oUndirectedVertices.Add();
            IVertex oUndirectedVertexB = oUndirectedVertices.Add();
            IVertex oUndirectedVertexC = oUndirectedVertices.Add();
            IVertex oUndirectedVertexD = oUndirectedVertices.Add();

            IEdgeCollection oEdges = oUndirectedGraph.Edges;

            IEdge oEdge1 = oEdges.Add(oUndirectedVertexA, oUndirectedVertexB,
                                      false);

            IEdge oEdge2 = oEdges.Add(oUndirectedVertexA, oUndirectedVertexB,
                                      false);

            IEdge oEdge3 = oEdges.Add(oUndirectedVertexB, oUndirectedVertexA,
                                      false);

            IEdge oEdge4 = oEdges.Add(oUndirectedVertexA, oUndirectedVertexC,
                                      false);

            Int64 i64VertexIDPair1 = EdgeUtil.GetVertexIDPair(oEdge1, false);
            Int64 i64VertexIDPair2 = EdgeUtil.GetVertexIDPair(oEdge2, false);
            Int64 i64VertexIDPair3 = EdgeUtil.GetVertexIDPair(oEdge3, false);
            Int64 i64VertexIDPair4 = EdgeUtil.GetVertexIDPair(oEdge4, false);

            // Make sure that the left-shift worked.

            Assert.IsTrue(i64VertexIDPair1 > Int32.MaxValue);
            Assert.IsTrue(i64VertexIDPair2 > Int32.MaxValue);
            Assert.IsTrue(i64VertexIDPair3 > Int32.MaxValue);
            Assert.IsTrue(i64VertexIDPair4 > Int32.MaxValue);

            Assert.AreEqual(i64VertexIDPair1, i64VertexIDPair2);
            Assert.AreEqual(i64VertexIDPair1, i64VertexIDPair3);
            Assert.AreNotEqual(i64VertexIDPair1, i64VertexIDPair4);

            Assert.AreEqual(i64VertexIDPair2, i64VertexIDPair3);
            Assert.AreNotEqual(i64VertexIDPair2, i64VertexIDPair4);

            Assert.AreNotEqual(i64VertexIDPair3, i64VertexIDPair4);
        }
        TestMoveNext4()
        {
            // N vertices, connect last vertex to all other vertices.

            const Int32 Vertices = 2000;

            // Add the vertices.

            IVertex[] aoVertices = AddVertices(Vertices);

            // Connect the first vertex to all other vertices.

            Int32 iEdges = Vertices - 1;

            IEdge[] aoAddedEdges = new IEdge[iEdges];

            IVertex oVertex1 = aoVertices[Vertices - 1];

            IEdgeCollection oEdgeCollection = m_oGraph.Edges;

            Int32 i;

            for (i = 0; i < Vertices - 1; i++)
            {
                IVertex oVertex2 = aoVertices[i];

                IEdge oEdge = new Edge(oVertex1, oVertex2, false);

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

                aoAddedEdges[i] = oEdge;

                oEdgeCollection.Add(oEdge);
            }

            // Enumerate the edges using m_oEnumerator and compare the enumerated
            // edges with the edges that were added to the edge collection.

            EnumerateAndCompare(aoAddedEdges);

            // Reset the enumerator and repeat.

            m_oEnumerator.Reset();

            EnumerateAndCompare(aoAddedEdges);
        }
        SetUp()
        {
            m_oGraph = new Graph();

            Debug.Assert(m_oGraph.Edges is EdgeCollection);

            IEdgeCollection oEdgeCollection = m_oGraph.Edges;

            Debug.Assert(oEdgeCollection.GetEnumerator() is
                         EdgeCollection.Enumerator);

            m_oEnumerator =
                (EdgeCollection.Enumerator)oEdgeCollection.GetEnumerator();

            Debug.Assert(m_oGraph.Vertices is VertexCollection);

            m_oVertexCollection = m_oGraph.Vertices;
        }
Example #23
0
        TestGetVertexIDPair()
        {
            // Directed graph.

            IGraph            oDirectedGraph    = new Graph(GraphDirectedness.Directed);
            IVertexCollection oDirectedVertices = oDirectedGraph.Vertices;

            IVertex oDirectedVertexA = oDirectedVertices.Add();
            IVertex oDirectedVertexB = oDirectedVertices.Add();
            IVertex oDirectedVertexC = oDirectedVertices.Add();
            IVertex oDirectedVertexD = oDirectedVertices.Add();

            IEdgeCollection oEdges = oDirectedGraph.Edges;

            IEdge oEdge1 = oEdges.Add(oDirectedVertexA, oDirectedVertexB, true);
            IEdge oEdge2 = oEdges.Add(oDirectedVertexA, oDirectedVertexB, true);
            IEdge oEdge3 = oEdges.Add(oDirectedVertexB, oDirectedVertexA, true);
            IEdge oEdge4 = oEdges.Add(oDirectedVertexA, oDirectedVertexC, true);

            Int64 i64VertexIDPair1 = EdgeUtil.GetVertexIDPair(oEdge1);
            Int64 i64VertexIDPair2 = EdgeUtil.GetVertexIDPair(oEdge2);
            Int64 i64VertexIDPair3 = EdgeUtil.GetVertexIDPair(oEdge3);
            Int64 i64VertexIDPair4 = EdgeUtil.GetVertexIDPair(oEdge4);

            // Make sure that the left-shift worked.

            Assert.IsTrue(i64VertexIDPair1 > Int32.MaxValue);
            Assert.IsTrue(i64VertexIDPair2 > Int32.MaxValue);
            Assert.IsTrue(i64VertexIDPair3 > Int32.MaxValue);
            Assert.IsTrue(i64VertexIDPair4 > Int32.MaxValue);

            Assert.AreEqual(i64VertexIDPair1, i64VertexIDPair2);
            Assert.AreNotEqual(i64VertexIDPair1, i64VertexIDPair3);
            Assert.AreNotEqual(i64VertexIDPair1, i64VertexIDPair4);

            Assert.AreNotEqual(i64VertexIDPair2, i64VertexIDPair3);
            Assert.AreNotEqual(i64VertexIDPair2, i64VertexIDPair4);

            Assert.AreNotEqual(i64VertexIDPair3, i64VertexIDPair4);
        }
Example #24
0
        TestGraphContainsDuplicateEdges()
        {
            // Directed graph, no duplicate edges.

            m_oDuplicateEdgeDetector = new DuplicateEdgeDetector(m_oDirectedGraph);

            IEdgeCollection oEdges = m_oDirectedGraph.Edges;

            oEdges.Add(m_oDirectedVertexA, m_oDirectedVertexB, true);
            oEdges.Add(m_oDirectedVertexB, m_oDirectedVertexA, true);
            oEdges.Add(m_oDirectedVertexA, m_oDirectedVertexA, true);
            oEdges.Add(m_oDirectedVertexB, m_oDirectedVertexB, true);
            oEdges.Add(m_oDirectedVertexC, m_oDirectedVertexD, true);
            oEdges.Add(m_oDirectedVertexC, m_oDirectedVertexWithNullName, true);

            Assert.IsFalse(m_oDuplicateEdgeDetector.GraphContainsDuplicateEdges);
            Assert.AreEqual(6, m_oDuplicateEdgeDetector.UniqueEdges);
            Assert.AreEqual(0, m_oDuplicateEdgeDetector.EdgesWithDuplicates);

            Assert.AreEqual(4, m_oDuplicateEdgeDetector.
                            TotalEdgesAfterMergingDuplicatesNoSelfLoops);
        }
Example #25
0
        MakeGraphComplete
        (
            IGraph oGraph,
            IVertex [] aoVertices,
            Boolean bDirected
        )
        {
            Debug.Assert(oGraph != null);
            Debug.Assert(aoVertices != null);

            Int32 iVertices = aoVertices.Length;

            Int32 iEdges = GetEdgeCountForCompleteGraph(iVertices);

            IEdge[] aoAddedEdges = new IEdge[iEdges];

            IEdgeCollection oEdgeCollection = oGraph.Edges;

            Int32 iEdge = 0;

            for (Int32 i = 0; i < iVertices; i++)
            {
                for (Int32 j = i + 1; j < iVertices; j++)
                {
                    IEdge oEdge = oEdgeCollection.Add(
                        aoVertices[i], aoVertices[j], bDirected);

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

                    aoAddedEdges[iEdge] = oEdge;

                    iEdge++;
                }
            }

            Debug.Assert(oEdgeCollection.Count == iEdges);

            return(aoAddedEdges);
        }
Example #26
0
        TestLargeGraph()
        {
            // Create a large graph, make sure there are no exceptions or
            // assertions.

            const Int32 Vertices = 1000000;

            const Int32 Edges = 100000;

            IVertex [] aoVertices = TestGraphUtil.AddVertices(m_oGraph, Vertices);

            Random oRandom = new Random(1);

            for (Int32 i = 0; i < Edges; i++)
            {
                IVertex oVertex1 = aoVertices[oRandom.Next(Vertices)];
                IVertex oVertex2 = aoVertices[oRandom.Next(Vertices)];

                IEdgeCollection oEdgeCollection = m_oGraph.Edges;

                oEdgeCollection.Add(oVertex1, oVertex2);
            }

            Assert.AreEqual(Vertices, m_oGraph.Vertices.Count);
            Assert.AreEqual(Edges, m_oGraph.Edges.Count);

            m_oGraph.Edges.Clear();

            Assert.AreEqual(Vertices, m_oGraph.Vertices.Count);
            Assert.AreEqual(0, m_oGraph.Edges.Count);

            m_oGraph.Vertices.Clear();

            Assert.AreEqual(0, m_oGraph.Vertices.Count);
            Assert.AreEqual(0, m_oGraph.Edges.Count);
        }
 public void SetUp()
 {
     m_oGraph = null;
     m_oVertices = null;
     m_oEdges = null;
 }
        //*************************************************************************
        //  Method: CreateGraph()
        //
        /// <summary>
        /// Creates the original graph.
        /// </summary>
        ///
        /// <param name="bDirected">
        /// true for directed, false for undirected.
        /// </param>
        //*************************************************************************
        protected void CreateGraph(
            Boolean bDirected
            )
        {
            m_oGraph = new Graph(bDirected ? GraphDirectedness.Directed :
            GraphDirectedness.Undirected);

            m_oVertices = m_oGraph.Vertices;
            m_oEdges = m_oGraph.Edges;
        }
Example #29
0
        CloneVertexIntoSubgraph
        (
            IVertex oOriginalVertex,
            IGraph oSubgraph,
            Decimal decLevels
        )
        {
            Debug.Assert(oOriginalVertex != null);
            Debug.Assert(oSubgraph != null);
            Debug.Assert(decLevels >= 0);
            AssertValid();

            // Get the original vertices and edges to clone.  For the vertex
            // dictionary, the key is the IVertex and the value is the vertex's
            // level, which is the distance of the vertex from oOriginalVertex.
            // For the edge HashSet, the key is the IEdge.

            Dictionary <IVertex, Int32> oOriginalVerticesToClone;
            HashSet <IEdge>             oOriginalEdgesToClone;

            SubgraphCalculator.GetSubgraph(oOriginalVertex, decLevels, true,
                                           out oOriginalVerticesToClone, out oOriginalEdgesToClone);

            // Clone the vertices.  This dictionary maps the IDs of the original
            // vertices to their clones.

            Dictionary <Int32, IVertex> oOriginalToSubgraphVertexMapper =
                new Dictionary <Int32, IVertex>();

            IVertexCollection oSubgraphVertices = oSubgraph.Vertices;

            foreach (IVertex oOriginalVertexToClone in
                     oOriginalVerticesToClone.Keys)
            {
                IVertex oSubgraphVertex =
                    oOriginalVertexToClone.Clone(false, false);

                oSubgraphVertices.Add(oSubgraphVertex);

                oOriginalToSubgraphVertexMapper.Add(oOriginalVertexToClone.ID,
                                                    oSubgraphVertex);
            }

            // This dictionary is no longer needed.

            oOriginalVerticesToClone.Clear();
            oOriginalVerticesToClone = null;

            // Clone the edges.

            IEdgeCollection oSubgraphEdges = oSubgraph.Edges;

            foreach (IEdge oOriginalEdgeToClone in oOriginalEdgesToClone)
            {
                IVertex [] aoOriginalVertices = oOriginalEdgeToClone.Vertices;

                IVertex oSubgraphVertex1 =
                    oOriginalToSubgraphVertexMapper[aoOriginalVertices[0].ID];

                IVertex oSubgraphVertex2 =
                    oOriginalToSubgraphVertexMapper[aoOriginalVertices[1].ID];

                oSubgraphEdges.Add(oSubgraphVertex1, oSubgraphVertex2,
                                   oOriginalEdgeToClone.IsDirected);
            }

            Debug.Assert(oOriginalToSubgraphVertexMapper.ContainsKey(
                             oOriginalVertex.ID));

            return(oOriginalToSubgraphVertexMapper[oOriginalVertex.ID]);
        }
Example #30
0
        ImportWorkbookIntoGraph
        (
            Worksheet oSourceWorksheet,
            Range oNonEmptySourceRange,
            Int32 iColumnNumberToUseForVertex1OneBased,
            Int32 iColumnNumberToUseForVertex2OneBased,
            ICollection <Int32> oEdgeColumnNumbersToImportOneBased,
            ICollection <Int32> oVertex1ColumnNumbersToImportOneBased,
            ICollection <Int32> oVertex2ColumnNumbersToImportOneBased,
            Boolean bSourceColumnsHaveHeaders
        )
        {
            Debug.Assert(oSourceWorksheet != null);
            Debug.Assert(oNonEmptySourceRange != null);
            Debug.Assert(iColumnNumberToUseForVertex1OneBased >= 1);
            Debug.Assert(iColumnNumberToUseForVertex2OneBased >= 1);
            Debug.Assert(oEdgeColumnNumbersToImportOneBased != null);
            Debug.Assert(oVertex1ColumnNumbersToImportOneBased != null);
            Debug.Assert(oVertex2ColumnNumbersToImportOneBased != null);
            AssertValid();

            String [] asWorkbookColumnNames = GetWorkbookColumnNames(
                oSourceWorksheet, oNonEmptySourceRange, bSourceColumnsHaveHeaders);

            Int32 iColumns = oNonEmptySourceRange.Columns.Count;

            Int32 iFirstNonEmptyColumnOneBased =
                oNonEmptySourceRange.Columns.Column;

            if (bSourceColumnsHaveHeaders)
            {
                // Skip the header row.

                if (oNonEmptySourceRange.Rows.Count < 2)
                {
                    OnInvalidSourceWorkbook(
                        "If the columns in the other workbook have headers, then"
                        + " there must be at least two rows.",

                        oSourceWorksheet, 1, 1
                        );
                }

                ExcelUtil.OffsetRange(ref oNonEmptySourceRange, 1, 0);

                ExcelUtil.ResizeRange(ref oNonEmptySourceRange,
                                      oNonEmptySourceRange.Rows.Count - 1, iColumns);
            }

            IGraph            oGraph    = new Graph(GraphDirectedness.Undirected);
            IVertexCollection oVertices = oGraph.Vertices;
            IEdgeCollection   oEdges    = oGraph.Edges;

            // The key is a vertex name and the value is the corresponding IVertex
            // object.

            Dictionary <String, IVertex> oVertexNameDictionary =
                new Dictionary <String, IVertex>();

            foreach (Range oSubrange in
                     ExcelRangeSplitter.SplitRange(oNonEmptySourceRange, 500))
            {
                Object [,] oSubrangeValues = ExcelUtil.GetRangeValues(oSubrange);
                Int32 iSubrangeRows = oSubrangeValues.GetUpperBound(0);

                for (Int32 iRowOneBased = 1; iRowOneBased <= iSubrangeRows;
                     iRowOneBased++)
                {
                    String sVertex1Name, sVertex2Name;

                    if (
                        !ExcelUtil.TryGetNonEmptyStringFromCell(oSubrangeValues,
                                                                iRowOneBased,
                                                                iColumnNumberToUseForVertex1OneBased -
                                                                iFirstNonEmptyColumnOneBased + 1,
                                                                out sVertex1Name)
                        ||
                        !ExcelUtil.TryGetNonEmptyStringFromCell(oSubrangeValues,
                                                                iRowOneBased,
                                                                iColumnNumberToUseForVertex2OneBased -
                                                                iFirstNonEmptyColumnOneBased + 1,
                                                                out sVertex2Name)
                        )
                    {
                        continue;
                    }

                    IVertex oVertex1 = WorksheetReaderBase.VertexNameToVertex(
                        sVertex1Name, oVertices, oVertexNameDictionary);

                    IVertex oVertex2 = WorksheetReaderBase.VertexNameToVertex(
                        sVertex2Name, oVertices, oVertexNameDictionary);

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

                    // Add the edge and vertex attributes.

                    AddAttributeValuesToEdgeOrVertex(asWorkbookColumnNames,
                                                     oSubrangeValues, iRowOneBased,
                                                     iFirstNonEmptyColumnOneBased,
                                                     oEdgeColumnNumbersToImportOneBased, oEdge);

                    AddAttributeValuesToEdgeOrVertex(asWorkbookColumnNames,
                                                     oSubrangeValues, iRowOneBased,
                                                     iFirstNonEmptyColumnOneBased,
                                                     oVertex1ColumnNumbersToImportOneBased, oVertex1);

                    AddAttributeValuesToEdgeOrVertex(asWorkbookColumnNames,
                                                     oSubrangeValues, iRowOneBased,
                                                     iFirstNonEmptyColumnOneBased,
                                                     oVertex2ColumnNumbersToImportOneBased, oVertex2);
                }
            }

            // Store metadata on the graph indicating the sets of keys that may be
            // present on the graph's edges and vertices.

            oGraph.SetValue(ReservedMetadataKeys.AllEdgeMetadataKeys,

                            GetColumnNamesToImport(oNonEmptySourceRange,
                                                   asWorkbookColumnNames, oEdgeColumnNumbersToImportOneBased)
                            );

            List <Int32> oVertexColumnNumbersToImportOneBased = new List <Int32>();

            oVertexColumnNumbersToImportOneBased.AddRange(
                oVertex1ColumnNumbersToImportOneBased);

            oVertexColumnNumbersToImportOneBased.AddRange(
                oVertex2ColumnNumbersToImportOneBased);

            oGraph.SetValue(ReservedMetadataKeys.AllVertexMetadataKeys,

                            GetColumnNamesToImport(oNonEmptySourceRange, asWorkbookColumnNames,
                                                   oVertexColumnNumbersToImportOneBased)
                            );

            return(oGraph);
        }
    AddEdgeToGraph
    (
        PajekEdgeData oEdgeData,
        IEdgeCollection oEdges,
        IVertex [] aoVertices,
        Boolean bDirected
    )
    {
        Debug.Assert(oEdges != null);
        Debug.Assert(aoVertices != null);

        Int32 iVertices = aoVertices.Length;

        Int32 iFirstVertexNumber = oEdgeData.FirstVertexNumber;
        Int32 iSecondVertexNumber = oEdgeData.SecondVertexNumber;

        Debug.Assert(iFirstVertexNumber >= 1);
        Debug.Assert(iFirstVertexNumber <= iVertices);
        Debug.Assert(aoVertices[iFirstVertexNumber - 1] != null);

        Debug.Assert(iSecondVertexNumber >= 1);
        Debug.Assert(iSecondVertexNumber <= iVertices);
        Debug.Assert(aoVertices[iSecondVertexNumber - 1] != null);

        IEdge oEdge = oEdges.Add(aoVertices[iFirstVertexNumber - 1],
            aoVertices[iSecondVertexNumber - 1], bDirected);

        oEdge.SetValue(ReservedMetadataKeys.EdgeWeight, oEdgeData.Weight);
    }
Example #32
0
        public void TearDown()
        {
            m_oEdgeCollection = null;
            m_oGraph = null;

            m_bEdgeAdded = false;
            m_oAddedEdge = null;

            m_bEdgeRemoved = false;
            m_oRemovedEdge = null;
        }
Example #33
0
        CountEdges()
        {
            AssertValid();

            if (m_bEdgesCounted)
            {
                return;
            }

            m_iUniqueEdges         = 0;
            m_iEdgesWithDuplicates = 0;

            IEdgeCollection oEdges = m_oGraph.Edges;

            Boolean bGraphIsDirected =
                (m_oGraph.Directedness == GraphDirectedness.Directed);

            // Create a dictionary of vertex name pairs.  The key is the vertex
            // name pair and the value is true if the edge has duplicates or false
            // if it doesn't.

            Dictionary <String, Boolean> oVertexNamePairs =
                new Dictionary <String, Boolean>(oEdges.Count);

            foreach (IEdge oEdge in oEdges)
            {
                IVertex [] aoVertices   = oEdge.Vertices;
                String     sVertex0Name = aoVertices[0].Name;
                String     sVertex1Name = aoVertices[1].Name;

                if (String.IsNullOrEmpty(sVertex0Name) ||
                    String.IsNullOrEmpty(sVertex1Name))
                {
                    continue;
                }

                String sVertexNamePair = Edge.GetVertexNamePair(
                    sVertex0Name, sVertex1Name, bGraphIsDirected);

                Boolean bEdgeHasDuplicate;

                if (oVertexNamePairs.TryGetValue(sVertexNamePair,
                                                 out bEdgeHasDuplicate))
                {
                    if (!bEdgeHasDuplicate)
                    {
                        // This is the edge's first duplicate.

                        m_iUniqueEdges--;
                        m_iEdgesWithDuplicates++;

                        oVertexNamePairs[sVertexNamePair] = true;
                    }

                    m_iEdgesWithDuplicates++;
                }
                else
                {
                    m_iUniqueEdges++;

                    oVertexNamePairs.Add(sVertexNamePair, false);
                }
            }

            m_iTotalEdgesAfterMergingDuplicatesNoSelfLoops = 0;

            foreach (String sVertexNamePair in oVertexNamePairs.Keys)
            {
                String [] asVertexNames = sVertexNamePair.Split(
                    Edge.VertexNamePairSeparator);

                Debug.Assert(asVertexNames.Length == 2);

                if (asVertexNames[0] != asVertexNames[1])
                {
                    m_iTotalEdgesAfterMergingDuplicatesNoSelfLoops++;
                }
            }

            m_bEdgesCounted = true;

            AssertValid();
        }
 /// <summary>
 /// Collects edge data from all edges in the specified collection.
 /// Used for edges that already have control points metadata.
 /// </summary>
 /// 
 /// <param name="edges">
 /// Collection of edges whose data should be collected
 /// </param>
 private void AddAllExistingData(IEdgeCollection edges)
 {
     subdivisionPoints = 0;
     foreach (IEdge e in edges)
         if (!e.IsSelfLoop)
             AddExistingData(e);
 }
 public void TearDown()
 {
     m_oConnectedComponentCalculator = null;
     m_oGraph = null;
     m_oVertices = null;
     m_oEdges = null;
 }
 public void TearDown()
 {
     m_oGraph = null;
     m_oVertices = null;
     m_oEdges = null;
 }
Example #37
0
        ReadEdges
        (
            Microsoft.Office.Interop.Excel.Worksheet oSourceWorksheet,
            Int32 iFirstEdgeWeightRowOneBased,
            Int32 iFirstEdgeWeightColumnOneBased,
            IGraph oGraph,
            IVertex [] aoOrderedVertices
        )
        {
            Debug.Assert(oSourceWorksheet != null);
            Debug.Assert(iFirstEdgeWeightRowOneBased >= 1);
            Debug.Assert(iFirstEdgeWeightColumnOneBased >= 1);
            Debug.Assert(oGraph != null);
            Debug.Assert(aoOrderedVertices != null);
            Debug.Assert(oGraph.Vertices.Count == aoOrderedVertices.Length);

            Boolean bGraphIsDirected =
                (oGraph.Directedness == GraphDirectedness.Directed);

            Int32           iVertices = aoOrderedVertices.Length;
            IEdgeCollection oEdges    = oGraph.Edges;

            for (Int32 i = 0; i < iVertices; i++)
            {
                Int32 iRowOneBased = iFirstEdgeWeightRowOneBased + i;

                Object [,] oRowOfEdgeWeightValues = ExcelUtil.GetValuesInRow(
                    oSourceWorksheet, iRowOneBased, iFirstEdgeWeightColumnOneBased,
                    iVertices);

                // In a directed graph, look at the whole row.  In an undirected
                // graph, look only at the cell on the diagonal and the cells to
                // the right.

                for (Int32 j = (bGraphIsDirected ? 0 : i); j < iVertices; j++)
                {
                    Double dEdgeWeight     = 0;
                    Int32  iColumnOneBased = iFirstEdgeWeightColumnOneBased + j;

                    if (!ExcelUtil.TryGetDoubleFromCell(oRowOfEdgeWeightValues, 1,
                                                        j + 1, out dEdgeWeight))
                    {
                        OnInvalidSourceWorkbook(String.Format(

                                                    "The edge weight in {0} must be a number."
                                                    ,
                                                    ExcelUtil.GetCellAddress(oSourceWorksheet,
                                                                             iRowOneBased, iColumnOneBased)
                                                    ),
                                                oSourceWorksheet, iRowOneBased, iColumnOneBased
                                                );
                    }

                    if (dEdgeWeight != 0)
                    {
                        IEdge oEdge = oEdges.Add(aoOrderedVertices[i],
                                                 aoOrderedVertices[j], bGraphIsDirected);

                        oEdge.SetValue(ReservedMetadataKeys.EdgeWeight,
                                       dEdgeWeight);
                    }
                }
            }
        }
Example #38
0
        //*************************************************************************
        //  Method: InitializeGraph()
        //
        /// <summary>
        /// Initializes m_oGraph and related member fields.
        /// </summary>
        ///
        /// <param name="eDirectedness">
        /// Directedness of m_oGraph.
        /// </param>
        //*************************************************************************
        protected void InitializeGraph(
            GraphDirectedness eDirectedness
            )
        {
            m_oGraph = new Graph(eDirectedness);

            Debug.Assert(m_oGraph.Edges is EdgeCollection);

            m_oEdgeCollection = m_oGraph.Edges;

            ( (EdgeCollection)m_oEdgeCollection ).EdgeAdded +=
            new EdgeEventHandler(this.EdgeCollection_EdgeAdded);

            ( (EdgeCollection)m_oEdgeCollection ).EdgeRemoved +=
            new EdgeEventHandler(this.EdgeCollection_EdgeRemoved);

            m_bEdgeAdded = false;
            m_oAddedEdge = null;

            m_bEdgeRemoved = false;
            m_oRemovedEdge = null;
        }
Example #39
0
        LoadGraphCore
        (
            Stream stream
        )
        {
            Debug.Assert(stream != null);
            AssertValid();

            // For now, support only directed graphs.

            IGraph oGraph = new Graph(GraphDirectedness.Directed);

            IVertexCollection oVertices = oGraph.Vertices;

            IEdgeCollection oEdges = oGraph.Edges;

            StreamReader oStreamReader = new StreamReader(stream, StreamEncoding);

            // Create a dictionary to keep track of the vertices that have been
            // added to the graph.  The key is the vertex name and the value is the
            // vertex.

            Dictionary <String, IVertex> oDictionary =
                new Dictionary <String, IVertex>();

            Int32 iLineNumber = 1;

            while (true)
            {
                String sLine = oStreamReader.ReadLine();

                if (sLine == null)
                {
                    break;
                }

                // Skip empty lines.

                if (sLine.Trim().Length > 0)
                {
                    // Parse the line.

                    String [] asTokens = sLine.Split('\t');

                    if (asTokens.Length != 2)
                    {
                        OnLoadFormatError(sLine, iLineNumber, ExpectedFormat);
                    }

                    String sVertex1Name = asTokens[0];
                    String sVertex2Name = asTokens[1];

                    if (!VertexNameIsValid(sVertex1Name) ||
                        !VertexNameIsValid(sVertex2Name))
                    {
                        OnLoadFormatError(sLine, iLineNumber, ExpectedFormat);
                    }

                    // Retrieve or create the specified vertices.

                    IVertex oVertex1 =
                        VertexNameToVertex(sVertex1Name, oVertices, oDictionary);

                    IVertex oVertex2 =
                        VertexNameToVertex(sVertex2Name, oVertices, oDictionary);

                    // Add an edge connecting the vertices.

                    oEdges.Add(oVertex1, oVertex2, true);
                }

                iLineNumber++;
            }

            oDictionary.Clear();

            return(oGraph);
        }
 /// <summary>
 /// Collects edge data from all edges in the specified collection.
 /// Used by the <see cref="BundleAllEdges"/> method.
 /// </summary>
 /// 
 /// <param name="edges">
 /// Collection of edges whose data should be collected
 /// </param>
 private void AddDataForAllEdges(IEdgeCollection edges)
 {
     foreach (IEdge e in edges)
         if (!e.IsSelfLoop)
             AddEdgeData(e);
 }
Example #41
0
        Clone
        (
            Boolean copyMetadataValues,
            Boolean copyTag
        )
        {
            AssertValid();

            const String MethodName = "Clone";

            IGraph oNewGraph = new Graph(m_eDirectedness);

            // Copy the base-class fields to the new edge.

            this.CopyTo(oNewGraph, copyMetadataValues, copyTag);

            // The vertices need to be copied to the new graph.  Loop through the
            // vertices in this original graph.

            IVertexCollection oNewVertices = oNewGraph.Vertices;

            foreach (IVertex oOriginalVertex in m_oVertexCollection)
            {
                IVertex oNewVertex = oOriginalVertex.Clone(
                    copyMetadataValues, copyTag);

                // To make it easier to copy the edges in this original graph,
                // temporarily store the ID of the new vertex in the Tag of the
                // original vertex.  Save the Tag so it can be restored later.

                oOriginalVertex.Tag =
                    new VertexMapper(oOriginalVertex.Tag, oNewVertex);

                oNewVertices.Add(oNewVertex);
            }

            // The edges need to be copied to the new graph.  Loop through the
            // edges in this original graph.

            IEdgeCollection oNewEdges = oNewGraph.Edges;

            foreach (IEdge oOriginalEdge in m_oEdgeCollection)
            {
                // Get the original edge's vertices.

                IVertex oOriginalVertex1, oOriginalVertex2;

                EdgeUtil.EdgeToVertices(oOriginalEdge, this.ClassName, MethodName,
                                        out oOriginalVertex1, out oOriginalVertex2);

                // Retrieve the VertexMapper objects that were temporarily stored
                // in the vertices' Tags.

                Debug.Assert(oOriginalVertex1.Tag is VertexMapper);
                Debug.Assert(oOriginalVertex2.Tag is VertexMapper);

                VertexMapper oVertexMapper1 = (VertexMapper)oOriginalVertex1.Tag;
                VertexMapper oVertexMapper2 = (VertexMapper)oOriginalVertex2.Tag;

                // Get the new vertices that correspond to the original edge's
                // vertices.

                IVertex oNewVertex1 = oVertexMapper1.NewVertex;
                IVertex oNewVertex2 = oVertexMapper2.NewVertex;

                // Copy the original edge, connecting the new vertices in the
                // process.

                IEdge oNewEdge = oOriginalEdge.Clone(copyMetadataValues, copyTag,
                                                     oNewVertex1, oNewVertex2,
                                                     oOriginalEdge.IsDirected);

                oNewEdges.Add(oNewEdge);
            }

            // Restore the original vertices' Tags.

            foreach (IVertex oOriginalVertex in m_oVertexCollection)
            {
                Debug.Assert(oOriginalVertex.Tag is VertexMapper);

                VertexMapper oVertexMapper = (VertexMapper)oOriginalVertex.Tag;

                oOriginalVertex.Tag = oVertexMapper.OriginalVertexTag;
            }

            return(oNewGraph);
        }
 public void SetUp()
 {
     m_oGraph = new Graph();
     m_oVertices = m_oGraph.Vertices;
     m_oEdges = m_oGraph.Edges;
 }
Example #43
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
            }

            Smrf.NodeXL.Visualization.Wpf.VertexShape[] aeShapes
                = (Smrf.NodeXL.Visualization.Wpf.VertexShape[])
                  Enum.GetValues(typeof(Smrf.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)(
                    Smrf.NodeXL.Visualization.Wpf.VertexDrawer.MinimumRadius +
                    (0.1 *
                     Smrf.NodeXL.Visualization.Wpf.VertexDrawer.MaximumRadius
                     - Smrf.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 #44
0
        GetSubgraphAsNewGraph
        (
            ICollection <IVertex> verticesToInclude
        )
        {
            Debug.Assert(verticesToInclude != null);
            Debug.Assert(verticesToInclude.Count > 0);

            IVertex oFirstVertex = verticesToInclude.First();
            IGraph  oParentGraph = oFirstVertex.ParentGraph;

            IGraph            oNewGraph    = new Graph(oParentGraph.Directedness);
            IEdgeCollection   oNewEdges    = oNewGraph.Edges;
            IVertexCollection oNewVertices = oNewGraph.Vertices;

            // This maps vertex IDs in the original graph to the corresponding new
            // vertices in the new graph.

            Dictionary <Int32, IVertex> oVertexIDToNewVertexDictionary =
                new Dictionary <Int32, IVertex>(verticesToInclude.Count);

            // Copy the vertices into the new graph.

            foreach (IVertex oVertex in verticesToInclude)
            {
                IVertex oNewVertex = oNewVertices.Add();
                oNewVertex.Name = oVertex.Name;
                oVertexIDToNewVertexDictionary.Add(oVertex.ID, oNewVertex);
            }

            // This contains the IDs of the original edges that have been copied
            // into the new graph.

            HashSet <Int32> oIDsOfCopiedEdges = new HashSet <Int32>();

            // Copy the edges connecting the vertices into the new graph.

            foreach (IVertex oVertex in verticesToInclude)
            {
                foreach (IEdge oIncidentEdge in oVertex.IncidentEdges)
                {
                    IVertex oAdjacentVertex = oIncidentEdge.GetAdjacentVertex(
                        oVertex);

                    IVertex oNewAdjacentVertex;

                    if (
                        !oVertexIDToNewVertexDictionary.TryGetValue(
                            oAdjacentVertex.ID, out oNewAdjacentVertex)
                        ||
                        oIDsOfCopiedEdges.Contains(oIncidentEdge.ID)
                        )
                    {
                        // The adjacent vertex is not in the set of vertices to
                        // include, or the edge has already been copied into the
                        // new graph.

                        continue;
                    }

                    IVertex oNewVertex =
                        oVertexIDToNewVertexDictionary[oVertex.ID];

                    IEdge   oNewEdge;
                    Boolean bIncidentEdgeIsDirected = oIncidentEdge.IsDirected;

                    if (oVertex == oIncidentEdge.Vertices[0])
                    {
                        oNewEdge = oNewEdges.Add(oNewVertex, oNewAdjacentVertex,
                                                 bIncidentEdgeIsDirected);
                    }
                    else
                    {
                        oNewEdge = oNewEdges.Add(oNewAdjacentVertex, oNewVertex,
                                                 bIncidentEdgeIsDirected);
                    }

                    oIDsOfCopiedEdges.Add(oIncidentEdge.ID);
                }
            }

            return(oNewGraph);
        }
Example #45
0
        SaveGraphCore
        (
            IGraph graph,
            Stream stream
        )
        {
            Debug.Assert(graph != null);
            Debug.Assert(stream != null);
            AssertValid();

            // The Pajek format requires coordinates to be between 0 and 1.0.  Get
            // a Matrix that will transform the vertex locations to this range.

            RectangleF oCurrentBoundingRectangle =
                LayoutUtil.GetGraphBoundingRectangle(graph);

            RectangleF oNewBoundingRectangle =
                new RectangleF(PointF.Empty, new SizeF(1.0F, 1.0F));

            Matrix oRectangleTransformation =
                LayoutUtil.GetRectangleTransformation(
                    oCurrentBoundingRectangle, oNewBoundingRectangle
                    );

            // Create a dictionary to keep track of vertices.  The keys are vertex
            // IDs and the values are the one-based vertex numbers used by the
            // Pajek format.

            Dictionary <Int32, Int32> oVertexIDToNumber =
                new Dictionary <Int32, Int32>();

            IVertexCollection oVertices = graph.Vertices;

            StreamWriter oStreamWriter = new StreamWriter(stream, StreamEncoding);

            // Add the *vertices section.

            oStreamWriter.WriteLine(

                "*vertices {0}"
                ,
                oVertices.Count
                );

            Int32 iVertexNumber = 1;

            foreach (IVertex oVertex in oVertices)
            {
                // Format:
                //
                // 1 "vertex 1 name" x y z

                // Transform the vertex location.

                PointF oTransformedLocation = LayoutUtil.TransformPointF(
                    oVertex.Location, oRectangleTransformation);

                // Limit the range in case of rounding errors.

                Single fX = Math.Max(0F, oTransformedLocation.X);
                fX = Math.Min(1F, fX);

                Single fY = Math.Max(0F, oTransformedLocation.Y);
                fY = Math.Min(1F, fY);

                oStreamWriter.WriteLine(

                    "{0} \"{1}\" {2:N6} {3:N6} 0"
                    ,
                    iVertexNumber,
                    oVertex.Name,
                    fX,
                    fY
                    );

                oVertexIDToNumber.Add(oVertex.ID, iVertexNumber);

                iVertexNumber++;
            }

            IEdgeCollection oEdges = graph.Edges;

            GraphDirectedness eDirectedness = graph.Directedness;

            Boolean bSectionNameWritten = false;

            if (eDirectedness != GraphDirectedness.Directed)
            {
                // If appropriate, add the *edges section, which specifies
                // undirected edges.

                foreach (IEdge oEdge in oEdges)
                {
                    // The graph could be mixed.

                    if (oEdge.IsDirected)
                    {
                        continue;
                    }

                    if (!bSectionNameWritten)
                    {
                        oStreamWriter.WriteLine("*edges");

                        bSectionNameWritten = true;
                    }

                    WriteEdge(oEdge, oVertexIDToNumber, oStreamWriter);
                }
            }

            bSectionNameWritten = false;

            if (eDirectedness != GraphDirectedness.Undirected)
            {
                // If appropriate, add the *arcs section, which specifies
                // directed edges.

                foreach (IEdge oEdge in oEdges)
                {
                    // The graph could be mixed.

                    if (!oEdge.IsDirected)
                    {
                        continue;
                    }

                    if (!bSectionNameWritten)
                    {
                        oStreamWriter.WriteLine("*arcs");

                        bSectionNameWritten = true;
                    }

                    WriteEdge(oEdge, oVertexIDToNumber, oStreamWriter);
                }
            }

            oStreamWriter.Flush();
        }
Example #46
0
        ImportEdges
        (
            IGraph oSourceGraph,
            String [] asEdgeAttributes,
            ListObject oEdgeTable,
            Range oVertex1NameColumnData,
            Range oVertex2NameColumnData,
            Boolean bAppendToTable
        )
        {
            Debug.Assert(oSourceGraph != null);
            Debug.Assert(oEdgeTable != null);
            Debug.Assert(oVertex1NameColumnData != null);
            Debug.Assert(oVertex2NameColumnData != null);
            AssertValid();

            Int32 iRowOffsetToWriteTo = 0;

            if (bAppendToTable)
            {
                iRowOffsetToWriteTo =
                    ExcelUtil.GetOffsetOfFirstEmptyTableRow(oEdgeTable);

                ExcelUtil.OffsetRange(ref oVertex1NameColumnData,
                                      iRowOffsetToWriteTo, 0);

                ExcelUtil.OffsetRange(ref oVertex2NameColumnData,
                                      iRowOffsetToWriteTo, 0);
            }

            Range [] aoEdgeAttributeColumnData = null;
            Object [][,] aaoEdgeAttributeValues = null;
            Int32           iEdgeAttributes = 0;
            IEdgeCollection oEdges          = oSourceGraph.Edges;
            Int32           iEdges          = oEdges.Count;

            // Create vertex name and edge attribute arrays that will be written to
            // the edge table.

            Object [,] aoVertex1NameValues =
                ExcelUtil.GetSingleColumn2DArray(iEdges);

            Object [,] aoVertex2NameValues =
                ExcelUtil.GetSingleColumn2DArray(iEdges);

            if (asEdgeAttributes != null)
            {
                iEdgeAttributes           = asEdgeAttributes.Length;
                aoEdgeAttributeColumnData = new Range[iEdgeAttributes];
                aaoEdgeAttributeValues    = new Object[iEdgeAttributes][, ];
                ListColumn oEdgeAttributeColumn;
                Range      oEdgeAttributeColumnData;

                for (Int32 i = 0; i < iEdgeAttributes; i++)
                {
                    String sEdgeAttribute = asEdgeAttributes[i];

                    if (
                        !ExcelUtil.TryGetOrAddTableColumn(oEdgeTable,
                                                          sEdgeAttribute, ExcelUtil.AutoColumnWidth, null,
                                                          out oEdgeAttributeColumn)
                        ||
                        !ExcelUtil.TryGetTableColumnData(oEdgeAttributeColumn,
                                                         out oEdgeAttributeColumnData)
                        )
                    {
                        throw new WorkbookFormatException(
                                  "The " + sEdgeAttribute + " column couldn't be added."
                                  );
                    }

                    if (bAppendToTable)
                    {
                        ExcelUtil.OffsetRange(ref oEdgeAttributeColumnData,
                                              iRowOffsetToWriteTo, 0);
                    }

                    aoEdgeAttributeColumnData[i] = oEdgeAttributeColumnData;

                    aaoEdgeAttributeValues[i] =
                        ExcelUtil.GetSingleColumn2DArray(iEdges);
                }
            }

            // Fill in the vertex name and edge attribute arrays.

            Int32 iEdge = 1;

            foreach (IEdge oEdge in oEdges)
            {
                IVertex [] aoVertices = oEdge.Vertices;

                aoVertex1NameValues[iEdge, 1] = aoVertices[0].Name;
                aoVertex2NameValues[iEdge, 1] = aoVertices[1].Name;

                Object oEdgeAttribute;

                for (Int32 i = 0; i < iEdgeAttributes; i++)
                {
                    if (oEdge.TryGetValue(asEdgeAttributes[i],
                                          out oEdgeAttribute))
                    {
                        aaoEdgeAttributeValues[i][iEdge, 1] =
                            RemoveFormulaFromAttribute(oEdgeAttribute);
                    }
                }

                iEdge++;
            }

            // Write the vertex name and edge attribute arrays to the table.

            ExcelUtil.SetRangeValues((Range)oVertex1NameColumnData.Cells[1, 1],
                                     aoVertex1NameValues);

            ExcelUtil.SetRangeValues((Range)oVertex2NameColumnData.Cells[1, 1],
                                     aoVertex2NameValues);

            for (Int32 i = 0; i < iEdgeAttributes; i++)
            {
                ExcelUtil.SetRangeValues(
                    (Range)aoEdgeAttributeColumnData[i].Cells[1, 1],
                    aaoEdgeAttributeValues[i]);
            }
        }