public void SetUp() { IVertex oVertex1 = new Vertex(); IVertex oVertex2 = new Vertex(); IGraph oGraph = new Graph(); oGraph.Vertices.Add(oVertex1); oGraph.Vertices.Add(oVertex2); m_oEdge = new Edge(oVertex1, oVertex2, true); m_oEdgeEventArgs = new EdgeEventArgs(m_oEdge); }
public void TestSort() { // Ascending sort using default comparer, which sorts by ID. const Int32 Vertices = 100; IGraph oGraph = new Graph(); IVertex [] aoUnsortedVertices = TestGraphUtil.AddVertices(oGraph, Vertices); IVertexCollection oVertexCollection = oGraph.Vertices; ICollection<IVertex> oSortedVertices = m_oByDelegateVertexSorter.Sort(oVertexCollection); Assert.AreEqual(Vertices, oSortedVertices.Count); Int32 iPreviousID = -1; foreach (IVertex oSortedVertex in oSortedVertices) { Int32 iID = oSortedVertex.ID; if (iPreviousID != -1) { Assert.AreEqual(iPreviousID + 1, iID); } iPreviousID = iID; } }
public void TestParentGraph2() { // Create a graph, populate the graph with vertices and edges, remove // the vertex from the graph. const Int32 Vertices = 100; // Create a graph with each vertex connected to all others. IGraph oGraph = new Graph(); IVertex [] aoVertices = TestGraphUtil.AddVertices(oGraph, Vertices); TestGraphUtil.MakeGraphComplete(oGraph, aoVertices, false); // Pick one of the vertices to test. IVertex oVertex = aoVertices[0]; Assert.AreEqual(oGraph, oVertex.ParentGraph); // Remove the vertex. oGraph.Vertices.Remove(oVertex); Assert.IsNull(oVertex.ParentGraph); }
public void TestLayOutGraphBad2() { // null layoutContext. try { IGraph oGraph = new Graph(); m_oFruchtermanReingoldLayout.LayOutGraph(oGraph, null); } catch (ArgumentNullException oArgumentNullException) { Assert.AreEqual( "Microsoft.NodeXL.Layouts.FruchtermanReingoldLayout." + "LayOutGraph: layoutContext argument can't be null.\r\n" + "Parameter name: layoutContext" , oArgumentNullException.Message ); throw oArgumentNullException; } }
//************************************************************************* // Method: Clone() // /// <summary> /// Creates a copy of the graph. /// </summary> /// /// <param name="copyMetadataValues"> /// If true, the key/value pairs that were set with <see /// cref="IMetadataProvider.SetValue" /> are copied to the new graph, /// vertices, and edges. (This is a shallow copy. The objects pointed to /// by the original values are NOT cloned.) If false, the key/value pairs /// are not copied. /// </param> /// /// <param name="copyTag"> /// If true, the <see cref="IMetadataProvider.Tag" /> properties on the new /// graph, vertices, and edges are set to the same value as in the original /// objects. (This is a shallow copy. The objects pointed to by the /// original <see cref="IMetadataProvider.Tag" /> properties are NOT /// cloned.) If false, the <see cref="IMetadataProvider.Tag "/> /// properties on the new graph, vertices, and edges are set to null. /// </param> /// /// <returns> /// The copy of the graph, as an <see cref="IGraph" />. /// </returns> /// /// <remarks> /// The new graph, vertices, and edges have the same <see /// cref="IIdentityProvider.Name" /> values as the originals, but they are /// assigned new <see cref="IIdentityProvider.ID" />s. /// </remarks> //************************************************************************* public IGraph 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); }
//************************************************************************* // Method: CreateGraph() // /// <summary> /// Creates a graph of a specified directedness that is compatible with /// <see cref="PajekGraphAdapter" />. /// </summary> /// /// <param name="eDirectedness"> /// Directedness of the new graph. /// </param> /// /// <returns> /// A new compatible graph. /// </returns> //************************************************************************* protected IGraph CreateGraph( GraphDirectedness eDirectedness ) { IGraph oGraph = new Graph(eDirectedness); return (oGraph); }
private void BuildNetwork(object sender, RoutedEventArgs e) { string cs = ""; string inserts = ""; string networkkey = "PAYR"; Repository localenginecreate = new Repository(); localenginecreate.Open_Repository(); // Go grab everything we need, based on the net id string DataBaseRoot = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString()).Replace(@"file:\", "") + "\\Friends.db"; cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Firefly\\List of customers for firefly poc\\List of customers for firefly poc.mdb"; // Node SQL string nodeSQL = "select cust_skey, cust_name from cust where cust_type_MDM in ('PLAN', 'PAYR', 'CORP','PHAR', 'UNSP')"; int nodenameMap; int nodeidMap; string nodename; double nodeid; // Edge SQL string edgeSQL = "select from_cust_skey, to_cust_skey from cust_affl WHERE affl_type in ('PLAN_to_PAYR', 'PHAR_to_CORP', 'PAYR_to_CORP', 'CORP_to_CORP')"; int EdgeFromidMap = 0; int EdgeToidMap = 1; double from; double to; double nodecount = 0; try { // Set up a network object Graph oGraph = new Graph(GraphDirectedness.Directed); IVertexCollection oVertices = oGraph.Vertices; IEdgeCollection oEdges = oGraph.Edges; // connection OleDbConnection TestConn = new OleDbConnection(cs); TestConn.Open(); OleDbCommand aCommand = new OleDbCommand(nodeSQL, TestConn); //create the datareader object to connect to table OleDbDataReader aReader = aCommand.ExecuteReader(); // Get the Nodes!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! nodenameMap = 1; nodeidMap = 0; while (aReader.Read()) { nodename = aReader.GetString(nodenameMap); nodeid = aReader.GetDouble(nodeidMap); // Add a node... IVertex oVertexA = oVertices.Add(); oVertexA.Name = nodename; oVertexA.Tag = nodeid; nodecount++; } aReader.Close(); // Get the Edges!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! OleDbCommand aEdgeCommand = new OleDbCommand(edgeSQL, TestConn); //create the datareader object to connect to table OleDbDataReader aEdgeReader = aEdgeCommand.ExecuteReader(); EdgeFromidMap = 0; EdgeToidMap = 1; while (aEdgeReader.Read()) { from = aEdgeReader.GetDouble(EdgeFromidMap); to = aEdgeReader.GetDouble(EdgeToidMap); // Add an edge IVertex oFrom = null; IVertex oTo = null; foreach (IVertex oVertex in oVertices) { if (oVertex.Tag.ToString() == from.ToString()) { oFrom = oVertex; } if (oVertex.Tag.ToString() == to.ToString()) { oTo = oVertex; } } IEdge oEdge1 = oEdges.Add(oFrom, oTo, true); } aEdgeReader.Close(); // Perform a layout // Apply Layout // ================================================================== double xdim; double ydim; xdim = 5000; ydim = xdim; string layoutmethod = "Fruchterman/Reingold Layout"; switch (layoutmethod) { case "Circular Layout": ILayout oLayout_cir = new CircleLayout(); LayoutContext oLayoutContext_cir = new LayoutContext(new System.Drawing.Rectangle(0, 0, (int)xdim, (int)ydim)); oLayout_cir.LayOutGraph(oGraph, oLayoutContext_cir); break; case "Random Layout": ILayout oLayout_rand = new RandomLayout(); LayoutContext oLayoutContext_rand = new LayoutContext(new System.Drawing.Rectangle(0, 0, (int)xdim, (int)ydim)); oLayout_rand.LayOutGraph(oGraph, oLayoutContext_rand); break; case "Sugiyama Layout": ILayout oLayout_Sugi = new SugiyamaLayout(); LayoutContext oLayoutContext_Sugi = new LayoutContext(new System.Drawing.Rectangle(0, 0, (int)xdim, (int)ydim)); oLayout_Sugi.LayOutGraph(oGraph, oLayoutContext_Sugi); break; case "Grid Layout": ILayout oLayout_grid = new GridLayout(); LayoutContext oLayoutContext_grid = new LayoutContext(new System.Drawing.Rectangle(0, 0, (int)xdim, (int)ydim)); oLayout_grid.LayOutGraph(oGraph, oLayoutContext_grid); break; case "Spiral Layout": ILayout oLayout_spiral = new SpiralLayout(); LayoutContext oLayoutContext_spiral = new LayoutContext(new System.Drawing.Rectangle(0, 0, (int)xdim, (int)ydim)); oLayout_spiral.LayOutGraph(oGraph, oLayoutContext_spiral); break; case "Fruchterman/Reingold Layout": ILayout oLayout_Fruch = new FruchtermanReingoldLayout(); LayoutContext oLayoutContext_Fruch = new LayoutContext(new System.Drawing.Rectangle(0, 0, (int)xdim, (int)ydim)); oLayout_Fruch.LayOutGraph(oGraph, oLayoutContext_Fruch); break; case "Sinusoid H Layout": ILayout oLayout_SinH = new SinusoidHorizontalLayout(); LayoutContext oLayoutContext_SinH = new LayoutContext(new System.Drawing.Rectangle(0, 0, (int)xdim, (int)ydim)); oLayout_SinH.LayOutGraph(oGraph, oLayoutContext_SinH); break; case "Sinusoid V Layout": ILayout oLayout_SinV = new SinusoidVerticalLayout(); LayoutContext oLayoutContext_SinV = new LayoutContext(new System.Drawing.Rectangle(0, 0, (int)xdim, (int)ydim)); oLayout_SinV.LayOutGraph(oGraph, oLayoutContext_SinV); break; } // Save the Nodes back out to the Firefly database // List the results. int xoffset = 0; int yoffset = 0; int size=10; double xx2, yy2,xx,yy; foreach (IVertex oVertex in oVertices) { UniversePadPoint p2 = new UniversePadPoint(); p2.PadName = oVertex.Name; xx2 = oVertex.Location.X; yy2 = oVertex.Location.Y; xx2 = xx2 + xoffset; yy2 = yy2 + yoffset; size = 10; inserts = "insert into Nodes(id, nodename, networkid,x,y,z) values (" + oVertex.Tag.ToString() + ", '" + oVertex.Name.ToString() + "', '" + networkkey + "'," + xx2.ToString() + "," + yy2.ToString() + ",0)"; OleDbCommand postnode = new OleDbCommand(inserts, localenginecreate.RepositoryConnection); OleDbDataReader Poster = postnode.ExecuteReader(); Poster.Close(); } foreach (IEdge e2 in oEdges) { IVertex f1 = e2.BackVertex; IVertex t2 = e2.FrontVertex; xx = f1.Location.X; yy = f1.Location.Y; xx2 = t2.Location.X; yy2 = t2.Location.Y; xx = xx + xoffset; yy = yy + yoffset; xx2 = xx2 + xoffset; yy2 = yy2 + yoffset; inserts = "insert into Edges(fromid, toid, networkid) values (" + f1.Tag.ToString() + ", " + t2.Tag.ToString() + ", '" + networkkey + "')"; OleDbCommand postedge = new OleDbCommand(inserts, localenginecreate.RepositoryConnection); OleDbDataReader Poster = postedge.ExecuteReader(); Poster.Close(); } } //Some usual exception handling catch (OleDbException eWriteNodes) { MessageBox.Show(eWriteNodes.Message); } localenginecreate.Close_Repository(); MessageBox.Show("Done creating network."); }
public void TestSaveGraph() { // Directed and undirected graphs. foreach (Boolean bDirected in TestGraphUtil.AllBoolean) { IGraph oGraph = new Graph(bDirected ? GraphDirectedness.Directed : GraphDirectedness.Undirected); IVertexCollection oVertices = oGraph.Vertices; IEdgeCollection oEdges = oGraph.Edges; IVertex oVertex1 = oVertices.Add(); oVertex1.Name = "Vertex1"; oVertex1.SetValue("VertexAttribute1", 123); // Int32 IVertex oVertex2 = oVertices.Add(); oVertex2.Name = "Vertex2"; oVertex2.SetValue("VertexAttribute2", "abc"); // String IVertex oVertex3 = oVertices.Add(); oVertex3.Name = "Vertex3"; oVertex3.SetValue("VertexAttribute1", 4.0); // Double oVertex3.SetValue("VertexAttribute2", 23456.0F); // Single IVertex oVertex4 = oVertices.Add(); oVertex4.Name = "Vertex4"; IVertex oVertex5 = oVertices.Add(); oVertex5.Name = "Vertex5"; IEdge oEdge; oEdge = oEdges.Add(oVertex1, oVertex2, bDirected); oEdge.SetValue("EdgeAttribute1", "ea1"); oEdge = oEdges.Add(oVertex3, oVertex4, bDirected); oEdge.SetValue("EdgeAttribute2", "ea2"); oGraph.SetValue( ReservedMetadataKeys.AllVertexMetadataKeys, new String [] { "VertexAttribute1", "VertexAttribute2", } ); oGraph.SetValue(ReservedMetadataKeys.AllEdgeMetadataKeys, new String [] { "EdgeAttribute1", "EdgeAttribute2", } ); m_oGraphAdapter.SaveGraph(oGraph, m_sTempFileName); String sFileContents; using ( StreamReader oStreamReader = new StreamReader(m_sTempFileName) ) { sFileContents = oStreamReader.ReadToEnd(); } XmlDocument oXmlDocument = new XmlDocument(); oXmlDocument.LoadXml(sFileContents); XmlNamespaceManager oXmlNamespaceManager = new XmlNamespaceManager( oXmlDocument.NameTable); oXmlNamespaceManager.AddNamespace("g", GraphMLGraphAdapter.GraphMLUri); String [] asRequiredXPaths = new String [] { // Graph node. String.Format("/g:graphml/g:graph[@edgedefault='{0}']", bDirected ? "directed" : "undirected"), "/g:graphml/g:key[@id='V-VertexAttribute1' and @for='node'" + " and @attr.name='VertexAttribute1'" + " and @attr.type='string']", // Vertex nodes. "/g:graphml/g:key[@id='V-VertexAttribute2' and @for='node'" + " and @attr.name='VertexAttribute2'" + " and @attr.type='string']", "/g:graphml/g:key[@id='E-EdgeAttribute1' and @for='edge'" + " and @attr.name='EdgeAttribute1'" + " and @attr.type='string']", "/g:graphml/g:key[@id='E-EdgeAttribute2' and @for='edge'" + " and @attr.name='EdgeAttribute2'" + " and @attr.type='string']", "/g:graphml/g:graph/g:node[@id='Vertex1']/" + "g:data[@key='V-VertexAttribute1' and .='123']", "/g:graphml/g:graph/g:node[@id='Vertex2']/" + "g:data[@key='V-VertexAttribute2' and .='abc']", "/g:graphml/g:graph/g:node[@id='Vertex3']/" + "g:data[@key='V-VertexAttribute1' and .='4']", "/g:graphml/g:graph/g:node[@id='Vertex3']/" + "g:data[@key='V-VertexAttribute2' and .='23456']", "/g:graphml/g:graph/g:node[@id='Vertex4']", "/g:graphml/g:graph/g:node[@id='Vertex5']", // Edge nodes. "/g:graphml/g:graph/g:edge[@source='Vertex1' and" + " @target='Vertex2']/" + "g:data[@key='E-EdgeAttribute1' and .='ea1']", "/g:graphml/g:graph/g:edge[@source='Vertex3' and" + " @target='Vertex4']/" + "g:data[@key='E-EdgeAttribute2' and .='ea2']", }; foreach (String sRequiredXPath in asRequiredXPaths) { XmlNode oXmlNode = oXmlDocument.SelectSingleNode( sRequiredXPath, oXmlNamespaceManager); Assert.IsNotNull(oXmlNode); } } }
public void TestIsOutgoingEdgeBad() { // null edge. try { IGraph oGraph = new Graph(); IVertex [] aoVertices = TestGraphUtil.AddVertices(oGraph, 1); aoVertices[0].IsOutgoingEdge(null); } catch (ArgumentNullException oArgumentNullException) { Assert.AreEqual( "Microsoft.NodeXL.Core." + "Vertex.IsOutgoingEdge: edge argument can't be null.\r\n" + "Parameter name: edge" , oArgumentNullException.Message ); throw oArgumentNullException; } }
public void TestIsIncidentEdge() { IGraph oGraph = new Graph(); IVertex [] aoVertices = TestGraphUtil.AddVertices(oGraph, 4); IVertex oVertex0 = aoVertices[0]; IVertex oVertex1 = aoVertices[1]; IVertex oVertex2 = aoVertices[2]; IVertex oVertex3 = aoVertices[3]; IEdgeCollection oEdges = oGraph.Edges; IEdge oUndirectedEdge = oEdges.Add(oVertex0, oVertex1, false); Assert.IsTrue( oVertex0.IsIncidentEdge(oUndirectedEdge) ); Assert.IsTrue( oVertex0.IsOutgoingEdge(oUndirectedEdge) ); Assert.IsTrue( oVertex0.IsIncomingEdge(oUndirectedEdge) ); IEdge oIncomingEdge = oEdges.Add(oVertex2, oVertex0, true); Assert.IsTrue( oVertex0.IsIncidentEdge(oIncomingEdge) ); Assert.IsFalse( oVertex0.IsOutgoingEdge(oIncomingEdge) ); Assert.IsTrue( oVertex0.IsIncomingEdge(oIncomingEdge) ); IEdge oOutgoingEdge = oEdges.Add(oVertex0, oVertex3, true); Assert.IsTrue( oVertex0.IsIncidentEdge(oOutgoingEdge) ); Assert.IsTrue( oVertex0.IsOutgoingEdge(oOutgoingEdge) ); Assert.IsFalse( oVertex0.IsIncomingEdge(oOutgoingEdge) ); IEdge oUndirectedSelfLoop = oEdges.Add(oVertex0, oVertex0, false); Assert.IsTrue( oVertex0.IsIncidentEdge(oUndirectedSelfLoop) ); Assert.IsTrue( oVertex0.IsOutgoingEdge(oUndirectedSelfLoop) ); Assert.IsTrue( oVertex0.IsIncomingEdge(oUndirectedSelfLoop) ); IEdge oDirectedSelfLoop = oEdges.Add(oVertex0, oVertex0, true); Assert.IsTrue( oVertex0.IsIncidentEdge(oDirectedSelfLoop) ); Assert.IsTrue( oVertex0.IsOutgoingEdge(oDirectedSelfLoop) ); Assert.IsTrue( oVertex0.IsIncomingEdge(oDirectedSelfLoop) ); IEdge oDisconnectedEdge = oEdges.Add(oVertex2, oVertex3, false); Assert.IsFalse( oVertex0.IsIncidentEdge(oDisconnectedEdge) ); Assert.IsFalse( oVertex0.IsOutgoingEdge(oDisconnectedEdge) ); Assert.IsFalse( oVertex0.IsIncomingEdge(oDisconnectedEdge) ); }
public void TestGetConnectingEdgesBad() { // null otherVertex. try { IGraph oGraph = new Graph(); IVertex [] aoVertices = TestGraphUtil.AddVertices(oGraph, 1); ICollection<IEdge> oConnectingEdges = aoVertices[0].GetConnectingEdges(null); } catch (ArgumentNullException oArgumentNullException) { Assert.AreEqual( "Microsoft.NodeXL.Core." + "Vertex.GetConnectingEdges: otherVertex argument can't be" + " null.\r\n" + "Parameter name: otherVertex" , oArgumentNullException.Message ); throw oArgumentNullException; } }
public void TestGetConnectingEdges2() { // Create a graph and populate it with multiple self-loops. IGraph oGraph = new Graph(); // Add two vertices. IVertex [] aoVertices = TestGraphUtil.AddVertices(oGraph, 2); IVertex oVertex = aoVertices[0]; IEdgeCollection oEdgeCollection = oGraph.Edges; // Add multiple self-loops, both undirected and directed. IEdge oUndirectedEdge1 = oEdgeCollection.Add(oVertex, oVertex, false); IEdge oUndirectedEdge2 = oEdgeCollection.Add(oVertex, oVertex, false); IEdge oDirectedEdge1 = oEdgeCollection.Add(oVertex, oVertex, true); IEdge oDirectedEdge2 = oEdgeCollection.Add(oVertex, oVertex, true); // Add a non-self-loop. IEdge oNonSelfLoopEdge = oEdgeCollection.Add( oVertex, aoVertices[1], false); // If GetConnectingEdges() is passed its own vertex, it should return // self-loops. ICollection<IEdge> oConnectingEdges = oVertex.GetConnectingEdges(oVertex); Assert.IsNotNull(oConnectingEdges); Assert.AreEqual(4, oConnectingEdges.Count); // If GetConnectingEdges() is not passed its own vertex, it should not // return self-loops. oConnectingEdges = oVertex.GetConnectingEdges( aoVertices[1] ); Assert.IsNotNull(oConnectingEdges); Assert.AreEqual(1, oConnectingEdges.Count); Assert.AreEqual( oNonSelfLoopEdge, oConnectingEdges.First() ); }
//************************************************************************* // Method: TestLoopVertices() // /// <summary> /// Tests the PredecessorVertices, SuccessorVertices, or AdjacentVertices /// property when an edge is a self-loop (an edge that connects a vertex to /// itself). /// </summary> /// /// <param name="bTestPredecessorVertices"> /// true to test the PredecessorVertices property. /// </param> /// /// <param name="bTestSuccessorVertices"> /// true to test the SuccessorVertices property. /// </param> /// /// <param name="bTestAdjacentVertices"> /// true to test the AdjacentVertices property. /// </param> //************************************************************************* protected void TestLoopVertices( Boolean bTestPredecessorVertices, Boolean bTestSuccessorVertices, Boolean bTestAdjacentVertices ) { IGraph oGraph = new Graph(); // Add one vertex. IVertex [] aoVertices = TestGraphUtil.AddVertices(oGraph, 1); IVertex oVertex = aoVertices[0]; IEdgeCollection oEdgeCollection = oGraph.Edges; // Add multiple self-loops, both undirected and directed. IEdge oUndirectedEdge1 = oEdgeCollection.Add(oVertex, oVertex, false); IEdge oUndirectedEdge2 = oEdgeCollection.Add(oVertex, oVertex, false); IEdge oDirectedEdge1 = oEdgeCollection.Add(oVertex, oVertex, true); IEdge oDirectedEdge2 = oEdgeCollection.Add(oVertex, oVertex, true); ICollection<IVertex> oVerticesA = null; if (bTestPredecessorVertices) { oVerticesA = oVertex.PredecessorVertices; } else if (bTestSuccessorVertices) { oVerticesA = oVertex.SuccessorVertices; } else if (bTestAdjacentVertices) { oVerticesA = oVertex.AdjacentVertices; } else { Debug.Assert(false); } Assert.AreEqual(1, oVerticesA.Count); HashSet<IVertex> oVerticesAHashSet = new HashSet<IVertex>(oVerticesA); Assert.IsTrue( oVerticesAHashSet.Contains(oVertex) ); }
//************************************************************************* // Method: TestLoopEdges() // /// <summary> /// Tests the IncomingEdges, OutgoingEdges, or IncidentEdges property when /// an edge is a self-loop (an edge that connects a vertex to itself). /// </summary> /// /// <param name="bTestIncomingEdges"> /// true to test the IncomingEdges property. /// </param> /// /// <param name="bTestOutgoingEdges"> /// true to test the OutgoingEdges property. /// </param> /// /// <param name="bTestIncidentEdges"> /// true to test the IncidentEdges property. /// </param> //************************************************************************* protected void TestLoopEdges( Boolean bTestIncomingEdges, Boolean bTestOutgoingEdges, Boolean bTestIncidentEdges ) { IGraph oGraph = new Graph(); // Add one vertex. IVertex [] aoVertices = TestGraphUtil.AddVertices(oGraph, 1); IVertex oVertex = aoVertices[0]; IEdgeCollection oEdgeCollection = oGraph.Edges; // Add multiple self-loops, both undirected and directed. IEdge oUndirectedEdge1 = oEdgeCollection.Add(oVertex, oVertex, false); IEdge oUndirectedEdge2 = oEdgeCollection.Add(oVertex, oVertex, false); IEdge oDirectedEdge1 = oEdgeCollection.Add(oVertex, oVertex, true); IEdge oDirectedEdge2 = oEdgeCollection.Add(oVertex, oVertex, true); ICollection<IEdge> oEdges = null; if (bTestIncomingEdges) { oEdges = oVertex.IncomingEdges; } else if (bTestOutgoingEdges) { oEdges = oVertex.OutgoingEdges; } else if (bTestIncidentEdges) { oEdges = oVertex.IncidentEdges; Assert.AreEqual(oEdges.Count, oVertex.Degree); } else { Debug.Assert(false); } Assert.AreEqual(4, oEdges.Count); HashSet<IEdge> oEdgesHashSet = new HashSet<IEdge>(oEdges); Assert.IsTrue( oEdgesHashSet.Contains(oUndirectedEdge1) ); Assert.IsTrue( oEdgesHashSet.Contains(oUndirectedEdge2) ); Assert.IsTrue( oEdgesHashSet.Contains(oDirectedEdge1) ); Assert.IsTrue( oEdgesHashSet.Contains(oDirectedEdge2) ); }
//************************************************************************* // Method: CreateAndPopulateGraph() // /// <summary> /// Creates a graph and populates it with a random mix of incoming and /// outgoing edges. /// </summary> /// /// <param name="iVertices"> /// Number of vertices to add to the graph. /// </param> /// /// <returns> /// The new graph. /// </returns> //************************************************************************* protected IGraph CreateAndPopulateGraph( Int32 iVertices ) { Debug.Assert(iVertices >= 0); Random oRandom = new Random(1); IGraph oGraph = new Graph(); // Add the vertices. IVertex [] aoVertices = TestGraphUtil.AddVertices(oGraph, iVertices); IEdgeCollection oEdgeCollection = oGraph.Edges; // Add random directed and undirected edges. Int32 iRandomEdges = 100 * iVertices; for (Int32 i = 0; i < iRandomEdges; i++) { Int32 iVertex1Index = oRandom.Next(iVertices); Int32 iVertex2Index = oRandom.Next(iVertices); Boolean bIsDirected = (oRandom.Next(2) == 0); oEdgeCollection.Add( aoVertices[iVertex2Index], aoVertices[iVertex1Index], bIsDirected); } return (oGraph); }
public void TestSort2() { // Ascending sort on IVertex.Name. m_oByDelegateVertexSorter.VertexComparer = this.CompareVerticesByName; const Int32 Vertices = 100; IGraph oGraph = new Graph(); IVertex [] aoUnsortedVertices = TestGraphUtil.AddVertices(oGraph, Vertices); IVertexCollection oVertexCollection = oGraph.Vertices; Int32 i; for (i = 0; i < Vertices; i++) { aoUnsortedVertices[i].Name = (Vertices - i).ToString("D3"); } ICollection<IVertex> oSortedVertices = m_oByDelegateVertexSorter.Sort(oVertexCollection); Assert.AreEqual(Vertices, oSortedVertices.Count); i = 0; foreach (IVertex oSortedVertex in oSortedVertices) { Assert.AreEqual( (i + 1).ToString("D3"), oSortedVertex.Name ); i++; } }
//************************************************************************* // Method: ReadWorkbookInternal() // /// <summary> /// Creates a NodeXL graph from the contents of an Excel workbook. /// </summary> /// /// <param name="workbook"> /// Workbook containing the graph data. /// </param> /// /// <param name="readWorkbookContext"> /// Provides access to objects needed for converting an Excel workbook to a /// NodeXL graph. /// </param> /// /// <returns> /// A new graph. /// </returns> /// /// <remarks> /// If <paramref name="workbook" /> contains valid graph data, a new <see /// cref="IGraph" /> is created from the workbook contents and returned. /// Otherwise, a <see cref="WorkbookFormatException" /> is thrown. /// </remarks> //************************************************************************* protected IGraph ReadWorkbookInternal( Microsoft.Office.Interop.Excel.Workbook workbook, ReadWorkbookContext readWorkbookContext ) { Debug.Assert(readWorkbookContext != null); Debug.Assert(workbook != null); AssertValid(); if (readWorkbookContext.PopulateVertexWorksheet) { // Create and use the object that fills in the vertex worksheet. VertexWorksheetPopulator oVertexWorksheetPopulator = new VertexWorksheetPopulator(); try { oVertexWorksheetPopulator.PopulateVertexWorksheet( workbook, false); } catch (WorkbookFormatException) { // Ignore this type of error, which occurs when the vertex // worksheet is missing, for example. } } // Create a graph with the appropriate directedness. PerWorkbookSettings oPerWorkbookSettings = new PerWorkbookSettings(workbook); IGraph oGraph = new Graph(oPerWorkbookSettings.GraphDirectedness); // Read the edge worksheet. This adds data to oGraph, // ReadWorkbookContext.VertexNameDictionary, and // ReadWorkbookContext.EdgeIDDictionary. EdgeWorksheetReader oEdgeWorksheetReader = new EdgeWorksheetReader(); oEdgeWorksheetReader.ReadWorksheet(workbook, readWorkbookContext, oGraph); oEdgeWorksheetReader = null; // Read the vertex worksheet. This adds metadata to the vertices in // oGraph; adds any isolated vertices to oGraph and // ReadWorkbookContext.VertexNameDictionary; and removes any skipped // vertices (and their incident edges) from // ReadWorkbookContext.VertexNameDictionary, // ReadWorkbookContext.EdgeIDDictionary, and oGraph. VertexWorksheetReader oVertexWorksheetReader = new VertexWorksheetReader(); oVertexWorksheetReader.ReadWorksheet(workbook, readWorkbookContext, oGraph); oVertexWorksheetReader = null; if (readWorkbookContext.ReadAllEdgeAndVertexColumns) { // The other worksheets should be ignored. return (oGraph); } if (readWorkbookContext.ReadGroups) { // Read the group worksheets. This adds metadata to the vertices // in oGraph and to oGraph itself. GroupWorksheetReader oGroupWorksheetReader = new GroupWorksheetReader(); oGroupWorksheetReader.ReadWorksheet(workbook, readWorkbookContext, oGraph); oGroupWorksheetReader = null; } // Read the per-workbook settings that are stored directly on the // graph. oPerWorkbookSettings.ReadWorksheet(workbook, readWorkbookContext, oGraph); return (oGraph); }
//************************************************************************* // Method: LoadGraphCore() // /// <summary> /// Creates a graph and loads it with graph data read from a <see /// cref="Stream" />. /// </summary> /// /// <param name="stream"> /// <see cref="Stream" /> containing graph data. /// </param> /// /// <returns> /// A new graph loaded with graph data read from <paramref /// name="stream" />. /// </returns> /// /// <remarks> /// This method creates a graph, loads it with the graph data read from /// <paramref name="stream" />. It does not close <paramref /// name="stream" />. /// /// <para> /// The arguments have already been checked for validity. /// </para> /// /// </remarks> //************************************************************************* protected override IGraph LoadGraphCore( Stream stream ) { Debug.Assert(stream != null); AssertValid(); const String DataMarker = "DATA:"; IGraph oGraph = new Graph(m_eLoadedGraphDirectedness); IVertexCollection oVertices = oGraph.Vertices; // The key is the zero-based vertex order as listed in the file, and // the value is the corresponding IVertex. Dictionary<Int32, IVertex> oVertexDictionary = new Dictionary<Int32, IVertex>(); StreamReader oStreamReader = new StreamReader(stream, StreamEncoding); String sLine; Int32 iLineNumber = 0; // Look for the DL marker. if ( !TryReadLine(oStreamReader, out sLine, ref iLineNumber) || !sLine.StartsWith("DL") ) { OnLoadFormatError( "The file must start with a \"DL\" marker." ); } // Look for the vertex count. Int32 iVertices = 0; while ( TryReadLine(oStreamReader, out sLine, ref iLineNumber) ) { const String Pattern = @"N=(?<Vertices>\d+)"; Regex oRegex = new Regex(Pattern); Match oMatch = oRegex.Match(sLine); if (oMatch.Success && MathUtil.TryParseCultureInvariantInt32( oMatch.Groups["Vertices"].Value, out iVertices) ) { goto LookForFullMatrixMarker; } } OnLoadFormatError( "The file must contain a vertex count in the format \"N=123\"." ); LookForFullMatrixMarker: while ( TryReadLine(oStreamReader, out sLine, ref iLineNumber) ) { if (sLine.IndexOf("FULLMATRIX") >= 0) { goto LookForLabels; } } OnLoadFormatError( "The file must contain a \"FULLMATRIX\" marker." ); LookForLabels: // UCINET 6.223 uses both "ROW LABELS:" and "COLUMN LABELS:" with // identical label sets, although the UCINET Guide says that "LABELS:" // is also supported. Look for either "ROW LABELS:" or "LABELS:". while ( TryReadLine(oStreamReader, out sLine, ref iLineNumber) ) { if (sLine.IndexOf("LABELS:") >= 0) { goto ReadLabels; } if (sLine.IndexOf(DataMarker) >= 0) { // There are no labels. Assign arbitrary vertex names. for (Int32 i = 0; i < iVertices; i++) { AddLoadedVertex("Vertex " + (i + 1).ToString(), oVertices, oVertexDictionary); } goto ReadMatrix; } } goto NoData; ReadLabels: while ( TryReadLine(oStreamReader, out sLine, ref iLineNumber) ) { if (sLine.IndexOf(DataMarker) >= 0) { goto ReadMatrix; } if (sLine.IndexOf("COLUMN LABELS:") >= 0) { goto LookForData; } AddLoadedVertex(sLine.Replace("\"", ""), oVertices, oVertexDictionary); } LookForData: while ( TryReadLine(oStreamReader, out sLine, ref iLineNumber) ) { if (sLine.IndexOf(DataMarker) >= 0) { goto ReadMatrix; } } NoData: OnLoadFormatError( "The file must contain a \"DATA:\" marker." ); ReadMatrix: if (oVertices.Count != iVertices) { OnLoadFormatError( String.Format( "Expected number of vertex labels: {0}. Actual number of" + " vertex labels: {1}." , iVertices, oVertices.Count ) ); } LoadGraphEdges(oGraph, oStreamReader, oVertexDictionary, ref iLineNumber); return (oGraph); }
//************************************************************************* // Method: LoadGraphCore() // /// <summary> /// Creates a graph and loads it with graph data read from a <see /// cref="Stream" />. /// </summary> /// /// <param name="stream"> /// <see cref="Stream" /> containing graph data. /// </param> /// /// <returns> /// A new graph loaded with graph data read from <paramref /// name="stream" />. /// </returns> /// /// <remarks> /// This method creates a graph, loads it with the graph data read from /// <paramref name="stream" />. It does not close <paramref /// name="stream" />. /// /// <para> /// The arguments have already been checked for validity. /// </para> /// /// </remarks> //************************************************************************* protected override IGraph LoadGraphCore( Stream stream ) { Debug.Assert(stream != null); AssertValid(); XmlDocument oXmlDocument = new XmlDocument(); oXmlDocument.Load(stream); XmlNamespaceManager oXmlNamespaceManager = new XmlNamespaceManager( oXmlDocument.NameTable); oXmlNamespaceManager.AddNamespace(GraphMLPrefix, GraphMLUri); XmlNode oGraphMLXmlNode = oXmlDocument.DocumentElement; XmlNode oGraphXmlNode = XmlUtil2.SelectRequiredSingleNode( oGraphMLXmlNode, GraphMLPrefix + ":graph", oXmlNamespaceManager); // Parse the vertex and edge attribute definitions. // // The key is the id attribute of a "key" XML node, and the value is // the corresponding GraphMLAttribute object. Dictionary<String, GraphMLAttribute> oGraphMLAttributeDictionary = ParseGraphMLAttributeDefinitions(oGraphMLXmlNode, oXmlNamespaceManager); GraphDirectedness eGraphDirectedness = GetGraphDirectedness(oGraphXmlNode); IGraph oGraph = new Graph(eGraphDirectedness); // The key is the id attribute of the "node" XML node, and the value is // the corresponding IVertex. Dictionary<String, IVertex> oVertexDictionary = ParseVertices(oGraph, oGraphXmlNode, oXmlNamespaceManager, oGraphMLAttributeDictionary); ParseEdges(oGraph, oGraphXmlNode, oXmlNamespaceManager, oVertexDictionary, oGraphMLAttributeDictionary); SaveGraphMLAttributeNames(oGraph, oGraphMLAttributeDictionary); return (oGraph); }
//************************************************************************* // Method: LoadGraphCore() // /// <summary> /// Creates a graph and loads it with graph data read from a <see /// cref="Stream" />. /// </summary> /// /// <param name="stream"> /// <see cref="Stream" /> containing graph data. /// </param> /// /// <returns> /// A new graph loaded with graph data read from <paramref /// name="stream" />. /// </returns> /// /// <remarks> /// This method creates a graph, loads it with the graph data read from /// <paramref name="stream" />. It does not close <paramref /// name="stream" />. /// /// <para> /// The arguments have already been checked for validity. /// </para> /// /// </remarks> //************************************************************************* protected override IGraph 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); }
//************************************************************************* // Method: CreateSubgraph() // /// <summary> /// Creates a subgraph for one of a graph's vertices. /// </summary> /// /// <param name="oOriginalVertex"> /// The vertex to create a subgraph for. /// </param> /// /// <param name="oCreateSubgraphImagesAsyncArgs"> /// Contains the arguments needed to asynchronously create subgraph images. /// </param> /// /// <returns> /// A new subgraph. /// </returns> //************************************************************************* protected IGraph CreateSubgraph( IVertex oOriginalVertex, CreateSubgraphImagesAsyncArgs oCreateSubgraphImagesAsyncArgs ) { Debug.Assert(oOriginalVertex != null); Debug.Assert(oCreateSubgraphImagesAsyncArgs != null); AssertValid(); // Create a new empty graph that will contain the vertex's subgraph. IGraph oSubgraph = new Graph(); // Clone the original vertex, its adjacent vertices, and the connecting // edges into the subgraph. Decimal decLevels = oCreateSubgraphImagesAsyncArgs.Levels; IVertex oSubgraphVertex = CloneVertexIntoSubgraph(oOriginalVertex, oSubgraph, decLevels); if (oCreateSubgraphImagesAsyncArgs.SelectVertex) { // Select the vertex. oSubgraphVertex.SetValue(ReservedMetadataKeys.IsSelected, true); } if (oCreateSubgraphImagesAsyncArgs.SelectIncidentEdges) { // Select the vertex's incident edges. foreach (IEdge oIncidentEdge in oSubgraphVertex.IncidentEdges) { oIncidentEdge.SetValue(ReservedMetadataKeys.IsSelected, true); } } return (oSubgraph); }
private void CheckLayout(object sender, RoutedEventArgs e) { // Create a graph. The graph has no visual representation -- // it is just a data structure. Graph oGraph = new Graph(GraphDirectedness.Directed); IVertexCollection oVertices = oGraph.Vertices; IEdgeCollection oEdges = oGraph.Edges; // Add three vertices. IVertex oVertexA = oVertices.Add(); oVertexA.Name = "Vertex A"; IVertex oVertexB = oVertices.Add(); oVertexB.Name = "Vertex B"; IVertex oVertexC = oVertices.Add(); oVertexC.Name = "Vertex C"; // Connect the vertices with directed edges. IEdge oEdge1 = oEdges.Add(oVertexA, oVertexB, true); IEdge oEdge2 = oEdges.Add(oVertexB, oVertexC, true); IEdge oEdge3 = oEdges.Add(oVertexC, oVertexA, true); // Lay out the graph within a 100x100 rectangle. This sets // the IVertex.Location property of each vertex. ILayout oLayout = new FruchtermanReingoldLayout(); LayoutContext oLayoutContext = new LayoutContext(new System.Drawing.Rectangle(0,0,100,100)); oLayout.LayOutGraph(oGraph, oLayoutContext); // List the results. foreach (IVertex oVertex in oVertices) { MessageBox.Show("The location of " + oVertex.Name + " is " + oVertex.Location.ToString()); } }
//************************************************************************* // Method: GetSubgraphAsNewGraph() // /// <summary> /// Creates a new graph containing copies of a specified set of vertices /// and the edges that connect them. /// </summary> /// /// <param name="verticesToInclude"> /// A collection of one or more vertices to copy into the new graph. (The /// vertices must all be from the same graph.) /// </param> /// /// <returns> /// A new graph that contains copies of the vertices in <paramref /// name="verticesToInclude" />, along with copies of the edges that /// connect them. /// /// <para> /// No metadata is copied to the new graph, its vertices, or its edges. /// </para> /// /// </returns> //************************************************************************* public static IGraph 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); }
private void Build_Universe_Network(string layoutmethod, string netid) { string SQL; string NodeName; int NodeID, FromID, ToID, EdgeID; double xx2, yy2, size, xx,yy; double px, py; int comments; Random rnd = new Random(); Graph oGraph = new Graph(GraphDirectedness.Directed); IVertexCollection oVertices = oGraph.Vertices; IEdgeCollection oEdges = oGraph.Edges; // Nuke the Display UniverseBackground.Children.Clear(); // Add the Whiskers Programmatically Add_Whiskers(); SQL = "select id, nodename,x,y from nodes where networkid = '" + netid + "'"; OleDbCommand aCommand = new OleDbCommand(SQL, localengine.RepositoryConnection); try { //create the datareader object to connect to table OleDbDataReader aReader = aCommand.ExecuteReader(); //Iterate throuth the database while (aReader.Read()) { NodeID = aReader.GetInt32(0); NodeName = aReader.GetString(1); ListBoxItem li = new ListBoxItem(); li.Content = NodeName; li.Tag = NodeID.ToString(); NodeList.Items.Add(li); px = (double)aReader.GetInt32(2); py = (double)aReader.GetInt32(3); IVertex oVertexA = oVertices.Add(); oVertexA.Name = NodeName; oVertexA.Tag = NodeID; } aReader.Close(); } catch (Exception e) { MessageBox.Show(e.Message); } // Connect the edges SQL = "select edgeid, fromid, toid from edges where networkid='" + netid + "'"; aCommandEdge = new OleDbCommand(SQL, localengine.RepositoryConnection); try { //create the datareader object to connect to table aReaderEdge = aCommandEdge.ExecuteReader(); //Iterate throuth the database while (aReaderEdge.Read()) { EdgeID = aReaderEdge.GetInt32(0); FromID = aReaderEdge.GetInt32(1); ToID = aReaderEdge.GetInt32(2); xx = Getx(FromID); yy = Gety(FromID); xx2 = Getx(ToID); yy2 = Gety(ToID); Line l = new Line(); l.X1 = xx+5; l.Y1 = yy+5; l.X2 = xx2+5; l.Y2 = yy2+5; l.Tag = "EDGE(" + FromID.ToString() + ":" + ToID.ToString() + ")"; l.ToolTip = l.Tag; l.Stroke = new SolidColorBrush(Colors.Gray); UniverseBackground.Children.Add(l); IVertex oFrom=null; IVertex oTo=null; foreach (IVertex oVertex in oVertices) { if (oVertex.Tag.ToString() == FromID.ToString()) { oFrom = oVertex; } if (oVertex.Tag.ToString() == ToID.ToString()) { oTo = oVertex; } } IEdge oEdge1 = oEdges.Add(oFrom, oTo, true); } //aReaderEdge.Close(); } catch (Exception eEdge) { MessageBox.Show(eEdge.Message); } // Apply Layout // ================================================================== switch(layoutmethod) { case "Circular Layout": ILayout oLayout_cir = new CircleLayout(); LayoutContext oLayoutContext_cir = new LayoutContext(new System.Drawing.Rectangle(0, 0, 5000, 5000)); oLayout_cir.LayOutGraph(oGraph, oLayoutContext_cir); break; case "Random Layout": ILayout oLayout_rand = new RandomLayout(); LayoutContext oLayoutContext_rand = new LayoutContext(new System.Drawing.Rectangle(0, 0, 5000, 5000)); oLayout_rand.LayOutGraph(oGraph, oLayoutContext_rand); break; case "Sugiyama Layout": ILayout oLayout_Sugi = new SugiyamaLayout(); LayoutContext oLayoutContext_Sugi = new LayoutContext(new System.Drawing.Rectangle(0, 0, 5000, 5000)); oLayout_Sugi.LayOutGraph(oGraph, oLayoutContext_Sugi); break; case "Grid Layout": ILayout oLayout_grid = new GridLayout(); LayoutContext oLayoutContext_grid = new LayoutContext(new System.Drawing.Rectangle(0, 0, 5000, 5000)); oLayout_grid.LayOutGraph(oGraph, oLayoutContext_grid); break; case "Spiral Layout": ILayout oLayout_spiral = new SpiralLayout(); LayoutContext oLayoutContext_spiral = new LayoutContext(new System.Drawing.Rectangle(0, 0, 5000, 5000)); oLayout_spiral.LayOutGraph(oGraph, oLayoutContext_spiral); break; case "Fruchterman/Reingold Layout": ILayout oLayout_Fruch = new FruchtermanReingoldLayout(); LayoutContext oLayoutContext_Fruch = new LayoutContext(new System.Drawing.Rectangle(0, 0, 5000, 5000)); oLayout_Fruch.LayOutGraph(oGraph, oLayoutContext_Fruch); break; case "Sinusoid H Layout": ILayout oLayout_SinH = new SinusoidHorizontalLayout(); LayoutContext oLayoutContext_SinH = new LayoutContext(new System.Drawing.Rectangle(0, 0, 5000, 5000)); oLayout_SinH.LayOutGraph(oGraph, oLayoutContext_SinH); break; case "Sinusoid V Layout": ILayout oLayout_SinV = new SinusoidVerticalLayout(); LayoutContext oLayoutContext_SinV = new LayoutContext(new System.Drawing.Rectangle(0, 0, 500, 500)); oLayout_SinV.LayOutGraph(oGraph, oLayoutContext_SinV); break; } // List the results. int xoffset=0; int yoffset=0; Random rc = new Random(); Random rx = new Random(); Random ry = new Random(); Random coin = new Random(); foreach (IVertex oVertex in oVertices) { UniversePadPoint p2 = new UniversePadPoint(); p2.PadName = oVertex.Name; xx2 = oVertex.Location.X; yy2 = oVertex.Location.Y; xx2 = xx2 + xoffset; yy2 = yy2 + yoffset; // BUG p2.WhiskX = XWhisker; // BUG p2.WhiskY = YWhisker; size = (double)10; p2.Render(UniverseBackground, FieldBackground, xx2, yy2, size, (int)oVertex.Tag, oVertex.Name); Ellipse re = new Ellipse(); re.Width = rnd.NextDouble() * 80; re.Height = re.Width; re.Opacity = 0.25; re.Tag = "METRIC"; re.Fill = new SolidColorBrush(Colors.Blue); UniverseBackground.Children.Add(re); Canvas.SetLeft(re, xx2-(re.Width/2)+5); Canvas.SetTop(re, yy2 - (re.Width / 2)+5); } foreach (IEdge e2 in oEdges) { IVertex f1 = e2.BackVertex; IVertex t2 = e2.FrontVertex; xx = f1.Location.X; yy = f1.Location.Y; xx2 = t2.Location.X; yy2 = t2.Location.Y; xx = xx + xoffset; yy = yy + yoffset; xx2 = xx2 + xoffset; yy2 = yy2 + yoffset; Line l = new Line(); l.X1 = xx + 5; l.Y1 = yy + 5; l.X2 = xx2 + 5; l.Y2 = yy2 + 5; l.Tag = "EDGE(" + f1.Tag.ToString() + ":" + t2.Tag.ToString() + ")"; l.ToolTip = l.Tag; l.Stroke = new SolidColorBrush(Colors.Gray); UniverseBackground.Children.Add(l); } }
public void TestLayOut() { const Int32 Vertices = 100; IGraph oGraph = new Graph(); IVertex [] aoVertices = TestGraphUtil.AddVertices(oGraph, Vertices); TestGraphUtil.MakeGraphComplete(oGraph, aoVertices, false); // Initialize the vertex locations to impossible values. const Int32 ImpossibleCoordinate = Int32.MinValue; foreach (IVertex oVertex in aoVertices) { oVertex.Location = new Point( ImpossibleCoordinate, ImpossibleCoordinate); } const Int32 Width = 1000; const Int32 Height = 600; Rectangle oRectangle = new Rectangle(0, 0, Width, Height); LayoutContext oLayoutContext = new LayoutContext(oRectangle); m_oFruchtermanReingoldLayout.LayOutGraph(oGraph, oLayoutContext); foreach (IVertex oVertex in aoVertices) { PointF oLocation = oVertex.Location; Single fX = oLocation.X; Assert.AreNotEqual(fX, ImpossibleCoordinate); Assert.IsTrue(fX >= 0); Assert.IsTrue(fX <= Width); Single fY = oLocation.Y; Assert.AreNotEqual(fY, ImpossibleCoordinate); Assert.IsTrue(fY >= 0); Assert.IsTrue(fY <= Height); } }
private void Draw_Universe(string netid) { string SQL; string NodeName; int NodeID, FromID, ToID, EdgeID; double xx2, yy2, size, xx, yy; double px, py; int comments; Random rnd = new Random(); Graph oGraph = new Graph(GraphDirectedness.Directed); IVertexCollection oVertices = oGraph.Vertices; IEdgeCollection oEdges = oGraph.Edges; // Nuke the Display UniverseBackground.Children.Clear(); // Add the Whiskers Programmatically Add_Whiskers(); SQL = "select id, nodename,x,y from nodes where networkid = '" + netid + "'"; OleDbCommand aCommand = new OleDbCommand(SQL, localengine.RepositoryConnection); try { //create the datareader object to connect to table OleDbDataReader aReader = aCommand.ExecuteReader(); //Iterate throuth the database while (aReader.Read()) { NodeID = aReader.GetInt32(0); NodeName = aReader.GetString(1); ListBoxItem li = new ListBoxItem(); li.Content = NodeName; li.Tag = NodeID.ToString(); NodeList.Items.Add(li); px = (double)aReader.GetInt32(2); py = (double)aReader.GetInt32(3); UniversePadPoint p2 = new UniversePadPoint(); p2.PadName = NodeName; xx2 = px; yy2 = py; xx2 = xx2 + 0; yy2 = yy2 + 0; // BUG p2.WhiskX = XWhisker; // BUG p2.WhiskY = YWhisker; size = (double)10; p2.SetDrillFeature(DrillDetailLabel, DrillDetailList, localengine.RepositoryConnection); p2.Render(UniverseBackground, FieldBackground, xx2, yy2, size, (int)NodeID, NodeName); Ellipse re = new Ellipse(); re.Width = rnd.NextDouble() * 80; re.Height = re.Width; re.Opacity = 0.25; re.Tag = "METRIC"; re.Fill = new SolidColorBrush(Colors.Blue); UniverseBackground.Children.Add(re); Canvas.SetLeft(re, xx2 - (re.Width / 2) + 5); Canvas.SetTop(re, yy2 - (re.Width / 2) + 5); } aReader.Close(); } catch (Exception e) { MessageBox.Show(e.Message); } // Connect the edges SQL = "SELECT e.edgeid, e.fromid, n1.x, n1.y, e.toid, n2.x, n2.y "; SQL = SQL + "FROM Edges e, Nodes n1, Nodes n2 "; SQL = SQL + "where e.networkid = '" + netid + "' and n1.networkid = '" + netid + "' and n2.networkid = '" + netid + "' "; SQL = SQL + " and n1.id = e.fromid and n2.id = e.toid "; aCommandEdge = new OleDbCommand(SQL, localengine.RepositoryConnection); try { //create the datareader object to connect to table aReaderEdge = aCommandEdge.ExecuteReader(); //Iterate throuth the database while (aReaderEdge.Read()) { EdgeID = aReaderEdge.GetInt32(0); FromID = aReaderEdge.GetInt32(1); ToID = aReaderEdge.GetInt32(4); xx = aReaderEdge.GetInt32(2); yy = aReaderEdge.GetInt32(3); xx2 = aReaderEdge.GetInt32(5); yy2 = aReaderEdge.GetInt32(6); Line l = new Line(); l.X1 = xx + 5; l.Y1 = yy + 5; l.X2 = xx2 + 5; l.Y2 = yy2 + 5; l.Tag = "EDGE(" + FromID.ToString() + ":" + ToID.ToString() + ")"; l.ToolTip = l.Tag; l.Stroke = new SolidColorBrush(Colors.Gray); UniverseBackground.Children.Add(l); } //aReaderEdge.Close(); } catch (Exception eEdgedDraw) { MessageBox.Show(eEdgedDraw.Message); } }
public void TestTransformLayoutBad3() { // null newLayoutContext. try { IGraph oGraph = new Graph(); LayoutContext oLayoutContext = new LayoutContext(Rectangle.Empty); m_oFruchtermanReingoldLayout.TransformLayout( oGraph, oLayoutContext, null); } catch (ArgumentNullException oArgumentNullException) { Assert.AreEqual( "Microsoft.NodeXL.Layouts.FruchtermanReingoldLayout." + "TransformLayout: newLayoutContext argument can't be" + " null.\r\n" + "Parameter name: newLayoutContext" , oArgumentNullException.Message ); throw oArgumentNullException; } }
public void TestParentGraph() { // Add the vertex to a graph. IGraph oGraph = new Graph(); oGraph.Vertices.Add(m_oVertex); Assert.AreEqual(oGraph, m_oVertex.ParentGraph); }