Debian Codegraph @

lib/mlrisc-lib/MLRISC/Doc/latex/graphs.tex

raw
1 \section{The Graph Library}
2
3 \subsection{Overview}
4
5 Graphs are the most fundamental data structure in the \MLRISC{} system,
6 and in fact in many optimizing compilers.
7 \MLRISC{} now contains an extensive library for working with graphs.
8
9 All graphs in \MLRISC{}
10 are modeled as edge- and node-labeled directed multi-graphs.
11 Briefly, this means that nodes and edges can carry user supplied data, and
12 multiple directed edges can be attached between any two nodes.
13 Self-loops are also allowed.
14
15 A node is uniquely identified by its \sml{node_id}, which is
16 simply an integer. Node ids can be assigned externally
17 by the user, or else generated automatically by a graph. All graphs
18 keep track of all node ids that are currently used,
19 and the method \sml{new_id : unit -> node_id} generates a new unused id.
20
21 A node is modeled as a node id and node label pair, $(i,l)$.
22 An edge is modeled as a triple $i \edge{l} j$, which contains
23 the \newdef{source} and \newdef{target} node ids $i$ and $j$,
24 and the edge label $l$. These types are defined as follows:
25 \begin{SML}
26 type 'n node = node_id * 'n
27 type 'e edge = node_id * node_id * 'e
28 \end{SML}
29
30 \subsubsection{The graph signature}
31
32 All graphs are accessed through an abstract interface
33 of the polymorphic type \sml{('n,'e,'g) graph}.
34 Here, \sml{'n} is the type of the node labels, \sml{'e} is the type
35 of the edge labels, and \sml{'g} is the type of any extra information
36 embedded in a graph. We call the latter \sml{graph info}.
37
38 Formally, a graph $G$ is a quadruple $(V,L,E,I)$
39 where $V$ is a set of node ids, $L : V -> 'a$ is a node labeling
40 function from vertices to node labels, $E$ is a multi-set
41 of labeled-edges of type $V * V * 'e$, and $I: 'g$
42 is the graph info.
43
44 The interface of a graph is packaged into a
45 record of methods that manipulate the base representation:
46 \begin{SML}
47 signature \mlrischref{graphs/graph.sig}{GRAPH} = sig
48 type node_id = int
49 type 'n node = node_id * 'n
50 type 'e edge = node_id * node_id * 'e
51
52 exception Graph of string
53 exception Subgraph
54 exception NotFound
55 exception Unimplemented
56 exception Readonly
57
58 datatype ('n,'e,'g) graph = GRAPH of ('n,'e,'g) graph_methods
59 withtype ('n,'e,'g) graph_methods =
60 \{ name : string,
61 graph_info : 'g,
62 (* selectors *)
63 (* mutators *)
64 (* iterators *)
65 \}
66 end
67 \end{SML}
68
69 A few exceptions are predefined in this signature, which have
70 the following informal interpretation.
71 Exception \sml{Graph} is raised when a bug is encountered.
72 The exception \sml{Subgraph} is raised if certain semantics constraints
73 imposed on a graph are violated.
74 The exception \sml{NotFound} is raised if lookup of a node id fails.
75 The exception \sml{Unimplemented} is raised if a certain feature
76 is accessed but is undefined on the graph. The exception
77 \sml{Readonly} is raised if the graph is readonly and an update operation
78 is attempted.
79
80 \subsubsection{Selectors}
81
82 Methods that access the structure of a graph are listed below:
83 \begin{methods}
84 nodes : unit -> $'n$ node list &
85 Return a list of all nodes in a graph em \\
86 edges : unit -> $'e$ edge list &
87 Return a list of all edges in a graph \\
88 order : unit -> int &
89 Return the number of nodes in a graph. The graph is empty
90 if its order is zero \\
91 size : unit -> int &
92 Return the number of edges in a graph \\
93 capacity : unit -> int &
94 Return the maximum node id in the graph, plus 1.
95 This can be used as a new id \\
96 succ : node\_id -> node\_id list &
97 Given a node id $i$, return the node ids of all its successors,
98 i.e. $\{ j | i \edge{l} j \in E\}$. \\
99 pred : node\_id -> node\_id list &
100 Given a node id $j$, return the node ids of all its predecessors,
101 i.e. $\{ i | i \edge{l} j \in E\}$. \\
102 out\_edges : node\_id -> $'e$ edge list &
103 Given a node id $i$, return all the out-going edges from node $i$,
104 i.e. all edges whose source is $i$. \\
105 in\_edges : node\_id -> $'e$ edge list &
106 Given a node id $j$, return all the in-coming edges from node $j$,
107 i.e. all edges whose target is $j$. \\
108 has\_edge : node\_id * node\_id -> bool &
109 Given two node ids $i$ and $j$, find out if an edge
110 with source $i$ and target $j$ exists. \\
111 has\_node : node\_id -> bool &
112 Given a node id $i$, find out if a node of id $i$ exists. \\
113 node\_info : node\_id -> $'n$ &
114 Given a node id, return its node label. If the node does not
115 exist, raise exception \sml{NotFound}. \\
116 \end{methods}
117
118 \subsubsection{Graph hierarchy}
119
120 A graph $G$ may in fact be a subgraph of a \newdef{base graph} $G'$, or
121 obtained from $G'$ via some transformation $T$.
122 In such cases the following methods may be used to determine of the
123 relationship between $G$ and $G'$.
124 An \newdef{entry edge} is an edge
125 in $G'$ that terminates at a node in $G$, but is not an edge in $G$.
126 Similarly, an \newdef{exit edge} is an edge in $G'$ that originates from
127 a node in $G$, but is not an edge in $G$. An \newdef{entry node}
128 is a node in $G$ that has an incoming entry edge.
129 An \newdef{exit node} is a node in $G$ that has an out-going exit edge.
130 If $G$ is not
131 a subgraph, all these methods will return nil.
132 \begin{methods}
133 entries : unit -> node\_id list &
134 Return the node ids of all the entry nodes. \\
135 exits : unit -> node\_id list &
136 Return the node ids of all the exit nodes. \\
137 entry\_edges : node\_id -> $'e$ edge list &
138 Given a node id $i$, return all the entry edges whose sources are
139 $i$. \\
140 exit\_edges : node\_id -> $'e$ edge list &
141 Given a node id $i$, return all the exit edges whose targets are $i$.
142 \end{methods}
143
144 \subsubsection{Mutators}
145
146 Methods to update a graph are listed below:
147 \begin{methods}
148 new\_id : unit -> node\_id &
149 Return a unique node id guaranteed to be
150 absent in the current graph. \\
151 add\_node : 'n node -> unit &
152 Insert node into the graph. If a node of the same node id
153 already exists, replace the old node with the new. \\
154 add\_edge : 'e edge -> unit &
155 Insert an edge into the graph. \\
156 remove\_node : node\_id -> unit &
157 Given a node id $n$, remove the node with the node id from the graph.
158 This also automatically removes all edges with source or target $n$. \\
159 set\_out\_edges : node\_id * 'e edge list -> unit &
160 Given a node id $n$, and a list of edges $e_1,\ldots,e_n$
161 with sources $n$, replace all out-edges of $n$ by $e_1,\ldots,e_n$. \\
162 set\_in\_edges : node\_id * 'e edge list -> unit &
163 Given a node id $n$, and a list of edges $e_1,\ldots,e_n$
164 with targets $n$, replace all in-edges of $n$ by $e_1,\ldots,e_n$. \\
165 set\_entries : node\_id list -> unit &
166 Set the entry nodes of a graph. \\
167 set\_exits : node\_id list -> unit &
168 Set the exit nodes of a graph. \\
169 garbage\_collect : unit -> unit &
170 Reclaim all node ids of nodes that have been removed by
171 \sml{remove_node}. Subsequent \sml{new_id} will reuse these
172 node ids. \\
173 \end{methods}
174
175 \subsubsection{Iterators}
176
177 Two primitive iterators are supported in the graph interface.
178 Method \sml{forall_nodes} iterates over all the nodes in a graph,
179 while method \sml{forall_edges} iterates over all the edges.
180 Other more complex iterators can be found in other modules.
181 \begin{methods}
182 forall\_nodes : ($'n$ node -> unit) -> unit &
183 Given a function $f$ on nodes, apply $f$ on all the nodes in the graph. \\
184 forall\_edges : ($'e$ edge -> unit) -> unit &
185 Given a function $f$ on edges, apply $f$ on all the edges in the graph.
186 \end{methods}
187
188 \subsubsection{Manipulating a graph}
189
190 Since operations on the graph type are packaged into
191 a record, an ``object oriented'' style of graph manipulation should be used.
192 For example, if \sml{G} is a graph object, then we can obtain all the
193 nodes and edges of \sml{G} as follows.
194 \begin{SML}
195 val GRAPH g = G
196 val edges = #edges g ()
197 val nodes = #nodes g ()
198 \end{SML}
199 We can view \sml{#edges g} as sending the message to \sml{G}.
200 While all this seems like mere syntactic deviation from the usual
201 signature/structure approach, there are two crucial differences which
202 we will exploit:
203 \emph{(i)} records are first class objects
204 while structures are not (consequently
205 late binding of ``methods'' and cannot be easily simulated on the
206 structure level); \emph{(ii)} recursion
207 is possible on the type level, while recursive structures are not available.
208 The extra flexibility of this choice becomes apparent with the
209 introduction of views later.
210
211 \subsubsection{Creating a Graph}
212
213 A graph implementation has the following signature
214 \begin{SML}
215 signature \mlrischref{graphs/graphimpl.sig}{GRAPH_IMPLEMENTATION} = sig
216 val graph : string * 'g * int -> ('n,'e,'g) graph
217 end
218 \end{SML}
219 The function \sml{graph} takes a string (the name of the graph),
220 graph info, and a default size as arguments and create an empty graph.
221
222 The functor \sml{DirectedGraph}:
223 \begin{SML}
224 functor DirectedGraph(A : ARRAY_SIG) : GRAPH_IMPLEMENTATION
225 \end{SML}
226 implements a graph using adjacency lists as internal representation.
227 It takes an array type as a parameter. For graphs with
228 node ids that are dense enumerations, the \sml{DynamicArray} structure
229 should be used as the parameter to this functor.
230 The structure \sml{DirectedGraph} is predefined as follows:
231 \begin{SML}
232 structure \mlrischref{graphs/digraph.sml}{DirectedGraph} = DirectedGraph(DynamicArray)
233 \end{SML}
234
235 For node ids that are sparse enumerations, the structure \sml{HashArray},
236 which implements integer-keyed hash tables
237 with the signature of arrays, can be used
238 as argument to \sml{DirectedGraph}.
239 For graphs with fixed sizes determined at creation time,
240 the structure \sml{Array} can be used (see also
241 functor \mlrischref{library/undoable-array.sml}{\sml{UndoableArray}},
242 which creates arrays with undoable updates, and transaction-like semantics.)
243
244 \subsubsection{Basic Graph Algorithms}
245
246 \subsubsection{Depth-/Breath-First Search}
247
248 \begin{SML}
249 val dfs : ('n,'e,'g) graph ->
250 (node_id -> unit) ->
251 ('e edge -> unit) ->
252 node_id list -> unit
253 \end{SML}
254 The function \sml{dfs} takes as arguments a graph,
255 a function \sml{f : node_id -> unit}, a function
256 \sml{g : 'e edge -> unit}, and a
257 set of source vertices. It performs depth first search on the
258 graph. The function \sml{f} is invoked
259 whenever a new node is being visited, while the function \sml{g}
260 is invoked whenever a new edge is being traversed.
261 This algorithm has running time $O(|V|+|E|)$.
262
263 \begin{SML}
264 val dfsfold : ('n,'e,'g) graph ->
265 (node_id * 'a -> 'a) ->
266 ('e edge * 'b -> 'a) ->
267 node_id list -> 'a * 'b -> 'a * 'b
268 val dfsnum : ('n,'e,'g) graph ->
269 (node_id * 'a -> 'a) ->
270 { dfsnum : int array, compnum : int array }
271 \end{SML}
272
273 The function \sml{bfs} is similar to \sml{dfs}
274 except that breath first search is performed.
275 \begin{SML}
276 val bfs : ('n,'e,'g) graph ->
277 (node_id -> unit) ->
278 ('e edge -> unit) ->
279 node_id list -> unit
280 val bfsdist : ('n,'e,'g) graph -> node_id list -> int array
281 \end{SML}
282
283 \subsubsection{Preorder/Postorder numbering}
284 \begin{SML}
285 val preorder_numbering : ('n,'e,'g) graph -> int -> int array
286 val postorder_numbering : ('n,'e,'g) graph -> int -> int array
287 \end{SML}
288 Both these functions take a tree $T$ and a root $v$, and return
289 the preorder numbering and the postorder numbering of the tree respectively.
290
291 \subsubsection{Topological Sort}
292 \begin{SML}
293 val topsort : ('n,'e,'g) graph -> node_id list -> node_id list
294 \end{SML}
295 The function
296 \sml{topsort} takes a graph $G$ and a set of source vertices $S$
297 as arguments. It returns a topological sort of all the nodes reachable from
298 the set $S$.
299 This algorithm has running time $O(|S|+|V|+|E|)$.
300
301 \subsubsection{Strongly Connected Components}
302 \begin{SML}
303 val strong_components : ('n,'e,'g) graph ->
304 (node_id list * 'a -> 'a) -> 'a -> 'a
305 \end{SML}
306 The function \sml{strong_components} takes a graph $G$ and
307 an aggregate function $f$ with type
308 \begin{SML}
309 node_id list * 'a -> 'a
310 \end{SML}
311 \noindent and an identity element \sml{x : 'a} as arguments.
312 Function $f$ is invoked with a strongly connected component
313 (represented as a list of node ids) as each is discovered.
314 That is, the function \sml{strong_components} computes
315
316 \[
317 f(SCC_n,f(SCC_{n-1},\ldots, f(SCC_1,x)))
318 \]
319
320 where $SCC_1,\ldots,SCC_n$ are the strongly connected components
321 in topological order. This algorithm has running time $O(|V|+|E|)$.
322
323 \subsubsection{Biconnected Components}
324 \begin{SML}
325 val biconnected_components : ('n,'e,'g) graph ->
326 ('e edge list * 'a -> 'a) -> 'a -> 'a
327 \end{SML}
328 The function \sml{biconnected_components} takes a graph $G$ and
329 an aggregate function $f$ with type
330 \begin{SML}
331 'e edge list * 'a -> 'a
332 \end{SML}
333 \noindent and an identity element \sml{x : 'a} as arguments.
334 Function $f$ is invoked with a biconnected component
335 (represented as a list of edges) as each is discovered.
336 That is, the function \sml{biconnected_components} computes
337
338 \[
339 f(BCC_n,f(BCC_{n-1},\ldots, f(BCC_1,x)))
340 \]
341
342 where $BCC_1,\ldots,BCC_n$ are the biconnected components.
343 This algorithm has running time $O(|V|+|E|)$.
344
345 \subsubsection{Cyclic Test}
346 \begin{SML}
347 val is_cyclic : ('n,'e,'g) graph -> bool
348 \end{SML}
349 Function \sml{is_cyclic} tests if a graph is cyclic.
350 This algorithm has running time $O(|V|+|E|)$.
351
352 \subsubsection{Enumerate Simple Cycles}
353 \begin{SML}
354 val cycles : ('n,'e,'g) graph -> ('e edge list * 'a -> 'a) -> 'a ->'a
355 \end{SML}
356 A simple cycle is a circuit that visits each vertex only once.
357 The function \sml{cycles} enumerates all simple cycles in a graph $G$.
358 It takes as argument an aggregate function $f$ of type
359 \begin{SML}
360 'e edge list * 'a -> 'a
361 \end{SML}
362 and an identity element $e$, and computes as result the expression
363 \[
364 f(c_n,f(c_{n-1},f(c_{n-2},\ldots, f(c_1,e))))
365 \]
366 where $c_1,\ldots,c_n$ are all the simple cycles in the graph.
367 All cycles $c_1,\ldots,c_n$ are guaranteed to be distinct.
368 A cycle is represented as a sequence of
369 adjacent edges, i.e. in the order of
370 \[
371 v_1 -> v_2, v_2 -> v_3, v_3 -> v_4, \ldots, v_{n-1} -> v_n, v_n -> v_1
372 \]
373 Our implementation works by first decomposing the graph into
374 its strongly connected components, then uses backtracking to enumerate
375 simple cycles in each component.
376 \subsubsection{Minimal Cost Spanning Tree}
377 \begin{SML}
378 signature \mlrischref{graphs/spanning-tree.sig}{MIN_COST_SPANNING_TREE} = sig
379 exception Unconnected
380
381 val spanning_tree : \{ weight : 'e edge -> 'a,
382 < : 'a * 'a -> bool
383 \} -> ('n, 'e, 'g) graph
384 -> ('e edge * 'a -> 'a) -> 'a -> 'a
385 end
386 structure \mlrischref{graphs/kruskal.sml}{Kruskal} : MIN_COST_SPANNING_TREE
387 \end{SML}
388
389 Structure \sml{Kruskal} implements Kruskal's algorithm for
390 computing a minimal cost spanning tree of a graph.
391 The function \sml{spanning_tree} takes as arguments:
392 \begin{itemize}
393 \item a \sml{weight} function which when given an edge returns its weight
394 \item an ordering function \sml{<}, which is used to compare the weights
395 \item a graph $G$
396 \item an accumulator function $f$, and
397 \item an identity element $x$
398 \end{itemize}
399 The function \sml{spanning_tree} computes
400 \[
401 f(e_{n},f(e_{n-1},\ldots, f(e_1,x)))
402 \]
403
404 where $e_1,\ldots,e_n$ are the edges in a minimal cost spanning tree
405 of the graph.
406 The exception \sml{Unconnected} is raised if the graph is unconnected.
407
408 \subsubsection{Abelian Groups}
409 Graph algorithms that deal with numeric weights or distances
410 are parameterized with respect to the signatures
411 \sml{ABELIAN_GROUP} or \sml{ABELIAN_GROUP_WITH_INF}.
412 These are defined as follows:
413 \begin{SML}
414 signature \mlrischref{graphs/groups.sig}{ABELIAN_GROUP} = sig
415 type elem
416 val + : elem * elem -> elem
417 val - : elem * elem -> elem
418 val : elem -> elem
419 val zero : elem
420 val < : elem * elem -> bool
421 val == : elem * elem -> bool
422 end
423 signature \mlrischref{graphs/groups.sig}{ABELIAN_GROUP_WITH_INF} = sig
424 include ABELIAN_GROUP
425 val inf : elem
426 end
427 \end{SML}
428 Signature \sml{ABELIAN_GROUP} specifies an ordered commutative group,
429 while signature \sml{ABELIAN_GROUP_WITH_INF} specifies an ordered commutative
430 group with an infinity element \sml{inf}.
431
432 \subsubsection{Single Source Shortest Paths}
433 \begin{SML}
434 signature \mlrischref{graphs/shortest-paths.sig}{SINGLE_SOURCE_SHORTEST_PATHS} = sig
435 structure Num : ABELIAN_GROUP_WITH_INF
436 val single_source_shortest_paths :
437 \{ graph : ('n,'e,'g) graph,
438 weight : 'e edge -> Num.elem,
439 s : node_id
440 \} ->
441 \{ dist : Num.elem array,
442 pred : node_id array
443 \}
444 end
445 functor \mlrischref{graphs/dijkstra.sml}{Dijkstra}(Num : ABELIAN_GROUP_WITH_INF)
446 : SINGLE_SOURCE_SHORTEST_PATHS
447 \end{SML}
448 The functor \sml{Dijkstra} implements Dijkstra's algorithm
449 for single source shortest paths. The function \linebreak
450 \sml{single_source_shortest_paths} takes as arguments:
451 \begin{itemize}
452 \item a graph $G$,
453 \item a \sml{weight} function on edges, and
454 \item the source vertex $s$.
455 \end{itemize}
456 It returns two arrays \sml{dist} and \sml{pred}
457 indexed by vertices. These arrays have the following
458 interpretation. Given a vertex $v$,
459 \begin{itemize}
460 \item \sml{dist}[$v$] contains the distance of $v$ from the source $s$
461 \item \sml{pred}[$v$] contains the predecessor of $v$ in the shortest
462 path from $s$ to $v$, or -1 if $v=s$.
463 \end{itemize}
464
465 Dijkstra's algorithm fails to work on graphs that have
466 negative edge weights.
467 To handle negative weights, Bellman-Ford's algorithm can be used.
468 The exception \sml{NegativeCycle} is raised if a cycle of
469 negative total weight is detected.
470 \begin{SML}
471 functor \mlrischref{graphs/bellman-ford.sml}{BellmanFord}(Num : ABELIAN_GROUP_WITH_INF) : sig
472 include SINGLE_SOURCE_SHORTEST_PATHS
473 exception NegativeCycle
474 end
475 \end{SML}
476 \subsubsection{All Pairs Shortest Paths}
477 \begin{SML}
478 signature \mlrischref{graphs/shortest-paths.sig}{ALL_PAIRS_SHORTEST_PATHS} = sig
479 structure Num : ABELIAN_GROUP_WITH_INF
480 val all_pairs_shortest_paths :
481 \{ graph : ('n,'e,'g) graph,
482 weight : 'e edge -> Num.elem
483 \} ->
484 \{ dist : Num.elem Array2.array,
485 pred : node_id Array2.array
486 \}
487 end
488 functor \mlrischref{graphs/floyd-warshall.sml}{FloydWarshall}(Num : ABELIAN_GROUP_WITH_INF)
489 : ALL_PAIRS_SHORTEST_PATHS
490 \end{SML}
491 The functor \sml{FloydWarshall} implements Floyd-Warshall's algorithm
492 for all pairs shortest paths. The function
493 \sml{all_pairs_shortest_paths} takes as arguments:
494 \begin{itemize}
495 \item a graph $G$, and
496 \item a \sml{weight} function on edges
497 \end{itemize}
498 It returns two 2-dimensional arrays \sml{dist} and \sml{pred}
499 indexed by vertices $(u,v)$. These arrays have the following
500 interpretation. Given a pair $(u,v)$,
501 \begin{itemize}
502 \item \sml{dist}[$u,v$] contains the distance from $u$ to $v$.
503 \item \sml{pred}[$u,v$] contains the predecessor of $v$ in the shortest
504 path from $u$ to $v$, or $-1$ if $u=v$.
505 \end{itemize}
506 This algorithm runs in time $O(|V|^3+|E|)$.
507
508 An alternative implementation is available that uses Johnson's algorithm,
509 which works better for sparse graphs:
510 \begin{SML}
511 functor \mlrischref{graphs/johnson.sml}{Johnson}(Num : ABELIAN_GROUP_WITH_INF)
512 : sig include ALL_PAIRS_SHORTEST_PATHS
513 exception Negative Cycle
514 end
515 \end{SML}
516
517 \subsubsection{Transitive Closure}
518 \begin{SML}
519 signature \mlrischref{graphs/trans-closure.sml}{TRANSITIVE_CLOSURE} = sig
520 val acyclic_transitive_closure : { + : ('e * 'e -> 'e), simple : bool }
521 -> ('n,'e,'g) graph -> unit
522 val acyclic_transitive_closure2 :
523 \{ + : 'e * 'e -> 'e,
524 max : 'e * 'e -> 'e
525 \} -> ('n,'e,'g) graph -> unit
526 val transitive_closure : ('e * 'e -> 'e) -> ('n,'e,'g) graph -> unit
527 structure \mlrischref{graphs/trans-closure.sml}{TransitiveClosure} : TRANSITIVE_CLOSURE
528 \end{SML}
529 Structure \sml{TransitiveClosure} implements
530 in-place transitive closures on graphs. Three functions are implemented.
531 Functions \sml{acyclic_transitive_closure} and
532 \sml{acyclic_transitive_closure2} can be used
533 to compute the transitive closure of an acyclic graph, whereas the
534 function \sml{transitive_closure} computes the transitive closure of
535 a cyclic graph. All take a binary function
536 \begin{SML}
537 + : 'e * 'e -> 'e
538 \end{SML}
539 defined on edge labels.
540 Transitive edges are inserted in the following manner:
541
542 \begin{itemize}
543 \item \sml{acyclic_transitive_closure}:
544 given $u \edge{l} v$ and $v \edge{l'} w$,
545 if the flag \sml{simple} is false or if
546 the transitive edge $u \rightarrow w$ does not exists,
547 then $u \edge{l + l'} w$ is added to the graph.
548 \item \sml{acyclic_transitive_closure2}:
549 given $u \edge{l} v$ and $v \edge{l'} w$,
550 the transitive $u \edge{l + l'} w$ is added to the graph.
551 Furthermore, all parallel edges
552 \[
553 u \edge{l_1} w, \ldots, u \edge{l_n} w
554 \]
555 are coalesced into a single edge $u \edge{l} w$, where
556 $l = {\tt max}_{i = 1 \ldots n} l_i$
557 \end{itemize}
558
559 \subsubsection{Max Flow}
560
561 The function \sml{max_flow} computes the
562 maximum flow between the source vertex \sml{s} and the sink vertex
563 \sml{t} in the \sml{graph} when given a \sml{capacity} function.
564 \begin{SML}
565 signature \mlrischref{graphs/max-flow.sig}{MAX_FLOW} = sig
566 structure Num : ABELIAN_GROUP
567 val max_flow : \{ graph : ('n,'e,'g) graph,
568 s : node_id,
569 t : node_id,
570 capacity : 'e edge -> Num.elem,
571 flows : 'e edge * Num.elem -> unit
572 \} -> Num.elem
573 end
574 functor \mlrischref{graphs/max-flow.sml}{MaxFlow}(Num : ABELIAN_GROUP) : MAX_FLOW
575 \end{SML}
576 The function \sml{max_flow} returns its result in the follow manner:
577 The function returns the total flow as its result value.
578 Furthermore, the function \sml{flows} is called once for each edge $e$ in the
579 graph with its associated flow $f_e$.
580
581 This algorithm uses Goldberg's preflow-push approach, and runs
582 in $O(|V|^2|E|)$ time.
583 \subsubsection{Min Cut}
584 The function \sml{min_cut} computes the
585 minimum (undirected) cut in a \sml{graph}
586 when given a \sml{weight} function on
587 its edges.
588 \begin{SML}
589 signature \mlrischref{graphs/min-cut.sig}{MIN_CUT} = sig
590 structure Num : ABELIAN_GROUP
591 val min_cut : \{ graph : ('n,'e,'g) graph,
592 weight : 'e edge -> Num.elem
593 \} -> node_id list * Num.elem
594 end
595 functor \mlrischref{graphs/min-cut.sml}{MinCut}(Num : ABELIAN_GROUP) : MIN_CUT
596 \end{SML}
597 The function \sml{min_cut} returns a list of node ids denoting
598 one side of the cut $C$ (the other side of the cut is $(V - C)$ and
599 the weight cut.
600
601 \subsubsection{Max Cardinality Matching}
602
603 \begin{SML}
604 val matching : ('n,'e,'g) graph -> ('e edge * 'a -> 'a) -> 'a -> 'a * int
605 \end{SML}
606
607 The function \sml{BipartiteMatching.matching} computes the
608 maximal cardinality matching of a bipartite graph. As result,
609 the function iterates over all the matched edges and returns the
610 number of matched edges. The algorithm runs in time $O(|V||E|)$.
611
612 \subsubsection{Node Partition}
613 \begin{SML}
614 signature NODE_PARTITION = sig
615 type 'n node_partition
616
617 val node_partition : ('n,'e,'g) graph -> 'n node_partition
618 val !! : 'n node_partition -> node_id -> 'n node
619 val == : 'n node_partition -> node_id * node_id -> bool
620 val union : 'n node_partition -> ('n node * 'n node -> 'n node) ->
621 node_id * node_id -> bool
622 val union': 'n node_partition -> node_id * node_id -> bool
623
624 end
625 \end{SML}
626
627 \subsubsection{Node Priority Queue}
628 \begin{SML}
629 signature NODE_PRIORITY_QUEUE = sig
630 type node_priority_queue
631
632 exception EmptyPriorityQueue
633
634 val create : (node_id * node_id -> bool) -> node_priority_queue
635 val fromGraph : (node_id * node_id -> bool) ->
636 ('n,'e,'g) graph -> node_priority_queue
637 val isEmpty : node_priority_queue -> bool
638 val clear : node_priority_queue -> unit
639 val min : node_priority_queue -> node_id
640 val deleteMin : node_priority_queue -> node_id
641 val decreaseWeight : node_priority_queue * node_id -> unit
642 val insert : node_priority_queue * node_id -> unit
643 val toList : node_priority_queue -> node_id list
644 end
645 \end{SML}
646
647 \subsection{Views}\label{sec:views}
648 Simply put, a view is an alternative presentation
649 of a data structure to a client. A graph, such as the control flow
650 graph, frequently has to be presented in different ways in a compiler.
651 For example, when global scheduling is applied on a region
652 (a subgraph of the CFG),
653 we want to be able to concentrate on just the region and ignore all
654 nodes and edges that are not part of the current focus.
655 All transformations that are applied on the current region view should be
656 automatically reflected back to the entire CFG as a whole.
657 Furthermore, we want to be able to freely intermix
658 graphs and subgraphs of the same type in our program, without having
659 to introducing sums in our type representations.
660
661 The \sml{subgraph_view} view combinator accomplishes this. \sml{Subgraph}
662 takes a list of nodes and produces a graph object which is a view of the
663 node induced subgraph of the original graph.
664 All modification to the subgraph are automatically
665 reflected back to the original graph. From the client point of view,
666 a graph and a subgraph are entirely indistinguishable, and furthermore,
667 graphs and subgraphs can be freely mixed together (they are the same
668 type from ML's point of view.)
669
670 This transparency is obtained by selective method overriding, composition,
671 and delegation. For example, a generic graph object provides the
672 following methods for setting and looking up the entries and exits
673 from a graph.
674 \begin{SML}
675 set_entries : node_id list -> unit
676 set_exits : node_id list -> unit
677 entries : unit -> node_id list
678 exits : unit -> node_id list
679 \end{SML}
680
681 For example, a CFG usually has a single entry and a single exit.
682 These methods allow the client to destinate one node as the
683 entry and another as
684 the exit. In the case of subgraph view, these methods are overridden so
685 that the proper conventions are preserved:
686 a node in a subgraph is an entry (exit) iff there is an in-edge (out-edge)
687 from (to) outside the (sub-)graph.
688 Similarly, the methods \sml{entry_edges} and \sml{exit_edges} can be used
689 return the entry and exit edges associated with a node in a subgraph.
690 \begin{SML}
691 entry_edges : node_id -> 'e edge list
692 exit_edges : node_id -> 'e edge list
693 \end{SML}
694 These methods are initially defined to return \sml{[]} in a graph and
695 subsequently overridden in a subgraph.
696
697 \subsubsection{ Update Transparency }
698
699 Suppose a view $G'$ is created from some base graphs or views.
700 \newdef{Update transparency} refers to the fact that
701 $G'$ behaves
702 consistently according to its conventions and semantics when updates
703 are performed. There are 4 different type of update transparencies:
704 \begin{itemize}
705 \item\newdef{update opaque} A update opaque view disallows updates to both
706 itself and its base graphs.
707 \item\newdef{globally update transparent} A globally update transparent
708 view allows updates to its base graphs but not to itself. Changes
709 will then be automatically reflected in the view.
710 \item\newdef{locally update transparent} A locally update transparent
711 view allows updates to itself but not to its base graphs.
712 Changes will be automatically reflected to the base graphs.
713 \item\newdef{fully update transparent} A fully update transparent
714 view allows updates through its methods or through its base
715 graphs'.
716 \end{itemize}
717
718 \subsubsection{Structural Views}\label{sec:structural-views}
719
720 \subsubsection{Reversal}
721 \begin{SML}
722 val \mlrischref{graphs/revgraph.sml}{ReversedGraphView.rev_view} : ('n,'e,'g) graph -> ('n,'e,'g) graph
723 \end{SML}
724 This combinator takes a graph $G$ and produces a view $G^R$
725 which reverses the direction
726 of all its edges, including entry and exit edges. Thus
727 the edge $i \edge{l} j$ in $G$ becomes the edge
728 $j \edge{l} i$ in $G^R$. This view is fully update transparent.
729
730 \subsubsection{Readonly}
731 \begin{SML}
732 val \mlrischref{graphs/readonly.sml}{ReadOnlyGraphView.readonly_view} : ('n,'e,'g) graph -> ('n,'e,'g) graph
733 \end{SML}
734 This function takes a graph $G$ and produces a view $G'$
735 in which no mutator methods can be used. Invoking a mutator
736 method raises the exception \sml{Readonly}.
737 This view is globally update transparent.
738
739 \subsubsection{Snapshot}
740 \begin{SML}
741 functor \mlrischref{graphs/snap-shot.sml}{GraphSnapShot}(GI : GRAPH_IMPLEMENTATION) : GRAPH_SNAPSHOT
742 signature GRAPH_SNAPSHOT = sig
743 val snapshot : ('n,'e,'g) graph ->
744 \{ picture : ('n,'e,'g) graph, button : unit -> unit \}
745 end
746 \end{SML}
747
748 The function \sml{snapshot} can be used to keep a cached copy
749 of a view a.k.a the \sml{picture}. This cached copy
750 can be updated locally but the modification will not be reflected back
751 to the base graph. The function \sml{button} can be used to
752 keep the view and the base graph up-to-date.
753
754 \subsubsection{Map}
755 \begin{SML}
756 val \mlrischref{graphs/isograph.sml}{IsomorphicGraphView.map} :
757 ('n node -> 'n') -> ('e edge -> 'e') -> ('g -> 'g') ->
758 ('n,'e,'g) graph -> ('n','e','g') graph
759 \end{SML}
760 The function \sml{map} is a generalization of the \sml{map}
761 function on lists. It takes three functions
762 \begin{SML}
763 f : 'n node -> 'n
764 g : 'e edge -> 'e
765 h : 'g -> g'
766 \end{SML}
767 and a graph $G=(V,L,E,I)$ as arguments.
768 It computes the view $G'=(V,L',E',I')$ where
769 \begin{eqnarray*}
770 L'(v) & = & f(v,L(v)) \mbox{\ for all $v \in V$} \\
771 E' & = & { i \edge{g(i,j,l)} j | i \edge{l} j \in E } \\
772 I' & = & h(I)
773 \end{eqnarray*}
774
775 \subsubsection{Singleton}
776 \begin{SML}
777 val \mlrischref{graphs/singleton.sml}{SingletonGraphView.singleton_view} : ('n,'e,'g) graph -> node_id -> ('n,'e,'g) graph
778 \end{SML}
779 Function \sml{singleton_view}
780 takes a graph $G$ and a node id $v$ (which must exists in $G$)
781 and return an edge-free graph with only one node ($v$).
782 This view is opaque.
783
784 \subsubsection{Node id renaming}
785 \begin{SML}
786 val \mlrischref{graphs/renamegraph.sml}{RenamedGraphView.rename_view} : int -> ('n,'e,'g) graph -> ('n','e','g') graph
787 \end{SML}
788 The function \sml{rename_view} takes an integer $n$ and
789 a graph $G$ and create a fully update transparent
790 view where all node ids are incremented by $n$. Formally,
791 given graph $G=(V,E,L,I)$ it computes the view $G'=(V',E',L',I)$
792 where
793 \begin{eqnarray*}
794 V' & = & { v + n | v \in V } \\
795 E' & = & { i+n \edge{l} j+n | i \edge{l} j \in E } \\
796 L' & = & \lambda v. L(v-n)
797 \end{eqnarray*}
798
799 \subsubsection{Union and Sum}
800 \begin{SML}
801 val \mlrischref{graphs/uniongraph.sml}{UnionGraphView.union_view} : ('g * 'g') -> 'g'') ->
802 ('n,'e,'g) graph * ('n,'e,'g') graph -> ('n','e','g'') graph
803 GraphCombinations.unions : ('n,'e,'g) graph list -> ('n,'e,'g) graph
804 GraphCombinations.sum : ('n,'e,'g) graph * ('n,'e,'g) graph -> ('n,'e,'g) graph
805 GraphCombinations.sums : ('n,'e,'g) graph list -> ('n,'e,'g) graph
806 \end{SML}
807
808 Function \sml{union_view} takes as arguments
809 a function $f$, and two graphs
810 $G=(V,L,E,I)$ and $G'=(V',L',E',I')$, it computes the union $G+G'$ of
811 these graphs. Formally, $G \union G'=(V'',L'',E'',I'')$ where
812 \begin{eqnarray*}
813 V'' & = & V \union V' \\
814 L'' & = & L \overrides L' \\
815 E'' & = & E \union E' \\
816 I'' & = & f(I,I')
817 \end{eqnarray*}
818
819 The function \sml{sum} constructs a \newdef{disjoint sum} of two
820 graphs.
821 \subsubsection{Simple Graph View}
822 \begin{SML}
823 val \mlrischref{graphs/simple-graph.sml}{SimpleGraph.simple_graph} : (node_id * node_id * 'e list -> 'e) ->
824 ('n,'e,'g) graph -> ('n,'e,'g) graph
825 \end{SML}
826 Function \sml{simple_graph} takes a merge function $f$
827 and a multi-graph $G$ as arguments and return a view in which
828 all parallel multi-edges (edges with the same source and target) are combined
829 into a single edge: i.e. any collection of multi-edges between
830 the same source $s$ and target $t$ and with labels $l_1,\ldots,l_n$,
831 are replaced by the edge $s \edge{l_{st}} t$ in the view, where
832 $l_{st} = f(s,t,[l_1,\ldots,l_n])$. The function $f$ is assumed
833 to satisfy the equality $l = f(s,t,[l])$ for all $l$, $s$ and $t$.
834
835 \subsubsection{No Entry or No Exit}
836 \begin{SML}
837 val \mlrischref{graphs/no-exit.sml}{NoEntryView.no_entry_view} : ('n,'e,'g) graph -> ('n,'e,'g) graph
838 NoEntryView.no_exit_view : ('n,'e,'g) graph -> ('n,'e,'g) graph
839 \end{SML}
840
841 The function \sml{no_entry_view} creates a view in which
842 all entry edges (and thus entry nodes) are removed. The function
843 \sml{no_exit_view} is the dual of this and creates a view in which
844 all exit edges are removed. This view is fully update transparent.
845 It is possible to remove all entry and exit edges by composing these
846 two functions.
847
848 \subsubsection{Subgraphs}
849 \begin{SML}
850 val \mlrischref{graphs/subgraph.sml}{SubgraphView.subgraph_view} : node_id list -> ('e edge -> bool) ->
851 ('n,'e,'g) graph -> (n','e','g') graph
852 \end{SML}
853
854 The function \sml{subgraph_view} takes as arguments a set of node ids
855 $S$, an edge predicate $p$ and a graph $G=(V,L,E,I)$. It
856 returns a view in which only the visible nodes are $S$ and
857 the only visible edges $e$ are those that satisfy $p(e)$ and
858 with sources and targets in $S$. $S$ must be a subset of $V$.
859
860 \begin{SML}
861 val \mlrischref{graphs/subgraph-p.sml}{Subgraph_P_View.subgraph_p_view} : node_id list ->
862 (node_id -> bool) -> (node_id * node_id -> bool) ->
863 ('n,'e,'g) graph -> ('n','e','g') graph
864 \end{SML}
865
866 The function \sml{subgraph_view} takes as arguments a set of node ids
867 $S$, a node predicate $p$, an edge predicate $q$ and a graph $G=(V,L,E,I)$. It
868 returns a view in which only the visible nodes $v$ are those
869 in $S$ satisfying $p(v)$, and
870 the only visible edges $e$ are those that satisfy $q(e)$ and
871 with sources and targets in $S$. $S$ must be a subset of $V$.
872
873 \subsubsection{Trace}
874 \begin{SML}
875 val \mlrischref{graphs/trace-graph.sml}{TraceView.trace_view} : node_id list -> ('n,'e,'g) graph -> ('n','e','g') graph
876 \end{SML}
877
878 \begin{wrapfigure}{r}{3in}
879 \begin{Boxit}
880 % \psfig{figure=../pictures/eps/trace.eps,width=2.8in}
881 \includegraphics[width=2.8in]{../pictures/pdf/trace}
882 \end{Boxit}
883 \label{fig:trace-view}
884 \caption{A trace view}
885 \end{wrapfigure}
886 A \newdef{trace} is an acyclic path in a graph.
887 The function \sml{trace_view} takes a trace of node ids
888 $v_1,\ldots,v_n$ and a graph $G$ and
889 returns a view in which only the nodes are visible.
890 Only the edges that connected two adjacent nodes on the trace, i.e.
891 $v_i -> v_{i+1}$ for some $i = 1 \ldots n-1$ are considered be within
892 the view. Thus if there is an edge $v_i -> v_j$ in $G$ where
893 $j \ne i+1$ this edge is not considered to be within the view --- it
894 is considered to be an exit edge from $v_i$ and an entry edge
895 from $v_j$ however. Trace views can be used to construct a CFG region
896 suitable for trace scheduling \cite{trace-scheduling,bulldog}.
897
898 Figure \ref{fig:trace-view} illustrates this concept graphically.
899 Here, the trace view is formed from the
900 nodes \sml{A, C, D, F} and \sml{G}. The
901 solid edges linking the trace is visible within the view. All other
902 dotted edges are considered to be either entry of exit edges into
903 the trace. The edge from node \sml{G} to \sml{A} is considered to
904 be both since it exits from \sml{G} and enters into \sml{A}.
905
906 \subsubsection{Acyclic Subgraph}
907 \begin{SML}
908 val \mlrischref{graphs/acyclic-graph.sml}{AcyclicSubgraphView.acyclic_view} :
909 node_id list ->
910 ('n,'e,'g) graph -> ('n,'e,'g) graph
911 \end{SML}
912 \begin{wrapfigure}{r}{3in}
913 \begin{Boxit}
914 \includegraphics[width=2.8in]{../pictures/pdf/subgraph}
915 % \psfig{figure=../pictures/eps/subgraph.eps,width=2.8in}
916 \end{Boxit}
917 \label{fig:acyclic-subgraph-view}
918 \caption{An acyclic subgraph}
919 \end{wrapfigure}
920 The function \sml{acyclic_view} takes an ordered
921 list of node ids $v_1,\ldots,v_n$ and a graph $G$ as arguments
922 and return a view $G'$ such that only the nodes $v_1,\ldots,v_n$
923 are visible. In addition, only the edges with directions consistent
924 with the order list are considered to be within the view.
925 Thus an edge $v_i -> v_j$ from $G$ is in $G'$ iff $1 \le i < j \le n$.
926 Acyclic views can be used to construct a CFG region suitable
927 for DAG scheduling.
928 Figure \ref{fig:acyclic-subgraph-view} illustrates this concept graphically.
929
930 \subsubsection{Start and Stop}
931 \begin{SML}
932 val \mlrischref{graphs/start-stop.sml}{StartStopView.start_stop_view} :
933 \{ start : 'n node,
934 stop : 'n node,
935 edges : 'e edge list
936 \} -> ('n,'e,'g) graph -> ('n','e','g') graph
937 \end{SML}
938
939 The function \sml{start_stop_view}
940
941 \subsubsection{Single-Entry/Multiple-Exits}
942 \begin{SML}
943 \mlrischref{graphs/SEME.sml}{SingleEntryMultipleExit.SEME}
944 exit : 'n node -> ('n,'e,'g) graph -> ('n,'e,'g) graph
945 \end{SML}
946
947 The function \sml{SEME} converts a single-entry/multiple-exits
948 graph $G$ into a single entry/single exit graph.
949 It takes an exit node $e$ and a graph $G$ and returns
950 a view $G'$. Suppose $i \edge{l} j$ is an exit edge in $G$.
951 In view $G$ this edge is replaced by a new normal edge $i \edge{l} e$
952 and a new exit edge $e \edge{l} j$. Thus $e$ becomes the sole exit
953 node in the new view.
954
955 \subsubsection{Behavioral Views}
956
957 \subsubsection{Behavioral Primitives}
958
959 Figure \ref{fig:behavioral-view-primitives} lists
960 the set of behavioral primitives defined
961 in structure \mlrischref{graphs/wrappers.sml}{\sml{GraphWrappers}}.
962 These functions allow the user
963 to attach an action $a$ to a mutator method $m$ such that whenever $m$
964 is invoked so does $a$. Given a graph $G$, the combinator
965 \begin{SML}
966 do_before_\(xxx\) : f -> ('n,'e,'g) graph -> ('n,'e,'g) graph
967 \end{SML}
968 \noindent returns a view $G'$ such that whenever method $xxx$ is invoked
969 in $G'$, the function $f$ is called.
970 Similarly, the combinator
971 \begin{SML}
972 do_after_\(xxx\) : f -> ('n,'e,'g) graph -> ('n,'e,'g) graph
973 \end{SML}
974 \noindent creates a new view $G''$ such that the function $f$
975 is called after the method is invoked.
976 \begin{Figure}
977 \begin{boxit}
978 \begin{SML}
979 do_before_new_id : (unit -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
980 do_after_new_id : (node_id -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
981 do_before_add_node : ('n node -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
982 do_after_add_node : ('n node -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
983 do_before_add_edge : ('e edge -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
984 do_after_add_edge : ('e edge -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
985 do_before_remove_node : (node_id -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
986 do_after_remove_node : (node_id -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
987 do_before_set_in_edges : (node_id * 'e edge list -> unit) ->
988 ('n,'e,'g) graph -> ('n,'e,'g) graph
989 do_after_set_in_edges : (node_id * 'e edge list -> unit) ->
990 ('n,'e,'g) graph -> ('n,'e,'g) graph
991 do_before_set_out_edges : (node_id * 'e edge list -> unit) ->
992 ('n,'e,'g) graph -> ('n,'e,'g) graph
993 do_after_set_out_edges : (node_id * 'e edge list -> unit) ->
994 ('n,'e,'g) graph -> ('n,'e,'g) graph
995 do_before_set_entries : (node_id list -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
996 do_after_set_entries : (node_id list -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
997 do_before_set_exits : (node_id list -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
998 do_after_set_exits : (node_id list -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
999 \end{SML}
1000 \end{boxit}
1001 \label{fig:behavioral-view-primitives}
1002 \caption{Behavioral view primitives}
1003 \end{Figure}
1004
1005 Frequently it is not necessary to know precisely by which method a graph's
1006 structure has been modified, only that it is. The following two methods
1007 take a notification function $f$ and returns a new view. $f$ is
1008 invoked before a modification is attempted in a view created
1009 by \sml{do_before_changed}. It is invoked after the modification in
1010 a view created by \sml{do_after_changed}.
1011 \begin{SML}
1012 do_before_changed : (('n,'e,'g) graph -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
1013 do_after_changed : (('n,'e,'g) graph -> unit) -> ('n,'e,'g) graph -> ('n,'e,'g) graph
1014 \end{SML}
1015
1016 Behavioral views created by the above functions are all fully update
1017 transparent.