packages feed

hsmt-0.1.0.0: src/HSMT/Theory/Arith/Simplex.hs

-- | General simplex for linear arithmetic, in the style of Dutertre and
-- de Moura ("A fast linear-arithmetic solver for DPLL(T)", CAV 2006).
--
-- The tableau keeps every basic variable as a linear combination of
-- nonbasic variables. Constraints are bounds on variables; every bound
-- carries the literals that justify it, so infeasibility is explained by a
-- set of bounds (a Farkas certificate read off a tableau row).
--
-- Bounds are backtrackable: 'push' opens a level and 'pop' restores the
-- bounds of older levels. The assignment and the tableau are kept across
-- backtracking, which is sound because loosening bounds never invalidates
-- the tableau equations.
--
-- Arithmetic is exact, over 'Rational'.
module HSMT.Theory.Arith.Simplex
  ( Simplex
  , SVar
  , Bound (..)
  , newSimplex
  , newVar
  , addRow
  , assertUpper
  , assertLower
  , check
  , push
  , pop
  , level
  , value
  , lowerBound
  , upperBound
  , rowOf
  , isBasic
  , gomoryCut
  ) where

import Control.Monad (forM_, when)
import Data.IORef
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import Data.Maybe (isNothing)
import qualified Data.IntSet as IntSet

import HSMT.SAT.Types (Lit)

-- | A simplex variable (an index into the tableau).
type SVar = Int

-- | A bound and its justification. An empty justification marks a fact
-- that holds unconditionally.
data Bound = Bound
  { bValue :: !Rational
    -- ^ The value of the bound.
  , bReason :: ![Lit]
    -- ^ The literals whose assignment asserted the bound.
  }
  deriving (Show)

-- | Mutable simplex state: assignment, bounds, tableau and the trail used
-- to undo bounds on backtracking.
data Simplex = Simplex
  { sxNext :: !(IORef Int)
  , sxValue :: !(IORef (IntMap Rational))
  , sxLower :: !(IORef (IntMap Bound))
  , sxUpper :: !(IORef (IntMap Bound))
  , sxRows :: !(IORef (IntMap (IntMap Rational)))
    -- ^ Basic variable to its row over nonbasic variables.
  , sxCols :: !(IORef (IntMap IntSet))
    -- ^ Nonbasic variable to the basic variables whose rows mention it.
  , sxTrail :: !(IORef [(SVar, Bool, Maybe Bound)])
    -- ^ Previous bounds (flag: upper), most recent first.
  , sxTrailLen :: !(IORef Int)
  , sxLevels :: !(IORef [Int])
    -- ^ Trail length when each level was opened, innermost first.
  , sxDirty :: !(IORef IntSet)
    -- ^ Basic variables that may violate a bound: those whose value or
    -- bounds changed since the last 'check'. Every violated basic variable
    -- is in this set.
  }

-- | An empty simplex with no variables and no open levels.
newSimplex :: IO Simplex
newSimplex =
  Simplex
    <$> newIORef 0
    <*> newIORef IntMap.empty
    <*> newIORef IntMap.empty
    <*> newIORef IntMap.empty
    <*> newIORef IntMap.empty
    <*> newIORef IntMap.empty
    <*> newIORef []
    <*> newIORef 0
    <*> newIORef []
    <*> newIORef IntSet.empty

-- | A fresh unbounded nonbasic variable with value 0.
newVar :: Simplex -> IO SVar
newVar sx = do
  v <- readIORef (sxNext sx)
  writeIORef (sxNext sx) (v + 1)
  pure v

-- | The current value of a variable (0 for a fresh one).
value :: Simplex -> SVar -> IO Rational
value sx v = IntMap.findWithDefault 0 v <$> readIORef (sxValue sx)

-- | The current lower and upper bound of a variable, if any.
lowerBound, upperBound :: Simplex -> SVar -> IO (Maybe Bound)
lowerBound sx v = IntMap.lookup v <$> readIORef (sxLower sx)
upperBound sx v = IntMap.lookup v <$> readIORef (sxUpper sx)

