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,
28 # include "HsVersions.h"
30 ------------------------------------------------------------------------------
31 -- A version of the graph algorithms described in:
33 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
34 -- by David King and John Launchbury
36 -- Also included is some additional code for printing tree structures ...
37 ------------------------------------------------------------------------------
40 import Util ( sortLe )
44 import Control.Monad.ST
51 #if __GLASGOW_HASKELL__ > 604
54 import Data.Array.ST hiding ( indices, bounds )
59 %************************************************************************
63 %************************************************************************
66 data SCC vertex = AcyclicSCC vertex
69 flattenSCCs :: [SCC a] -> [a]
70 flattenSCCs = concatMap flattenSCC
72 flattenSCC (AcyclicSCC v) = [v]
73 flattenSCC (CyclicSCC vs) = vs
75 instance Outputable a => Outputable (SCC a) where
76 ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
77 ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
83 => [(node, key, [key])] -- The graph; its ok for the
84 -- out-list to contain keys which arent
85 -- a vertex key, they are ignored
86 -> [SCC node] -- Returned in topologically sorted order
87 -- Later components depend on earlier ones, but not vice versa
89 stronglyConnComp edges
90 = map get_node (stronglyConnCompR edges)
92 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
93 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
95 -- The "R" interface is used when you expect to apply SCC to
96 -- the (some of) the result of SCC, so you dont want to lose the dependency info
99 => [(node, key, [key])] -- The graph; its ok for the
100 -- out-list to contain keys which arent
101 -- a vertex key, they are ignored
102 -> [SCC (node, key, [key])] -- Topologically sorted
104 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
105 stronglyConnCompR edges
108 (graph, vertex_fn) = _scc_ "graphFromEdges" graphFromEdges edges
109 forest = _scc_ "Digraph.scc" scc graph
110 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
111 | otherwise = AcyclicSCC (vertex_fn v)
112 decode other = CyclicSCC (dec other [])
114 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
115 mentions_itself v = v `elem` (graph ! v)
118 %************************************************************************
122 %************************************************************************
127 type Table a = Array Vertex a
128 type Graph = Table [Vertex]
129 type Bounds = (Vertex, Vertex)
130 type Edge = (Vertex, Vertex)
134 vertices :: Graph -> [Vertex]
137 edges :: Graph -> [Edge]
138 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
140 mapT :: (Vertex -> a -> b) -> Table a -> Table b
141 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
143 buildG :: Bounds -> [Edge] -> Graph
144 buildG bounds edges = accumArray (flip (:)) [] bounds edges
146 transposeG :: Graph -> Graph
147 transposeG g = buildG (bounds g) (reverseE g)
149 reverseE :: Graph -> [Edge]
150 reverseE g = [ (w, v) | (v, w) <- edges g ]
152 outdegree :: Graph -> Table Int
153 outdegree = mapT numEdges
154 where numEdges v ws = length ws
156 indegree :: Graph -> Table Int
157 indegree = outdegree . transposeG
164 => [(node, key, [key])]
165 -> (Graph, Vertex -> (node, key, [key]))
166 graphFromEdges edges =
167 case graphFromEdges' edges of (graph, vertex_fn, _) -> (graph, vertex_fn)
171 => [(node, key, [key])]
172 -> (Graph, Vertex -> (node, key, [key]), key -> Maybe Vertex)
173 graphFromEdges' edges
174 = (graph, \v -> vertex_map ! v, key_vertex)
176 max_v = length edges - 1
177 bounds = (0,max_v) :: (Vertex, Vertex)
179 (_,k1,_) `le` (_,k2,_) = case k1 `compare` k2 of { GT -> False; other -> True }
182 edges1 = zipWith (,) [0..] sorted_edges
184 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
185 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
186 vertex_map = array bounds edges1
189 -- key_vertex :: key -> Maybe Vertex
190 -- returns Nothing for non-interesting vertices
191 key_vertex k = find 0 max_v
195 find a b = case compare k (key_map ! mid) of
200 mid = (a + b) `div` 2
203 %************************************************************************
207 %************************************************************************
210 data Tree a = Node a (Forest a)
211 type Forest a = [Tree a]
213 mapTree :: (a -> b) -> (Tree a -> Tree b)
214 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
218 instance Show a => Show (Tree a) where
219 showsPrec p t s = showTree t ++ s
221 showTree :: Show a => Tree a -> String
222 showTree = drawTree . mapTree show
224 showForest :: Show a => Forest a -> String
225 showForest = unlines . map showTree
227 drawTree :: Tree String -> String
228 drawTree = unlines . draw
230 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
231 where this = s1 ++ x ++ " "
233 space n = replicate n ' '
236 stLoop [t] = grp s2 " " (draw t)
237 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
239 rsLoop [t] = grp s5 " " (draw t)
240 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
242 grp fst rst = zipWith (++) (fst:repeat rst)
244 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
248 %************************************************************************
250 %* Depth first search
252 %************************************************************************
255 #if __GLASGOW_HASKELL__ >= 504
256 newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)
257 newSTArray = newArray
259 readSTArray :: Ix i => STArray s i e -> i -> ST s e
260 readSTArray = readArray
262 writeSTArray :: Ix i => STArray s i e -> i -> e -> ST s ()
263 writeSTArray = writeArray
266 type Set s = STArray s Vertex Bool
268 mkEmpty :: Bounds -> ST s (Set s)
269 mkEmpty bnds = newSTArray bnds False
271 contains :: Set s -> Vertex -> ST s Bool
272 contains m v = readSTArray m v
274 include :: Set s -> Vertex -> ST s ()
275 include m v = writeSTArray m v True
279 dff :: Graph -> Forest Vertex
280 dff g = dfs g (vertices g)
282 dfs :: Graph -> [Vertex] -> Forest Vertex
283 dfs g vs = prune (bounds g) (map (generate g) vs)
285 generate :: Graph -> Vertex -> Tree Vertex
286 generate g v = Node v (map (generate g) (g!v))
288 prune :: Bounds -> Forest Vertex -> Forest Vertex
289 prune bnds ts = runST (mkEmpty bnds >>= \m ->
292 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
293 chop m [] = return []
294 chop m (Node v ts : us)
295 = contains m v >>= \visited ->
299 include m v >>= \_ ->
302 return (Node v as : bs)
306 %************************************************************************
310 %************************************************************************
312 ------------------------------------------------------------
313 -- Algorithm 1: depth first search numbering
314 ------------------------------------------------------------
317 --preorder :: Tree a -> [a]
318 preorder (Node a ts) = a : preorderF ts
320 preorderF :: Forest a -> [a]
321 preorderF ts = concat (map preorder ts)
323 tabulate :: Bounds -> [Vertex] -> Table Int
324 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
326 preArr :: Bounds -> Forest Vertex -> Table Int
327 preArr bnds = tabulate bnds . preorderF
331 ------------------------------------------------------------
332 -- Algorithm 2: topological sorting
333 ------------------------------------------------------------
336 --postorder :: Tree a -> [a]
337 postorder (Node a ts) = postorderF ts ++ [a]
339 postorderF :: Forest a -> [a]
340 postorderF ts = concat (map postorder ts)
342 postOrd :: Graph -> [Vertex]
343 postOrd = postorderF . dff
345 topSort :: Graph -> [Vertex]
346 topSort = reverse . postOrd
350 ------------------------------------------------------------
351 -- Algorithm 3: connected components
352 ------------------------------------------------------------
355 components :: Graph -> Forest Vertex
356 components = dff . undirected
358 undirected :: Graph -> Graph
359 undirected g = buildG (bounds g) (edges g ++ reverseE g)
363 -- Algorithm 4: strongly connected components
366 scc :: Graph -> Forest Vertex
367 scc g = dfs g (reverse (postOrd (transposeG g)))
371 ------------------------------------------------------------
372 -- Algorithm 5: Classifying edges
373 ------------------------------------------------------------
376 back :: Graph -> Table Int -> Graph
377 back g post = mapT select g
378 where select v ws = [ w | w <- ws, post!v < post!w ]
380 cross :: Graph -> Table Int -> Table Int -> Graph
381 cross g pre post = mapT select g
382 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
384 forward :: Graph -> Graph -> Table Int -> Graph
385 forward g tree pre = mapT select g
386 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
390 ------------------------------------------------------------
391 -- Algorithm 6: Finding reachable vertices
392 ------------------------------------------------------------
395 reachable :: Graph -> Vertex -> [Vertex]
396 reachable g v = preorderF (dfs g [v])
398 path :: Graph -> Vertex -> Vertex -> Bool
399 path g v w = w `elem` (reachable g v)
403 ------------------------------------------------------------
404 -- Algorithm 7: Biconnected components
405 ------------------------------------------------------------
408 bcc :: Graph -> Forest [Vertex]
409 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
411 dnum = preArr (bounds g) forest
413 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
414 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
415 where us = map (do_label g dnum) ts
416 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
417 ++ [lu | Node (u,du,lu) xs <- us])
419 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
420 bicomps (Node (v,dv,lv) ts)
421 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
423 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
424 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
425 where collected = map collect ts
426 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
427 cs = concat [ if lw<dv then us else [Node (v:ws) us]
428 | (lw, Node ws us) <- collected ]