-- Companion checks for "Reducing P vs NP to Seven Statements" (Qais Alassa). -- Pure Haskell 2010 (base only). Build and run: ghc -O2 verify.hs && ./verify module Main (main) where import Control.Applicative ((<|>)) import Control.Monad (ap, replicateM, unless) import Data.Bits (bit, setBit, shiftL, shiftR, testBit, xor, (.&.), (.|.)) import Data.List (minimumBy, nub, tails) import Data.Maybe (fromMaybe, isJust, isNothing) import Data.Ord (comparing) import Data.Word (Word64) import System.Exit (die) -- SplitMix64 generator in a minimal state monad. newtype Rand a = Rand { runRand :: Word64 -> (a, Word64) } instance Functor Rand where fmap f (Rand m) = Rand $ \s -> let (x, s') = m s in (f x, s') instance Applicative Rand where pure x = Rand $ \s -> (x, s) (<*>) = ap instance Monad Rand where Rand m >>= k = Rand $ \s -> let (x, s') = m s in runRand (k x) s' randWord :: Rand Word64 randWord = Rand $ \s -> let s' = s + 0x9e3779b97f4a7c15 z1 = (s' `xor` shiftR s' 30) * 0xbf58476d1ce4e5b9 z2 = (z1 `xor` shiftR z1 27) * 0x94d049bb133111eb in (z2 `xor` shiftR z2 31, s') randInt :: Int -> Rand Int randInt k = (\w -> fromIntegral (w `mod` fromIntegral k)) <$> randWord randRange :: Int -> Int -> Rand Int randRange lo hi = (lo +) <$> randInt (hi - lo + 1) pick :: Int -> [a] -> Rand [a] pick 0 _ = pure [] pick _ [] = pure [] pick k xs = do i <- randInt (length xs) case splitAt i xs of (as, b : bs) -> (b :) <$> pick (k - 1) (as ++ bs) _ -> pure [] check :: String -> Bool -> String -> IO () check tag ok msg = do unless ok $ die ("failed (" ++ tag ++ "): " ++ msg) putStrLn (tag ++ ": " ++ msg) -- CNF representation and DPLL solver with Integer bitmask propagation. type Lit = Int type Clause = [Lit] type CNF = [Clause] type Env = [(Int, Bool)] evalLit :: Env -> Lit -> Bool evalLit env l = maybe False (== (l > 0)) (lookup (abs l) env) satisfies :: CNF -> Env -> Bool satisfies cnf env = all (any (evalLit env)) cnf propagate :: CNF -> Env -> Maybe (CNF, Env) propagate cnf env = case [l | [l] <- cnf] of [] -> Just (cnf, env) us -> let posM = foldl setBit (0 :: Integer) [u | u <- us, u > 0] negM = foldl setBit (0 :: Integer) [-u | u <- us, u < 0] inU l = testBit (if l > 0 then posM else negM) (abs l) env' = [(abs u, u > 0) | u <- nub us] ++ env step [] acc = Just (reverse acc) step (c : cs) acc | any inU c = step cs acc | otherwise = case filter (not . inU . negate) c of [] -> Nothing c' -> step cs (c' : acc) in if (posM .&. negM) /= 0 then Nothing else step cnf [] >>= \cnf' -> propagate cnf' env' solve :: CNF -> Maybe Env solve cnf | any null cnf = Nothing | otherwise = go cnf [] where go cs env = do (cs', env') <- propagate cs env case cs' of [] -> Just env' _ -> case minimumBy (comparing length) cs' of (l : _) -> go ([l] : cs') env' <|> go ([-l] : cs') env' [] -> Nothing randomCnf :: Int -> Int -> Int -> Rand CNF randomCnf nVars nClauses width = replicateM nClauses $ do vs <- pick (min width nVars) [1 .. nVars] mapM (\v -> (\b -> if b == 0 then v else -v) <$> randInt 2) vs -- 1. Cook-Levin tableau reduction vs direct nondeterministic simulation. type Trans = [((Int, Int), [(Int, Int, Int)])] qStart, qAccept, symBlank :: Int qStart = 0 qAccept = 1 symBlank = 2 setTape :: Int -> Int -> [(Int, Int)] -> [(Int, Int)] setTape p a [] = [(p, a) | a /= symBlank] setTape p a ((q, b) : rest) | p < q = [(p, a) | a /= symBlank] ++ ((q, b) : rest) | p == q = [(p, a) | a /= symBlank] ++ rest | otherwise = (q, b) : setTape p a rest ntmAccepts :: Trans -> [Int] -> Int -> Bool ntmAccepts delta x tMax = step 0 [(qStart, 0, initTape)] where initTape = [(i, b) | (i, b) <- zip [0 ..] x, b /= symBlank] step t front | any (\(q, _, _) -> q == qAccept) front = True | t >= tMax = False | otherwise = step (t + 1) $ nub [ (q2, p + m, setTape p a2 tp) | (q, p, tp) <- front , let cur = fromMaybe symBlank (lookup p tp) , (q2, a2, m) <- fromMaybe [] (lookup (q, cur) delta) ] cookLevin :: Bool -> Trans -> Int -> [Int] -> Int -> CNF cookLevin useFrame delta nStates x tMax = wellFormed ++ initCfg ++ transitions ++ [[vS tMax qAccept]] where (pLo, pHi) = (-tMax, max (length x) 1 + tMax) cells = [pLo .. pHi] nC = length cells b1 = (tMax + 1) * nStates b2 = b1 + (tMax + 1) * nC b3 = b2 + (tMax + 1) * nC * 3 maxDeg = maximum (1 : map (length . snd) delta) vS t q = 1 + t * nStates + q vH t pc = b1 + 1 + t * nC + pc vC t pc a = b2 + 1 + (t * nC + pc) * 3 + a vE t pc a q i = b3 + 1 + (((t * nC + pc) * 3 + a) * nStates + q) * maxDeg + i one vs = vs : [[-a, -b] | (a : bs) <- tails vs, b <- bs] wellFormed = concat [ one [vS t q | q <- [0 .. nStates - 1]] ++ one [vH t pc | pc <- [0 .. nC - 1]] ++ concat [one [vC t pc a | a <- [0 .. 2]] | pc <- [0 .. nC - 1]] | t <- [0 .. tMax] ] initCfg = [vS 0 qStart] : [vH 0 (0 - pLo)] : [ [vC 0 pc (if 0 <= p && p < length x then x !! p else symBlank)] | (pc, p) <- zip [0 ..] cells ] transitions = concat [ [[vH t pc, -vC t pc a, vC (t + 1) pc a] | useFrame] ++ concat [ let raw = if q == qAccept then [(qAccept, a, 0)] else fromMaybe [] (lookup (q, a) delta) mvs = [ (q2, a2, m) | (q2, a2, m) <- raw , p + m >= pLo, p + m <= pHi ] es = [vE t pc a q i | i <- [0 .. length mvs - 1]] in (-vS t q : -vH t pc : -vC t pc a : es) : concat [ [ [-e, vS (t + 1) q2] , [-e, vH (t + 1) (pc + m)] , [-e, vC (t + 1) pc a2] ] | (e, (q2, a2, m)) <- zip es mvs ] | q <- [0 .. nStates - 1] ] | t <- [0 .. tMax - 1], (pc, p) <- zip [0 ..] cells, a <- [0 .. 2] ] randomNtm :: Int -> Rand Trans randomNtm nStates = mapM mkEntry keys where keys = [(q, a) | q <- [0 .. nStates - 1], q /= qAccept, a <- [0 .. 2]] mkEntry qa = do d <- ([0, 1, 2, 2] !!) <$> randInt 4 mvs <- replicateM d $ (,,) <$> randInt nStates <*> randInt 2 <*> ((+ (-1)) <$> randInt 3) pure (qa, mvs) checkS1 :: Rand (IO ()) checkS1 = do let (nS, tMax) = (4, 4) inputs = concatMap (\n -> sequence (replicate n [0, 1])) [0 .. 3] deltas <- replicateM 60 (randomNtm nS) let runs = [ (truth, isJust (solve (cookLevin True d nS x tMax)) == truth) | d <- deltas, x <- inputs, let truth = ntmAccepts d x tMax ] acc = length (filter fst runs) away = [((0, 0), [(2, 0, 1)]), ((2, 2), [(3, 2, -1)]), ((3, 1), [(1, 1, 0)])] frameNeeded = not (ntmAccepts away [0] tMax) && isNothing (solve (cookLevin True away nS [0] tMax)) && isJust (solve (cookLevin False away nS [0] tMax)) pure $ check "S1" (all snd runs && acc > 0 && acc < length runs && frameNeeded) (show (length runs) ++ " NTM/CNF runs agree (" ++ show acc ++ " accepting); frame-axiom omission caught") -- 2. Self-reducibility (witness recovery from decision queries). searchSat :: (CNF -> Bool) -> CNF -> Int -> (Maybe Env, Int) searchSat dec cnf nVars | not (dec cnf) = (Nothing, 1) | otherwise = (Just [(abs l, l > 0) | [l] <- fixed], 1 + nVars) where fixed = foldl (\acc v -> acc ++ [[if dec (cnf ++ acc ++ [[v]]) then v else -v]]) [] [1 .. nVars] checkS2 :: Rand (IO ()) checkS2 = do trials <- replicateM 400 $ do n <- randRange 3 12 m <- randRange 2 (5 * n) cnf <- randomCnf n m 3 let truth = isJust (solve cnf) (ans, calls) = searchSat (isJust . solve) cnf n sound = calls <= n + 1 && maybe (not truth) (\a -> truth && satisfies cnf a) ans bad = truth && maybe True (not . satisfies cnf) (fst (searchSat (const True) cnf n)) pure (sound, truth, bad) let satCnt = length [() | (_, True, _) <- trials] caught = length [() | (_, _, True) <- trials] pure $ check "S2" (all (\(ok, _, _) -> ok) trials && satCnt > 0 && caught > 0) ("400 trials solved in <= v+1 queries (" ++ show satCnt ++ " SAT); dishonest oracle rejected " ++ show caught ++ " times") -- 3. Levin universal search via the step monad Run. data Run a = Halt a | Step (Run a) instance Functor Run where fmap f (Halt x) = Halt (f x) fmap f (Step r) = Step (fmap f r) instance Applicative Run where pure = Halt (<*>) = ap instance Monad Run where Halt x >>= k = k x Step r >>= k = Step (r >>= k) tick :: Run () tick = Step (Halt ()) delay :: Int -> a -> Run a delay k x | k <= 0 = Halt x | otherwise = Step (delay (k - 1) x) type Prog = CNF -> Int -> Run (Maybe Env) pConst :: Bool -> Prog pConst val _ n = tick >> pure (Just [(v, val) | v <- [1 .. n]]) pLoop :: Prog pLoop _ _ = let spin = Step spin in spin pMajority :: Prog pMajority cnf n = go (concat cnf) [(v, 0 :: Int) | v <- [1 .. n]] where go [] sc = pure (Just [(v, s >= 0) | (v, s) <- sc]) go (l : ls) sc = tick >> go ls [(v, if v == abs l then s + (if l > 0 then 1 else -1) else s) | (v, s) <- sc] pWalk :: Prog pWalk cnf n = let s0 = fromIntegral (length cnf * 1000 + n + 17) (a0, s1) = runRand (mapM (\v -> (\b -> (v, b == 1)) <$> randInt 2) [1 .. n]) s0 in walk (40 * n) a0 s1 where walk 0 _ _ = pure Nothing walk k a s = do tick case [c | c <- cnf, not (any (evalLit a) c)] of [] -> pure (Just a) bs -> let ((ci, li), s') = runRand ((,) <$> randInt (length bs) <*> randWord) s cl = bs !! ci tgt = abs (cl !! fromIntegral (li `mod` fromIntegral (length cl))) in walk (k - 1) [(v, if v == tgt then not b else b) | (v, b) <- a] s' pBrute :: Prog pBrute cnf n = go (sequence (replicate n [False, True])) where go [] = pure Nothing go (bs : rest) = tick >> let a = zip [1 .. n] bs in if satisfies cnf a then pure (Just a) else go rest programs :: [Prog] programs = [pConst False, pLoop, pConst True, pMajority, pWalk, pBrute] checked :: Bool -> Prog -> CNF -> Int -> Run (Maybe Env) checked ver prog cnf n = do out <- prog cnf n case out of Nothing -> pure Nothing Just a -> delay (length cnf) $ if not ver || satisfies cnf a then Just a else Nothing runAlone :: Int -> Run (Maybe Env) -> (Maybe Env, Int) runAlone cap = go 0 where go s _ | s >= cap = (Nothing, s) go s (Halt out) = (out, s + 1) go s (Step r) = go (s + 1) r universal :: Bool -> Maybe Int -> CNF -> Int -> (Maybe Env, Int) universal ver mClock cnf n = runPhase 1 1 0 where runPhase k i s | i > min k (length programs) = runPhase (k + 1) 1 s | otherwise = slice (bit (k - i) :: Int) (checked ver (programs !! (i - 1)) cnf n) s where slice 0 _ st = runPhase k (i + 1) st slice b r st | maybe False (st >=) mClock = (Nothing, st) | otherwise = case r of Halt (Just a) -> (Just a, st + 1) Halt Nothing -> runPhase k (i + 1) (st + 1) Step r' -> slice (b - 1) r' (st + 1) checkS3 :: Rand (IO ()) checkS3 = do let gather comps okAll | comps >= 1500 = pure (comps, okAll) gather comps okAll = do n <- randRange 3 8 m <- randRange 2 (3 * n) cnf <- randomCnf n m 3 if isNothing (solve cnf) then gather comps okAll else do let (mOut, tU) = universal True Nothing cnf n valid = maybe False (satisfies cnf) mOut runs = [ (i, tI) | (i, p) <- zip [1 ..] programs , let (res, tI) = runAlone 2000 (checked True p cnf n) , isJust res ] holds = all (\(i, tI) -> valid && tU < bit (i + 2) * tI) runs gather (comps + length runs) (okAll && holds) (comps, boundOk) <- gather 0 True clocked <- replicateM 120 $ do m <- randRange 6 16 cnf <- randomCnf 4 m 2 let truth = isJust (solve cnf) big = bit (length programs + 2) * (bit (4 :: Int) + 2 * length cnf + 2) acc = [isJust (fst (universal True (Just b) cnf 4)) | b <- [8, 64, 512, big]] sound = (truth || not (or acc)) && and [not x || y | (x, y) <- zip acc (drop 1 acc)] && (acc !! 3 == truth) unverifiedAccept = not truth && isJust (fst (universal False (Just 64) cnf 4)) pure (sound, not truth, unverifiedAccept) let unsat = length [() | (_, True, _) <- clocked] falseAcc = length [() | (_, _, True) <- clocked] pure $ check "S3" (boundOk && all (\(s, _, _) -> s) clocked && unsat > 0 && falseAcc > 0) ("T_U < 2^(i+2) T_i across " ++ show comps ++ " runs; 120 clocked 2-CNFs (" ++ show unsat ++ " UNSAT); " ++ show falseAcc ++ " unverified false accepts") -- 4. Constructive refutation R(c,n) on 2-CNF over v in {2,3}. clauseUniv :: Int -> [Clause] clauseUniv v = [[s * x] | x <- [1 .. v], s <- [1, -1]] ++ [ [s1 * x, s2 * y] | x <- [1 .. v], y <- [x + 1 .. v], s1 <- [1, -1], s2 <- [1, -1] ] lowWeight :: Int -> Int -> [Env] lowWeight v k = [ zip [1 .. v] bs | bs <- sequence (replicate v [False, True]), length (filter id bs) <= k ] candidate :: CNF -> Int -> Int -> Maybe Env candidate cnf v k = case [a | a <- lowWeight v k, satisfies cnf a] of (a : _) -> Just a [] -> Nothing buildPsi :: Bool -> Int -> Int -> [Clause] -> CNF buildPsi withRej v k univ = [(- (v + 1 + j)) : c | (j, c) <- zip [0 ..] univ] ++ [ [v + 1 + j | (j, c) <- zip [0 ..] univ, not (satisfies [c] a)] | withRej, a <- lowWeight v k ] decodePsi :: Env -> Int -> [Clause] -> (CNF, Env) decodePsi sol v univ = ( [c | (j, c) <- zip [0 ..] univ, fromMaybe False (lookup (v + 1 + j) sol)] , [(i, fromMaybe False (lookup i sol)) | i <- [1 .. v]] ) isError :: CNF -> Int -> Int -> Bool isError x v k = isJust (solve x) && isNothing (candidate x v k) refuter :: Int -> Int -> [Clause] -> (CNF, Int) refuter v k univ = let psi = buildPsi True v k univ nVars = v + length univ in case candidate psi nVars k of Just sol -> (fst (decodePsi sol v univ), v) Nothing -> (psi, nVars) checkS4 :: Rand (IO ()) checkS4 = do let pairs = [(v, k) | v <- [2, 3], k <- [0 .. v]] stats <- mapM testPair pairs let scanned = sum [sc | (sc, _, _, _) <- stats] refuted = sum [rf | (_, rf, _, _) <- stats] decoded = sum [dc | (_, _, dc, _) <- stats] pure $ check "S4" (all (\(_, _, _, ok) -> ok) stats && refuted > 0 && decoded > 0) (show scanned ++ " formulas scanned across 7 (v,k) cases: " ++ show refuted ++ " refuted, " ++ show decoded ++ " witnesses decoded") where testPair (v, k) = do let univ = clauseUniv v allAsg = lowWeight v v fullM = (1 `shiftL` length allAsg) - (1 :: Int) cMasks = [ foldl (.|.) 0 [bit i | (i, a) <- zip [0 ..] allAsg, satisfies [c] a] | c <- univ ] satSets = foldl (\acc m -> acc ++ map (.&. m) acc) [fullM] cMasks lowM = foldl (.|.) 0 [ bit i | (i, a) <- zip [0 ..] allAsg , length [() | (_, True) <- a] <= k ] hasErr = any (\s -> s /= 0 && (s .&. lowM) == 0) satSets psi = buildPsi True v k univ refOk = not hasErr || let (tgt, nv) = refuter v k univ in isJust (solve tgt) && isNothing (candidate tgt nv k) noRejBad = maybe False (\(x, _) -> not (isError x v k)) (decodePsi <$> solve (buildPsi False v k univ) <*> pure v <*> pure univ) lits = [s * p | p <- [1 .. v + length univ], s <- [1, -1]] samples <- replicateM (if hasErr then 200 else 0) $ do blk <- pick 3 lits pure $ case solve (psi ++ [[l] | l <- blk]) of Nothing -> (0 :: Int, True) Just sol -> let (x, y) = decodePsi sol v univ in (1, satisfies x y && isError x v k) pure ( length satSets, if hasErr then 1 else 0 :: Int, sum (map fst samples) , (isJust (solve psi) == hasErr) && refOk && noRejBad && all snd samples ) -- 5. Finite prefixes vs asymptotic growth (exact Integer powers). checkS5 :: IO () checkS5 = do let lim = 1000 :: Integer fit e = all (\n -> (2 :: Integer) ^ n <= n ^ e + e) [1 .. lim] c = case [e | e <- [1 :: Integer .. 200], fit e] of (e : _) -> e; [] -> 0 brk = case [n | n <- [lim .. 2000], (2 :: Integer) ^ n > n ^ c + c] of (n : _) -> n [] -> 0 check "S5" (c == 101 && fit c && brk == 1008) ("2^n <= n^101 + 101 holds for 1 <= n <= 1000 and first fails at n = " ++ show brk) -- 6. Baker-Gill-Solovay decision-tree diagonalization step. data Tree = Ans Bool | Ask Int Tree Tree runTree :: Tree -> [Int] -> (Bool, [Int]) runTree (Ans b) _ = (b, []) runTree (Ask q noT yesT) orc = let (ans, qs) = runTree (if q `elem` orc then yesT else noT) orc in (ans, q : qs) fooled :: Int -> Tree -> Bool fooled uSize tree = let (ans0, qs) = runTree tree [] in if ans0 then True else case [s | s <- [0 .. uSize - 1], s `notElem` qs] of [] -> False (s : _) -> not (fst (runTree tree [s])) allTrees :: Int -> Int -> [Tree] allTrees _ 0 = [Ans True, Ans False] allTrees sz d = let subs = allTrees sz (d - 1) in Ans True : Ans False : [Ask q noT yesT | q <- [0 .. sz - 1], noT <- subs, yesT <- subs] randTree :: Int -> Int -> Rand Tree randTree _ 0 = Ans . (== 1) <$> randInt 2 randTree sz d = do stop <- randInt 10 if stop == 0 then Ans . (== 1) <$> randInt 2 else Ask <$> randInt sz <*> randTree sz (d - 1) <*> randTree sz (d - 1) checkS6 :: Rand (IO ()) checkS6 = do let exh = allTrees 3 2 full = foldr (\s rest -> Ask s rest (Ans True)) (Ans False) [0, 1, 2] smp <- replicateM 2000 (randTree 16 15) pure $ check "S6" (all (fooled 3) exh && all (fooled 16) smp && not (fooled 3 full)) ("adversary fooled all " ++ show (length exh) ++ " depth-2 and " ++ show (length smp) ++ " depth-15 trees; full-query tree escaped") main :: IO () main = do let suite = sequence [checkS1, checkS2, checkS3, checkS4, pure checkS5, checkS6] sequence_ (fst (runRand suite 20261127))