From 4b6d1dbe4d79641d93676a311baa849b659cd12f Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Mon, 5 Nov 2018 22:04:48 +0000 Subject: Generate random undirected graph --- src/Main.hs | 49 ++++++++++++++++++++----------------------------- 1 file changed, 20 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/src/Main.hs b/src/Main.hs index c52ad16..6aff865 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -6,42 +6,33 @@ import Data.GraphViz import Data.Graph.Inductive.Example (clr479, dag4) import Data.Graph.Inductive.Graph import Data.Graph.Inductive.PatriciaTree +import Data.GraphViz.Attributes.Complete +import Data.Text.Lazy +import Data.GraphViz.Commands +import Data.Graph.Generators.Random.WattsStrogatz +import System.Random.MWC +import Data.Graph.Generators.FGL +import Data.Graph.Generators type Input = Bool data Gate = Nand - deriving (Show) + | And + | Or + deriving (Show, Eq, Ord) -data Circuit a = In a - | Node Gate (Circuit a) (Circuit a) - deriving (Show) +instance Labellable Gate where + toLabelValue gate = StrLabel . pack $ show gate instance Arbitrary Gate where - arbitrary = return Nand + arbitrary = elements [Nand, And, Or] -instance (Arbitrary a) => Arbitrary (Circuit a) where - arbitrary = do - x <- arbitrary - frequency [(1, return (In x)), (1, arbNode)] - where - arbNode = Node <$> arbitrary <*> arbitrary <*> arbitrary +randomTree :: Gr Gate String +randomTree = mkGraph [(1, Nand), (2, Nand), (3, Or), (4, Nand), (5, Nand), (6, Nand), (7, Or)] [(3, 1, ""), (7, 1, ""), (5, 1, ""), (6, 2, ""), (7, 2, ""), (5, 2, ""), (1, 4, ""), (2, 4, ""), (3, 4, ""), (6, 4, "")] -eval :: (Bits a) => Circuit a -> a -eval (In val) = val -eval (Node Nand c1 c2) = complement $ eval c1 .&. eval c2 - -visualize :: (Show a) => Circuit a -> Gr String String -visualize circ = - graph Nothing 0 (empty :: Gr String String) circ - where - graph parent nl graph circ = - let newNode str graph = (head $ newNodes 1 graph, str) in - case (parent, circ) of - (Nothing, (In val)) -> - insNode (newNode "IN" graph) graph - _ -> - graph - -main :: IO () +main :: IO FilePath --main = sample (arbitrary :: Gen (Circuit Input)) -main = preview $ visualize (In True) +main = do + gen <- withSystemRandom . asGenIO $ return + gr <- wattsStrogatzGraph gen 50 3 0.6 + runGraphviz (graphToDot nonClusteredParams (graphInfoToUGr gr)) Png "output.png" -- cgit