GraphSCC (empty) → 1.0
raw patch · 6 files changed
+320/−0 lines, 6 filesdep +arraydep +basedep +containerssetup-changed
Dependencies added: array, base, containers
Files
- Data/Graph/ArraySCC.hs +99/−0
- Data/Graph/MapSCC.hs +99/−0
- Data/Graph/SCC.hs +84/−0
- GraphSCC.cabal +28/−0
- LICENSE +7/−0
- Setup.hs +3/−0
+ Data/Graph/ArraySCC.hs view
@@ -0,0 +1,99 @@+-- | Implements Tarjan's algorithm for computing the strongly connected+-- components of a graph. For more details see:+-- <http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm>+{-# LANGUAGE Rank2Types #-}+module Data.Graph.ArraySCC(scc) where++import Data.Graph(Graph,Vertex)+import Data.Array.ST+import Data.Array as A+import Control.Monad.ST+import Control.Monad(ap)++-- | Computes the strongly connected components (SCCs) of the graph in+-- O(#edges + #vertices) time. The resulting tuple contains:+-- * A (reversed) topologically sorted list of SCCs.+-- Each SCCs is assigned a unique identifier of type 'Int'.+-- * An O(1) mapping from vertices in the original graph to the identifier+-- of their SCC. This mapping will raise an "out of bounds"+-- exception if it is applied to integers that do not correspond to+-- vertices in the input graph.+--+-- This function assumes that the adjacency lists in the original graph+-- mention only nodes that are in the graph. Violating this assumption+-- will result in "out of bounds" array exception.+scc :: Graph -> ([(Int,[Vertex])], Vertex -> Int)+scc g = runST (+ do ixes <- newArray (bounds g) 0+ lows <- newArray (bounds g) 0+ s <- roots g ixes lows (S [] 1 [] 1) (indices g)+ sccm <- unsafeFreeze ixes+ return (sccs s, \i -> sccm ! i)+ )++type Func s a =+ Graph -- ^ The original graph+ -> STUArray s Vertex Int -- ^ Index in DFS traversal, or SCC for vertex.+ -- Legend for the index array:+ -- 0: Node not visited+ -- -ve: Node is on the stack with the given number+ -- +ve: Node belongs to the SCC with the given number+ -> STUArray s Vertex Int -- ^ Least reachable node+ -> S -- ^ State+ -> a++data S = S { stack :: ![Vertex] -- ^ Traversal stack+ , num :: !Int -- ^ Next node number+ , sccs :: ![(Int,[Vertex])] -- ^ Finished SCCs+ , next_scc :: !Int -- ^ Next SCC number+ }+++roots :: Func s ([Vertex] -> ST s S)+roots g ixes lows st (v:vs) =+ do i <- readArray ixes v+ if i == 0 then do s1 <- from_root g ixes lows st v+ roots g ixes lows s1 vs+ else roots g ixes lows st vs+roots _ _ _ s [] = return s+++from_root :: Func s (Vertex -> ST s S)+from_root g ixes lows s v =+ do let me = num s+ writeArray ixes v (negate me)+ writeArray lows v me+ newS <- check_adj g ixes lows+ s { stack = v : stack s, num = me + 1 } v (g ! v)++ x <- readArray lows v+ if x < me then return newS else+ case span (/= v) (stack newS) of+ (as,b:bs) ->+ do let this = b : as+ n = next_scc newS+ mapM_ (\i -> writeArray ixes i n) this+ return S { stack = bs+ , num = num newS+ , sccs = (n,this) : sccs newS+ , next_scc = n + 1+ }+ _ -> error ("bug in scc---vertex not on the stack: " ++ show v)++check_adj :: Func s (Vertex -> [Vertex] -> ST s S)+check_adj g ixes lows st v (v':vs) =+ do i <- readArray ixes v'+ case () of+ _ | i == 0 ->+ do newS <- from_root g ixes lows st v'+ new_low <- min `fmap` readArray lows v `ap` readArray lows v'+ writeArray lows v new_low+ check_adj g ixes lows newS v vs+ | i < 0 ->+ do j <- readArray lows v+ writeArray lows v (min j (negate i))+ check_adj g ixes lows st v vs+ | otherwise -> check_adj g ixes lows st v vs+check_adj _ _ _ st _ [] = return st++
+ Data/Graph/MapSCC.hs view
@@ -0,0 +1,99 @@+-- | Implements Tarjan's algorithm for computing the strongly connected+-- components of a graph. For more details see:+-- <http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm>.+--+-- This implementation uses 'IntMap' instead of mutable arrays in the algorithm.+-- The benefit is that the implementation conforms to the Haskell 98 standard,+-- however, the algorithm is a bit slower on large graphs.+module Data.Graph.MapSCC(scc) where++import Data.Graph(Graph,Vertex)+import qualified Data.IntMap as Map+import Data.Array+import Control.Monad(ap)+import Data.List(foldl')++-- | Computes the strongly connected components (SCCs) in the graph in O(???)+-- time. The resulting tuple contains:+-- * A (reversed) topologically sorted list of SCCs.+-- Each SCCs is assigned a unique identifier of type 'Int'.+-- * An O(log(V)) mapping from vertices in the original graph to+-- the identifier of their SCC. This mapping will raise an exception+-- if it is applied to integers that do not correspond to+-- vertices in the input graph.+--+-- This function assumes that the adjacency lists in the original graph+-- mention only nodes that are in the graph. Violating this assumption+-- will result in an exception.+scc :: Graph -> ([(Int,[Vertex])], Vertex -> Int)+scc g =+ let s = roots g (S Map.empty Map.empty [] 1 [] 1) (indices g)+ sccm = ixes s+ in (sccs s, \i -> Map.findWithDefault (err i) i sccm)+ where err i = error $ show i ++ " is not a vertex in the graph"+++data S = S { ixes :: !(Map.IntMap Int)+ -- ^ Index in DFS traversal, or SCC for vertex.+ -- Legend for the index array:+ -- -ve: Node is on the stack with the given number+ -- +ve: Node belongs to the SCC with the given number++ , lows :: !(Map.IntMap Int) -- ^ Least reachable node+ , stack :: ![Vertex] -- ^ Traversal stack+ , num :: !Int -- ^ Next node number+ , sccs :: ![(Int,[Vertex])] -- ^ Finished SCCs+ , next_scc :: !Int -- ^ Next SCC number+ }++roots :: Graph -> S -> [Vertex] -> S+roots g st (v:vs) =+ case Map.lookup v (ixes st) of+ Just {} -> roots g st vs+ Nothing -> roots g (from_root g st v) vs+roots _ s [] = s+++from_root :: Graph -> S -> Vertex -> S+from_root g s v =+ let me = num s+ newS = check_adj g+ s { ixes = Map.insert v (negate me) (ixes s)+ , lows = Map.insert v me (lows s)+ , stack = v : stack s, num = me + 1 } v (g ! v)+ in case Map.lookup v (lows newS) of+ Just x+ | x < me -> newS+ | otherwise ->+ case span (/= v) (stack newS) of+ (as,b:bs) ->+ let this = b : as+ n = next_scc newS+ ixes' = foldl' (\m i -> Map.insert i n m) (ixes newS) this+ in S { ixes = ixes'+ , lows = lows newS+ , stack = bs+ , num = num newS+ , sccs = (n,this) : sccs newS+ , next_scc = n + 1+ }+ _ -> error ("bug in scc---vertex not on the stack: " ++ show v)+ Nothing -> error ("bug in scc--vertex disappeared from lows: " ++ show v)++check_adj :: Graph -> S -> Vertex -> [Vertex] -> S+check_adj g st v (v':vs) =+ case Map.lookup v' (ixes st) of+ Nothing ->+ let newS = from_root g st v'+ Just new_low = min `fmap` Map.lookup v (lows newS)+ `ap` Map.lookup v' (lows newS)+ lows' = Map.insert v new_low (lows newS)+ in check_adj g newS { lows = lows' } v vs+ Just i+ | i < 0 -> let lows' = Map.adjust (min (negate i)) v (lows st)+ in check_adj g st { lows = lows' } v vs+ | otherwise -> check_adj g st v vs++check_adj _ st _ [] = st++
+ Data/Graph/SCC.hs view
@@ -0,0 +1,84 @@+{-# LANGUAGE CPP #-}+module Data.Graph.SCC+ ( scc+ , sccList+ , sccListR+ , sccGraph+ , stronglyConnComp+ , stronglyConnCompR+ ) where++#ifdef USE_MAPS+import Data.Graph.MapSCC+#else+import Data.Graph.ArraySCC+#endif+import Data.Graph(SCC(..),Graph,Vertex,graphFromEdges')++import Data.Array as A+import Data.List(nub)++-- | Compute the list of strongly connected components of a graph.+-- The components are topologically sorted:+-- if v1 in C1 points to v2 in C2, then C2 will come before C1 in the list.+sccList :: Graph -> [SCC Vertex]+sccList g = reverse $ map (to_scc g lkp) cs+ where (cs,lkp) = scc g++-- | Compute the list of strongly connected components of a graph.+-- Each component contains the adjecency information from the original graph.+-- The components are topologically sorted:+-- if v1 in C1 points to v2 in C2, then C2 will come before C1 in the list.+sccListR :: Graph -> [SCC (Vertex,[Vertex])]+sccListR g = reverse $ map cvt cs+ where (cs,lkp) = scc g+ cvt (n,[v]) = let adj = g ! v+ in if n `elem` map lkp adj+ then CyclicSCC [(v,adj)]+ else AcyclicSCC (v,adj)+ cvt (_,vs) = CyclicSCC [ (v, g ! v) | v <- vs ]++-- | Quotient a graph with the relation that relates vertices that+-- belong to the same SCC. The vertices in the new graph are the+-- SCCs of the old graph, and there is an edge between two components,+-- if there is an edge between any of their vertices.+-- The entries in the resulting list are in reversed-topologically sorted:+-- if v1 in C1 points to v2 in C2, then C1 will come before C2 in the list.+sccGraph :: Graph -> [(SCC Int, Int, [Int])]+sccGraph g = map to_node cs+ where (cs,lkp) = scc g+ to_node x@(n,this) = ( to_scc g lkp x+ , n+ , nub $ concatMap (map lkp . (g !)) this+ )+++stronglyConnComp :: Ord key => [(node, key, [key])] -> [SCC node]+stronglyConnComp es = reverse $ map cvt cs+ where (g,back) = graphFromEdges' es+ (cs,lkp) = scc g+ cvt (n,[v]) = let (node,_,_) = back v+ in if n `elem` map lkp (g ! v)+ then CyclicSCC [node]+ else AcyclicSCC node+ cvt (_,vs) = CyclicSCC [ node | (node,_,_) <- map back vs ]+++stronglyConnCompR :: Ord key => [(node, key, [key])] -> [SCC (node, key, [key])]+stronglyConnCompR es = reverse $ map cvt cs+ where (g,back) = graphFromEdges' es+ (cs,lkp) = scc g+ cvt (n,[v]) = if n `elem` map lkp (g ! v)+ then CyclicSCC [back v]+ else AcyclicSCC (back v)+ cvt (_,vs) = CyclicSCC (map back vs)++++--------------------------------------------------------------------------------+to_scc :: Graph -> (Vertex -> Int) -> (Int,[Vertex]) -> SCC Vertex+to_scc g lkp (n,[v]) = if n `elem` map lkp (g ! v) then CyclicSCC [v]+ else AcyclicSCC v+to_scc _ _ (_,vs) = CyclicSCC vs++
+ GraphSCC.cabal view
@@ -0,0 +1,28 @@+Name: GraphSCC+Version: 1.0+License: BSD3+License-file: LICENSE+Author: Iavor S. Diatchki+Maintainer: diatchki@galois.com+Category: Algorithms+Synopsis: Tarjan's algorithm for computing the strongly connected components of a graph.+Description: Tarjan's algorithm for computing the strongly connected components of a graph.+Build-type: Simple+Cabal-Version: >= 1.2++flag use-maps+ default: False+ description: Use IntMap instead of mutable arrays.++library+ Build-Depends: base, array, containers+ Exposed-modules: Data.Graph.SCC+ Extensions: CPP+ GHC-options: -O2 -Wall+ if flag(use-maps)+ Other-modules: Data.Graph.MapSCC+ cpp-options: -DUSE_MAPS+ else+ Extensions: Rank2Types+ Other-modules: Data.Graph.ArraySCC+
+ LICENSE view
@@ -0,0 +1,7 @@+Copyright (c) 2008 Iavor S. Diatchki++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ Setup.hs view
@@ -0,0 +1,3 @@+import Distribution.Simple++main = defaultMain