Last active
March 19, 2016 02:46
-
-
Save emmanueldenloye/26832a8b8b39b6e88658 to your computer and use it in GitHub Desktop.
(Using FGL) Determine the shortestPath matrix if and only if the graph is fully connected.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Monad.ST | |
import Data.Graph.Inductive | |
import qualified Data.Graph.Inductive.PatriciaTree as GP | |
import Data.Maybe | |
import Data.STRef | |
import Numeric.LinearAlgebra | |
import Numeric.LinearAlgebra.Devel | |
-- The result is wrapped in a Maybe just in case, the graph is not fully connected. | |
-- There is a function to test for connectivity in FGL, but in my use case, | |
-- I am usually not dealing with graphs that aren't. I still wrap the result | |
-- just to be safe. | |
shortestPathMatrix :: GP.Gr () Double -> Maybe (Matrix Double) | |
shortestPathMatrix gr = | |
if (count * 2) == numNodes * (numNodes - 1) | |
then Just result | |
else Nothing | |
where numNodes = noNodes gr | |
(count,result) = | |
runST $ | |
do m <- newMatrix 0 numNodes numNodes | |
numWrites <- newSTRef (0 :: Int) | |
mapM_ (innerLoop m numWrites) | |
[0 .. numNodes - 1] | |
mat <- unsafeFreezeMatrix m | |
totalnumWrites <- readSTRef numWrites | |
return (totalnumWrites,mat) | |
where innerLoop m' ref n = mapM_ writeMatrix' tree | |
where writeMatrix' (n'',d) = | |
do unsafeWriteMatrix m' n n'' d | |
unsafeWriteMatrix m' n'' n d | |
modifySTRef' ref (+ 1) | |
tree = | |
filter ((< n) . fst) . | |
mapMaybe (listToMaybe . unLPath) $ | |
spTree n gr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment