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,
28 # include "HsVersions.h"
30 ------------------------------------------------------------------------------
31 -- A version of the graph algorithms described in:
33 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
34 -- by David King and John Launchbury
36 -- Also included is some additional code for printing tree structures ...
37 ------------------------------------------------------------------------------
40 import Util ( sortLe )
44 import Control.Monad.ST
51 #if __GLASGOW_HASKELL__ > 604
54 import Data.Array.ST hiding ( indices, bounds )
59 %************************************************************************
63 %************************************************************************
66 data SCC vertex = AcyclicSCC vertex
69 flattenSCCs :: [SCC a] -> [a]
70 flattenSCCs = concatMap flattenSCC
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)))
83 => [(node, key, [key])] -- The graph; its ok for the
84 -- out-list to contain keys which arent
85 -- a vertex key, they are ignored
86 -> [SCC node] -- Returned in topologically sorted order
87 -- Later components depend on earlier ones, but not vice versa
89 stronglyConnComp edges
90 = map get_node (stronglyConnCompR edges)
92 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
93 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
95 -- The "R" interface is used when you expect to apply SCC to
96 -- the (some of) the result of SCC, so you dont want to lose the dependency info
99 => [(node, key, [key])] -- The graph; its ok for the
100 -- out-list to contain keys which arent
101 -- a vertex key, they are ignored
102 -> [SCC (node, key, [key])] -- Topologically sorted
104 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
105 stronglyConnCompR edges
108 (graph, vertex_fn) = _scc_ "graphFromEdges" graphFromEdges edges
109 forest = _scc_ "Digraph.scc" scc graph
110 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
111 | otherwise = AcyclicSCC (vertex_fn v)
112 decode other = CyclicSCC (dec other [])
114 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
115 mentions_itself v = v `elem` (graph ! v)
118 %************************************************************************
122 %************************************************************************
127 type Table a = Array Vertex a
128 type Graph = Table [Vertex]
129 type Bounds = (Vertex, Vertex)
130 type Edge = (Vertex, Vertex)
134 vertices :: Graph -> [Vertex]
137 edges :: Graph -> [Edge]
138 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
140 mapT :: (Vertex -> a -> b) -> Table a -> Table b
141 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
143 buildG :: Bounds -> [Edge] -> Graph
144 buildG bounds edges = accumArray (flip (:)) [] bounds edges
146 transposeG :: Graph -> Graph
147 transposeG g = buildG (bounds g) (reverseE g)
149 reverseE :: Graph -> [Edge]
150 reverseE g = [ (w, v) | (v, w) <- edges g ]
152 outdegree :: Graph -> Table Int
153 outdegree = mapT numEdges
154 where numEdges v ws = length ws
156 indegree :: Graph -> Table Int
157 indegree = outdegree . transposeG
164 => [(node, key, [key])]
165 -> (Graph, Vertex -> (node, key, [key]))
166 graphFromEdges edges =
167 case graphFromEdges' edges of (graph, vertex_fn, _) -> (graph, vertex_fn)
171 => [(node, key, [key])]
172 -> (Graph, Vertex -> (node, key, [key]), key -> Maybe Vertex)
173 graphFromEdges' edges
174 = (graph, \v -> vertex_map ! v, key_vertex)
176 max_v = length edges - 1
177 bounds = (0,max_v) :: (Vertex, Vertex)
179 (_,k1,_) `le` (_,k2,_) = case k1 `compare` k2 of { GT -> False; other -> True }
182 edges1 = zipWith (,) [0..] sorted_edges
184 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
185 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
186 vertex_map = array bounds edges1
189 -- key_vertex :: key -> Maybe Vertex
190 -- returns Nothing for non-interesting vertices
191 key_vertex k = find 0 max_v
195 find a b = case compare k (key_map ! mid) of
200 mid = (a + b) `div` 2
203 %************************************************************************
207 %************************************************************************
210 data Tree a = Node a (Forest a)
211 type Forest a = [Tree a]
213 mapTree :: (a -> b) -> (Tree a -> Tree b)
214 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
218 instance Show a => Show (Tree a) where
219 showsPrec p t s = showTree t ++ s
221 showTree :: Show a => Tree a -> String
222 showTree = drawTree . mapTree show
224 showForest :: Show a => Forest a -> String
225 showForest = unlines . map showTree
227 drawTree :: Tree String -> String
228 drawTree = unlines . draw
230 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
231 where this = s1 ++ x ++ " "
233 space n = replicate n ' '
236 stLoop [t] = grp s2 " " (draw t)
237 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
239 rsLoop [t] = grp s5 " " (draw t)
240 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
242 grp fst rst = zipWith (++) (fst:repeat rst)
244 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
248 %************************************************************************
250 %* Depth first search
252 %************************************************************************
255 type Set s = STArray s Vertex Bool
257 mkEmpty :: Bounds -> ST s (Set s)
258 mkEmpty bnds = newArray bnds False
260 contains :: Set s -> Vertex -> ST s Bool
261 contains m v = readArray m v
263 include :: Set s -> Vertex -> ST s ()
264 include m v = writeArray m v True
268 dff :: Graph -> Forest Vertex
269 dff g = dfs g (vertices g)
271 dfs :: Graph -> [Vertex] -> Forest Vertex
272 dfs g vs = prune (bounds g) (map (generate g) vs)
274 generate :: Graph -> Vertex -> Tree Vertex
275 generate g v = Node v (map (generate g) (g!v))
277 prune :: Bounds -> Forest Vertex -> Forest Vertex
278 prune bnds ts = runST (mkEmpty bnds >>= \m ->
281 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
282 chop m [] = return []
283 chop m (Node v ts : us)
284 = contains m v >>= \visited ->
288 include m v >>= \_ ->
291 return (Node v as : bs)
295 %************************************************************************
299 %************************************************************************
301 ------------------------------------------------------------
302 -- Algorithm 1: depth first search numbering
303 ------------------------------------------------------------
306 --preorder :: Tree a -> [a]
307 preorder (Node a ts) = a : preorderF ts
309 preorderF :: Forest a -> [a]
310 preorderF ts = concat (map preorder ts)
312 tabulate :: Bounds -> [Vertex] -> Table Int
313 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
315 preArr :: Bounds -> Forest Vertex -> Table Int
316 preArr bnds = tabulate bnds . preorderF
320 ------------------------------------------------------------
321 -- Algorithm 2: topological sorting
322 ------------------------------------------------------------
325 --postorder :: Tree a -> [a]
326 postorder (Node a ts) = postorderF ts ++ [a]
328 postorderF :: Forest a -> [a]
329 postorderF ts = concat (map postorder ts)
331 postOrd :: Graph -> [Vertex]
332 postOrd = postorderF . dff
334 topSort :: Graph -> [Vertex]
335 topSort = reverse . postOrd
339 ------------------------------------------------------------
340 -- Algorithm 3: connected components
341 ------------------------------------------------------------
344 components :: Graph -> Forest Vertex
345 components = dff . undirected
347 undirected :: Graph -> Graph
348 undirected g = buildG (bounds g) (edges g ++ reverseE g)
352 -- Algorithm 4: strongly connected components
355 scc :: Graph -> Forest Vertex
356 scc g = dfs g (reverse (postOrd (transposeG g)))
360 ------------------------------------------------------------
361 -- Algorithm 5: Classifying edges
362 ------------------------------------------------------------
365 back :: Graph -> Table Int -> Graph
366 back g post = mapT select g
367 where select v ws = [ w | w <- ws, post!v < post!w ]
369 cross :: Graph -> Table Int -> Table Int -> Graph
370 cross g pre post = mapT select g
371 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
373 forward :: Graph -> Graph -> Table Int -> Graph
374 forward g tree pre = mapT select g
375 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
379 ------------------------------------------------------------
380 -- Algorithm 6: Finding reachable vertices
381 ------------------------------------------------------------
384 reachable :: Graph -> Vertex -> [Vertex]
385 reachable g v = preorderF (dfs g [v])
387 path :: Graph -> Vertex -> Vertex -> Bool
388 path g v w = w `elem` (reachable g v)
392 ------------------------------------------------------------
393 -- Algorithm 7: Biconnected components
394 ------------------------------------------------------------
397 bcc :: Graph -> Forest [Vertex]
398 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
400 dnum = preArr (bounds g) forest
402 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
403 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
404 where us = map (do_label g dnum) ts
405 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
406 ++ [lu | Node (u,du,lu) xs <- us])
408 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
409 bicomps (Node (v,dv,lv) ts)
410 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
412 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
413 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
414 where collected = map collect ts
415 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
416 cs = concat [ if lw<dv then us else [Node (v:ws) us]
417 | (lw, Node ws us) <- collected ]