-- | Whether the variable is currently basic (has a tableau row).
isBasic :: Simplex -> SVar -> IO Bool
isBasic sx v = IntMap.member v <$> readIORef (sxRows sx)

-- | The row of a basic variable.
rowOf :: Simplex -> SVar -> IO (Maybe (IntMap Rational))
rowOf sx v = IntMap.lookup v <$> readIORef (sxRows sx)

-- | A fresh basic variable equal to the given combination.
addRow :: Simplex -> [(Rational, SVar)] -> IO SVar
addRow sx combo = do
  s <- newVar sx
  rows <- readIORef (sxRows sx)
  vals <- readIORef (sxValue sx)
  -- Express the combination over nonbasic variables.
  let expand (a, x) = case IntMap.lookup x rows of
        Just r -> IntMap.map (* a) r
        Nothing -> IntMap.singleton x a
      row = IntMap.filter (/= 0) (IntMap.unionsWith (+) (map expand combo))
      val = sum [a * IntMap.findWithDefault 0 x vals | (x, a) <- IntMap.toList row]
  writeIORef (sxRows sx) (IntMap.insert s row rows)
  modifyIORef' (sxCols sx) $ \cols ->
    foldl' (\m x -> IntMap.insertWith IntSet.union x (IntSet.singleton s) m) cols (IntMap.keys row)
  modifyIORef' (sxValue sx) (IntMap.insert s val)
  modifyIORef' (sxDirty sx) (IntSet.insert s)
  pure s

-------------------------------------------------------------------------------
-- Levels

-- | Open a new backtracking level for bounds.
push :: Simplex -> IO ()
push sx = readIORef (sxTrailLen sx) >>= \n -> modifyIORef' (sxLevels sx) (n :)

-- | The number of open levels.
level :: Simplex -> IO Int
level sx = length <$> readIORef (sxLevels sx)

-- | Return to the given number of open levels.
pop :: Simplex -> Int -> IO ()
pop sx lvl = do
  levels <- readIORef (sxLevels sx)
  let excess = length levels - lvl
  when (excess > 0) $ case drop (excess - 1) levels of
    (mark : older) -> do
      writeIORef (sxLevels sx) older
      n <- readIORef (sxTrailLen sx)
      trail <- readIORef (sxTrail sx)
      let (undo, keep) = splitAt (n - mark) trail
      forM_ undo $ \(v, isUpper, old) -> do
        let ref = if isUpper then sxUpper sx else sxLower sx
        modifyIORef' ref (maybe (IntMap.delete v) (IntMap.insert v) old)
      writeIORef (sxTrail sx) keep
      writeIORef (sxTrailLen sx) mark
    [] -> pure ()

record :: Simplex -> SVar -> Bool -> Maybe Bound -> IO ()
record sx v isUpper old = do
  modifyIORef' (sxTrail sx) ((v, isUpper, old) :)
  modifyIORef' (sxTrailLen sx) (+ 1)

-------------------------------------------------------------------------------
-- Bounds

-- | Assert @v <= c@. Returns the explanation of a conflict with the lower
-- bound, if any.
assertUpper :: Simplex -> SVar -> Rational -> [Lit] -> IO (Maybe [Lit])
assertUpper sx v c reason = do
  up <- upperBound sx v
  lo <- lowerBound sx v
  case () of
    _
      | Just u <- up, bValue u <= c -> pure Nothing
      | Just l <- lo, bValue l > c -> pure (Just (reason <> bReason l))
      | otherwise -> do
          record sx v True up
          modifyIORef' (sxUpper sx) (IntMap.insert v (Bound c reason))
          basic <- isBasic sx v
          when basic $ modifyIORef' (sxDirty sx) (IntSet.insert v)
          x <- value sx v
          when (not basic && x > c) $ update sx v c
          pure Nothing

-- | Assert @v >= c@.
assertLower :: Simplex -> SVar -> Rational -> [Lit] -> IO (Maybe [Lit])
assertLower sx v c reason = do
  up <- upperBound sx v
  lo <- lowerBound sx v
  case () of
    _
      | Just l <- lo, bValue l >= c -> pure Nothing
      | Just u <- up, bValue u < c -> pure (Just (reason <> bReason u))
      | otherwise -> do
          record sx v False lo
          modifyIORef' (sxLower sx) (IntMap.insert v (Bound c reason))
          basic <- isBasic sx v
          when basic $ modifyIORef' (sxDirty sx) (IntSet.insert v)
          x <- value sx v
          when (not basic && x < c) $ update sx v c
          pure Nothing

