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 ( sortLe )
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) = _scc_ "graphFromEdges" graphFromEdges edges
104 forest = _scc_ "Digraph.scc" scc graph
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)
167 (_,k1,_) `le` (_,k2,_) = case k1 `compare` k2 of { GT -> False; other -> True }
170 edges1 = zipWith (,) [0..] sorted_edges
172 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
173 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
174 vertex_map = array bounds edges1
177 -- key_vertex :: key -> Maybe Vertex
178 -- returns Nothing for non-interesting vertices
179 key_vertex k = find 0 max_v
183 find a b = case compare k (key_map ! mid) of
188 mid = (a + b) `div` 2
191 %************************************************************************
195 %************************************************************************
198 data Tree a = Node a (Forest a)
199 type Forest a = [Tree a]
201 mapTree :: (a -> b) -> (Tree a -> Tree b)
202 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
206 instance Show a => Show (Tree a) where
207 showsPrec p t s = showTree t ++ s
209 showTree :: Show a => Tree a -> String
210 showTree = drawTree . mapTree show
212 showForest :: Show a => Forest a -> String
213 showForest = unlines . map showTree
215 drawTree :: Tree String -> String
216 drawTree = unlines . draw
218 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
219 where this = s1 ++ x ++ " "
221 space n = replicate n ' '
224 stLoop [t] = grp s2 " " (draw t)
225 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
227 rsLoop [t] = grp s5 " " (draw t)
228 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
230 grp fst rst = zipWith (++) (fst:repeat rst)
232 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
236 %************************************************************************
238 %* Depth first search
240 %************************************************************************
243 #if __GLASGOW_HASKELL__ >= 504
244 newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)
245 newSTArray = newArray
247 readSTArray :: Ix i => STArray s i e -> i -> ST s e
248 readSTArray = readArray
250 writeSTArray :: Ix i => STArray s i e -> i -> e -> ST s ()
251 writeSTArray = writeArray
254 type Set s = STArray s Vertex Bool
256 mkEmpty :: Bounds -> ST s (Set s)
257 mkEmpty bnds = newSTArray bnds False
259 contains :: Set s -> Vertex -> ST s Bool
260 contains m v = readSTArray m v
262 include :: Set s -> Vertex -> ST s ()
263 include m v = writeSTArray m v True
267 dff :: Graph -> Forest Vertex
268 dff g = dfs g (vertices g)
270 dfs :: Graph -> [Vertex] -> Forest Vertex
271 dfs g vs = prune (bounds g) (map (generate g) vs)
273 generate :: Graph -> Vertex -> Tree Vertex
274 generate g v = Node v (map (generate g) (g!v))
276 prune :: Bounds -> Forest Vertex -> Forest Vertex
277 prune bnds ts = runST (mkEmpty bnds >>= \m ->
280 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
281 chop m [] = return []
282 chop m (Node v ts : us)
283 = contains m v >>= \visited ->
287 include m v >>= \_ ->
290 return (Node v as : bs)
294 %************************************************************************
298 %************************************************************************
300 ------------------------------------------------------------
301 -- Algorithm 1: depth first search numbering
302 ------------------------------------------------------------
305 --preorder :: Tree a -> [a]
306 preorder (Node a ts) = a : preorderF ts
308 preorderF :: Forest a -> [a]
309 preorderF ts = concat (map preorder ts)
311 tabulate :: Bounds -> [Vertex] -> Table Int
312 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
314 preArr :: Bounds -> Forest Vertex -> Table Int
315 preArr bnds = tabulate bnds . preorderF
319 ------------------------------------------------------------
320 -- Algorithm 2: topological sorting
321 ------------------------------------------------------------
324 --postorder :: Tree a -> [a]
325 postorder (Node a ts) = postorderF ts ++ [a]
327 postorderF :: Forest a -> [a]
328 postorderF ts = concat (map postorder ts)
330 postOrd :: Graph -> [Vertex]
331 postOrd = postorderF . dff
333 topSort :: Graph -> [Vertex]
334 topSort = reverse . postOrd
338 ------------------------------------------------------------
339 -- Algorithm 3: connected components
340 ------------------------------------------------------------
343 components :: Graph -> Forest Vertex
344 components = dff . undirected
346 undirected :: Graph -> Graph
347 undirected g = buildG (bounds g) (edges g ++ reverseE g)
351 -- Algorithm 4: strongly connected components
354 scc :: Graph -> Forest Vertex
355 scc g = dfs g (reverse (postOrd (transposeG g)))
359 ------------------------------------------------------------
360 -- Algorithm 5: Classifying edges
361 ------------------------------------------------------------
364 back :: Graph -> Table Int -> Graph
365 back g post = mapT select g
366 where select v ws = [ w | w <- ws, post!v < post!w ]
368 cross :: Graph -> Table Int -> Table Int -> Graph
369 cross g pre post = mapT select g
370 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
372 forward :: Graph -> Graph -> Table Int -> Graph
373 forward g tree pre = mapT select g
374 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
378 ------------------------------------------------------------
379 -- Algorithm 6: Finding reachable vertices
380 ------------------------------------------------------------
383 reachable :: Graph -> Vertex -> [Vertex]
384 reachable g v = preorderF (dfs g [v])
386 path :: Graph -> Vertex -> Vertex -> Bool
387 path g v w = w `elem` (reachable g v)
391 ------------------------------------------------------------
392 -- Algorithm 7: Biconnected components
393 ------------------------------------------------------------
396 bcc :: Graph -> Forest [Vertex]
397 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
399 dnum = preArr (bounds g) forest
401 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
402 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
403 where us = map (do_label g dnum) ts
404 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
405 ++ [lu | Node (u,du,lu) xs <- us])
407 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
408 bicomps (Node (v,dv,lv) ts)
409 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
411 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
412 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
413 where collected = map collect ts
414 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
415 cs = concat [ if lw<dv then us else [Node (v:ws) us]
416 | (lw, Node ws us) <- collected ]