{-# LANGUAGE ViewPatterns #-} module Main where import Control.Monad import Data.Fixed (mod') import Data.Foldable (toList) import Data.List import qualified Data.Map as M import Numeric.Log hiding (sum) import Options.Applicative import PPL import System.Random (mkStdGen, setStdGen) cumsum = scanl1 (+) first f xs = snd . head . filter (f . fst) $ zip xs [0 ..] stirling n = n * log n - n pois lambda (fromIntegral -> k) = lambda' ** k' * Exp (negate lambda) / Exp (stirling k) where lambda' = Exp $ log lambda k' = Exp $ log k -- (infinite) binary trees data Tree a = Empty | Tree a (Tree a) (Tree a) deriving (Show) instance Foldable Tree where foldMap f t = bftrav [t] where bftrav [] = mempty bftrav (Empty : ts) = bftrav ts bftrav ((Tree a l r) : ts) = f a <> bftrav (ts <> [l, r]) -- Infinite trees from infinite lists -- NB: it's harder to partition a list so that it folds back to -- equivalence. It doesn't really matter here since we're only -- unfolding random uniforms anyway. treeFromList (x : xs) = Tree x (treeFromList lpart) (treeFromList rpart) where (lpart, rpart) = unzip $ partition xs partition (a : b : xs) = (a, b) : partition xs -- Constrain trees so leaves sum to node value normTree :: Tree Double -> Tree Double normTree (Tree x l r) = go $ Tree x l r where go (Tree x (Tree u l r) (Tree v l' r')) = let s = x / (u + v) in Tree x (go $ Tree (s * u) l r) (go $ Tree (s * v) l' r') drawTreeProbs = toList . normTree . treeFromList <$> iid uniform model :: [[Int]] -> Meas ([[Double]], [Int]) model xs = do (ps, params, clusters) <- sample $ do -- Sample hyperparameters a <- bounded 1 10 -- CRP style dir <- cumsum <$> dirichletProcess a rs <- iid uniform ps <- iid drawTreeProbs let clusters = map (\r -> first (>= r) dir) rs params = map (transpose ps !!) clusters pure (ps, params, clusters) mapM_ scoreLog $ zipWith likelihood params xs let cls = take (length xs) clusters k = maximum cls + 1 n = length (head xs) `div` 2 pure (map (take k) $ take n ps, cls) where likelihood ps cnts = product $ zipWith go ps (pairs cnts) where go p (c, d) = max (pois (fromIntegral d * p) c) (pois (fromIntegral d * p / 2) c) pairs (a : b : rs) = (a, b) : pairs rs pairs [] = [] pairs _ = error "unexpected number of columns, expecting count/depth pairs" -- Tabulate list tabulate xs = M.elems $ M.fromListWith (+) [(c, 1) | c <- xs] -- Draws a phylogeny to DOT format drawGraph :: FilePath -> [[Double]] -> [Int] -> IO () drawGraph path ps cl = writeFile path $ "digraph{" <> edges <> "}" where edges = concatMap calcEdges [1 .. length tab - 1] calcEdges idx = fmt (parent idx) <> "->" <> fmt idx <> ";" fmt i = "\"" <> intercalate "," (map fmtDbl $ ps' !! i) <> " " <> show (tab !! i) <> "\"" tab = tabulate cl parent = flip div 2 . (\x -> x - 1) fmtDbl = show . (/ 10) . fromIntegral . round . (* 1000) ps' = transpose $ map norm ps -- Normalise to purity of first node norm :: [Double] -> [Double] norm (x : xs) = x : map (/ x) xs -- Command line args data Options = Options { seed :: Int, nsamples :: Int, mhfrac :: Double, input :: FilePath, propsPath :: FilePath, clusterPath :: FilePath, dotPath :: FilePath } main = run =<< execParser opts where opts = info (parser <**> helper) (fullDesc <> progDesc "Infer a phylogeny from SNV calls in multiple samples" <> header "phylogey - Bayesian phylogeny inference") parser = Options <$> option auto (long "seed" <> short 's' <> help "random seed" <> showDefault <> value 42 <> metavar "INT") <*> option auto (long "nsamples" <> short 'n' <> help "number of samples from posterior" <> value 100000 <> metavar "INT" <> showDefault) <*> option probability (long "mhfrac" <> short 'm' <> help "Metropolis-Hastings mutation probability" <> value 0.3 <> metavar "(0,1]" <> showDefault) <*> argument str (metavar "INPUT") <*> argument str (metavar "PROPS") <*> argument str (metavar "TREE") <*> strOption (long "dot" <> short 'd' <> help "draw graph of phylogeny in dot format" <> value "" <> metavar "PATH") probability = eitherReader $ \arg -> case reads arg of [(r, "")] -> if r <= 1 && r > 0 then Right r else Left "mhfrac not a valid probability" _ -> Left "mhfrac not a valid probability" run opts = do setStdGen . mkStdGen $ seed opts (hdr : lines) <- lines <$> readFile (input opts) let parsed = map (map dbl . tail . words) lines dbl = round . read :: String -> Int ((ps, cl), _) <- foldl1' (\a c -> if mml a < mml c then a else c) . take (nsamples opts) <$> mh (mhfrac opts) (model parsed) writeFile (propsPath opts) . unlines $ map (intercalate "," . map show) ps writeFile (clusterPath opts) . unlines $ map show cl when (dotPath opts /= "") $ drawGraph (dotPath opts) ps cl where mml ((ps, cl), lik) = sum' (sum' (log . (+ 1))) ps + sum' (log . (+ 1)) tab - sum' stirling tab - ln lik where tab = tabulate cl sum' f = sum . map f