forked from adamwalker/syntcomp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolver.hs
312 lines (271 loc) · 10.4 KB
/
Solver.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
{-# LANGUAGE OverloadedStrings, RecordWildCards, DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
import Control.Applicative
import qualified Data.Text.IO as T
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Control.Monad.ST.Strict
import Control.Monad
import Data.List
import Data.Tuple.All
import Data.Bits
import Control.Monad.ST.Unsafe
import System.Directory
import System.IO
import System.CPUTime
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import qualified Data.Traversable as T
import Control.Monad.Trans.Either
import Control.Monad.Trans
import Options.Applicative as O
import Safe
import Data.Attoparsec.Text as P
import qualified Cudd.Imperative as Cudd
import Cudd.Imperative (STDdManager, DDNode)
import Cudd.Reorder
--Parsing
data Header = Header {
m :: Int,
i :: Int,
l :: Int,
o :: Int,
a :: Int
} deriving (Show)
data InputType = Cont | UCont deriving (Show)
data SymbolType = Is InputType | Ls | Os deriving (Show)
data Symbol = Symbol {
typ :: SymbolType,
idx :: Int,
str :: String
} deriving (Show)
data AAG = AAG {
header :: Header,
inputs :: [Int],
latches :: [(Int, Int)],
outputs :: [Int],
andGates :: [(Int, Int, Int)],
symbols :: [Symbol]
} deriving (Show)
ws = skipSpace
eol = endOfLine
header' = Header <$ string "aag"
<* ws
<*> decimal
<* ws
<*> decimal
<* ws
<*> decimal
<* ws
<*> decimal
<* ws
<*> decimal
<* eol
input = decimal <* eol
latch = (,) <$> decimal <* ws <*> decimal <* eol
output = decimal <* eol
andGate = (,,) <$> decimal <* ws <*> decimal <* ws <*> decimal <* eol
symbol = iSymbol <|> lSymbol <|> oSymbol
where
iSymbol = constructISymbol <$ char 'i' <*> decimal <* ws <*> isCont <*> manyTill anyChar endOfLine
where
isCont = P.option UCont (Cont <$ string "controllable")
constructISymbol idx cont name = Symbol (Is cont) idx name
lSymbol = Symbol <$> (Ls <$ char 'l') <*> decimal <* ws <*> manyTill anyChar endOfLine
oSymbol = Symbol <$> (Os <$ char 'o') <*> decimal <* ws <*> manyTill anyChar endOfLine
aag = do
header@Header{..} <- header'
inputs <- replicateM i input
latches <- replicateM l latch
outputs <- replicateM o output
andGates <- replicateM a andGate
symbols <- many symbol
return $ AAG {..}
--BDD operations
data Ops s a = Ops {
bAnd :: a -> a -> ST s a,
bOr :: a -> a -> ST s a,
lEq :: a -> a -> ST s Bool,
neg :: a -> a,
vectorCompose :: a -> [a] -> ST s a,
newVar :: ST s a,
computeCube :: [a] -> ST s a,
computeCube2 :: [a] -> [Bool] -> ST s a,
getSize :: ST s Int,
ithVar :: Int -> ST s a,
bforall :: a -> a -> ST s a,
bexists :: a -> a -> ST s a,
deref :: a -> ST s (),
ref :: a -> ST s (),
btrue :: a,
bfalse :: a,
andAbstract :: a -> a -> a -> ST s a
}
constructOps :: STDdManager s u -> Ops s (DDNode s u)
constructOps m = Ops {..}
where
bAnd = Cudd.band m
bOr = Cudd.bor m
lEq = Cudd.leq m
neg = Cudd.bnot
vectorCompose = Cudd.vectorCompose m
newVar = Cudd.newVar m
computeCube = Cudd.nodesToCube m
computeCube2 = Cudd.computeCube m
getSize = Cudd.readSize m
ithVar = Cudd.ithVar m
bforall = flip $ Cudd.bforall m
bexists = flip $ Cudd.bexists m
deref = Cudd.deref m
ref = Cudd.ref
btrue = Cudd.bone m
bfalse = Cudd.bzero m
andAbstract c x y = Cudd.andAbstract m x y c
bddSynopsis :: (Show a, Eq a) => Ops s a -> a -> ST s ()
bddSynopsis Ops{..} x
| x == btrue = unsafeIOToST $ putStrLn "True"
| x == bfalse = unsafeIOToST $ putStrLn "False"
| otherwise = unsafeIOToST $ print x
--Compiling the AIG
makeAndMap :: [(Int, Int, Int)] -> Map Int (Int, Int)
makeAndMap = Map.fromList . map func
where func (out, x, y) = (out, (x, y))
doAndGates :: Ops s a -> Map Int (Int, Int) -> Map Int a -> Int -> ST s (Map Int a, a)
doAndGates ops@Ops{..} andGateInputs accum andGate =
case Map.lookup andGate accum of
Just x -> return (accum, x)
Nothing -> do
let varIdx = clearBit andGate 0
(x, y) = fromJustNote "doAndGates" $ Map.lookup varIdx andGateInputs
(accum', x) <- doAndGates ops andGateInputs accum x
(accum'', y) <- doAndGates ops andGateInputs accum' y
res <- bAnd x y
let finalMap = Map.insert varIdx res (Map.insert (varIdx + 1) (neg res) accum'')
return (finalMap, fromJustNote "doAndGates2" $ Map.lookup andGate finalMap)
mapAccumLM :: Monad m => (acc -> x -> m (acc, y)) -> acc -> [x] -> m (acc, [y])
mapAccumLM _ s [] = return (s, [])
mapAccumLM f s (x:xs) = do
(s1, x') <- f s x
(s2, xs') <- mapAccumLM f s1 xs
return (s2, x' : xs')
--Synthesis
data SynthState a = SynthState {
cInputCube :: a,
uInputCube :: a,
safeRegion :: a,
trel :: [a],
initState :: a
} deriving (Functor, Foldable, Traversable)
substitutionArray :: Ops s a -> Map Int Int -> Map Int a -> ST s [a]
substitutionArray Ops{..} latches andGates = do
sz <- getSize
--unsafeIOToST $ print sz
mapM func [0..(sz-1)]
where
func idx = case Map.lookup (idx * 2 + 2) latches of
Nothing -> ithVar idx
Just input -> return $ fromJustNote ("substitutionArray: " ++ show input) $ Map.lookup input andGates
compile :: Ops s a -> [Int] -> [Int] -> [(Int, Int)] -> [(Int, Int, Int)] -> Int -> ST s (SynthState a)
compile ops@Ops{..} controllableInputs uncontrollableInputs latches ands safeIndex = do
let andGates = map sel1 ands
andMap = makeAndMap ands
--create an entry for each controllable input
cInputVars <- sequence $ replicate (length controllableInputs) newVar
cInputCube <- computeCube cInputVars
--create an entry for each uncontrollable input
uInputVars <- sequence $ replicate (length uncontrollableInputs) newVar
uInputCube <- computeCube uInputVars
--create an entry for each latch
latchVars <- sequence $ replicate (length latches) newVar
ref btrue
ref bfalse
--create the symbol table
let func idx var = [(idx, var), (idx + 1, neg var)]
tf = Map.fromList $ [(0, bfalse), (1, btrue)]
mpCI = Map.fromList $ concat $ zipWith func controllableInputs cInputVars
mpUI = Map.fromList $ concat $ zipWith func uncontrollableInputs uInputVars
mpL = Map.fromList $ concat $ zipWith func (map fst latches) latchVars
im = Map.unions [tf, mpCI, mpUI, mpL]
--compile the and gates
stab <- fmap fst $ mapAccumLM (doAndGates ops andMap) im andGates
--get the safety condition
let sr = fromJustNote "compile" $ Map.lookup safeIndex stab
--construct the initial state
initState <- computeCube2 latchVars (replicate (length latchVars) False)
--construct the transition relation
let latchMap = Map.fromList latches
trel <- substitutionArray ops latchMap stab
mapM ref trel
ref sr
let func k v = when (even k) (deref v)
Map.traverseWithKey func stab
return $ SynthState cInputCube uInputCube (neg sr) trel initState
safeCpre :: (Show a, Eq a) => Bool -> Ops s a -> SynthState a -> a -> ST s a
safeCpre quiet ops@Ops{..} SynthState{..} s = do
when (not quiet) $ unsafeIOToST $ print "*"
scu' <- vectorCompose s trel
scu <- andAbstract cInputCube safeRegion scu'
deref scu'
s <- bforall uInputCube scu
deref scu
return s
fixedPoint :: Eq a => Ops s a -> a -> a -> (a -> ST s a) -> ST s Bool
fixedPoint ops@Ops{..} init start func = do
res <- func start
deref start
win <- init `lEq` res
case win of
False -> deref res >> return False
True ->
case (res == start) of
True -> deref res >> return True
False -> fixedPoint ops init res func
solveSafety :: (Eq a, Show a) => Bool -> Ops s a -> SynthState a -> a -> a -> ST s Bool
solveSafety quiet ops@Ops{..} ss init safeRegion = do
ref btrue
fixedPoint ops init btrue $ safeCpre quiet ops ss
setupManager :: Options -> STDdManager s u -> ST s ()
setupManager Options{..} m = void $ do
unless noReord $ cuddAutodynEnable m CuddReorderGroupSift
unless quiet $ void $ do
regStdPreReordHook m
regStdPostReordHook m
cuddEnableReorderingReporting m
categorizeInputs :: [Symbol] -> [Int] -> ([Int], [Int])
categorizeInputs symbols inputs = (cont, inputs \\ cont)
where
cont = map (inputs !!) theSet
theSet = map idx $ filter (isControllable . typ) symbols
isControllable (Is Cont) = True
isControllable _ = False
doIt :: Options -> IO (Either String Bool)
doIt o@Options{..} = runEitherT $ do
contents <- lift $ T.readFile filename
aag@AAG{..} <- hoistEither $ parseOnly aag contents
lift $ do
let (cInputs, uInputs) = categorizeInputs symbols inputs
stToIO $ Cudd.withManagerDefaults $ \m -> do
setupManager o m
let ops = constructOps m
ss@SynthState{..} <- compile ops cInputs uInputs latches andGates (head outputs)
res <- solveSafety quiet ops ss initState safeRegion
T.mapM (deref ops) ss
Cudd.quit m
return res
run :: Options -> IO ()
run g = do
res <- doIt g
case res of
Left err -> putStrLn $ "Error: " ++ err
Right True -> putStrLn "REALIZABLE"
Right False -> putStrLn "UNREALIZABLE"
data Options = Options {
quiet :: Bool,
noReord :: Bool,
filename :: String
}
main = execParser opts >>= run
where
opts = info (helper <*> parser) (fullDesc <> progDesc "Solve the game specified in INPUT" <> O.header "Simple BDD solver")
parser = Options <$> flag False True (long "quiet" <> short 'q' <> help "Be quiet")
<*> flag False True (long "noreord" <> short 'n' <> help "Disable reordering")
<*> argument O.str (metavar "INPUT")