|
||||||||||||||||||||||
|
||||||||||||||||||||||
|
Announcements
Services
Chapters
Feature Zones
|
There has been a lot of changes to the source code and the article below, since the first submission on Dec. 8. IntroductionThis article presents a Generic Graph Library, 100% C#. This library is an attempt to port the Boost Graph Library (BGL) from C++ to C#. Graph problems arise in a number of situations (more often that you would think): file compilation order, network band-with, shortest path, etc. The library provides the basic data structure to represent vertices, edges and graphs, and also provides generic implementation of various graph algorithms such as the depth-first-search, the Dijkstra shortest path, etc. As the library comes with a full NDoc reference manual, this article will not enter into deep coding details. About Graph TheoryThis is a quick remainder about graph theory:
A directed graph G=(VxE) consists of a finite set V=V(G) of vertices and a finite multi-set E contained in VxV = {(u,v)| u,v in V} of edges that are ordered pair of vertices. If e=(u,v), then e is an outgoing edge of u and an incoming edge of v. indegree(v) denotes the number of incoming edges of v and outdegree(u), the number of outgoing edges of u. Classic graph examples are:
What is the BoostGraphLibrary?This section discusses aspects about the porting from C++ to C# of the BoostGraphLibrary. The BoostGraphLibrary is a C++ generic graph library that introduces itself as such: "Graphs are mathematical abstractions that are useful for solving many types of problems in computer science. Consequently, these abstractions must also be represented in computer programs. A standardized generic interface for traversing graphs is of utmost importance to encourage reuse of graph algorithms and data structures. Part of the Boost Graph Library is an interface for how the structure of a graph can be accessed using a generic interface that hides the details of the graph data structure implementation. This is an "open" interface in the sense that any graph library that implements this interface will be interoperable with the BGL generic algorithms and with other algorithms that also use this interface. BGL provides some general purpose graph classes that conform to this interface, but they are not meant to be the "only" graph classes; there certainly will be other graph classes better for certain situations. We believe that the main contribution of the BGL is the formulation of this interface." Introduction taken from the BGL introduction page. QuickGraphLibrary has been highly influenced by the BGL implementation and, indeed, a large part of the concept and structure of the library is directly taken from the BGL. Here below, some major points about porting the BGL to C# are discussed. No templates in C#:This is, for sure, the biggest issue: C# does not support templates... yet (Generics in .NET 2.0). So class templates, function templates and partial template specialization could not be used. At first, without templates, the genericity of the library is seriously compromised. Concepts and C# interface: natural friendsThe C# interfaces come to the rescue. Indeed, they are the natural C# equivalent of the abstract concepts. In fact, turning a BGL concept into a C# interface is just a matter of ... writing the valid expressions into an interface. For example, the public interface IVertexListGraph :
IGraph // this interface defines the Graph conecpt
{
IVertex AddVertex();
void RemoveVertex(IVertex u);
}
A model of the public class AdjacencyGraph : ..., IVertexListGraph
All the QuickGraph concepts are centralized in the ConceptChecking and C# interface: natural friendsC# interfaces have a lot of advantages. In fact, they enforce the implementation of their defined methods which is implicitly a form of ConceptChecking. Visitors ... no Events!The BGL adds great flexibility and reusability to its algorithms through the use of visitors (see the VisitorPattern of the GoF). In the BGL, to define visitors, you must first create a visitor class that defines a number of methods. For instance, in the In QuickGraph, the decision could be done to reuse the BGL visitor pattern, but it turned out that C# provided a much flexible solution: events. In C#, events are delegates, i.e. function calls dispatcher, to which static functions or instance bound methods (handlers) can be attached. Whenever this event is fired, the handlers are called. Therefore, the BGL visitor methods naturally translate into events where visitors can attach their handlers. Another interesting advantage about delegates is that they are multi-cast. Therefore, multiple visitors can be attached to the same algorithm out-of-the-box. Vertex, edge descriptors... ProvidersIn the BGL, the choice of vertex and edge descriptor comes out-of-the-box with the use of templates. To tackle this problem, QuickGraph asks the user to provide Quick description of the libraryAs in the BGL, concepts play crucial role in QuickGraph. They are implemented by interfaces in the
The AdjacencyGraph classThe // Create new graph
AdjacencyGraph g = new AdjacencyGraph(
new VertexAndEdgeProvider(), // vertex and edge provider
true // directed graph
);
// adding vertices u,v
IVertex u = g.AddVertex(); // IVertexMutableGraph
IVertex v = g.AddVertex();
// adding the edge (u,v)
IEdge e = g.AddEdge(u,v); // IEdgeMutableGraph
Since the vertices and the edges are sets, indexing and ordering does not have a sense on these collections. However, they can easily be iterated: //iterating vertices
foreach(IVertex v in g.Vertices) // IVertexListGraph
{
...
}
// iterating edges
foeach(IEdge e in g.Edges) // IEdgeListGraph
{
...
}
Vertices and edges can also be removed from the graph: //this will automatically remove the in and out edges of u
g.Remove(u); // IVertexMutableGraph
g.Remove(e);
Attaching data to vertices and edgesSimilarly to the BGL property map, it is the user's job to create and maintain data maps to associate data to vertices and edges. The namespace The following example shows how to create a vertex name map: using QuickGraph.Collections;
...
VertexStringDictionary names = new VertexStringDictionary();
IVertex u = g.AddVertex();
names[u] = "u";
AlgorithmsAlgorithms are the problem solvers of the library. Without algorithms, this library would not have much sense. Similar to the BGL, the algorithms are implemented in a generic way using a Visitor pattern. The algorithms call user defined actions at specific events: when a vertex is discovered for the first time, when an edge is discovered for the first time, etc... In QuickGraph, the visitor pattern is implemented through events. Quick Example
Let us illustrate that with an example, the depth-first-search algorithm. When possible, a depth-first traversal chooses a vertex adjacent to the current vertex to visit next. If all adjacent vertices have already been discovered, or there are no adjacent vertices, then the algorithm backtracks to the last vertex that had undiscovered neighbors. Once all reachable vertices have been visited, the algorithm selects from any remaining undiscovered vertices and continues the traversal. The algorithm finishes when all vertices have been visited. Depth-first search is useful for categorizing edges in a graph, and for imposing an ordering on the vertices. To achieve that, the algorithms use colors: vertex color markers:
In QuickGraph, the depth first search is implemented by the
The application of the depth first search to a simple graph is detailed in the figures below. The code to achieve this looks (more or less) as follows: // A graph that implements the IVertexListGraph interface
IVertexListGraph g = ...;
// create algorithm
DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g);
//do the search
dfs.Compute();
The figures above show when the events are called. The events can be used by the user to achieve custom actions. For example, suppose that you want to record the vertex predecessors (this will create an ordering), first you need to create a class that provides a delegate for the class PredecessorRecorder
{
private VertexEdgeDictionary m_Predecessors;
public PredecessorRecorder()
{
m_Predecessors = new VertexEdgeDictionary();
}
// the delegate
public void RecordPredecessor(object sender, EdgeEventArgs args)
{
m_Predecessors[ args.Edge.Target ] = args.Edge;
}
}
The PredecessorRecorder p = new PredecessorRecorder();
// adding handler
dfs.TreeEdge += new EdgeHandler( p.RecordPredecessor );
Therefore, plugging custom actions to algorithms is quite easy and take full advantage of the event-multidelegates feature of C#. Other algorithms are available and detailed in the NDoc documentation. GraphViz Renderer and Web ControlVisualization of the graph can be done using the Graphviz renderer and web control. Graphviz is an open source C application for drawing directed and undirected graphs. A BIG thanks can be done to Leppie who took the time and work to port the Graphviz application to .NET Graphviz RendererQuickGraph provides a number of helper classes to output your graphs using Graphviz:
The following examples renders the graph to SVG and uses the vertex name map to render the vertices' name: public class MyRenderer
{
private VertexStringDictionary m_Names; // name map
private GraphvizVertex m_Vertex; // helper
...
// vertex delegate
public WriteVertex(Object sender, VertexEventArgs args)
{
// sender is of type GraphvizWriterAlgorithm
GraphvizWriterAlgorithm algo = (GraphvizWriterAlgorithm)sender;
// setting name
m_Vertex.Label = m_Names[args.Vertex];
// outputing
algo.Output.Write( m_Vertex.ToDot() );
}
// rendering method
public void Render(Graph g, VerteStringDictionary names)
{
m_Names =names;
GraphvizWriterAlgorithm algo = new GraphvizWriterAlgorithm(g);
algo.WriteVertex += new VertexHandler( this.WriteVertex );
algo.Renderer.ImageType = GraphvizImageType.Svg;
algo.Compute();
}
}
Graphviz Web ControlA server web control, The following examples show how to use the control:
Licensezlib/png license. History
References
| |||||||||||||||||||||