Skip to content

Commit

Permalink
Add bus example and necessary Poisson pdf (#232)
Browse files Browse the repository at this point in the history
* Add bus example and necessary Poisson pdf

* Remove cruft

* Fix lint complaint

* Add more context to the example
  • Loading branch information
idontgetoutmuch authored Nov 21, 2022
1 parent 50b4865 commit 721ed40
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Control/Monad/Bayes/Class.hs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ module Control.Monad.Bayes.Class
discrete,
normalPdf,
Bayesian (..),
poissonPdf,
posterior,
priorPredictive,
posteriorPredictive,
Expand Down Expand Up @@ -96,7 +97,7 @@ import Data.Vector.Generic as VG (Vector, map, mapM, null, sum, (!))
import Numeric.Log (Log (..))
import Statistics.Distribution
( ContDistr (logDensity, quantile),
DiscreteDistr (probability),
DiscreteDistr (logProbability, probability),
)
import Statistics.Distribution.Beta (betaDistr)
import Statistics.Distribution.Gamma (gammaDistr)
Expand Down Expand Up @@ -285,6 +286,9 @@ normalPdf ::
Log Double
normalPdf mu sigma x = Exp $ logDensity (normalDistr mu sigma) x

poissonPdf :: Double -> Integer -> Log Double
poissonPdf rate n = Exp $ logProbability (Poisson.poisson rate) (fromIntegral n)

-- | multivariate normal
mvNormal :: MonadDistribution m => V.Vector Double -> Matrix Double -> m (V.Vector Double)
mvNormal mu bigSigma = do
Expand Down
27 changes: 27 additions & 0 deletions src/Control/Monad/Bayes/Traced/Static.hs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,35 @@ mhStep (Traced m d) = Traced m d'
where
d' = d >>= mhTransFree m

-- $setup
-- >>> import Control.Monad.Bayes.Class
-- >>> import Control.Monad.Bayes.Sampler.Strict
-- >>> import Control.Monad.Bayes.Weighted

-- | Full run of the Trace Metropolis-Hastings algorithm with a specified
-- number of steps. Newest samples are at the head of the list.
--
-- For example:
--
-- * I have forgotten what day it is.
-- * There are ten buses per hour in the week and three buses per hour at the weekend.
-- * I observe four buses in a given hour.
-- * What is the probability that it is the weekend?
--
-- >>> :{
-- let
-- bus = do x <- bernoulli (2/7)
-- let rate = if x then 3 else 10
-- factor $ poissonPdf rate 4
-- return x
-- mhRunBusSingleObs = do
-- let nSamples = 2
-- sampleIOfixed $ unweighted $ mh nSamples bus
-- in mhRunBusSingleObs
-- :}
-- [True,True,True]
--
-- Of course, it will need to be run more than twice to get a reasonable estimate.
mh :: MonadDistribution m => Int -> Traced m a -> m [a]
mh n (Traced m d) = fmap (map output . NE.toList) (f n)
where
Expand Down

0 comments on commit 721ed40

Please sign in to comment.