-- | Change the value of a nonbasic variable, updating the basic ones.
update :: Simplex -> SVar -> Rational -> IO ()
update sx v new = do
  old <- value sx v
  let delta = new - old
  rows <- readIORef (sxRows sx)
  cols <- readIORef (sxCols sx)
  let affectedSet = IntMap.findWithDefault IntSet.empty v cols
      affected = IntSet.toList affectedSet
  modifyIORef' (sxDirty sx) (IntSet.union affectedSet)
  modifyIORef' (sxValue sx) $ \vals ->
    foldl'
      (\m b -> IntMap.adjust (+ (rows IntMap.! b IntMap.! v) * delta) b m)
      (IntMap.insert v new vals)
      affected

-------------------------------------------------------------------------------
-- Checking

-- | Restore feasibility. Returns an explanation (a set of bound
-- justifications) when the bounds are infeasible. Bland's rule (smallest
-- variable first) guarantees termination. Only the basic variables that may
-- have become violated (@sxDirty@) are inspected.
check :: Simplex -> IO (Maybe [Lit])
check sx = loop
  where
    loop = do
      rows <- readIORef (sxRows sx)
      dirty <- readIORef (sxDirty sx)
      vals <- readIORef (sxValue sx)
      lows <- readIORef (sxLower sx)
      ups <- readIORef (sxUpper sx)
      let valOf x = IntMap.findWithDefault 0 x vals
          violation b
            | Just l <- IntMap.lookup b lows, valOf b < bValue l = Just (b, True, l)
            | Just u <- IntMap.lookup b ups, valOf b > bValue u = Just (b, False, u)
            | otherwise = Nothing
      -- Dirty variables that are no longer basic or not violated can be
      -- dropped; the first violated one stays.
      let candidates = filter (`IntMap.member` rows) (IntSet.toAscList dirty)
          rest = dropWhile (isNothing . violation) candidates
      writeIORef (sxDirty sx) (IntSet.fromList rest)
      case firstJust violation rest of
        Nothing -> pure Nothing
        Just (b, tooLow, bnd) -> do
          let row = rows IntMap.! b
              canIncrease x = maybe True (\u -> valOf x < bValue u) (IntMap.lookup x ups)
              canDecrease x = maybe True (\l -> valOf x > bValue l) (IntMap.lookup x lows)
              -- To raise b, raise x when a > 0 or lower it when a < 0.
              suitable (x, a)
                | tooLow = if a > 0 then canIncrease x else canDecrease x
                | otherwise = if a > 0 then canDecrease x else canIncrease x
          case filter suitable (IntMap.toList row) of
            ((x, _) : _) -> do
              pivotAndUpdate sx b x (bValue bnd)
              -- The entering variable may now violate its own bounds.
              modifyIORef' (sxDirty sx) (IntSet.insert x)
              loop
            [] -> do
              let blocking (x, a)
                    | tooLow == (a > 0) = maybe [] bReason (IntMap.lookup x ups)
                    | otherwise = maybe [] bReason (IntMap.lookup x lows)
              pure (Just (bReason bnd <> concatMap blocking (IntMap.toList row)))

    firstJust f = \case
      [] -> Nothing
      (x : xs) -> maybe (firstJust f xs) Just (f x)

-- | Set basic @b@ to @v@ by moving nonbasic @x@, then swap their roles.
pivotAndUpdate :: Simplex -> SVar -> SVar -> Rational -> IO ()
pivotAndUpdate sx b x v = do
  rows <- readIORef (sxRows sx)
  vb <- value sx b
  let a = rows IntMap.! b IntMap.! x
      theta = (v - vb) / a
  vx <- value sx x
  update sx x (vx + theta)
  pivot sx b x

