4 -- At present the only one with a "nice" external interface
5 stronglyConnComp, stronglyConnCompR, SCC(..), flattenSCC, flattenSCCs,
8 graphFromEdges, buildG, transposeG, reverseE, outdegree, indegree,
23 # include "HsVersions.h"
25 ------------------------------------------------------------------------------
26 -- A version of the graph algorithms described in:
28 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
29 -- by David King and John Launchbury
31 -- Also included is some additional code for printing tree structures ...
32 ------------------------------------------------------------------------------
35 import Util ( sortLt )
46 #if __GLASGOW_HASKELL__ >= 504
47 import Data.Array.ST hiding ( indices, bounds )
54 %************************************************************************
58 %************************************************************************
61 data SCC vertex = AcyclicSCC vertex
64 flattenSCCs :: [SCC a] -> [a]
65 flattenSCCs = concatMap flattenSCC
67 flattenSCC (AcyclicSCC v) = [v]
68 flattenSCC (CyclicSCC vs) = vs
70 instance Outputable a => Outputable (SCC a) where
71 ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
72 ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
78 => [(node, key, [key])] -- The graph; its ok for the
79 -- out-list to contain keys which arent
80 -- a vertex key, they are ignored
81 -> [SCC node] -- Returned in topologically sorted order
82 -- Later components depend on earlier ones, but not vice versa
84 stronglyConnComp edges
85 = map get_node (stronglyConnCompR edges)
87 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
88 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
90 -- The "R" interface is used when you expect to apply SCC to
91 -- the (some of) the result of SCC, so you dont want to lose the dependency info
94 => [(node, key, [key])] -- The graph; its ok for the
95 -- out-list to contain keys which arent
96 -- a vertex key, they are ignored
97 -> [SCC (node, key, [key])] -- Topologically sorted
99 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
100 stronglyConnCompR edges
103 (graph, vertex_fn) = graphFromEdges edges
105 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
106 | otherwise = AcyclicSCC (vertex_fn v)
107 decode other = CyclicSCC (dec other [])
109 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
110 mentions_itself v = v `elem` (graph ! v)
113 %************************************************************************
117 %************************************************************************
122 type Table a = Array Vertex a
123 type Graph = Table [Vertex]
124 type Bounds = (Vertex, Vertex)
125 type Edge = (Vertex, Vertex)
129 vertices :: Graph -> [Vertex]
132 edges :: Graph -> [Edge]
133 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
135 mapT :: (Vertex -> a -> b) -> Table a -> Table b
136 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
138 buildG :: Bounds -> [Edge] -> Graph
139 buildG bounds edges = accumArray (flip (:)) [] bounds edges
141 transposeG :: Graph -> Graph
142 transposeG g = buildG (bounds g) (reverseE g)
144 reverseE :: Graph -> [Edge]
145 reverseE g = [ (w, v) | (v, w) <- edges g ]
147 outdegree :: Graph -> Table Int
148 outdegree = mapT numEdges
149 where numEdges v ws = length ws
151 indegree :: Graph -> Table Int
152 indegree = outdegree . transposeG
159 => [(node, key, [key])]
160 -> (Graph, Vertex -> (node, key, [key]))
162 = (graph, \v -> vertex_map ! v)
164 max_v = length edges - 1
165 bounds = (0,max_v) :: (Vertex, Vertex)
166 sorted_edges = sortLt lt edges
167 edges1 = zipWith (,) [0..] sorted_edges
169 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
170 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
171 vertex_map = array bounds edges1
173 (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
175 -- key_vertex :: key -> Maybe Vertex
176 -- returns Nothing for non-interesting vertices
177 key_vertex k = find 0 max_v
181 find a b = case compare k (key_map ! mid) of
186 mid = (a + b) `div` 2
189 %************************************************************************
193 %************************************************************************
196 data Tree a = Node a (Forest a)
197 type Forest a = [Tree a]
199 mapTree :: (a -> b) -> (Tree a -> Tree b)
200 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
204 instance Show a => Show (Tree a) where
205 showsPrec p t s = showTree t ++ s
207 showTree :: Show a => Tree a -> String
208 showTree = drawTree . mapTree show
210 showForest :: Show a => Forest a -> String
211 showForest = unlines . map showTree
213 drawTree :: Tree String -> String
214 drawTree = unlines . draw
216 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
217 where this = s1 ++ x ++ " "
219 space n = replicate n ' '
222 stLoop [t] = grp s2 " " (draw t)
223 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
225 rsLoop [t] = grp s5 " " (draw t)
226 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
228 grp fst rst = zipWith (++) (fst:repeat rst)
230 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
234 %************************************************************************
236 %* Depth first search
238 %************************************************************************
241 #if __GLASGOW_HASKELL__ >= 504
242 newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)
243 newSTArray = newArray
245 readSTArray :: Ix i => STArray s i e -> i -> ST s e
246 readSTArray = readArray
248 writeSTArray :: Ix i => STArray s i e -> i -> e -> ST s ()
249 writeSTArray = writeArray
252 type Set s = STArray s Vertex Bool
254 mkEmpty :: Bounds -> ST s (Set s)
255 mkEmpty bnds = newSTArray bnds False
257 contains :: Set s -> Vertex -> ST s Bool
258 contains m v = readSTArray m v
260 include :: Set s -> Vertex -> ST s ()
261 include m v = writeSTArray m v True
265 dff :: Graph -> Forest Vertex
266 dff g = dfs g (vertices g)
268 dfs :: Graph -> [Vertex] -> Forest Vertex
269 dfs g vs = prune (bounds g) (map (generate g) vs)
271 generate :: Graph -> Vertex -> Tree Vertex
272 generate g v = Node v (map (generate g) (g!v))
274 prune :: Bounds -> Forest Vertex -> Forest Vertex
275 prune bnds ts = runST (mkEmpty bnds >>= \m ->
278 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
279 chop m [] = return []
280 chop m (Node v ts : us)
281 = contains m v >>= \visited ->
285 include m v >>= \_ ->
288 return (Node v as : bs)
292 %************************************************************************
296 %************************************************************************
298 ------------------------------------------------------------
299 -- Algorithm 1: depth first search numbering
300 ------------------------------------------------------------
303 --preorder :: Tree a -> [a]
304 preorder (Node a ts) = a : preorderF ts
306 preorderF :: Forest a -> [a]
307 preorderF ts = concat (map preorder ts)
309 tabulate :: Bounds -> [Vertex] -> Table Int
310 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
312 preArr :: Bounds -> Forest Vertex -> Table Int
313 preArr bnds = tabulate bnds . preorderF
317 ------------------------------------------------------------
318 -- Algorithm 2: topological sorting
319 ------------------------------------------------------------
322 --postorder :: Tree a -> [a]
323 postorder (Node a ts) = postorderF ts ++ [a]
325 postorderF :: Forest a -> [a]
326 postorderF ts = concat (map postorder ts)
328 postOrd :: Graph -> [Vertex]
329 postOrd = postorderF . dff
331 topSort :: Graph -> [Vertex]
332 topSort = reverse . postOrd
336 ------------------------------------------------------------
337 -- Algorithm 3: connected components
338 ------------------------------------------------------------
341 components :: Graph -> Forest Vertex
342 components = dff . undirected
344 undirected :: Graph -> Graph
345 undirected g = buildG (bounds g) (edges g ++ reverseE g)
349 -- Algorithm 4: strongly connected components
352 scc :: Graph -> Forest Vertex
353 scc g = dfs g (reverse (postOrd (transposeG g)))
357 ------------------------------------------------------------
358 -- Algorithm 5: Classifying edges
359 ------------------------------------------------------------
362 back :: Graph -> Table Int -> Graph
363 back g post = mapT select g
364 where select v ws = [ w | w <- ws, post!v < post!w ]
366 cross :: Graph -> Table Int -> Table Int -> Graph
367 cross g pre post = mapT select g
368 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
370 forward :: Graph -> Graph -> Table Int -> Graph
371 forward g tree pre = mapT select g
372 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
376 ------------------------------------------------------------
377 -- Algorithm 6: Finding reachable vertices
378 ------------------------------------------------------------
381 reachable :: Graph -> Vertex -> [Vertex]
382 reachable g v = preorderF (dfs g [v])
384 path :: Graph -> Vertex -> Vertex -> Bool
385 path g v w = w `elem` (reachable g v)
389 ------------------------------------------------------------
390 -- Algorithm 7: Biconnected components
391 ------------------------------------------------------------
394 bcc :: Graph -> Forest [Vertex]
395 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
397 dnum = preArr (bounds g) forest
399 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
400 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
401 where us = map (do_label g dnum) ts
402 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
403 ++ [lu | Node (u,du,lu) xs <- us])
405 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
406 bicomps (Node (v,dv,lv) ts)
407 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
409 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
410 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
411 where collected = map collect ts
412 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
413 cs = concat [ if lw<dv then us else [Node (v:ws) us]
414 | (lw, Node ws us) <- collected ]