\documentclass[11pt,letterpaper]{article} \usepackage{url} \usepackage{graphicx} \usepackage{newtxtext} \usepackage{xcolor} \usepackage[]{hyperref} \usepackage[cmintegrals,cmbraces]{newtxmath} % times roman, the classic \hypersetup{ colorlinks = true, %Colours links instead of ugly boxes urlcolor = {blue!80!black}, %Colour for external hyperlinks linkcolor = {blue!80!black}, %Colour of internal links citecolor = red %Colour of citations } \usepackage{lgrind} \usepackage{footnote} %\usepackage[margin=0.5in]{geometry} \addtolength{\oddsidemargin}{-.875in} \addtolength{\evensidemargin}{-.875in} \addtolength{\textwidth}{1.75in} \renewcommand\floatpagefraction{.9} \renewcommand\topfraction{.9} \renewcommand\bottomfraction{.9} \renewcommand\textfraction{.1} %\setcounter{totalnumber}{50} %\setcounter{topnumber}{50} %\setcounter{bottomnumber}{50} %\setlength{\textwidth}{8.0in} %\oddsidemargin 0in %\evensidemargin .5in %\textwidth 7.5in \author{Stephen C. North \\ {\small scnorth@gmail.com} \and Emden R.~Gansner \\ {\small erg@graphviz.com} } \title{Cgraph Tutorial} \date{\today} \begin{document} %\begin{titlepage} \maketitle \newpage \tableofcontents \newpage %\thispagestyle{empty} %\end{titlepage} %\pagenumbering{arabic} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Introduction} \label{sec:introduction} Cgraph is a C library for graph programming. It defines data types and operations for graphs comprised of attributed nodes, edges and subgraphs. Attributes may be string name-value pairs for convenient file I/O, or internal C data structures for efficient algorithm implementation. Cgraph is aimed at graph representation; it is not an library of higher-level algorithms such as shortest path or network flow. We envision these as higher-level libraries written on top of Cgraph. Efforts were made in Cgraph's design to strive for time and space efficiency. The basic (unattributed) graph representation takes 104 bytes per node and 64 bytes per edge, so storage of graphs with millions of objects is reasonable. For attributed graphs, Cgraph also maintains an internal shared string pool, so if all the nodes of a graph have \verb'color=red', only one copy of \verb'"color"' and \verb'"red"' are made. There are other tricks that experts can exploit for flat-out coding efficiency. For example, there are ways to inline the instructions for edge list traversal and internal data structure access. Cgraph uses Phong Vo's dictionary library, libcdt, to store node and edge sets. This library provides a uniform interface to hash tables and splay trees, and its API is usable for general programming (such as storing multisets, hash tables, lists and queues) in Cgraph programs. {\bf Notation} In the following, we use \verb"TRUE" to denote a non-zero value, and \verb"FALSE" to denote zero. \section{Graph Objects} \label{sec:graphobjects} Almost all Cgraph programming can be done with pointers to these data types: \begin{itemize} \item \verb"Agraph_t": a graph or subgraph \item \verb"Agnode_t": a node from a particular graph or subgraph \item \verb"Agedge_t": an edge from a particular graph or subgraph \item \verb"Agsym_t": a descriptor for a string-value pair attribute \item \verb"Agrec_t": an internal C data record attribute of a graph object \end{itemize} Cgraph is responsible for its own memory management; allocation and deallocation of Cgraph data structures is always done through Cgraph calls. \section{Graphs} \label{sec:graphs} A top-level graph (also called a root graph) defines a universe of nodes, edges, subgraphs, data dictionaries and other information. A graph has a name and two properties: whether it is directed or undirected, and whether it is strict (multi-edges are forbidden). \footnote{It is possible to specify that a graph is simple (neither multi-edges nor loops), or can have multi-edges but not loops.} Note that nodes, edges and subgraphs exists in exactly one root graph. They cannot be used independently of that graph, or attached to another root graph. The following examples use the convention that \verb"G" and \verb"g" are \verb"Agraph_t*" (graph pointers), \verb"n", \verb"u", \verb"v", \verb"w" are \verb"Agnode_t*" (node pointers), and \verb"e", \verb"f" are \verb"Agedge_t*" (edge pointers). To make a new, empty top-level directed graph: \begin{verbatim} Agraph_t *g; g = agopen("G", Agdirected, NULL); \end{verbatim} The first argument to \verb"agopen" is any string, and is not interpreted by Cgraph, except it is recorded and preserved when the graph is written as a file.\footnote{An application could, of course, maintain its own graph catalogue using graph names.} The second argument indicates the type of graph, and should be one of {\tt Agdirected}, {\tt Agstrictdirected}, {\tt Agundirected}, or {\tt Agstrictundirected}. The third argument is an optional pointer to a collection of methods for overriding certain default behaviors of Cgraph, and in most situations can just be {\tt NULL}. You can get the name of a graph by \verb"agnameof(g)", and you can get its properties by the predicate functions {\tt agisdirected(g)} and {\tt agisstrict(g)}. You can also construct a new graph by reading a file: \begin{verbatim} g = agread(stdin,NULL); \end{verbatim} Here, the graph's name, type and contents including attributes depend on the file contents. (The second argument is the same optional method pointer mentioned above for \verb"agopen"). If the default I/O discipline is used and the stream is wide-oriented, the behavior is undefined. Sometimes it is convenient to have the graph represented concretely as a character string \verb"str". In this case, the graph can be created using: \begin{verbatim} g = agmemread (str); \end{verbatim} You can write a representation of a graph to a file: \begin{verbatim} g = agwrite(g,stdout); \end{verbatim} \verb"agwrite" creates an external representation of a graph's contents and attributes (except for internal attributes), that can later be reconstructed by calling \verb"agread" on the same file.\footnote{It is the application programmer's job to convert between internal attributes to external strings when graphs are read and written, if desired. This seemed better than inventing a complicated way to automate this conversion.} If the default I/O discipline is used and the stream is wide-oriented, the behavior is undefined. \verb"agnnodes(g)", \verb"agnedges(g)" and \verb"agnsubg(g)" return the count of nodes, edges and (immediate) subgraphs in a graph (or subgraph). To delete a graph and its associated data structures, freeing their memory, one uses: \begin{verbatim} agclose(g); \end{verbatim} Finally, there is an interesting if obscure function to concatenate the contents of a graph file onto an existing graph, as shown here. \begin{verbatim} g = agconcat(g,stdin,NULL); \end{verbatim} \section{Nodes} \label{sec:nodes} In Cgraph, a node is usually identified by a unique string name and a unique internal integer ID assigned by Cgraph. (For convenience, you can also create "anonymous" nodes by giving \verb"NULL" as the node name.) A node also has in- and out-edge sets, even in undirected graphs. Once you have a graph, you can create or search for nodes this way: \begin{verbatim} Agnode_t *n; n = agnode(g,"node28",TRUE); \end{verbatim} The first argument is a graph or subgraph in which the node is to be created. The second is the name (or NULL for anonymous nodes.) When the third argument is \verb"TRUE", the node is created if it doesn't already exist. When it's \verb"FALSE", as shown below, then Cgraph searches to locate an existing node with the given name, returning NULL if none is found. \begin{verbatim} n = agnode(g,"node28",FALSE); \end{verbatim} The function \verb"agdegree(g, n, in, out)" gives the degree of a node in (sub)graph \verb"g", where \verb"in" and \verb"out" select the edge sets. \begin{itemize} \item \verb"agdegree(g,n,TRUE,FALSE)" returns the in-degree. \item \verb"agdegree(g,n,FALSE,TRUE)" returns the out-degree. \item \verb"agdegree(g,n,TRUE,TRUE)" returns their sum. \end{itemize} The function \verb"agcountuniqedges" is identical to {\tt agdegree} except when the last two arguments are both \verb"TRUE". In this case, a loop is only counted once. \verb"agnameof(n)" returns the printable string name of a node. Note that for various reasons this string may be a temporary buffer that can be overwritten by subsequent calls. Thus, the usage \begin{verbatim} printf("%s %s\n",agnameof(agtail(e)),agnameof(aghead(e))); \end{verbatim} is unsafe because the buffer may be overwritten when the arguments to printf are being computed. A node can be deleted from a graph or subgraph by \verb"agdelnode(g,n)". \section{Edges} \label{sec:edges} An edge is a node pair: an ordered pair in a directed graph, unordered in an undirected graph. For convenience there is a common edge data structure for both kinds and the endpoints are the fields \verb"tail" and \verb"head". \footnote{When an edge is created, the first node will be used as the tail node, and the second node as the head.} Because an edge is implemented as an edge pair, there are two valid pointers to the same edge, so simple pointer comparison does not work for edge equality. The function \verb"ageqedge(Agedge_t *e0, Agedge_t *e1)" evaluates to true if the two pointers represent the same abstract edge, and should usually be used for edge comparisons. An edge is made using \begin{verbatim} Agnode_t *u, *v; Agedge_t *e; /* assume u and v are already defined */ e = agedge(g,u,v,"e28",TRUE); \end{verbatim} \verb"u" and \verb"v" must belong to the same graph or subgraph for the operation to succeed. The ``name'' of an edge (more correctly, identifier) is treated as a unique identifier for edges between a particular node pair. That is, there can only be at most one edge with name \verb"e28" between any given \verb"u" and \verb"v", but there can be many other edges \verb"e28" between other nodes. \verb"agtail(e)" and \verb"aghead(e)" return the endpoints of \verb"e". If \verb"e" is created as in the call to \verb"agedge" above, \verb"u" will be the tail node and \verb"v" will be the head node. This holds true even for undirected graphs. The value \verb"e->node" is the ``other'' endpoint with respect to the node from which e was obtained. That is, if \verb"e" is an out-edge of node \verb"n" (equivalently, \verb"n" is the tail of \verb"e"), then \verb"e->node" is the head of \verb"e". A common idiom is: \begin{verbatim} for (e = agfstout(g,n); e; e = agnxtout(g,e)) /* do something with e->node */ \end{verbatim} \verb"agedge" can also search for edges: \begin{verbatim} /* finds any u,v edge */ e = agedge(g,u,v,NULL,FALSE); /* finds a u,v edge with name "e8" */ e = agedge(g,u,v,"e8",FALSE); \end{verbatim} In an undirected graph, an edge search will consider the given vertices as both tail and head nodes. An edge can be deleted from a graph or subgraph by \verb"agdeledge(g,e)". The \verb"agnameof" function can be used to get the ``name'' of an edge. Note that this will be the identifier string provided at edge creation. The names of the head and tail nodes will not be part of the string. In addition, it returns NULL for anonymous edges. \section{Traversals} \label{sec:traversals} Cgraph has functions for iterating over graph objects. For example, we can scan all the edges of a graph (directed or undirected) by the following: \begin{verbatim} for (n = agfstnode(g); n; n = agnxtnode(g,n)) { for (e = agfstout(g,n); e; e = agnxtout(g,e)) { /* do something with e */ } } \end{verbatim} \label{traversal} The functions \verb"agfstin(g,n)" and \verb"afnxtin(g,e)" are provided for walking in-edge lists. In the case of a directed edge, the meanings of ``in'' and ``out'' are obvious. For undirected graphs, Cgraph assigns an orientation based on the analogous order of the two nodes when the edge is created. To visit all the edges of a node in an undirected graph: \begin{verbatim} for (e = agfstedge(g,n); e; e = agnxtedge(g,e,n)) /* do something with e */ \end{verbatim} Be careful if your code deletes an edge or node during the traversal, as then the object will no longer be valid to get the next object. This is typically handled by code like: \begin{verbatim} for (e = agfstedge(g,n); e; e = f) { f = agnxtedge(g,e,n)) /* delete e */ } \end{verbatim} Traversals are guaranteed to visit the nodes of a graph, or edges of a node, in their order of creation in the root graph (unless we allow programmers to override object ordering, as mentioned in section~\ref{sec:openissues}). \section{External Attributes} \label{sec:externalattributes} Graph objects may have associated string name-value pairs. When a graph file is read, Cgraph's parser takes care of the details of this, so attributes can just be added anywhere in the file. In C programs, values must be declared before use. Cgraph assumes that all objects of a given kind (graphs/subgraphs, nodes, or edges) have the same attributes - there's no notion of subtyping within attributes. Information about attributes is stored in data dictionaries. Each graph has three (for graphs/subgraphs, nodes, and edges) for which you'll need the predefined constants AGRAPH, AGNODE and AGEDGE in calls to create, search and walk these dictionaries. Thus, to create an attribute for nodes, one uses: \begin{verbatim} Agsym_t *sym; sym = agattr(g,AGNODE,"shape","box"); \end{verbatim} If this succeeds, \verb"sym" points to a descriptor for the newly created (or updated) attribute. (Thus, even if \verb"shape" was previously declared and had some other default value, it would be set to \verb"box" by the above.) By using a NULL pointer as the value, you can use the same function to search the attribute definitions of a graph. \begin{verbatim} sym = agattr(g,AGNODE,"shape",0); if (sym) printf("The default shape is %s.\n",sym->defval); \end{verbatim} If you have the pointer to some graph object, you can also use the function \verb"agattrsym". \begin{verbatim} Agnode_t* n; Agsym_t* sym = agattrsym (n,"shape"); if (sym) printf("The default shape is %s.\n",sym->defval); \end{verbatim} Both functions return NULL if the attribute is not defined. Instead of looking for a particular attribute, it is possible to iterate over all of them: \begin{verbatim} sym = 0; /* to get the first one */ while (sym = agnxtattr(g,AGNODE,sym) printf("%s = %s\n",sym->name,sym->defval); \end{verbatim} Assuming an attribute already exists for some object, its value can be obtained or set using its string name or its \verb"Agsym_t" descriptor. To use the string name, we have: \begin{verbatim} str = agget(n,"shape"); agset(n,"shape","hexagon"); \end{verbatim} If an attribute will be referenced often, it is faster to use its descriptor as an index, as shown here: \begin{verbatim} Agsym_t *sym = agattr(g,AGNODE,"shape","box"); str = agxget(n,sym); agxset(n,sym,"hexagon"); \end{verbatim} Cgraph provides two helper functions for dealing with attributes. The function \verb"agsafeset(void *obj, char *name, char *value, char *def)" first checks that the attribute has been defined, defining it with the default value \verb"def" if not. It then uses \verb"value" as the specific value assigned to \verb"obj". It is sometimes useful to copy all of the values from one object to another. This can be easily done using \verb"agcopyattr(void *src, void* tgt)". This assumes that the source and target are the same type of graph objects, and that the attributes of \verb"src" have already been defined for \verb"tgt". If \verb"src" and \verb"tgt" belong to the same root graph, this will automatically be true. \section{Internal Attributes} \label{sec:internalattributes} It would be possible to do everything using just string-valued attributes. In general, though, this will be too inefficient. To deal with this, each graph object (graph, node or edge) may have a list of associated internal data records. The layout of each such record is programmer-defined, except each must have an \verb"Agrec_t" header. The records are allocated through Cgraph. For example: \begin{verbatim} typedef struct mynode_s { Agrec_t h; int count; } mynode_t; mynode_t *data; Agnode_t *n; n = agnode(g,"mynodename",TRUE); data = (mynode_t*)agbindrec(n,"mynode_t", sizeof(mynode_t),FALSE); data->count = 1; \end{verbatim} In a similar way, \verb"aggetrec" searches for a record, returning a pointer to the record if it exists and NULL otherwise; \verb"agdelrec" removes a record from an object. Although each graph object may have its own unique, individual collection of records, for convenience, there are functions that update an entire graph by allocating or removing the same record from all nodes, edges or subgraphs at the same time. These functions are: \begin{verbatim} void aginit(Agraph_t *g, int kind, char *rec_name, int rec_size, int move_to_front); void agclean(Agraph_t *g, int kind, char *rec_name); \end{verbatim} Note that in addition to \verb"agdelrec" and \verb"agclean", records are removed and their storage freed when their associated graph object is deleted. Only the record data structure is freed. If the application has attached any additional heap memory to a record, it is the responsibility of the application to handle this before the actual record is deleted. For further efficiency, there is a way to ``lock'' the data pointer of a graph object to point to a given record. This can be done by using \verb"TRUE" as the last argument in \verb"agbindrec", \verb"aginit" or \verb"aggetrec". If this is done, in the above example we could then simply cast this pointer to the appropriate type for direct (un-typesafe) access to the data. \begin{verbatim} (mydata_t*) (n->base.data)->count = 1; \end{verbatim} Typically, it is convenient to encapsulate this access using macros. For example, we may have: \begin{verbatim} #define ND_count(n) (((mydata_t*)(AGDATA(n)))->count) ND_count(n) = 1; \end{verbatim} As this is unsafe if the record was not allocated for some object, it is good form to two versions of the macro: \begin{verbatim} #ifdef DEBUG #define ND_count(n) \ (assert(aggetrec(n,"mynode_t",1)),((mynode_t*)(AGDATA(n)))->count) #else #define ND_count(n) (((mydata_t*)(AGDATA(n)))->count) #endif \end{verbatim} \section{Subgraphs} \label{sec:subgraphs} Subgraphs are an important construct in Cgraph. They are intended for organizing subsets of graph objects and can be used interchangeably with top-level graphs in almost all Cgraph functions. A subgraph may contain any nodes or edges of its parent. (When an edge is inserted in a subgraph, its nodes are also implicitly inserted if necessary. Similarly, insertion of a node or edge automatically implies insertion in all containing subgraphs up to the root.) Subgraphs of a graph form a hierarchy (a tree). Cgraph has functions to create, search, and iterate over subgraphs. For example, \begin{verbatim} Agraph_t *g, *h; /* search for subgraph by name */ h = agsubg(g,"mysubgraph",FALSE); if (!h) /* create subgraph by name */ h = agsubg(g,"mysubgraph",TRUE); for (h = agfstsubg(g); h; h = agnxtsubg(h)) { /* agparent is up one level */ assert (g == agparent(h)); /* Use subgraph h */ } \end{verbatim} The function \verb"agparent" returns the (sub)graph immediately containing the argument subgraph. The iteration done using \verb"agfstsubg" and \verb"agnxtsubg" returns only immediate subgraphs. To find subgraphs further down the hierarchy requires a recursive search. It is not uncommon to want to populate a subgraph with nodes and edges that have already been created. This can be done using the functions \verb"agsubnode" and \verb"agsubedge", \begin{verbatim} Agnode_t *agsubnode(Agraph_t *g, Agnode_t *n, int create); Agedge_t *agsubedge(Agraph_t *g, Agedge_t *e, int create); \end{verbatim} which take a subgraph, and an object from another subgraph of the same graph (or possibly a top-level object) and add it to the argument subgraph if the \verb"create" flag is \verb"TRUE". It is also added to all enclosing subgraphs, if necessary. If the \verb"create" flag is \verb"FALSE", then the request is only treated as a search and returns NULL for failure. A subgraph can be removed by \verb"agdelsubg(g,subg)" or by \verb"agclose(subg)". \section{Utility Functions and Macros} \label{sec:utilityfunctionsandmacros} For convenience, Cgraph provides some polymorphic functions and macros that apply to all Cgraph objects. (Most of these functions could be implemented in terms of others already described, or by accessing fields in the \verb"Agobj_t" base object. \begin{itemize} \item \verb"AGTYPE(obj)": object type - AGRAPH, AGNODE, or AGEDGE \item \verb"AGID(obj)": internal object ID (an unsigned long) \item \verb"AGSEQ(obj)": object creation timestamp (an integer) \item \verb"AGDATA(obj)": data record pointer (an \verb"Agrec_t*") \end{itemize} Other useful functions include: \begin{verbatim} /* Returns root graph of obj */ Agraph_t *agroot(void* obj); /* Returns root graph of obj or obj if a (sub)graph */ Agraph_t *agraphof(void* obj); /* True of obj belongs to g */ int agcontains(Agraph_t *g, void *obj); /* Delete obj from the (sub)graph */ int agdelete(Agraph_t *g, void *obj); /* Synonym of AGTYPE */ int agobjkind(void *obj); \end{verbatim} A root graph \verb"g" will always have \begin{verbatim} g == agroot(g) == agraphof(g) \end{verbatim} \section{Error Handling} \label{sec:errorhandling} Cgraph provides some basic error handling functions, hampered by the lack of exceptions in C. At present, there are basically two types of anomalies: warnings and errors. To report an anomaly, one uses: \begin{verbatim} typedef enum { AGWARN, AGERR, AGMAX, AGPREV } agerrlevel_t; int agerr(agerrlevel_t level, const char *fmt, ...); \end{verbatim} The \verb"agerr" function has a \verb"printf"-interface, with the first argument indicating the severity of the problem. A message is only written if its severity is higher than a programmer-controlled minimum, which is AGWARN by default. The programmer can set this value using \verb"agseterr", which returns the previous value. Calling \verb"agseterr(AGMAX)" turns off the writing of messages. Sometimes additional context information is only available in functions calling the function where the error is actually caught. In this case, the calling function can indicate that it is continuing the current error by using \verb"AGPREV" as the first argument. The function \verb"agwarningf" is shorthand for \verb"agerr(AGWARN,...)"; similarly, \verb"agerrorf" is shorthand for \verb"agerr(AGERR,...)". Some applications desire to directly control the writing of messages. Such an application can use the function \verb"agseterrf" to register a function that the library should call to actually write the message: \begin{verbatim} typedef int (*agusererrf) (char*); agusererrf agseterrf(agusererrf); \end{verbatim} The previous error function is returned. By default, the messages are written to \verb"stderr". Errors not written are stored in a log file. The last recorded error can be retrieved by calling \verb"aglasterr". The function \verb"agerrors" returns the maximum severity reported to \verb"agerr". The function \verb"agreseterrors" is identical, except it also resets the error level as though no errors have been reported. \section{Strings} \label{sec:strings} As mentioned, Cgraph maintains a reference-counted shared string pool for each graph. As there are often many identical strings used in a graph, this helps to reduce the memory overhead. \begin{verbatim} char *agstrdup(Agraph_t *, char *); char *agstrbind(Agraph_t *, char*); int agstrfree(Agraph_t *, char *); char *agstrdup_html(Agraph_t *, char *); int aghtmlstr(char *); char *agcanonStr(char *str); char *agstrcanon(char *, char *); char *agcanon(char *, int); \end{verbatim} Cgraph has functions to directly create and destroy references to shared strings. As with any reference-counted object, you can use these as ordinary strings, though the data should not be modified. If you need to store the pointer in some data structure, you should call \verb"agstrdup(g,s)". This will create a new copy of \verb"s" if necessary, and increment the count of references, ensuring that the string will not be freed by some other part of the program while you are still using it. Since \verb"agstrdup" makes a copy of the string, the argument string can use temporary storage. A call to \verb"agstrfree(g,s)" decrements the reference count and, if this becomes zero, frees the string. The function \verb"agstrbind(g,s)" checks if a shared string identical to \verb"s" exists and, if so, returns it. Otherwise, it returns NULL. The DOT language supports a special type of string, containing HTML-like markups. To make sure that the HTML semantics are used, the application should call \verb"agstrdup_html(g,s)" rather than \verb"agstrdup(g,s)". The following code makes sure the node's label will be interpreted as an HTML-like string and appear as a table. If \verb"agstrdup" were used, the label would appear as the literal string \verb"s". \begin{verbatim} Agraph_t* g; Agnode_t* n; char* s = "
| one cell |