4 -- At present the only one with a "nice" external interface
5 stronglyConnComp, stronglyConnCompR, SCC(..), flattenSCC, flattenSCCs,
8 graphFromEdges, graphFromEdges',
9 buildG, transposeG, reverseE, outdegree, indegree,
24 # include "HsVersions.h"
26 ------------------------------------------------------------------------------
27 -- A version of the graph algorithms described in:
29 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
30 -- by David King and John Launchbury
32 -- Also included is some additional code for printing tree structures ...
33 ------------------------------------------------------------------------------
36 import Util ( sortLe )
47 #if __GLASGOW_HASKELL__ >= 504
48 import Data.Array.ST hiding ( indices, bounds )
55 %************************************************************************
59 %************************************************************************
62 data SCC vertex = AcyclicSCC vertex
65 flattenSCCs :: [SCC a] -> [a]
66 flattenSCCs = concatMap flattenSCC
68 flattenSCC (AcyclicSCC v) = [v]
69 flattenSCC (CyclicSCC vs) = vs
71 instance Outputable a => Outputable (SCC a) where
72 ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
73 ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
79 => [(node, key, [key])] -- The graph; its ok for the
80 -- out-list to contain keys which arent
81 -- a vertex key, they are ignored
82 -> [SCC node] -- Returned in topologically sorted order
83 -- Later components depend on earlier ones, but not vice versa
85 stronglyConnComp edges
86 = map get_node (stronglyConnCompR edges)
88 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
89 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
91 -- The "R" interface is used when you expect to apply SCC to
92 -- the (some of) the result of SCC, so you dont want to lose the dependency info
95 => [(node, key, [key])] -- The graph; its ok for the
96 -- out-list to contain keys which arent
97 -- a vertex key, they are ignored
98 -> [SCC (node, key, [key])] -- Topologically sorted
100 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
101 stronglyConnCompR edges
104 (graph, vertex_fn) = _scc_ "graphFromEdges" graphFromEdges edges
105 forest = _scc_ "Digraph.scc" scc graph
106 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
107 | otherwise = AcyclicSCC (vertex_fn v)
108 decode other = CyclicSCC (dec other [])
110 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
111 mentions_itself v = v `elem` (graph ! v)
114 %************************************************************************
118 %************************************************************************
123 type Table a = Array Vertex a
124 type Graph = Table [Vertex]
125 type Bounds = (Vertex, Vertex)
126 type Edge = (Vertex, Vertex)
130 vertices :: Graph -> [Vertex]
133 edges :: Graph -> [Edge]
134 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
136 mapT :: (Vertex -> a -> b) -> Table a -> Table b
137 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
139 buildG :: Bounds -> [Edge] -> Graph
140 buildG bounds edges = accumArray (flip (:)) [] bounds edges
142 transposeG :: Graph -> Graph
143 transposeG g = buildG (bounds g) (reverseE g)
145 reverseE :: Graph -> [Edge]
146 reverseE g = [ (w, v) | (v, w) <- edges g ]
148 outdegree :: Graph -> Table Int
149 outdegree = mapT numEdges
150 where numEdges v ws = length ws
152 indegree :: Graph -> Table Int
153 indegree = outdegree . transposeG
160 => [(node, key, [key])]
161 -> (Graph, Vertex -> (node, key, [key]))
162 graphFromEdges edges =
163 case graphFromEdges' edges of (graph, vertex_fn, _) -> (graph, vertex_fn)
167 => [(node, key, [key])]
168 -> (Graph, Vertex -> (node, key, [key]), key -> Maybe Vertex)
169 graphFromEdges' edges
170 = (graph, \v -> vertex_map ! v, key_vertex)
172 max_v = length edges - 1
173 bounds = (0,max_v) :: (Vertex, Vertex)
175 (_,k1,_) `le` (_,k2,_) = case k1 `compare` k2 of { GT -> False; other -> True }
178 edges1 = zipWith (,) [0..] sorted_edges
180 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
181 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
182 vertex_map = array bounds edges1
185 -- key_vertex :: key -> Maybe Vertex
186 -- returns Nothing for non-interesting vertices
187 key_vertex k = find 0 max_v
191 find a b = case compare k (key_map ! mid) of
196 mid = (a + b) `div` 2
199 %************************************************************************
203 %************************************************************************
206 data Tree a = Node a (Forest a)
207 type Forest a = [Tree a]
209 mapTree :: (a -> b) -> (Tree a -> Tree b)
210 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
214 instance Show a => Show (Tree a) where
215 showsPrec p t s = showTree t ++ s
217 showTree :: Show a => Tree a -> String
218 showTree = drawTree . mapTree show
220 showForest :: Show a => Forest a -> String
221 showForest = unlines . map showTree
223 drawTree :: Tree String -> String
224 drawTree = unlines . draw
226 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
227 where this = s1 ++ x ++ " "
229 space n = replicate n ' '
232 stLoop [t] = grp s2 " " (draw t)
233 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
235 rsLoop [t] = grp s5 " " (draw t)
236 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
238 grp fst rst = zipWith (++) (fst:repeat rst)
240 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
244 %************************************************************************
246 %* Depth first search
248 %************************************************************************
251 #if __GLASGOW_HASKELL__ >= 504
252 newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)
253 newSTArray = newArray
255 readSTArray :: Ix i => STArray s i e -> i -> ST s e
256 readSTArray = readArray
258 writeSTArray :: Ix i => STArray s i e -> i -> e -> ST s ()
259 writeSTArray = writeArray
262 type Set s = STArray s Vertex Bool
264 mkEmpty :: Bounds -> ST s (Set s)
265 mkEmpty bnds = newSTArray bnds False
267 contains :: Set s -> Vertex -> ST s Bool
268 contains m v = readSTArray m v
270 include :: Set s -> Vertex -> ST s ()
271 include m v = writeSTArray m v True
275 dff :: Graph -> Forest Vertex
276 dff g = dfs g (vertices g)
278 dfs :: Graph -> [Vertex] -> Forest Vertex
279 dfs g vs = prune (bounds g) (map (generate g) vs)
281 generate :: Graph -> Vertex -> Tree Vertex
282 generate g v = Node v (map (generate g) (g!v))
284 prune :: Bounds -> Forest Vertex -> Forest Vertex
285 prune bnds ts = runST (mkEmpty bnds >>= \m ->
288 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
289 chop m [] = return []
290 chop m (Node v ts : us)
291 = contains m v >>= \visited ->
295 include m v >>= \_ ->
298 return (Node v as : bs)
302 %************************************************************************
306 %************************************************************************
308 ------------------------------------------------------------
309 -- Algorithm 1: depth first search numbering
310 ------------------------------------------------------------
313 --preorder :: Tree a -> [a]
314 preorder (Node a ts) = a : preorderF ts
316 preorderF :: Forest a -> [a]
317 preorderF ts = concat (map preorder ts)
319 tabulate :: Bounds -> [Vertex] -> Table Int
320 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
322 preArr :: Bounds -> Forest Vertex -> Table Int
323 preArr bnds = tabulate bnds . preorderF
327 ------------------------------------------------------------
328 -- Algorithm 2: topological sorting
329 ------------------------------------------------------------
332 --postorder :: Tree a -> [a]
333 postorder (Node a ts) = postorderF ts ++ [a]
335 postorderF :: Forest a -> [a]
336 postorderF ts = concat (map postorder ts)
338 postOrd :: Graph -> [Vertex]
339 postOrd = postorderF . dff
341 topSort :: Graph -> [Vertex]
342 topSort = reverse . postOrd
346 ------------------------------------------------------------
347 -- Algorithm 3: connected components
348 ------------------------------------------------------------
351 components :: Graph -> Forest Vertex
352 components = dff . undirected
354 undirected :: Graph -> Graph
355 undirected g = buildG (bounds g) (edges g ++ reverseE g)
359 -- Algorithm 4: strongly connected components
362 scc :: Graph -> Forest Vertex
363 scc g = dfs g (reverse (postOrd (transposeG g)))
367 ------------------------------------------------------------
368 -- Algorithm 5: Classifying edges
369 ------------------------------------------------------------
372 back :: Graph -> Table Int -> Graph
373 back g post = mapT select g
374 where select v ws = [ w | w <- ws, post!v < post!w ]
376 cross :: Graph -> Table Int -> Table Int -> Graph
377 cross g pre post = mapT select g
378 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
380 forward :: Graph -> Graph -> Table Int -> Graph
381 forward g tree pre = mapT select g
382 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
386 ------------------------------------------------------------
387 -- Algorithm 6: Finding reachable vertices
388 ------------------------------------------------------------
391 reachable :: Graph -> Vertex -> [Vertex]
392 reachable g v = preorderF (dfs g [v])
394 path :: Graph -> Vertex -> Vertex -> Bool
395 path g v w = w `elem` (reachable g v)
399 ------------------------------------------------------------
400 -- Algorithm 7: Biconnected components
401 ------------------------------------------------------------
404 bcc :: Graph -> Forest [Vertex]
405 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
407 dnum = preArr (bounds g) forest
409 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
410 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
411 where us = map (do_label g dnum) ts
412 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
413 ++ [lu | Node (u,du,lu) xs <- us])
415 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
416 bicomps (Node (v,dv,lv) ts)
417 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
419 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
420 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
421 where collected = map collect ts
422 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
423 cs = concat [ if lw<dv then us else [Node (v:ws) us]
424 | (lw, Node ws us) <- collected ]