packages feed

lazyppl-singlesite-0.2.0: test/PlainOptimisedClient.hs

module Main where

import Control.Monad (forM_, unless, when)
import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)
import qualified Data.Map.Strict as Map
import Data.Ratio ((%))
import qualified Data.Vector as Vector
import GuidedReference (pMixed)
import LazyPPL (Meas, sample, score, uniform)
import LazyPPL.SingleSite.Hooks
import Statistics.Test.ChiSquared (chi2test, testSignificance)
import Statistics.Types (pValue)
import System.Random (mkStdGen)

state :: (Bool, Bool) -> Int
state (a,b) = (if a then 2 else 0) + (if b then 1 else 0)

model :: Meas (Bool, Bool)
model = do
  a <- sample uniform
  b <- sample uniform
  let bits = (a < 0.5, b < 0.5)
  score ([1,2,3,4] !! state bits)
  pure bits

guide :: SiteSelector String (Bool, Bool)
guide snapshot = case snapshotSites snapshot of
  [a,b] -> do
    let p = [1%4,3%4,1%2,3%4] !! state (fst (snapshotResult snapshot))
    law <- either fail pure (mkSiteLaw [(a,p),(b,1-p)])
    pure (Complete law)
  sites -> fail ("expected two sites: " ++ show sites)

main :: IO ()
main = do
  kernel <- either fail pure (mkKernel (1%8) (pureEvaluator model) guide)
  initial <- initialise kernel (mkStdGen 57341)
  chain <- case initial of
    Initialised value -> pure value
    _ -> fail "initialisation failed"
  chainRef <- newIORef chain
  countsRef <- newIORef Map.empty
  totalsRef <- newIORef Map.empty
  forM_ [1..101000 :: Int] $ \i -> do
    old <- readIORef chainRef
    let from = state (fst (snapshotResult (chainSnapshot old)))
    result <- transition kernel old
    new <- case result of
      Transitioned value _ -> pure value
      _ -> fail "transition failed"
    let to = state (fst (snapshotResult (chainSnapshot new)))
    totals <- readIORef totalsRef
    when (i > 1000 && Map.findWithDefault 0 from totals < 5000) $ do
      modifyIORef' countsRef (Map.insertWith (+) (from,to) (1 :: Int))
      modifyIORef' totalsRef (Map.insertWith (+) from (1 :: Int))
    writeIORef chainRef new
  counts <- readIORef countsRef
  totals <- readIORef totalsRef
  forM_ [0..3] $ \i -> do
    unless (Map.findWithDefault 0 i totals == 5000) (fail "insufficient departures")
    let observed = [Map.findWithDefault 0 (i,j) counts | j <- [0..3]]
        expected = map ((5000 *) . fromRational) (pMixed !! i)
    result <- maybe (fail "chi-squared test needs two bins") pure
      (chi2test 0 (Vector.fromList (zip observed expected)))
    let probability = pValue (testSignificance result)
    putStrLn ("plain -O2 row " ++ show i ++ " counts=" ++ show observed ++ " p=" ++ show probability)
    unless (probability > 0.001) (fail "transition frequencies differ from the reference")