packages feed

hsmt-0.1.0.0: src/HSMT/SAT/Dimacs.hs

-- | Reading CNF formulas in DIMACS format.
module HSMT.SAT.Dimacs
  ( Cnf (..)
  , parseDimacs
  , loadCnf
  ) where

import Control.Monad (forM_, replicateM_)
import qualified Data.Text as T

import HSMT.SAT.Solver
import HSMT.SAT.Types

-- | A CNF formula as read from a DIMACS file.
data Cnf = Cnf
  { cnfVars :: !Int
    -- ^ Number of variables declared in the @p cnf@ header.
  , cnfClauses :: [[Int]]
    -- ^ Clauses using DIMACS numbering (non-zero, sign is polarity).
  }
  deriving (Eq, Show)

-- | Parse DIMACS CNF text. Comment lines (starting with @c@ or @%@) are
-- skipped; the clause count in the header is not checked.
parseDimacs :: T.Text -> Either String Cnf
parseDimacs txt = do
  let ls = filter (not . skip) (map T.strip (T.lines txt))
      skip l = T.null l || T.head l == 'c' || T.head l == '%'
  case ls of
    (hdr : body) -> case T.words hdr of
      ["p", "cnf", nv, _] -> do
        n <- readInt nv
        lits <- mapM readInt (concatMap T.words body)
        pure (Cnf n (splitZero lits))
      _ -> Left "missing 'p cnf' header"
    [] -> Left "empty input"
  where
    readInt t = case reads (T.unpack t) of
      [(n, "")] -> Right n
      _ -> Left ("not an integer: " <> T.unpack t)
    splitZero xs = case break (== 0) xs of
      ([], []) -> []
      (c, []) -> [c]
      (c, _ : rest) -> c : splitZero rest

-- | Load a CNF into a fresh solver. Returns 'False' if it is trivially
-- unsatisfiable.
loadCnf :: Solver -> Cnf -> IO Bool
loadCnf s (Cnf n clauses) = do
  existing <- numVars s
  replicateM_ (max 0 (maxVar - existing)) (newVar s)
  forM_ clauses $ \c -> addClause s (map toLit c)
  isOkay s
  where
    maxVar = maximum (n : [abs l | c <- clauses, l <- c])
    toLit l = mkLit (abs l - 1) (l < 0)