2 % (c) The University of Glasgow 2006
8 -- At present the only one with a "nice" external interface
9 stronglyConnComp, stronglyConnCompR, SCC(..), flattenSCC, flattenSCCs,
12 graphFromEdges, graphFromEdges',
13 buildG, transposeG, reverseE, outdegree, indegree,
27 # include "HsVersions.h"
29 ------------------------------------------------------------------------------
30 -- A version of the graph algorithms described in:
32 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
33 -- by David King and John Launchbury
35 -- Also included is some additional code for printing tree structures ...
36 ------------------------------------------------------------------------------
39 import Util ( sortLe )
43 import Control.Monad.ST
50 #if __GLASGOW_HASKELL__ > 604
53 import Data.Array.ST hiding ( indices, bounds )
58 %************************************************************************
62 %************************************************************************
65 data SCC vertex = AcyclicSCC vertex
68 flattenSCCs :: [SCC a] -> [a]
69 flattenSCCs = concatMap flattenSCC
71 flattenSCC (AcyclicSCC v) = [v]
72 flattenSCC (CyclicSCC vs) = vs
74 instance Outputable a => Outputable (SCC a) where
75 ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
76 ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
82 => [(node, key, [key])] -- The graph; its ok for the
83 -- out-list to contain keys which arent
84 -- a vertex key, they are ignored
85 -> [SCC node] -- Returned in topologically sorted order
86 -- Later components depend on earlier ones, but not vice versa
88 stronglyConnComp edges
89 = map get_node (stronglyConnCompR edges)
91 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
92 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
94 -- The "R" interface is used when you expect to apply SCC to
95 -- the (some of) the result of SCC, so you dont want to lose the dependency info
98 => [(node, key, [key])] -- The graph; its ok for the
99 -- out-list to contain keys which arent
100 -- a vertex key, they are ignored
101 -> [SCC (node, key, [key])] -- Topologically sorted
103 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
104 stronglyConnCompR edges
107 (graph, vertex_fn) = {-# SCC "graphFromEdges" #-} graphFromEdges edges
108 forest = {-# SCC "Digraph.scc" #-} scc graph
109 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
110 | otherwise = AcyclicSCC (vertex_fn v)
111 decode other = CyclicSCC (dec other [])
113 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
114 mentions_itself v = v `elem` (graph ! v)
117 %************************************************************************
121 %************************************************************************
126 type Table a = Array Vertex a
127 type Graph = Table [Vertex]
128 type Bounds = (Vertex, Vertex)
129 type Edge = (Vertex, Vertex)
133 vertices :: Graph -> [Vertex]
136 edges :: Graph -> [Edge]
137 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
139 mapT :: (Vertex -> a -> b) -> Table a -> Table b
140 mapT f t = array (bounds t) [ (v, f v (t ! v)) | v <- indices t ]
142 buildG :: Bounds -> [Edge] -> Graph
143 buildG bounds edges = accumArray (flip (:)) [] bounds edges
145 transposeG :: Graph -> Graph
146 transposeG g = buildG (bounds g) (reverseE g)
148 reverseE :: Graph -> [Edge]
149 reverseE g = [ (w, v) | (v, w) <- edges g ]
151 outdegree :: Graph -> Table Int
152 outdegree = mapT numEdges
153 where numEdges v ws = length ws
155 indegree :: Graph -> Table Int
156 indegree = outdegree . transposeG
163 => [(node, key, [key])]
164 -> (Graph, Vertex -> (node, key, [key]))
165 graphFromEdges edges =
166 case graphFromEdges' edges of (graph, vertex_fn, _) -> (graph, vertex_fn)
170 => [(node, key, [key])]
171 -> (Graph, Vertex -> (node, key, [key]), key -> Maybe Vertex)
172 graphFromEdges' edges
173 = (graph, \v -> vertex_map ! v, key_vertex)
175 max_v = length edges - 1
176 bounds = (0,max_v) :: (Vertex, Vertex)
178 (_,k1,_) `le` (_,k2,_) = case k1 `compare` k2 of { GT -> False; other -> True }
181 edges1 = zipWith (,) [0..] sorted_edges
183 graph = array bounds [ (v, mapMaybe key_vertex ks)
184 | (v, (_, _, ks)) <- edges1]
185 key_map = array bounds [ (v, k)
186 | (v, (_, k, _ )) <- edges1]
187 vertex_map = array bounds edges1
190 -- key_vertex :: key -> Maybe Vertex
191 -- returns Nothing for non-interesting vertices
192 key_vertex k = find 0 max_v
196 find a b = case compare k (key_map ! mid) of
201 mid = (a + b) `div` 2
204 %************************************************************************
208 %************************************************************************
211 data Tree a = Node a (Forest a)
212 type Forest a = [Tree a]
214 mapTree :: (a -> b) -> (Tree a -> Tree b)
215 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
219 instance Show a => Show (Tree a) where
220 showsPrec p t s = showTree t ++ s
222 showTree :: Show a => Tree a -> String
223 showTree = drawTree . mapTree show
225 showForest :: Show a => Forest a -> String
226 showForest = unlines . map showTree
228 drawTree :: Tree String -> String
229 drawTree = unlines . draw
231 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
232 where this = s1 ++ x ++ " "
234 space n = replicate n ' '
237 stLoop [t] = grp s2 " " (draw t)
238 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
240 rsLoop [t] = grp s5 " " (draw t)
241 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
243 grp fst rst = zipWith (++) (fst:repeat rst)
245 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
249 %************************************************************************
251 %* Depth first search
253 %************************************************************************
256 type Set s = STArray s Vertex Bool
258 mkEmpty :: Bounds -> ST s (Set s)
259 mkEmpty bnds = newArray bnds False
261 contains :: Set s -> Vertex -> ST s Bool
262 contains m v = readArray m v
264 include :: Set s -> Vertex -> ST s ()
265 include m v = writeArray m v True
269 dff :: Graph -> Forest Vertex
270 dff g = dfs g (vertices g)
272 dfs :: Graph -> [Vertex] -> Forest Vertex
273 dfs g vs = prune (bounds g) (map (generate g) vs)
275 generate :: Graph -> Vertex -> Tree Vertex
276 generate g v = Node v (map (generate g) (g!v))
278 prune :: Bounds -> Forest Vertex -> Forest Vertex
279 prune bnds ts = runST (mkEmpty bnds >>= \m ->
282 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
283 chop m [] = return []
284 chop m (Node v ts : us)
285 = contains m v >>= \visited ->
289 include m v >>= \_ ->
292 return (Node v as : bs)
296 %************************************************************************
300 %************************************************************************
302 ------------------------------------------------------------
303 -- Algorithm 1: depth first search numbering
304 ------------------------------------------------------------
307 --preorder :: Tree a -> [a]
308 preorder (Node a ts) = a : preorderF ts
310 preorderF :: Forest a -> [a]
311 preorderF ts = concat (map preorder ts)
313 tabulate :: Bounds -> [Vertex] -> Table Int
314 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
316 preArr :: Bounds -> Forest Vertex -> Table Int
317 preArr bnds = tabulate bnds . preorderF
321 ------------------------------------------------------------
322 -- Algorithm 2: topological sorting
323 ------------------------------------------------------------
326 postorder :: Tree a -> [a] -> [a]
327 postorder (Node a ts) = postorderF ts . (a :)
329 postorderF :: Forest a -> [a] -> [a]
330 postorderF ts = foldr (.) id $ map postorder ts
332 postOrd :: Graph -> [Vertex]
333 postOrd g = postorderF (dff g) []
335 topSort :: Graph -> [Vertex]
336 topSort = reverse . postOrd
340 ------------------------------------------------------------
341 -- Algorithm 3: connected components
342 ------------------------------------------------------------
345 components :: Graph -> Forest Vertex
346 components = dff . undirected
348 undirected :: Graph -> Graph
349 undirected g = buildG (bounds g) (edges g ++ reverseE g)
353 -- Algorithm 4: strongly connected components
356 scc :: Graph -> Forest Vertex
357 scc g = dfs g (reverse (postOrd (transposeG g)))
361 ------------------------------------------------------------
362 -- Algorithm 5: Classifying edges
363 ------------------------------------------------------------
366 back :: Graph -> Table Int -> Graph
367 back g post = mapT select g
368 where select v ws = [ w | w <- ws, post!v < post!w ]
370 cross :: Graph -> Table Int -> Table Int -> Graph
371 cross g pre post = mapT select g
372 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
374 forward :: Graph -> Graph -> Table Int -> Graph
375 forward g tree pre = mapT select g
376 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
380 ------------------------------------------------------------
381 -- Algorithm 6: Finding reachable vertices
382 ------------------------------------------------------------
385 reachable :: Graph -> Vertex -> [Vertex]
386 reachable g v = preorderF (dfs g [v])
388 path :: Graph -> Vertex -> Vertex -> Bool
389 path g v w = w `elem` (reachable g v)
393 ------------------------------------------------------------
394 -- Algorithm 7: Biconnected components
395 ------------------------------------------------------------
398 bcc :: Graph -> Forest [Vertex]
399 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
401 dnum = preArr (bounds g) forest
403 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
404 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
405 where us = map (do_label g dnum) ts
406 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
407 ++ [lu | Node (u,du,lu) xs <- us])
409 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
410 bicomps (Node (v,dv,lv) ts)
411 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
413 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
414 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
415 where collected = map collect ts
416 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
417 cs = concat [ if lw<dv then us else [Node (v:ws) us]
418 | (lw, Node ws us) <- collected ]