hsmt-0.1.0.0: src/HSMT/Theory/Arith.hs
-- | Linear integer arithmetic (LIA) for DPLL(T).
--
-- Every arithmetic atom is normalized to the form @x <= c@, where @x@ is a
-- simplex variable (an integer term, or a slack variable standing for a
-- linear combination with coprime integer coefficients) and @c@ is an
-- integer. Over the integers the negation of @x <= c@ is @x >= c + 1@, so
-- both polarities of an atom are bounds.
--
-- Satisfiability over the rationals is decided by the general simplex
-- ('HSMT.Theory.Arith.Simplex'); integrality is enforced by
-- branch-and-bound, which creates new atoms @x <= floor v@ for variables
-- with fractional values and lets the SAT solver decide them.
module HSMT.Theory.Arith
( Arith
, LinExpr (..)
, linConst
, linVar
, linAdd
, linScale
, linSub
, newArith
, termVar
, freshVar
, leAtom
, pendingLemmas
, queueClause
, arithHooks
, linValue
, varValue
, isUnbranchable
, resetBranching
, hasArithVars
) where
import Control.Monad (forM, forM_, unless)
import Data.IORef
import Data.List (sortOn)
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import qualified Data.IntSet as IntSet
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Ratio (denominator, numerator)
import HSMT.SAT.Solver (Solver)
import qualified HSMT.SAT.Solver as SAT
import HSMT.SAT.Types
import HSMT.Theory.Arith.Simplex (SVar)
import qualified HSMT.Theory.Arith.Simplex as Sx
-- | A linear combination of simplex variables plus a constant.
data LinExpr = LinExpr
{ linCoeffs :: !(IntMap Integer)
, linConstant :: !Integer
}
deriving (Eq, Ord, Show)
-- | A constant expression.
linConst :: Integer -> LinExpr
linConst = LinExpr IntMap.empty
-- | A single variable with coefficient 1.
linVar :: SVar -> LinExpr
linVar x = LinExpr (IntMap.singleton x 1) 0
-- | Sum of two expressions; zero coefficients are dropped.
linAdd :: LinExpr -> LinExpr -> LinExpr
linAdd (LinExpr a c) (LinExpr b d) = LinExpr (IntMap.filter (/= 0) (IntMap.unionWith (+) a b)) (c + d)
-- | Multiply an expression by a constant.
linScale :: Integer -> LinExpr -> LinExpr
linScale 0 _ = linConst 0
linScale k (LinExpr a c) = LinExpr (IntMap.map (* k) a) (k * c)
-- | Difference of two expressions.
linSub :: LinExpr -> LinExpr -> LinExpr
linSub a b = linAdd a (linScale (-1) b)
-- | The LIA theory solver: a simplex, the atoms over its variables and the
-- branch-and-bound state.
data Arith = Arith
{ arSolver :: !Solver
, arTrue :: !Lit
, arSimplex :: !Sx.Simplex
, arTermVars :: !(IORef (IntMap SVar))
-- ^ Simplex variable of each integer term.
, arBranchVars :: !(IORef IntSet.IntSet)
-- ^ Variables that must take integer values (all but slack variables).
, arForms :: !(IORef (Map [(SVar, Integer)] SVar))
-- ^ Slack variable of each normalized combination.
, arAtoms :: !(IORef (IntMap (SVar, Integer)))
-- ^ SAT variable to the atom @x <= c@ it stands for.
, arVarAtoms :: !(IORef (IntMap (Map Integer Lit)))
-- ^ Atoms of each simplex variable, by constant.
, arPending :: !(IORef [Lemma])
-- ^ Clauses waiting to be handed to the SAT solver.
, arConflict :: !(IORef (Maybe [Lit]))
, arBranches :: !(IORef Int)
, arBranchCount :: !(IORef (IntMap Int))
-- ^ How often each variable was branched on.
, arBranchLimit :: !Int
, arGaveUp :: !(IORef Bool)
}
-- | An empty solver attached to a SAT solver, given the literal that is
-- always true (used for constant atoms).
newArith :: Solver -> Lit -> IO Arith
newArith s t =
Arith s t
<$> Sx.newSimplex
<*> newIORef IntMap.empty
<*> newIORef IntSet.empty
<*> newIORef Map.empty
<*> newIORef IntMap.empty
<*> newIORef IntMap.empty
<*> newIORef []
<*> newIORef Nothing
<*> newIORef 0
<*> newIORef IntMap.empty
<*> pure 100000
<*> newIORef False
-- | The simplex variable of an integer term (by term id).
termVar :: Arith -> Int -> IO SVar
termVar ar t =
IntMap.lookup t <$> readIORef (arTermVars ar) >>= \case
Just x -> pure x
Nothing -> do
x <- freshVar ar
modifyIORef' (arTermVars ar) (IntMap.insert t x)
pure x
-- | A fresh integer variable not associated with a term.
freshVar :: Arith -> IO SVar
freshVar ar = do
x <- Sx.newVar (arSimplex ar)
modifyIORef' (arBranchVars ar) (IntSet.insert x)
pure x
-- | The literal of @e <= 0@.
leAtom :: Arith -> LinExpr -> IO Lit
leAtom ar (LinExpr coeffs k)
| IntMap.null coeffs = pure (if k <= 0 then arTrue ar else litNeg (arTrue ar))
| otherwise = do
-- sum a_i x_i <= -k, divided by the gcd g: sum (a_i/g) x_i <= floor(-k/g)
let g = foldr1 gcd (map abs (IntMap.elems coeffs))
c = floorDiv (negate k) g
normalized = IntMap.toList (IntMap.map (`div` g) coeffs)
case normalized of
((_, lead) : _)
| lead > 0 -> atomFor normalized c
| otherwise ->
-- sum b_i x_i >= -c with b = -a/g, i.e. not (sum b_i x_i <= -c - 1)
litNeg <$> atomFor [(x, negate a) | (x, a) <- normalized] (negate c - 1)
[] -> error "leAtom: empty combination"
where
floorDiv a b = floor (fromInteger a / fromInteger b :: Rational)
atomFor form c = do
x <- formVar form
atomLit x c
formVar = \case
[(x, 1)] -> pure x
form ->
Map.lookup form <$> readIORef (arForms ar) >>= \case
Just s -> pure s
Nothing -> do
s <- Sx.addRow (arSimplex ar) [(fromInteger a, x) | (x, a) <- form]
modifyIORef' (arForms ar) (Map.insert form s)
pure s
-- The atom x <= c, related by implications to its nearest neighbours
-- on the same variable (x <= c' implies x <= c for c' < c).
atomLit x c = do
byVar <- IntMap.findWithDefault Map.empty x <$> readIORef (arVarAtoms ar)
case Map.lookup c byVar of
Just l -> pure l
Nothing -> do
v <- SAT.newVar (arSolver ar)
let l = posLit v
modifyIORef' (arAtoms ar) (IntMap.insert v (x, c))
modifyIORef' (arVarAtoms ar) (IntMap.insert x (Map.insert c l byVar))
let below = Map.lookupLT c byVar
above = Map.lookupGT c byVar
forM_ below $ \(_, lb) -> queue ar [litNeg lb, l]
forM_ above $ \(_, la) -> queue ar [litNeg l, la]
pure l
queue :: Arith -> [Lit] -> IO ()
queue ar c = modifyIORef' (arPending ar) (permanent c :)
-- | Queue a permanent clause; it reaches the SAT solver at the next check.
queueClause :: Arith -> [Lit] -> IO ()
queueClause = queue
-- | Take the clauses produced while creating atoms.
pendingLemmas :: Arith -> IO [Lemma]
pendingLemmas ar = do
ls <- readIORef (arPending ar)
writeIORef (arPending ar) []
pure (reverse ls)
-- | The current (rational) value of a simplex variable.
varValue :: Arith -> SVar -> IO Rational
varValue ar = Sx.value (arSimplex ar)
-- | The value of an expression under the current simplex assignment.
linValue :: Arith -> LinExpr -> IO Rational
linValue ar (LinExpr coeffs k) = do
vs <- forM (IntMap.toList coeffs) $ \(x, a) -> (* fromInteger a) <$> varValue ar x
pure (fromInteger k + sum vs)
-- | True when some simplex variable exists.
hasArithVars :: Arith -> IO Bool
hasArithVars ar = not . IntSet.null <$> readIORef (arBranchVars ar)
-- | True when branch-and-bound gave up (the result must be unknown).
isUnbranchable :: Arith -> IO Bool
isUnbranchable = readIORef . arGaveUp
-- | Restore the branch-and-bound budget, for a new satisfiability check of
-- an incremental session.
resetBranching :: Arith -> IO ()
resetBranching ar = do
writeIORef (arBranches ar) 0
writeIORef (arGaveUp ar) False
-------------------------------------------------------------------------------
-- DPLL(T) interface
-- | Hooks connecting the arithmetic solver to the SAT engine: bounds are
-- asserted as atoms are assigned, feasibility is checked on propagation and
-- integrality (branch-and-bound and Gomory cuts) at the final check.
arithHooks :: Arith -> TheoryHooks
arithHooks ar =
TheoryHooks
{ thNewLevel = Sx.push sx
, thBacktrack = \lvl -> do
Sx.pop sx lvl
writeIORef (arConflict ar) Nothing
, thAssert = assertLit
, thPropagate = checkNow False
, thFinalCheck = checkNow True
}
where
sx = arSimplex ar
assertLit l = do
conflict <- readIORef (arConflict ar)
atom <- IntMap.lookup (litVar l) <$> readIORef (arAtoms ar)
case (conflict, atom) of
(Nothing, Just (x, c)) -> do
r <-
if litSign l
then Sx.assertLower sx x (fromInteger c + 1) [l]
else Sx.assertUpper sx x (fromInteger c) [l]
forM_ r (writeIORef (arConflict ar) . Just)
_ -> pure ()
checkNow final = do
pending <- pendingLemmas ar
conflict <- readIORef (arConflict ar)
case (pending, conflict) of
(_ : _, _) -> pure (TheoryLemmas pending)
(_, Just c) -> pure (TheoryConflict c)
_ ->
Sx.check sx >>= \case
Just c -> do
writeIORef (arConflict ar) (Just c)
pure (TheoryConflict c)
Nothing
| final -> branch
| otherwise -> pure TheoryOk
-- Integrality: alternate Gomory cuts and branching on the first
-- variable with a fractional value. Branching creates the atom
-- x <= floor v, whose two polarities are the two branches. Cuts alone
-- and branching alone may both diverge on unbounded problems; together
-- they usually converge quickly.
branch = do
vars <- IntSet.toList <$> readIORef (arBranchVars ar)
fractional <- filterM' (\x -> (/= 1) . denominator <$> Sx.value sx x) vars
counts <- readIORef (arBranchCount ar)
scored <- forM fractional $ \x -> do
lo <- Sx.lowerBound sx x
up <- Sx.upperBound sx x
let unbounded = length (filter null [() <$ lo, () <$ up])
pure ((IntMap.findWithDefault 0 x counts, unbounded), x)
-- Fairness: always branching on the same unbounded variables may
-- diverge while a bounded fractional variable is never split.
case map snd (sortOn fst scored) of
[] -> pure TheoryOk
(x : _) -> do
modifyIORef' (arBranchCount ar) (IntMap.insertWith (+) x 1)
n <- readIORef (arBranches ar)
writeIORef (arBranches ar) (n + 1)
if n >= arBranchLimit ar
then do
writeIORef (arGaveUp ar) True
pure TheoryOk
else do
cut <- if odd n then tryCut fractional else pure Nothing
maybe (splitOn x) pure cut
splitOn x = do
v <- Sx.value sx x
let fl = numerator v `div` denominator v
l <- leAtomVar x fl
pending <- pendingLemmas ar
-- The new atom is unassigned; the SAT solver decides it next. The
-- branch towards zero is tried first: rounding to the nearest integer
-- lets values drift away on unbounded problems, while small solutions
-- are the common case.
unless (litSign l) $ SAT.setPhase (arSolver ar) (litVar l) (v > 0)
pure (if null pending then TheoryOk else TheoryLemmas pending)
tryCut = \case
[] -> pure Nothing
(x : xs) -> do
basic <- Sx.isBasic sx x
cut <- if basic then Sx.gomoryCut sx x else pure Nothing
case cut of
Nothing -> tryCut xs
Just (coeffs, k, reasons) -> do
-- sum c_j x_j >= k, scaled to integers: d k - sum (d c_j) x_j <= 0
let d = foldr (lcm . denominator) (denominator k) (map fst coeffs)
scaleR q = numerator (q * fromInteger d)
lin = LinExpr (IntMap.filter (/= 0) (IntMap.fromListWith (+) [(y, negate (scaleR c)) | (c, y) <- coeffs])) (scaleR k)
l <- leAtom ar lin
pending <- pendingLemmas ar
pure (Just (TheoryLemmas (pending <> [removable (l : map litNeg reasons)])))
leAtomVar x c = leAtom ar (LinExpr (IntMap.singleton x 1) (negate c))
filterM' p = \case
[] -> pure []
(y : ys) -> do
keep <- p y
rest <- filterM' p ys
pure (if keep then y : rest else rest)