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 !defined(__GLASGOW_HASKELL__) || __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 :: SCC a -> [a]
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)))
80 Note [Nodes, keys, vertices]
81 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
82 * A 'node' is a big blob of client-stuff
84 * Each 'node' has a unique (client) 'key', but the latter
85 is in Ord and has fast comparison
87 * Digraph then maps each 'key' to a Vertex (Int) which is
88 arranged densely in 0.n
93 => [(node, key, [key])] -- The graph; its ok for the
94 -- out-list to contain keys which arent
95 -- a vertex key, they are ignored
96 -> [SCC node] -- Returned in topologically sorted order
97 -- Later components depend on earlier ones, but not vice versa
99 stronglyConnComp edges
100 = map get_node (stronglyConnCompR edges)
102 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
103 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
105 -- The "R" interface is used when you expect to apply SCC to
106 -- the (some of) the result of SCC, so you dont want to lose the dependency info
109 => [(node, key, [key])] -- The graph; its ok for the
110 -- out-list to contain keys which arent
111 -- a vertex key, they are ignored
112 -> [SCC (node, key, [key])] -- Topologically sorted
114 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
115 stronglyConnCompR edges
118 (graph, vertex_fn) = {-# SCC "graphFromEdges" #-} graphFromEdges edges
119 forest = {-# SCC "Digraph.scc" #-} scc graph
120 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
121 | otherwise = AcyclicSCC (vertex_fn v)
122 decode other = CyclicSCC (dec other [])
124 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
125 mentions_itself v = v `elem` (graph ! v)
128 %************************************************************************
132 %************************************************************************
137 type Table a = Array Vertex a
138 type Graph = Table [Vertex]
139 type Bounds = (Vertex, Vertex)
140 type Edge = (Vertex, Vertex)
144 vertices :: Graph -> [Vertex]
147 edges :: Graph -> [Edge]
148 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
150 mapT :: (Vertex -> a -> b) -> Table a -> Table b
151 mapT f t = array (bounds t) [ (v, f v (t ! v)) | v <- indices t ]
153 buildG :: Bounds -> [Edge] -> Graph
154 buildG bounds edges = accumArray (flip (:)) [] bounds edges
156 transposeG :: Graph -> Graph
157 transposeG g = buildG (bounds g) (reverseE g)
159 reverseE :: Graph -> [Edge]
160 reverseE g = [ (w, v) | (v, w) <- edges g ]
162 outdegree :: Graph -> Table Int
163 outdegree = mapT numEdges
164 where numEdges _ ws = length ws
166 indegree :: Graph -> Table Int
167 indegree = outdegree . transposeG
174 => [(node, key, [key])]
175 -> (Graph, Vertex -> (node, key, [key]))
176 graphFromEdges edges =
177 case graphFromEdges' edges of (graph, vertex_fn, _) -> (graph, vertex_fn)
181 => [(node, key, [key])]
182 -> (Graph, Vertex -> (node, key, [key]), key -> Maybe Vertex)
183 graphFromEdges' edges
184 = (graph, \v -> vertex_map ! v, key_vertex)
186 max_v = length edges - 1
187 bounds = (0,max_v) :: (Vertex, Vertex)
189 (_,k1,_) `le` (_,k2,_) = (k1 `compare` k2) /= GT
192 edges1 = zipWith (,) [0..] sorted_edges
194 graph = array bounds [ (v, mapMaybe key_vertex ks)
195 | (v, (_, _, ks)) <- edges1]
196 key_map = array bounds [ (v, k)
197 | (v, (_, k, _ )) <- edges1]
198 vertex_map = array bounds edges1
201 -- key_vertex :: key -> Maybe Vertex
202 -- returns Nothing for non-interesting vertices
203 key_vertex k = find 0 max_v
207 find a b = case compare k (key_map ! mid) of
212 mid = (a + b) `div` 2
215 %************************************************************************
219 %************************************************************************
222 data Tree a = Node a (Forest a)
223 type Forest a = [Tree a]
225 mapTree :: (a -> b) -> (Tree a -> Tree b)
226 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
230 instance Show a => Show (Tree a) where
231 showsPrec _ t s = showTree t ++ s
233 showTree :: Show a => Tree a -> String
234 showTree = drawTree . mapTree show
236 showForest :: Show a => Forest a -> String
237 showForest = unlines . map showTree
239 drawTree :: Tree String -> String
240 drawTree = unlines . draw
242 draw :: Tree String -> [String]
243 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
244 where this = s1 ++ x ++ " "
246 space n = replicate n ' '
249 stLoop [t] = grp s2 " " (draw t)
250 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
253 rsLoop [t] = grp s5 " " (draw t)
254 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
256 grp fst rst = zipWith (++) (fst:repeat rst)
258 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
262 %************************************************************************
264 %* Depth first search
266 %************************************************************************
269 type Set s = STArray s Vertex Bool
271 mkEmpty :: Bounds -> ST s (Set s)
272 mkEmpty bnds = newArray bnds False
274 contains :: Set s -> Vertex -> ST s Bool
275 contains m v = readArray m v
277 include :: Set s -> Vertex -> ST s ()
278 include m v = writeArray m v True
282 dff :: Graph -> Forest Vertex
283 dff g = dfs g (vertices g)
285 dfs :: Graph -> [Vertex] -> Forest Vertex
286 dfs g vs = prune (bounds g) (map (generate g) vs)
288 generate :: Graph -> Vertex -> Tree Vertex
289 generate g v = Node v (map (generate g) (g!v))
291 prune :: Bounds -> Forest Vertex -> Forest Vertex
292 prune bnds ts = runST (mkEmpty bnds >>= \m ->
295 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
296 chop _ [] = return []
297 chop m (Node v ts : us)
298 = contains m v >>= \visited ->
302 include m v >>= \_ ->
305 return (Node v as : bs)
309 %************************************************************************
313 %************************************************************************
315 ------------------------------------------------------------
316 -- Algorithm 1: depth first search numbering
317 ------------------------------------------------------------
320 preorder :: Tree a -> [a]
321 preorder (Node a ts) = a : preorderF ts
323 preorderF :: Forest a -> [a]
324 preorderF ts = concat (map preorder ts)
326 tabulate :: Bounds -> [Vertex] -> Table Int
327 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
329 preArr :: Bounds -> Forest Vertex -> Table Int
330 preArr bnds = tabulate bnds . preorderF
334 ------------------------------------------------------------
335 -- Algorithm 2: topological sorting
336 ------------------------------------------------------------
339 postorder :: Tree a -> [a] -> [a]
340 postorder (Node a ts) = postorderF ts . (a :)
342 postorderF :: Forest a -> [a] -> [a]
343 postorderF ts = foldr (.) id $ map postorder ts
345 postOrd :: Graph -> [Vertex]
346 postOrd g = postorderF (dff g) []
348 topSort :: Graph -> [Vertex]
349 topSort = reverse . postOrd
353 ------------------------------------------------------------
354 -- Algorithm 3: connected components
355 ------------------------------------------------------------
358 components :: Graph -> Forest Vertex
359 components = dff . undirected
361 undirected :: Graph -> Graph
362 undirected g = buildG (bounds g) (edges g ++ reverseE g)
366 -- Algorithm 4: strongly connected components
369 scc :: Graph -> Forest Vertex
370 scc g = dfs g (reverse (postOrd (transposeG g)))
374 ------------------------------------------------------------
375 -- Algorithm 5: Classifying edges
376 ------------------------------------------------------------
379 back :: Graph -> Table Int -> Graph
380 back g post = mapT select g
381 where select v ws = [ w | w <- ws, post!v < post!w ]
383 cross :: Graph -> Table Int -> Table Int -> Graph
384 cross g pre post = mapT select g
385 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
387 forward :: Graph -> Graph -> Table Int -> Graph
388 forward g tree pre = mapT select g
389 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
393 ------------------------------------------------------------
394 -- Algorithm 6: Finding reachable vertices
395 ------------------------------------------------------------
398 reachable :: Graph -> Vertex -> [Vertex]
399 reachable g v = preorderF (dfs g [v])
401 path :: Graph -> Vertex -> Vertex -> Bool
402 path g v w = w `elem` (reachable g v)
406 ------------------------------------------------------------
407 -- Algorithm 7: Biconnected components
408 ------------------------------------------------------------
411 bcc :: Graph -> Forest [Vertex]
412 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
414 dnum = preArr (bounds g) forest
416 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
417 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
418 where us = map (do_label g dnum) ts
419 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
420 ++ [lu | Node (_,_,lu) _ <- us])
422 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
423 bicomps (Node (v,_,_) ts)
424 = [ Node (v:vs) us | (_,Node vs us) <- map collect ts]
426 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
427 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
428 where collected = map collect ts
429 vs = concat [ ws | (lw, Node ws _) <- collected, lw<dv]
430 cs = concat [ if lw<dv then us else [Node (v:ws) us]
431 | (lw, Node ws us) <- collected ]