2 % (c) The University of Glasgow 2006
7 -- The above warning supression flag is a temporary kludge.
8 -- While working on this module you are encouraged to remove it and fix
9 -- any warnings in the module. See
10 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 -- At present the only one with a "nice" external interface
16 stronglyConnComp, stronglyConnCompR, SCC(..), flattenSCC, flattenSCCs,
19 graphFromEdges, graphFromEdges',
20 buildG, transposeG, reverseE, outdegree, indegree,
34 # include "HsVersions.h"
36 ------------------------------------------------------------------------------
37 -- A version of the graph algorithms described in:
39 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
40 -- by David King and John Launchbury
42 -- Also included is some additional code for printing tree structures ...
43 ------------------------------------------------------------------------------
46 import Util ( sortLe )
50 import Control.Monad.ST
57 #if __GLASGOW_HASKELL__ > 604
60 import Data.Array.ST hiding ( indices, bounds )
65 %************************************************************************
69 %************************************************************************
72 data SCC vertex = AcyclicSCC vertex
75 flattenSCCs :: [SCC a] -> [a]
76 flattenSCCs = concatMap flattenSCC
78 flattenSCC (AcyclicSCC v) = [v]
79 flattenSCC (CyclicSCC vs) = vs
81 instance Outputable a => Outputable (SCC a) where
82 ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
83 ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
89 => [(node, key, [key])] -- The graph; its ok for the
90 -- out-list to contain keys which arent
91 -- a vertex key, they are ignored
92 -> [SCC node] -- Returned in topologically sorted order
93 -- Later components depend on earlier ones, but not vice versa
95 stronglyConnComp edges
96 = map get_node (stronglyConnCompR edges)
98 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
99 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
101 -- The "R" interface is used when you expect to apply SCC to
102 -- the (some of) the result of SCC, so you dont want to lose the dependency info
105 => [(node, key, [key])] -- The graph; its ok for the
106 -- out-list to contain keys which arent
107 -- a vertex key, they are ignored
108 -> [SCC (node, key, [key])] -- Topologically sorted
110 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
111 stronglyConnCompR edges
114 (graph, vertex_fn) = {-# SCC "graphFromEdges" #-} graphFromEdges edges
115 forest = {-# SCC "Digraph.scc" #-} scc graph
116 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
117 | otherwise = AcyclicSCC (vertex_fn v)
118 decode other = CyclicSCC (dec other [])
120 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
121 mentions_itself v = v `elem` (graph ! v)
124 %************************************************************************
128 %************************************************************************
133 type Table a = Array Vertex a
134 type Graph = Table [Vertex]
135 type Bounds = (Vertex, Vertex)
136 type Edge = (Vertex, Vertex)
140 vertices :: Graph -> [Vertex]
143 edges :: Graph -> [Edge]
144 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
146 mapT :: (Vertex -> a -> b) -> Table a -> Table b
147 mapT f t = array (bounds t) [ (v, f v (t ! v)) | v <- indices t ]
149 buildG :: Bounds -> [Edge] -> Graph
150 buildG bounds edges = accumArray (flip (:)) [] bounds edges
152 transposeG :: Graph -> Graph
153 transposeG g = buildG (bounds g) (reverseE g)
155 reverseE :: Graph -> [Edge]
156 reverseE g = [ (w, v) | (v, w) <- edges g ]
158 outdegree :: Graph -> Table Int
159 outdegree = mapT numEdges
160 where numEdges v ws = length ws
162 indegree :: Graph -> Table Int
163 indegree = outdegree . transposeG
170 => [(node, key, [key])]
171 -> (Graph, Vertex -> (node, key, [key]))
172 graphFromEdges edges =
173 case graphFromEdges' edges of (graph, vertex_fn, _) -> (graph, vertex_fn)
177 => [(node, key, [key])]
178 -> (Graph, Vertex -> (node, key, [key]), key -> Maybe Vertex)
179 graphFromEdges' edges
180 = (graph, \v -> vertex_map ! v, key_vertex)
182 max_v = length edges - 1
183 bounds = (0,max_v) :: (Vertex, Vertex)
185 (_,k1,_) `le` (_,k2,_) = case k1 `compare` k2 of { GT -> False; other -> True }
188 edges1 = zipWith (,) [0..] sorted_edges
190 graph = array bounds [ (v, mapMaybe key_vertex ks)
191 | (v, (_, _, ks)) <- edges1]
192 key_map = array bounds [ (v, k)
193 | (v, (_, k, _ )) <- edges1]
194 vertex_map = array bounds edges1
197 -- key_vertex :: key -> Maybe Vertex
198 -- returns Nothing for non-interesting vertices
199 key_vertex k = find 0 max_v
203 find a b = case compare k (key_map ! mid) of
208 mid = (a + b) `div` 2
211 %************************************************************************
215 %************************************************************************
218 data Tree a = Node a (Forest a)
219 type Forest a = [Tree a]
221 mapTree :: (a -> b) -> (Tree a -> Tree b)
222 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
226 instance Show a => Show (Tree a) where
227 showsPrec p t s = showTree t ++ s
229 showTree :: Show a => Tree a -> String
230 showTree = drawTree . mapTree show
232 showForest :: Show a => Forest a -> String
233 showForest = unlines . map showTree
235 drawTree :: Tree String -> String
236 drawTree = unlines . draw
238 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
239 where this = s1 ++ x ++ " "
241 space n = replicate n ' '
244 stLoop [t] = grp s2 " " (draw t)
245 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
247 rsLoop [t] = grp s5 " " (draw t)
248 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
250 grp fst rst = zipWith (++) (fst:repeat rst)
252 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
256 %************************************************************************
258 %* Depth first search
260 %************************************************************************
263 type Set s = STArray s Vertex Bool
265 mkEmpty :: Bounds -> ST s (Set s)
266 mkEmpty bnds = newArray bnds False
268 contains :: Set s -> Vertex -> ST s Bool
269 contains m v = readArray m v
271 include :: Set s -> Vertex -> ST s ()
272 include m v = writeArray m v True
276 dff :: Graph -> Forest Vertex
277 dff g = dfs g (vertices g)
279 dfs :: Graph -> [Vertex] -> Forest Vertex
280 dfs g vs = prune (bounds g) (map (generate g) vs)
282 generate :: Graph -> Vertex -> Tree Vertex
283 generate g v = Node v (map (generate g) (g!v))
285 prune :: Bounds -> Forest Vertex -> Forest Vertex
286 prune bnds ts = runST (mkEmpty bnds >>= \m ->
289 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
290 chop m [] = return []
291 chop m (Node v ts : us)
292 = contains m v >>= \visited ->
296 include m v >>= \_ ->
299 return (Node v as : bs)
303 %************************************************************************
307 %************************************************************************
309 ------------------------------------------------------------
310 -- Algorithm 1: depth first search numbering
311 ------------------------------------------------------------
314 --preorder :: Tree a -> [a]
315 preorder (Node a ts) = a : preorderF ts
317 preorderF :: Forest a -> [a]
318 preorderF ts = concat (map preorder ts)
320 tabulate :: Bounds -> [Vertex] -> Table Int
321 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
323 preArr :: Bounds -> Forest Vertex -> Table Int
324 preArr bnds = tabulate bnds . preorderF
328 ------------------------------------------------------------
329 -- Algorithm 2: topological sorting
330 ------------------------------------------------------------
333 postorder :: Tree a -> [a] -> [a]
334 postorder (Node a ts) = postorderF ts . (a :)
336 postorderF :: Forest a -> [a] -> [a]
337 postorderF ts = foldr (.) id $ map postorder ts
339 postOrd :: Graph -> [Vertex]
340 postOrd g = postorderF (dff g) []
342 topSort :: Graph -> [Vertex]
343 topSort = reverse . postOrd
347 ------------------------------------------------------------
348 -- Algorithm 3: connected components
349 ------------------------------------------------------------
352 components :: Graph -> Forest Vertex
353 components = dff . undirected
355 undirected :: Graph -> Graph
356 undirected g = buildG (bounds g) (edges g ++ reverseE g)
360 -- Algorithm 4: strongly connected components
363 scc :: Graph -> Forest Vertex
364 scc g = dfs g (reverse (postOrd (transposeG g)))
368 ------------------------------------------------------------
369 -- Algorithm 5: Classifying edges
370 ------------------------------------------------------------
373 back :: Graph -> Table Int -> Graph
374 back g post = mapT select g
375 where select v ws = [ w | w <- ws, post!v < post!w ]
377 cross :: Graph -> Table Int -> Table Int -> Graph
378 cross g pre post = mapT select g
379 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
381 forward :: Graph -> Graph -> Table Int -> Graph
382 forward g tree pre = mapT select g
383 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
387 ------------------------------------------------------------
388 -- Algorithm 6: Finding reachable vertices
389 ------------------------------------------------------------
392 reachable :: Graph -> Vertex -> [Vertex]
393 reachable g v = preorderF (dfs g [v])
395 path :: Graph -> Vertex -> Vertex -> Bool
396 path g v w = w `elem` (reachable g v)
400 ------------------------------------------------------------
401 -- Algorithm 7: Biconnected components
402 ------------------------------------------------------------
405 bcc :: Graph -> Forest [Vertex]
406 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
408 dnum = preArr (bounds g) forest
410 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
411 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
412 where us = map (do_label g dnum) ts
413 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
414 ++ [lu | Node (u,du,lu) xs <- us])
416 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
417 bicomps (Node (v,dv,lv) ts)
418 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
420 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
421 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
422 where collected = map collect ts
423 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
424 cs = concat [ if lw<dv then us else [Node (v:ws) us]
425 | (lw, Node ws us) <- collected ]