-- | Make nonbasic @x@ basic and basic @b@ nonbasic.
pivot :: Simplex -> SVar -> SVar -> IO ()
pivot sx b x = do
  rows <- readIORef (sxRows sx)
  cols <- readIORef (sxCols sx)
  let rowB = rows IntMap.! b
      a = rowB IntMap.! x
      -- x = (b - sum_{k /= x} a_k k) / a
      rowX =
        IntMap.insert b (1 / a) (IntMap.map (\c -> negate c / a) (IntMap.delete x rowB))
      others = IntSet.toList (IntSet.delete b (IntMap.findWithDefault IntSet.empty x cols))
      substitute r =
        let c = r IntMap.! x
         in IntMap.filter (/= 0) (IntMap.unionWith (+) (IntMap.delete x r) (IntMap.map (* c) rowX))
      newRows = foldl' (\m o -> IntMap.adjust substitute o m) (IntMap.insert x rowX (IntMap.delete b rows)) others
  writeIORef (sxRows sx) newRows
  -- Rebuild the column index of the affected rows.
  let touched = x : others
      removeOld m r =
        foldl' (\acc y -> IntMap.adjust (IntSet.delete r) y acc) m (IntMap.keys (rows IntMap.! r))
      addNew m r =
        foldl' (\acc y -> IntMap.insertWith IntSet.union y (IntSet.singleton r) acc) m (IntMap.keys (newRows IntMap.! r))
      cols1 = foldl' removeOld (IntMap.delete x cols) (b : others)
      cols2 = foldl' addNew cols1 touched
  writeIORef (sxCols sx) (IntMap.filter (not . IntSet.null) cols2)

-------------------------------------------------------------------------------
-- Cuts

-- | A Gomory mixed-integer cut for a basic variable with a fractional value,
-- assuming every variable must be integral. Returns @(coefficients, k,
-- justification)@ for the cut @sum c_j x_j >= k@, which the current
-- assignment violates and every integral solution of the bounds in the
-- justification satisfies. Requires every nonbasic variable of the row to
-- sit at one of its bounds.
--
-- Writing each nonbasic variable as @x_j = l_j + y_j@ (at its lower bound)
-- or @x_j = u_j - y_j@ (at its upper bound), with @y_j >= 0@, the row reads
-- @x_i + sum d_j y_j = v_i@, where @d_j@ is minus the coefficient of @y_j@,
-- and the cut is
-- @sum_{f_j <= f0} (f_j / f0) y_j + sum_{f_j > f0} ((1 - f_j) / (1 - f0)) y_j >= 1@,
-- where @f@ is the fractional part, @f0 = f(v_i)@ and @f_j = f(d_j)@.
gomoryCut :: Simplex -> SVar -> IO (Maybe ([(Rational, SVar)], Rational, [Lit]))
gomoryCut sx xi = do
  rows <- readIORef (sxRows sx)
  vals <- readIORef (sxValue sx)
  lows <- readIORef (sxLower sx)
  ups <- readIORef (sxUpper sx)
  let valOf x = IntMap.findWithDefault 0 x vals
      frac q = q - fromInteger (floor q)
      f0 = frac (valOf xi)
      atBound (x, a)
        | Just l <- IntMap.lookup x lows, bValue l == valOf x = Just (x, a, True, l)
        | Just u <- IntMap.lookup x ups, bValue u == valOf x = Just (x, negate a, False, u)
        | otherwise = Nothing
      -- c is the coefficient of y_j in x_i = v_i + sum c_j y_j.
      coefficient c
        | frac (negate c) <= f0 = frac (negate c) / f0
        | otherwise = (1 - frac (negate c)) / (1 - f0)
  pure $ case IntMap.lookup xi rows of
    Just row
      | f0 /= 0
      , Just terms <- traverse atBound (IntMap.toList row) ->
          let cut =
                [ (if atLower then e else negate e, x, if atLower then e * bValue b else negate e * bValue b, bReason b)
                | (x, c, atLower, b) <- terms
                , let e = coefficient c
                , e /= 0
                ]
           in Just
                ( [(c, x) | (c, x, _, _) <- cut]
                , 1 + sum [k | (_, _, k, _) <- cut]
                , concat [r | (_, _, _, r) <- cut]
                )
    _ -> Nothing