{"text": "{-# LANGUAGE CPP\n , GADTs\n , KindSignatures\n , TypeOperators\n , TypeFamilies\n , EmptyCase\n , DataKinds\n , PolyKinds\n , ExistentialQuantification\n , FlexibleContexts\n , OverloadedStrings\n #-}\n\n{-# OPTIONS_GHC -Wall -fwarn-tabs #-}\n\nmodule Language.Hakaru.Sample where\n\nimport Numeric.SpecFunctions (logFactorial)\nimport qualified Data.Number.LogFloat as LF\nimport qualified Math.Combinatorics.Exact.Binomial as EB\n-- import qualified Numeric.Integration.TanhSinh as TS\nimport qualified System.Random.MWC as MWC\nimport qualified System.Random.MWC.CondensedTable as MWC\nimport qualified System.Random.MWC.Distributions as MWCD\n\nimport qualified Data.Vector as V\nimport Data.STRef\nimport Data.Sequence (Seq)\nimport qualified Data.Foldable as F\nimport qualified Data.List.NonEmpty as L\nimport Data.List.NonEmpty (NonEmpty(..))\nimport Data.Maybe (fromMaybe)\n\n#if __GLASGOW_HASKELL__ < 710\nimport Control.Applicative (Applicative(..), (<$>))\n#endif\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.Identity\nimport Control.Monad.Trans.Maybe\nimport Control.Monad.State.Strict\nimport qualified Data.IntMap as IM\n\nimport Data.Number.Nat (fromNat)\nimport Data.Number.Natural (fromNatural, fromNonNegativeRational, Natural, unsafeNatural)\nimport Language.Hakaru.Types.DataKind\nimport Language.Hakaru.Types.Coercion\nimport Language.Hakaru.Types.Sing\nimport Language.Hakaru.Types.HClasses\nimport Language.Hakaru.Syntax.IClasses\nimport Language.Hakaru.Syntax.TypeOf\nimport Language.Hakaru.Syntax.Value\nimport Language.Hakaru.Syntax.Reducer\nimport Language.Hakaru.Syntax.Datum\nimport Language.Hakaru.Syntax.DatumCase\nimport Language.Hakaru.Syntax.AST\nimport Language.Hakaru.Syntax.ABT\n\ndata EAssoc =\n forall a. EAssoc {-# UNPACK #-} !(Variable a) !(Value a)\n\nnewtype Env = Env (IM.IntMap EAssoc)\n\nemptyEnv :: Env\nemptyEnv = Env IM.empty\n\nupdateEnv :: EAssoc -> Env -> Env\nupdateEnv v@(EAssoc x _) (Env xs) =\n Env $ IM.insert (fromNat $ varID x) v xs\n\nupdateEnvs\n :: List1 Variable xs\n -> List1 Value xs\n -> Env\n -> Env\nupdateEnvs Nil1 Nil1 env = env\nupdateEnvs (Cons1 x xs) (Cons1 y ys) env =\n updateEnvs xs ys (updateEnv (EAssoc x y) env)\n\nlookupVar :: Variable a -> Env -> Maybe (Value a)\nlookupVar x (Env env) = do\n EAssoc x' e' <- IM.lookup (fromNat $ varID x) env\n Refl <- varEq x x'\n return e'\n\n---------------------------------------------------------------\n\n-- Makes use of Atkinson's algorithm as described in:\n-- Monte Carlo Statistical Methods pg. 55\n--\n-- Further discussion at:\n-- http://www.johndcook.com/blog/2010/06/14/generating-poisson-random-values/\npoisson_rng :: Double -> MWC.GenIO -> IO Int\npoisson_rng lambda g' = make_poisson g'\n where\n smu = sqrt lambda\n b = 0.931 + 2.53*smu\n a = -0.059 + 0.02483*b\n vr = 0.9277 - 3.6224/(b - 2)\n arep = 1.1239 + 1.1368/(b - 3.4)\n lnlam = log lambda\n\n make_poisson :: MWC.GenIO -> IO Int\n make_poisson g = do\n u <- MWC.uniformR (-0.5,0.5) g\n v <- MWC.uniformR (0,1) g\n let us = 0.5 - abs u\n k = floor $ (2*a / us + b)*u + lambda + 0.43\n case () of\n () | us >= 0.07 && v <= vr -> return k\n () | k < 0 -> make_poisson g\n () | us <= 0.013 && v > us -> make_poisson g\n () | accept_region us v k -> return k\n _ -> make_poisson g\n\n accept_region :: Double -> Double -> Int -> Bool\n accept_region us v k =\n log (v * arep / (a/(us*us)+b))\n <=\n -lambda + fromIntegral k * lnlam - logFactorial k\n\n\nnormalize :: [Value 'HProb] -> (LF.LogFloat, Double, [Double])\nnormalize [] = (0, 0, [])\nnormalize [(VProb x)] = (x, 1, [1])\nnormalize xs = (m, y, ys)\n where\n xs' = map (\\(VProb x) -> x) xs\n m = maximum xs'\n ys = [ LF.fromLogFloat (x/m) | x <- xs' ]\n y = sum ys\n\n\nnormalizeVector\n :: Value ('HArray 'HProb) -> (LF.LogFloat, Double, V.Vector Double)\nnormalizeVector (VArray xs) =\n let xs' = V.map (\\(VProb x) -> x) xs in\n case V.length xs of\n 0 -> (0, 0, V.empty)\n 1 -> (V.unsafeHead xs', 1, V.singleton 1)\n _ ->\n let m = V.maximum xs'\n ys = V.map (\\x -> LF.fromLogFloat (x/m)) xs'\n y = V.sum ys\n in (m, y, ys)\n\n---------------------------------------------------------------\n\nrunEvaluate\n :: (ABT Term abt)\n => abt '[] a\n -> Value a\nrunEvaluate prog = evaluate prog emptyEnv\n\nevaluate\n :: (ABT Term abt)\n => abt '[] a\n -> Env\n -> Value a\nevaluate e env = caseVarSyn e (evaluateVar env) (flip evaluateTerm env)\n\nevaluateVar :: Env -> Variable a -> Value a\nevaluateVar env v =\n case lookupVar v env of\n Nothing -> error \"variable not found!\"\n Just a -> a\n\nevaluateTerm\n :: (ABT Term abt)\n => Term abt a\n -> Env\n -> Value a\nevaluateTerm t env =\n case t of\n o :$ es -> evaluateSCon o es env\n NaryOp_ o es -> evaluateNaryOp o es env\n Literal_ v -> evaluateLiteral v\n Empty_ _ -> evaluateEmpty\n Array_ n es -> evaluateArray n es env\n ArrayLiteral_ es -> VArray . V.fromList $ map (flip evaluate env) es\n Bucket b e rs -> evaluateBucket b e rs env\n Datum_ d -> evaluateDatum d env\n Case_ o es -> evaluateCase o es env\n Superpose_ es -> evaluateSuperpose es env\n Reject_ _ -> VMeasure $ \\_ _ -> return Nothing\n\nevaluateSCon\n :: (ABT Term abt)\n => SCon args a\n -> SArgs abt args\n -> Env\n -> Value a\nevaluateSCon Lam_ (e1 :* End) env =\n caseBind e1 $ \\x e1' ->\n VLam $ \\v -> evaluate e1' (updateEnv (EAssoc x v) env)\nevaluateSCon App_ (e1 :* e2 :* End) env =\n case evaluate e1 env of\n VLam f -> f (evaluate e2 env)\nevaluateSCon Let_ (e1 :* e2 :* End) env =\n let v = evaluate e1 env\n in caseBind e2 $ \\x e2' ->\n evaluate e2' (updateEnv (EAssoc x v) env)\nevaluateSCon (CoerceTo_ c) (e1 :* End) env =\n coerceTo c $ evaluate e1 env\nevaluateSCon (UnsafeFrom_ c) (e1 :* End) env =\n coerceFrom c $ evaluate e1 env\nevaluateSCon (PrimOp_ o) es env = evaluatePrimOp o es env\nevaluateSCon (ArrayOp_ o) es env = evaluateArrayOp o es env\nevaluateSCon (MeasureOp_ m) es env = evaluateMeasureOp m es env\nevaluateSCon Dirac (e1 :* End) env =\n VMeasure $ \\p _ -> return $ Just (evaluate e1 env, p)\nevaluateSCon MBind (e1 :* e2 :* End) env =\n case evaluate e1 env of\n VMeasure m1 -> VMeasure $ \\ p g -> do\n x <- m1 p g\n case x of\n Nothing -> return Nothing\n Just (a, p') ->\n caseBind e2 $ \\x' e2' ->\n case evaluate e2' (updateEnv (EAssoc x' a) env) of\n VMeasure y -> y p' g\n\nevaluateSCon Plate (n :* e2 :* End) env =\n case evaluate n env of\n VNat n' -> caseBind e2 $ \\x e' ->\n VMeasure $ \\(VProb p) g -> runMaybeT $ do\n (v', ps) <- fmap V.unzip . V.mapM (performMaybe g) $\n V.generate (fromInteger $ fromNatural n') $ \\v ->\n evaluate e' $\n updateEnv (EAssoc x . VNat $ intToNatural v) env\n return\n ( VArray v'\n , VProb $ p * V.product (V.map (\\(VProb y) -> y) ps)\n )\n where\n performMaybe\n :: MWC.GenIO\n -> Value ('HMeasure a)\n -> MaybeT IO (Value a, Value 'HProb)\n performMaybe g (VMeasure m) = MaybeT $ m (VProb 1) g\n\nevaluateSCon Chain (n :* s :* e :* End) env =\n case (evaluate n env, evaluate s env) of\n (VNat n', start) ->\n caseBind e $ \\x e' ->\n let s' = VLam $ \\v -> evaluate e' (updateEnv (EAssoc x v) env) in\n VMeasure (\\(VProb p) g -> runMaybeT $ do\n (evaluates, sout) <- runStateT (replicateM (unsafeInt n') $ convert g s') start\n let (v', ps) = unzip evaluates\n bodyType :: Sing ('HMeasure (HPair a b)) -> Sing ('HArray a)\n bodyType = SArray . fst . sUnPair . sUnMeasure\n return\n ( VDatum $ dPair_ (bodyType $ caseBind e (const typeOf)) (typeOf s)\n (VArray . V.fromList $ v') sout\n , VProb $ p * product (map (\\(VProb y) -> y) ps)\n ))\n where\n convert\n :: MWC.GenIO\n -> Value (s ':-> 'HMeasure (HPair a s))\n -> StateT (Value s) (MaybeT IO) (Value a, Value 'HProb)\n convert g (VLam f) = StateT $ \\s' ->\n case f s' of\n VMeasure f' -> do\n (as'', p') <- MaybeT (f' (VProb 1) g)\n let (a, s'') = unPair as''\n return ((a, p'), s'')\n\n unPair :: Value (HPair a b) -> (Value a, Value b)\n unPair (VDatum (Datum \"pair\" _typ\n (Inl (Et (Konst a)\n (Et (Konst b) Done))))) = (a, b)\n unPair x = case x of {}\n\nevaluateSCon (Summate hd hs) (e1 :* e2 :* e3 :* End) env =\n case (evaluate e1 env, evaluate e2 env) of\n (lo, hi) ->\n caseBind e3 $ \\x e3' ->\n foldl (\\t i ->\n evalOp (Sum hs) t $\n evaluate e3' (updateEnv (EAssoc x i) env))\n (identityElement $ Sum hs)\n (enumFromUntilValue hd lo hi)\n\nevaluateSCon (Product hd hs) (e1 :* e2 :* e3 :* End) env =\n case (evaluate e1 env, evaluate e2 env) of\n (lo, hi) ->\n caseBind e3 $ \\x e3' ->\n foldl (\\t i ->\n evalOp (Prod hs) t $\n evaluate e3' (updateEnv (EAssoc x i) env))\n (identityElement $ Prod hs)\n (enumFromUntilValue hd lo hi)\n\nevaluateSCon s _ _ = error $ \"TODO: evaluateSCon{\" ++ show s ++ \"}\"\n\nevaluatePrimOp\n :: ( ABT Term abt, typs ~ UnLCs args, args ~ LCs typs)\n => PrimOp typs a\n -> SArgs abt args\n -> Env\n -> Value a\nevaluatePrimOp Not (e1 :* End) env = \n case evaluate e1 env of \n VDatum a -> if a == dTrue\n then VDatum dFalse\n else VDatum dTrue\n\nevaluatePrimOp Pi End _ = VProb . LF.logFloat $ pi\nevaluatePrimOp Cos (e1 :* End) env =\n case evaluate e1 env of\n VReal v1 -> VReal . cos $ v1\n\nevaluatePrimOp Sin (e1 :* End) env =\n case evaluate e1 env of\n VReal v1 -> VReal . sin $ v1\n\nevaluatePrimOp Tan (e1 :* End) env =\n case evaluate e1 env of\n VReal v1 -> VReal . tan $ v1\n\nevaluatePrimOp RealPow (e1 :* e2 :* End) env =\n case (evaluate e1 env, evaluate e2 env) of\n (VProb v1, VReal v2) -> VProb $ LF.pow v1 v2\n\nevaluatePrimOp Choose (e1 :* e2 :* End) env =\n case (evaluate e1 env, evaluate e2 env) of\n (VNat v1, VNat v2) -> VNat $ EB.choose v1 v2\n \nevaluatePrimOp Exp (e1 :* End) env =\n case evaluate e1 env of\n VReal v1 -> VProb . LF.logToLogFloat $ v1\n\nevaluatePrimOp Log (e1 :* End) env =\n case evaluate e1 env of\n VProb v1 -> VReal . LF.logFromLogFloat $ v1\n\nevaluatePrimOp (Infinity h) End _ =\n case h of\n HIntegrable_Nat -> error \"Can not evaluate infinity for natural numbers\"\n HIntegrable_Prob -> VProb $ LF.logFloat LF.infinity\n\nevaluatePrimOp (Equal _) (e1 :* e2 :* End) env = (VDatum . dBool) $ evaluate e1 env == evaluate e2 env\n\nevaluatePrimOp (Less _) (e1 :* e2 :* End) env =\n case (evaluate e1 env, evaluate e2 env) of\n (VNat v1, VNat v2) -> VDatum $ if v1 < v2 then dTrue else dFalse\n (VInt v1, VInt v2) -> VDatum $ if v1 < v2 then dTrue else dFalse\n (VProb v1, VProb v2) -> VDatum $ if v1 < v2 then dTrue else dFalse\n (VReal v1, VReal v2) -> VDatum $ if v1 < v2 then dTrue else dFalse\n _ -> error \"TODO: evaluatePrimOp{Less}\"\nevaluatePrimOp (NatPow _) (e1 :* e2 :* End) env = \n case evaluate e2 env of\n VNat v2 ->\n let v2' = fromNatural v2 in\n case evaluate e1 env of\n VNat v1 -> VNat (v1 ^ v2')\n VInt v1 -> VInt (v1 ^ v2')\n VProb v1 -> VProb (v1 ^ v2')\n VReal v1 -> VReal (v1 ^ v2')\n _ -> error \"NatPow should always return some kind of number\"\nevaluatePrimOp (Negate _) (e1 :* End) env = \n case evaluate e1 env of\n VInt v -> VInt (negate v)\n VReal v -> VReal (negate v)\n v -> case v of {}\nevaluatePrimOp (Abs _) (e1 :* End) env =\n case evaluate e1 env of\n VInt v -> VNat . unsafeNatural $ abs v\n VReal v -> VProb . LF.logFloat $ abs v\n v -> case v of {}\nevaluatePrimOp (Recip _) (e1 :* End) env = \n case evaluate e1 env of\n VProb v -> VProb (recip v)\n VReal v -> VReal (recip v)\n v -> case v of {}\nevaluatePrimOp (NatRoot _) (e1 :* e2 :* End) env =\n case (evaluate e1 env, evaluate e2 env) of\n (VProb v1, VNat v2) -> VProb $ LF.pow v1 (recip . fromIntegral $ v2)\n v -> case v of {} \n\nevaluatePrimOp (Floor) (e1 :* End) env =\n case (evaluate e1 env) of\n VProb v1 -> VNat (floor (LF.fromLogFloat v1))\n\nevaluatePrimOp prim _ _ =\n error (\"TODO: evaluatePrimOp{\" ++ show prim ++ \"}\")\n\nevaluateArrayOp\n :: ( ABT Term abt\n , typs ~ UnLCs args\n , args ~ LCs typs)\n => ArrayOp typs a\n -> SArgs abt args\n -> Env\n -> Value a\nevaluateArrayOp (Index _) = \\(e1 :* e2 :* End) env ->\n case (evaluate e1 env, evaluate e2 env) of\n (VArray v, VNat n) -> v V.! unsafeInt n\n\nevaluateArrayOp (Size _) = \\(e1 :* End) env ->\n case evaluate e1 env of\n VArray v -> VNat . intToNatural $ V.length v\n\nevaluateArrayOp (Reduce _) = \\(e1 :* e2 :* e3 :* End) env ->\n case ( evaluate e1 env\n , evaluate e2 env\n , evaluate e3 env) of\n (f, a, VArray v) -> V.foldl' (lam2 f) a v\n\nevaluateMeasureOp\n :: ( ABT Term abt\n , typs ~ UnLCs args\n , args ~ LCs typs)\n => MeasureOp typs a\n -> SArgs abt args\n -> Env\n -> Value ('HMeasure a)\n\nevaluateMeasureOp Lebesgue = \\(e1 :* e2 :* End) env ->\n case (evaluate e1 env, evaluate e2 env) of\n (VReal v1, VReal v2) | v1 < v2 ->\n VMeasure $ \\(VProb p) g ->\n case (isInfinite v1, isInfinite v2) of\n (False, False) -> do\n x <- MWC.uniformR (v1, v2) g\n return $ Just (VReal $ x,\n VProb $ p * LF.logFloat (v2 - v1))\n (False, True) -> do\n u <- MWC.uniform g\n let l = log u\n let n = -l\n return $ Just (VReal $ v1 + n,\n VProb $ p * LF.logToLogFloat n)\n (True, False) -> do\n u <- MWC.uniform g\n let l = log u\n let n = -l\n return $ Just (VReal $ v2 - n,\n VProb $ p * LF.logToLogFloat n)\n (True, True) -> do\n (u,b) <- MWC.uniform g\n let l = log u\n let n = -l\n return $ Just (VReal $ if b then n else l,\n VProb $ p * 2 * LF.logToLogFloat n)\n (VReal _, VReal _) -> error \"Lebesgue with length 0 or flipped endpoints\"\n\nevaluateMeasureOp Counting = \\End _ ->\n VMeasure $ \\(VProb p) g -> do\n let success = LF.logToLogFloat (-3 :: Double)\n let pow x y = LF.logToLogFloat (LF.logFromLogFloat x *\n (fromIntegral y :: Double))\n u' <- MWCD.geometric0 (LF.fromLogFloat success) g\n let u = toInteger u'\n b <- MWC.uniform g\n return $ Just\n ( VInt $ if b then -1-u else u\n , VProb $ p * 2 / pow (1-success) u / success)\n\nevaluateMeasureOp Categorical = \\(e1 :* End) env ->\n VMeasure $ \\p g -> do\n let (_,y,ys) = normalizeVector (evaluate e1 env)\n if not (y > (0::Double)) -- TODO: why not use @y <= 0@ ??\n then error \"Categorical needs positive weights\"\n else do\n u <- MWC.uniformR (0, y) g\n return $ Just\n ( VNat\n . intToNatural\n . fromMaybe 0\n . V.findIndex (u <=) \n . V.scanl1' (+)\n $ ys\n , p)\n\nevaluateMeasureOp Uniform = \\(e1 :* e2 :* End) env ->\n case (evaluate e1 env, evaluate e2 env) of\n (VReal v1, VReal v2) -> VMeasure $ \\p g -> do\n x <- MWC.uniformR (v1, v2) g\n return $ Just (VReal x, p)\n\nevaluateMeasureOp Normal = \\(e1 :* e2 :* End) env ->\n case (evaluate e1 env, evaluate e2 env) of \n (VReal v1, VProb v2) -> VMeasure $ \\ p g -> do\n x <- MWCD.normal v1 (LF.fromLogFloat v2) g\n return $ Just (VReal x, p)\n\nevaluateMeasureOp Poisson = \\(e1 :* End) env ->\n case evaluate e1 env of\n VProb v1 -> VMeasure $ \\ p g -> do\n x <- MWC.genFromTable (MWC.tablePoisson (LF.fromLogFloat v1)) g\n return $ Just (VNat $ intToNatural x, p)\n\nevaluateMeasureOp Gamma = \\(e1 :* e2 :* End) env ->\n case (evaluate e1 env, evaluate e2 env) of \n (VProb v1, VProb v2) -> VMeasure $ \\ p g -> do\n x <- MWCD.gamma (LF.fromLogFloat v1) (LF.fromLogFloat v2) g\n return $ Just (VProb $ LF.logFloat x, p)\n\nevaluateMeasureOp Beta = \\(e1 :* e2 :* End) env ->\n case (evaluate e1 env, evaluate e2 env) of \n (VProb v1, VProb v2) -> VMeasure $ \\ p g -> do\n x <- MWCD.beta (LF.fromLogFloat v1) (LF.fromLogFloat v2) g\n return $ Just (VProb $ LF.logFloat x, p)\n\nevaluateNaryOp\n :: (ABT Term abt)\n => NaryOp a -> Seq (abt '[] a) -> Env -> Value a\nevaluateNaryOp s es =\n F.foldr (evalOp s) (identityElement s) . mapEvaluate es\n\nidentityElement :: NaryOp a -> Value a\nidentityElement And = VDatum dTrue\nidentityElement (Sum HSemiring_Nat) = VNat 0\nidentityElement (Sum HSemiring_Int) = VInt 0\nidentityElement (Sum HSemiring_Prob) = VProb 0\nidentityElement (Sum HSemiring_Real) = VReal 0\nidentityElement (Prod HSemiring_Nat) = VNat 1\nidentityElement (Prod HSemiring_Int) = VInt 1\nidentityElement (Prod HSemiring_Prob) = VProb 1\nidentityElement (Prod HSemiring_Real) = VReal 1\nidentityElement (Max HOrd_Prob) = VProb 0\nidentityElement (Max HOrd_Real) = VReal LF.negativeInfinity\nidentityElement (Min HOrd_Prob) = VProb (LF.logFloat LF.infinity)\nidentityElement (Min HOrd_Real) = VReal LF.infinity\nidentityElement _ = error \"Missing identity elements?\"\n\n\nevalOp\n :: NaryOp a -> Value a -> Value a -> Value a\nevalOp And (VDatum a) (VDatum b) \n | a == dTrue && b == dTrue = VDatum dTrue\n | otherwise = VDatum dFalse\nevalOp (Sum HSemiring_Nat) (VNat a) (VNat b) = VNat (a + b)\nevalOp (Sum HSemiring_Int) (VInt a) (VInt b) = VInt (a + b)\nevalOp (Sum HSemiring_Prob) (VProb a) (VProb b) = VProb (a + b)\nevalOp (Sum HSemiring_Real) (VReal a) (VReal b) = VReal (a + b)\nevalOp (Prod HSemiring_Nat) (VNat a) (VNat b) = VNat (a * b)\nevalOp (Prod HSemiring_Int) (VInt a) (VInt b) = VInt (a * b) \nevalOp (Prod HSemiring_Prob) (VProb a) (VProb b) = VProb (a * b) \nevalOp (Prod HSemiring_Real) (VReal a) (VReal b) = VReal (a * b)\nevalOp (Max HOrd_Prob) (VProb a) (VProb b) = VProb (max a b)\nevalOp (Max HOrd_Real) (VReal a) (VReal b) = VReal (max a b)\nevalOp (Min HOrd_Prob) (VProb a) (VProb b) = VProb (min a b) \nevalOp (Min HOrd_Real) (VReal a) (VReal b) = VReal (min a b) \n\nevalOp op _ _ =\n error (\"TODO: evalOp{\" ++ show op ++ \"}\")\n\nmapEvaluate\n :: (ABT Term abt)\n => Seq (abt '[] a) -> Env -> Seq (Value a)\nmapEvaluate es env = fmap (flip evaluate env) es\n\n\nevaluateLiteral :: Literal a -> Value a\nevaluateLiteral (LNat n) = VNat . fromInteger $ fromNatural n -- TODO: catch overflow errors\nevaluateLiteral (LInt n) = VInt $ fromInteger n -- TODO: catch overflow errors\nevaluateLiteral (LProb n) = VProb . fromRational $ fromNonNegativeRational n\nevaluateLiteral (LReal n) = VReal $ fromRational n\n\nevaluateEmpty :: Value ('HArray a)\nevaluateEmpty = VArray V.empty\n\nevaluateArray\n :: (ABT Term abt)\n => (abt '[] 'HNat)\n -> (abt '[ 'HNat ] a)\n -> Env\n -> Value ('HArray a)\nevaluateArray n e env =\n case evaluate n env of\n VNat n' -> caseBind e $ \\x e' ->\n VArray $ V.generate (unsafeInt n') $ \\v ->\n let v' = VNat $ intToNatural v in\n evaluate e' (updateEnv (EAssoc x v') env)\n\nevaluateBucket\n :: (ABT Term abt)\n => abt '[] 'HNat\n -> abt '[] 'HNat\n -> Reducer abt '[] a\n -> Env\n -> Value a\nevaluateBucket b e rs env =\n case (evaluate b env, evaluate e env) of\n (VNat b', VNat e') -> runST $ do\n s' <- init Nil1 rs env\n mapM_ (\\i -> accum (VNat i) Nil1 rs s' env) [b' .. e' - 1]\n done s'\n where init :: (ABT Term abt)\n => List1 Value xs\n -> Reducer abt xs a\n -> Env\n -> ST s (VReducer s a)\n init ix (Red_Fanout r1 r2) env =\n VRed_Pair (type_ r1) (type_ r2) <$> init ix r1 env <*> init ix r2 env\n init ix (Red_Index n _ mr) env' =\n let (vars, n') = caseBinds n in\n case evaluate n' (updateEnvs vars ix env') of\n VNat n'' -> VRed_Array <$> V.generateM (fromIntegral n'')\n (\\bb -> init (Cons1 (vnat bb) ix) mr env')\n init ix (Red_Split _ r1 r2) env' =\n VRed_Pair (type_ r1) (type_ r2) <$> init ix r1 env <*> init ix r2 env'\n init _ Red_Nop _ = return VRed_Unit\n init _ (Red_Add h _) _ = VRed_Num <$> newSTRef (identityElement (Sum h))\n\n type_ = typeOfReducer\n\n vnat :: Int -> Value 'HNat\n vnat = VNat . fromIntegral\n\n accum :: (ABT Term abt)\n => Value 'HNat\n -> List1 Value xs\n -> Reducer abt xs a\n -> VReducer s a\n -> Env\n -> ST s ()\n accum n ix (Red_Fanout r1 r2) (VRed_Pair _ _ v1 v2) env' =\n accum n ix r1 v1 env >> accum n ix r2 v2 env'\n accum n ix (Red_Index n' a1 r2) (VRed_Array v) env' =\n caseBind a1 $ \\i a1' ->\n let (vars, a1'') = caseBinds a1'\n VNat ov = evaluate a1''\n (updateEnv (EAssoc i n) (updateEnvs vars ix env'))\n ov' = fromIntegral ov in\n accum n (Cons1 (VNat ov) ix) r2 (v V.! ov') env\n accum n ix (Red_Split bb r1 r2) (VRed_Pair _ _ v1 v2) env' =\n caseBind bb $ \\i b' ->\n let (vars, b'') = caseBinds b' in\n case evaluate b''\n (updateEnv (EAssoc i n) (updateEnvs vars ix env')) of\n VDatum bb -> if bb == dTrue then\n accum n ix r1 v1 env'\n else\n accum n ix r2 v2 env'\n accum n ix (Red_Add h ee) (VRed_Num s) env' =\n caseBind ee $ \\i e' ->\n let (vars, e'') = caseBinds e'\n v = evaluate e''\n (updateEnv (EAssoc i n) (updateEnvs vars ix env')) in\n modifySTRef' s (evalOp (Sum h) v)\n accum _ _ Red_Nop _ _ = return ()\n accum _ _ _ _ _ = error \"Some impossible combinations happened?\"\n\n done :: VReducer s a -> ST s (Value a)\n done (VRed_Num s) = readSTRef s\n done VRed_Unit = return (VDatum dUnit)\n done (VRed_Pair s1 s2 v1 v2) = do\n v1' <- done v1\n v2' <- done v2\n return (VDatum $ dPair_ s1 s2 v1' v2')\n done (VRed_Array v) = VArray <$> V.sequence (V.map done v)\n\nevaluateDatum\n :: (ABT Term abt)\n => Datum (abt '[]) (HData' a)\n -> Env\n -> Value (HData' a)\nevaluateDatum d env = VDatum (fmap11 (flip evaluate env) d)\n\nevaluateCase\n :: forall abt a b\n . (ABT Term abt)\n => abt '[] a\n -> [Branch a abt b]\n -> Env\n -> Value b\nevaluateCase o es env =\n case runIdentity $ matchBranches evaluateDatum' (evaluate o env) es of\n Just (Matched rho b) ->\n evaluate b (extendFromMatch (fromAssocs rho) env)\n _ -> error \"Missing cases in match expression\"\n where\n extendFromMatch :: [Assoc Value] -> Env -> Env\n extendFromMatch [] env' = env'\n extendFromMatch (Assoc x v : xvs) env' =\n extendFromMatch xvs (updateEnv (EAssoc x v) env')\n\n evaluateDatum' :: DatumEvaluator Value Identity\n evaluateDatum' = return . Just . getVDatum\n\n getVDatum :: Value (HData' a) -> Datum Value (HData' a)\n getVDatum (VDatum a) = a\n\nevaluateSuperpose\n :: (ABT Term abt)\n => NonEmpty (abt '[] 'HProb, abt '[] ('HMeasure a))\n -> Env\n -> Value ('HMeasure a)\nevaluateSuperpose ((q, m) :| []) env =\n case evaluate m env of\n VMeasure m' ->\n let VProb q' = evaluate q env\n in VMeasure (\\(VProb p) g -> m' (VProb $ p * q') g)\n \nevaluateSuperpose pms@((_, m) :| _) env =\n case evaluate m env of\n VMeasure m' ->\n let pms' = L.toList pms\n weights = map ((flip evaluate env) . fst) pms'\n (x,y,ys) = normalize weights\n in VMeasure $ \\(VProb p) g ->\n if not (y > (0::Double)) then return Nothing else do\n u <- MWC.uniformR (0, y) g\n case [ m1 | (v,(_,m1)) <- zip (scanl1 (+) ys) pms', u <= v ] of\n m2 : _ ->\n case evaluate m2 env of\n VMeasure m2' -> m2' (VProb $ p * x * LF.logFloat y) g\n [] -> m' (VProb $ p * x * LF.logFloat y) g\n\n----------------------------------------------------------------\n\n-- Useful 'short-hand'\nintToNatural :: Int -> Natural\nintToNatural = unsafeNatural . toInteger\n\nunsafeInt :: Natural -> Int\nunsafeInt = fromInteger . fromNatural\n----------------------------------------------------------- fin.\n", "meta": {"hexsha": "731c659cbe599e4aad10685499af193af90992f8", "size": 26095, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/Language/Hakaru/Sample.hs", "max_stars_repo_name": "vmchale/hakaru", "max_stars_repo_head_hexsha": "78922e13876e449d6812a55a11bf84c8eb0af4d6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-03T08:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T12:12:06.000Z", "max_issues_repo_path": "haskell/Language/Hakaru/Sample.hs", "max_issues_repo_name": "vmchale/hakaru", "max_issues_repo_head_hexsha": "78922e13876e449d6812a55a11bf84c8eb0af4d6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 155, "max_issues_repo_issues_event_min_datetime": "2015-05-05T17:57:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:43:39.000Z", "max_forks_repo_path": "haskell/Language/Hakaru/Sample.hs", "max_forks_repo_name": "vmchale/hakaru", "max_forks_repo_head_hexsha": "78922e13876e449d6812a55a11bf84c8eb0af4d6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2015-01-23T16:25:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T15:09:12.000Z", "avg_line_length": 36.0926694329, "max_line_length": 102, "alphanum_fraction": 0.5384939644, "num_tokens": 8044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.24747697404254204}} {"text": "-- |\n-- Module : Copernicus\n-- Description : Contains the core of the Copernicus project\n-- Copyright : (c) Jonatan H Sundqvist, 2015\n-- License : MIT\n-- Maintainer : Jonatan H Sundqvist\n-- Stability : experimental\n-- Portability : POSIX (not sure)\n-- \n-- Jonatan H Sundqvist\n-- November 25 2014\n--\n\n-- TODO | - Model planetary motion and physics in 2D\n-- - Cartoon earth with gravitational field\n-- - Flexible event handling\n-- - App typeclass (run, manage events, window properties, etc.)\n-- - Lenses\n-- - Options (eg. toggle grid) (cf. 'when')\n-- - UI\n-- - Use types to encode units (eg. SI, radians)\n-- - Move to Cairo (branch?)\n-- - Polymorphic types (not just Floats) (?)\n\n-- SPEC | -\n-- -\n\n\n\nmodule Copernicus where\n\n\n\n---------------------------------------------------------------------------------------------------\n-- We'll need these\n---------------------------------------------------------------------------------------------------\nimport Data.Complex\n-- import Control.Monad (when)\n\nimport Graphics.Gloss.Geometry.Angle (degToRad, radToDeg, normaliseAngle)\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Types\n---------------------------------------------------------------------------------------------------\n-- Make typeclass (mesh, body, bounding box, collision, etc) (?)\n-- type Number a = Floating a -- Real number\ntype Vector = Complex -- TODO: Polymorphic (cf. related TODO item)\ndata Body f = Body (Vector f) (Vector f) (Vector f) deriving Show -- Add argument\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Functions\n---------------------------------------------------------------------------------------------------\nclampAngle :: Float -> Float\nclampAngle = radToDeg . normaliseAngle . degToRad\n\n\n\n--\n-- TODO: Make them change colour when bouncing (?)\nanimate :: (RealFloat f, Floating f) => f -> Body f -> Body f\nanimate t (Body p v a) = collide ground $ Body (parabola t p v a) (v + (t:+0)*a) a\n\twhere ground = 0.0 -- 30+30/2-540/2 (previous hard-coded value)\n\n\n--\nparabola :: (RealFloat f, Floating f) => f -> Vector f -> Vector f -> Vector f -> Vector f\nparabola t p v a = let (px:+py) = p\n (vx:+vy) = v\n (ax:+ay) = a\n in (px + vx*t + 0.5*ax*t**2) :+ (py + vy*t + 0.5*ay*t**2)\n\n\n\n-- collide\n-- Very primitive for now\n-- TODO: Use 'contains' function (Range -> Value -> Bool)\n-- TODO: Don't hard-code bounds (left, right)\n-- TODO: Take bounds of Body into account (don't hard-code that either)\ncollide :: (RealFloat f, Floating f) => f -> Body f -> Body f\ncollide gnd (Body (px:+py) (vx:+vy) a) = Body (px:+py) ((invertIf (\\ _ -> (px <= left) || ( px >= right)) vx) :+ (invertIf (\\ v -> (v < 0) && (py <= gnd)) vy)) a\n\twhere invertIf p v | p v \t = -v\n\t | otherwise = v\n\t (left, right) = (-5, 5) --(15-720/2, 720/2-30/2)\n\n\n\n-- | ETA (estimated time of arrival)\n-- TODO: Rename (eg. timeUntil, solveForT, etc)\n-- TODO: Parabola type (eg. Parabola a v x)\n-- eta :: Acceleration\n\n\n\n-- Utilities (should eventually be moved to separate module or library ----------------------------\n-- Python-style String formatting (eg. keyword interpolation, {0}, customisation, format specs.)\n-- Parsec\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Entry point\n---------------------------------------------------------------------------------------------------", "meta": {"hexsha": "112d95819d6310cb9092e4f6a99638b417691907", "size": 3620, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Copernicus.hs", "max_stars_repo_name": "SwiftsNamesake/Copernicus", "max_stars_repo_head_hexsha": "142b1b6fa0c1a260011beab2bec7d190ed46413f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Copernicus.hs", "max_issues_repo_name": "SwiftsNamesake/Copernicus", "max_issues_repo_head_hexsha": "142b1b6fa0c1a260011beab2bec7d190ed46413f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Copernicus.hs", "max_forks_repo_name": "SwiftsNamesake/Copernicus", "max_forks_repo_head_hexsha": "142b1b6fa0c1a260011beab2bec7d190ed46413f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1509433962, "max_line_length": 161, "alphanum_fraction": 0.4654696133, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24214893705561955}} {"text": "{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, DeriveGeneric, TupleSections, RecordWildCards, TemplateHaskell, RankNTypes, FlexibleContexts #-}\n\nmodule BayesStack.Models.Topic.CitationInfluenceNoTopics\n ( -- * Primitives\n NetData\n , dHypers, dArcs, dItems, dNodeItems, dCitingNodes, dCitedNodes\n , netData\n , HyperParams(..)\n , MState\n , stGammas, stOmegas, stPsis, stCiting, stLambdas\n , CitingUpdateUnit\n , ItemSource(..)\n , CitedNode(..), CitedNodeItem(..)\n , CitingNode(..), CitingNodeItem(..)\n , Citing(..), Cited(..)\n , Item(..), Topic(..), NodeItem(..), Node(..), Arc(..)\n , setupNodeItems\n -- * Initialization\n , verifyNetData, cleanNetData\n , ModelInit\n , randomInitialize\n , model\n , updateUnits\n -- * Diagnostics\n , modelLikelihood\n ) where\n\nimport qualified Data.Vector as V\nimport Statistics.Sample (mean)\n\nimport Prelude hiding (mapM_, sum)\nimport Data.Maybe (fromMaybe)\n\nimport Control.Lens hiding (Setting)\nimport Data.Set (Set)\nimport qualified Data.Set as S\n\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\n\nimport Data.Foldable hiding (product)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (when)\nimport Control.Monad.Trans.State.Strict\nimport Control.Monad.Trans.Writer.Strict\n\nimport Data.Random\nimport Data.Random.Lift (lift)\nimport Data.Random.Distribution.Categorical (categorical)\nimport Numeric.Log hiding (sum)\n\nimport BayesStack.Types\nimport BayesStack.Gibbs\nimport BayesStack.DirMulti\nimport BayesStack.TupleEnum ()\nimport BayesStack.Models.Topic.Types\n\nimport GHC.Generics (Generic)\nimport Data.Binary (Binary)\nimport Control.DeepSeq\n\nat' :: At m => Index m -> IndexedLens' (Index m) m (IxValue m)\nat' i = at i . _fromMaybe\n where _fromMaybe = iso (fromMaybe $ error \"at': Unexpected Nothing\") Just\n\ndata ItemSource = Shared | Own deriving (Show, Eq, Enum, Ord, Generic)\ninstance Binary ItemSource\ninstance NFData ItemSource\n\nnewtype Citing a = Citing a deriving (Show, Eq, Enum, Ord, Generic, NFData)\nnewtype Cited a = Cited a deriving (Show, Eq, Enum, Ord, Generic, NFData)\ninstance Binary a => Binary (Citing a)\ninstance Binary a => Binary (Cited a)\n\ntype CitingNode = Citing Node\ntype CitedNode = Cited Node\ntype CitingNodeItem = Citing NodeItem\ntype CitedNodeItem = Cited NodeItem\n\n-- ^ A directed edge\ndata Arc = Arc { citingNode :: !CitingNode, citedNode :: !CitedNode }\n deriving (Show, Eq, Ord, Generic)\ninstance Binary Arc\n\ndata HyperParams = HyperParams\n { _alphaPsi :: Double\n , _alphaLambda :: Double\n , _alphaOmega :: Double\n , _alphaGammaShared :: Double\n , _alphaGammaOwn :: Double\n , _alphaBetaFG :: Double\n , _alphaBetaBG :: Double\n }\n deriving (Show, Eq, Generic)\ninstance Binary HyperParams\nmakeLenses ''HyperParams \n\ndata NetData = NetData { _dHypers :: !(HyperParams)\n , _dArcs :: !(Set Arc)\n , _dItems :: !(Map Item Double)\n , _dNodeItems :: !(Map NodeItem (Node, Item))\n , _dCitingNodes :: !(Map CitingNode (Set CitedNode))\n -- ^ Maps each citing node to the set of nodes cited by it\n , _dCitedNodes :: !(Map CitedNode (Set CitingNode))\n -- ^ Maps each cited node to the set of nodes citing it\n }\n deriving (Show, Eq, Generic)\ninstance Binary NetData\nmakeLenses ''NetData \n\nnetData :: HyperParams -> Set Arc -> Map Item Double -> Map NodeItem (Node,Item) -> NetData\nnetData hypers arcs items nodeItems =\n NetData { _dHypers = hypers\n , _dArcs = arcs\n , _dItems = items\n , _dNodeItems = nodeItems\n , _dCitingNodes = M.unionsWith S.union\n $ map (\\(Arc a b)->M.singleton a $ S.singleton b)\n $ S.toList arcs\n , _dCitedNodes = M.unionsWith S.union\n $ map (\\(Arc a b)->M.singleton b $ S.singleton a)\n $ S.toList arcs\n }\n\ndCitingNodeItems :: NetData -> Map CitingNodeItem (CitingNode, Item)\ndCitingNodeItems nd =\n M.mapKeys Citing\n $ M.map (\\(n,i)->(Citing n, i))\n $ M.filter (\\(n,i)->Citing n `M.member` (nd^.dCitingNodes))\n $ nd^.dNodeItems\n\nitemsOfCitingNode :: NetData -> CitingNode -> [Item]\nitemsOfCitingNode d (Citing u) =\n map snd $ M.elems $ M.filter (\\(n,_)->n==u) $ d^.dNodeItems\n\nconnectedNodes :: Set Arc -> Set Node\nconnectedNodes arcs =\n S.map ((\\(Cited n)->n) . citedNode) arcs `S.union` S.map ((\\(Citing n)->n) . citingNode) arcs\n\ncleanNetData :: NetData -> NetData\ncleanNetData d =\n let nodesWithItems = S.fromList $ map fst $ M.elems $ d^.dNodeItems\n nodesWithArcs = connectedNodes $ d^.dArcs\n keptNodes = nodesWithItems `S.intersection` nodesWithArcs\n keepArc (Arc (Citing citing) (Cited cited)) =\n citing `S.member` keptNodes && cited `S.member` keptNodes\n go = do dArcs %= S.filter keepArc\n dNodeItems %= M.filter (\\(n,i)->n `S.member` keptNodes)\n in execState go d\n\nverifyNetData :: (Node -> String) -> NetData -> [String]\nverifyNetData showNode d = execWriter $ do\n let nodesWithItems = S.fromList $ map fst $ M.elems $ d^.dNodeItems\n forM_ (d^.dArcs) $ \\(Arc (Citing citing) (Cited cited))->do\n when (cited `S.notMember` nodesWithItems)\n $ tell [showNode cited++\" has arc yet has no items\"]\n when (citing `S.notMember` nodesWithItems)\n $ tell [showNode citing++\" has arc yet has no items\"]\n\n-- Citing Update unit (Shared Taste-like)\ndata CitingUpdateUnit = CitingUpdateUnit { _uuNI :: CitingNodeItem\n , _uuN :: CitingNode\n , _uuX :: Item\n , _uuCites :: Set CitedNode\n , _uuItemWeight :: Double\n }\n deriving (Show, Generic)\ninstance Binary CitingUpdateUnit\nmakeLenses ''CitingUpdateUnit\n\ncitingUpdateUnits :: NetData -> [CitingUpdateUnit]\ncitingUpdateUnits d =\n map (\\(ni,(n,x))->CitingUpdateUnit { _uuNI = ni\n , _uuN = n\n , _uuX = x\n , _uuCites = d^.dCitingNodes . at' n\n , _uuItemWeight = (d ^. dItems . at' x)\n }\n ) $ M.assocs $ dCitingNodeItems d\n\nupdateUnits :: NetData -> [WrappedUpdateUnit MState]\nupdateUnits d = map WrappedUU (citingUpdateUnits d)\n\n-- | Model State \ndata CitingSetting = OwnSetting\n | SharedSetting !CitedNode\n deriving (Show, Eq, Generic)\ninstance Binary CitingSetting\ninstance NFData CitingSetting where\n rnf (OwnSetting) = ()\n rnf (SharedSetting c) = rnf c `seq` ()\n\ndata MState = MState { -- Citing model state\n _stGammas :: !(Map CitingNode (Multinom Int ItemSource))\n , _stOmegas :: !(Map CitingNode (Multinom Int Item))\n , _stPsis :: !(Map CitingNode (Multinom Int CitedNode))\n\n , _stCiting :: !(Map CitingNodeItem CitingSetting)\n\n -- Cited model state\n , _stLambdas :: !(Map CitedNode (Multinom Int Item))\n }\n deriving (Show, Generic)\ninstance Binary MState\nmakeLenses ''MState \n\n-- | Model initialization \ntype ModelInit = Map CitingNodeItem (Setting CitingUpdateUnit)\n\nmodify' :: Monad m => (a -> a) -> StateT a m ()\nmodify' f = do x <- get\n put $! f x\n\nrandomInitializeCiting :: NetData -> ModelInit -> RVar ModelInit\nrandomInitializeCiting d init = execStateT doInit init\n where doInit :: StateT ModelInit RVar ()\n doInit = let unset = M.keysSet (dCitingNodeItems d) `S.difference` M.keysSet init\n in mapM_ (randomInitCitingUU d) (S.toList unset)\n\nrandomInitCitingUU :: NetData -> CitingNodeItem -> StateT ModelInit RVar ()\nrandomInitCitingUU d cni@(Citing ni) =\n let (n,_) = d ^. dNodeItems . at' ni\n in case d ^. dCitingNodes . at' (Citing n) of\n a | S.null a -> do\n modify' $ M.insert cni OwnSetting\n\n citedNodes -> do\n s <- lift $ randomElement [Shared, Own]\n c <- lift $ randomElement $ toList citedNodes\n modify' $ M.insert cni $\n case s of Shared -> SharedSetting c\n Own -> OwnSetting\n\nrandomInitialize :: NetData -> RVar ModelInit\nrandomInitialize d = randomInitializeCiting d M.empty\n\nmodel :: NetData -> ModelInit -> MState\nmodel d citingInit =\n let citingNodes = M.keys $ d^.dCitingNodes\n hp = d^.dHypers\n s = MState { -- Citing model\n _stPsis = let dist n = case d ^. dCitingNodes . at' n . to toList of\n [] -> M.empty\n nodes -> M.singleton n\n $ symDirMulti (hp^.alphaPsi) nodes\n in foldMap dist citingNodes\n , _stGammas = let dist = multinom [ (Shared, hp^.alphaGammaShared)\n , (Own, hp^.alphaGammaOwn) ]\n in foldMap (\\t->M.singleton t dist) citingNodes\n , _stOmegas = let dist = symDirMulti (hp^.alphaOmega) (M.keys $ d^.dItems)\n in foldMap (\\t->M.singleton t dist) citingNodes\n , _stCiting = M.empty\n\n -- Cited model\n , _stLambdas = let dist = symDirMulti (hp^.alphaLambda) (M.keys $ d^.dItems)\n lambdas0 = foldMap (\\n->M.singleton n dist) $ M.keys $ d^.dCitedNodes\n in foldl' (\\dms (n,x)->M.adjust (incMultinom x) (Cited n) dms) lambdas0 (M.elems $ d^.dNodeItems)\n }\n\n initCitingUU :: CitingUpdateUnit -> State MState ()\n initCitingUU uu = do\n let err = error $ \"CitationInference: Initial value for \"++show uu++\" not given\\n\"\n s = maybe err id $ M.lookup (uu^.uuNI) citingInit\n modify' $ setCitingUU uu (Just s)\n\n in execState (mapM_ initCitingUU $ citingUpdateUnits d) s\n\nmodelLikelihood :: MState -> Probability\nmodelLikelihood model =\n product $ (model ^.. stGammas . folded . to likelihood)\n ++ (model ^.. stLambdas . folded . to likelihood)\n ++ (model ^.. stOmegas . folded . to likelihood)\n ++ (model ^.. stPsis . folded . to likelihood)\n\ninstance UpdateUnit CitingUpdateUnit where\n type ModelState CitingUpdateUnit = MState\n type Setting CitingUpdateUnit = CitingSetting\n fetchSetting uu ms = ms ^. stCiting . at' (uu^.uuNI)\n evolveSetting ms uu = categorical $ citingFullCond (setCitingUU uu Nothing ms) uu\n updateSetting uu _ s' = setCitingUU uu (Just s') . setCitingUU uu Nothing\n\ncitingProb :: MState -> CitingUpdateUnit -> Setting CitingUpdateUnit -> Double\ncitingProb st (CitingUpdateUnit {_uuN=n, _uuX=x}) setting =\n let gamma = st ^. stGammas . at' n\n omega = st ^. stOmegas . at' n\n psi = st ^. stPsis . at' n\n in case setting of\n SharedSetting c -> let lambda = st ^. stLambdas . at' c\n in sampleProb gamma Shared\n * sampleProb psi c\n * sampleProb lambda x\n OwnSetting -> sampleProb gamma Own\n * sampleProb omega x\n\ncitingFullCond :: MState -> CitingUpdateUnit -> [(Double, Setting CitingUpdateUnit)]\ncitingFullCond ms uu = map (\\s->(citingProb ms uu s, s)) $ citingDomain ms uu\n\ncitingDomain :: MState -> CitingUpdateUnit -> [Setting CitingUpdateUnit]\ncitingDomain ms uu = do\n s <- [Own, Shared]\n case s of\n Shared -> do c <- uu ^. uuCites . to S.toList\n return $ SharedSetting c\n Own -> do return $ OwnSetting\n\nsetCitingUU :: CitingUpdateUnit -> Maybe (Setting CitingUpdateUnit) -> MState -> MState\nsetCitingUU uu@(CitingUpdateUnit {_uuNI=ni, _uuN=n, _uuX=x}) setting ms = execState go ms\n where\n set = maybe Unset (const Set) setting\n go = case maybe (fetchSetting uu ms) id setting of\n SharedSetting c -> do stPsis . at' n %= setMultinom set c\n stLambdas . at' c %= setMultinom set x\n stGammas . at' n %= setMultinom set Shared\n stCiting . at ni .= setting\n\n OwnSetting -> do stOmegas . at' n %= setMultinom set x\n stGammas . at' n %= setMultinom set Own\n stCiting . at ni .= setting\n ", "meta": {"hexsha": "2b6156d135eb7aa8ea9e862b261e2c652026ab26", "size": 13548, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "network-topic-models/BayesStack/Models/Topic/CitationInfluenceNoTopics.hs", "max_stars_repo_name": "bgamari/bayes-stack", "max_stars_repo_head_hexsha": "020df7bb7263104fdea254e57d6c7daf7806da3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-04-06T22:59:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T12:03:19.000Z", "max_issues_repo_path": "network-topic-models/BayesStack/Models/Topic/CitationInfluenceNoTopics.hs", "max_issues_repo_name": "bgamari/bayes-stack", "max_issues_repo_head_hexsha": "020df7bb7263104fdea254e57d6c7daf7806da3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "network-topic-models/BayesStack/Models/Topic/CitationInfluenceNoTopics.hs", "max_forks_repo_name": "bgamari/bayes-stack", "max_forks_repo_head_hexsha": "020df7bb7263104fdea254e57d6c7daf7806da3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-02-13T06:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-20T14:40:13.000Z", "avg_line_length": 42.4702194357, "max_line_length": 151, "alphanum_fraction": 0.5563182758, "num_tokens": 3404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.23920795741478637}} {"text": "-- |\n-- Copyright: (c) 2020 Tom Westerhout\n-- SPDX-License-Identifier: BSD-3-Clause\n-- Maintainer: Tom Westerhout <14264576+twesterhout@users.noreply.github.com>\n--\n-- High-level wrapper around [PRIMME C\n-- library](https://github.com/primme/primme). /Quote from README/:\n--\n-- @\n-- PRIMME, pronounced as prime, is a high-performance library for computing a few\n-- eigenvalues/eigenvectors, and singular values/vectors. PRIMME is especially\n-- optimized for large, difficult problems. Real symmetric and complex Hermitian\n-- problems, standard @A x = λ x@ and generalized @A x = λ B x@, are supported.\n-- Besides, standard eigenvalue problems with a normal matrix are supported. It\n-- can find largest, smallest, or interior singular/eigenvalues, and can use\n-- preconditioning to accelerate convergence.\n-- @\nmodule Numeric.PRIMME\n ( -- * Defining the matrix\n\n -- | One of the great things about PRIMME library is that it works with\n -- block matrix-vector products (i.e. matrix-matrix products). Following the\n -- example of [vector](https://hackage.haskell.org/package/vector) library,\n -- we define two types for mutable and immutable dense blocks.\n MBlock (..),\n Block (..),\n -- | Now we are can define the \"operator\" we want to diagonalize. Since this\n -- library is meant to be used with rather large matrices, it might very\n -- well be the case that the matrix does not fit into the memory of your\n -- computer (even in sparse format such as CSR). Sometimes, however, we can\n -- define the \"operator\" implicitly, namely, by defining its action on a\n -- vector (or in case of PRIMME on a block of vectors). This is done with\n -- 'PrimmeOperator' type.\n PrimmeOperator,\n\n -- * Choosing what to compute\n\n -- | Having defined a 'PrimmeOperator' we now need to tell PRIMME what to\n -- compute. This is done by constructing a 'PrimmeOptions' object.\n PrimmeOptions (..),\n primmeDefaults,\n finalizeOptions,\n PrimmeTarget (..),\n\n -- * Diagonalizing\n eigh,\n eigh',\n\n -- * Logging\n PrimmeMonitor (..),\n PrimmeInfo (..),\n PrimmeEventInfo (..),\n PrimmeStats (..),\n primmePrettyInfo,\n\n -- * Dense Matrices\n\n -- | The most trivial example of an \"operator\" is of course a square dense\n -- matrix. We thus provide a function which constructs an operator from a\n -- matrix.\n primmeFromDense,\n\n -- * Misc\n getPrimmeVersion,\n PrimmeException (..),\n BlasDatatype (blasTag),\n BlasRealPart,\n BlasDatatypeTag (..),\n )\nwhere\n\nimport Control.Exception.Safe (throw)\nimport Control.Monad (forM_, unless)\nimport Control.Monad.ST (RealWorld)\nimport Data.Complex\nimport Data.Proxy\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as V\nimport Data.Vector.Storable.Mutable (MVector)\nimport qualified Data.Vector.Storable.Mutable as MV\nimport Foreign.C.Types (CInt (..))\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable\nimport qualified Language.C.Inline as C\nimport qualified Language.C.Inline.Unsafe as CU\nimport Numeric.PRIMME.Context\nimport Numeric.PRIMME.Dense\nimport Numeric.PRIMME.Monitor\nimport Numeric.PRIMME.Options\nimport Numeric.PRIMME.Types\nimport Prelude hiding (init)\n\nC.context (C.baseCtx <> primmeCtx)\nC.include \"\"\n\n-- | Diagonalize the operator to find the first few eigenpairs.\neigh ::\n forall a.\n BlasDatatype a =>\n PrimmeOptions ->\n PrimmeOperator a ->\n IO (Vector (BlasRealPart a), Block a, Vector (BlasRealPart a))\neigh options matrix = do\n let dim = pDim options\n numEvals = pNumEvals options\n (evals :: MVector RealWorld (BlasRealPart a)) <- MV.new numEvals\n (evecs :: MVector RealWorld a) <- MV.new (dim * numEvals)\n (rnorms :: MVector RealWorld (BlasRealPart a)) <- MV.new numEvals\n status <-\n MV.unsafeWith evals $ \\evalsPtr ->\n MV.unsafeWith evecs $ \\evecsPtr ->\n MV.unsafeWith rnorms $ \\rnormsPtr ->\n withOptions options matrix $ \\optionsPtr ->\n cPrimme evalsPtr evecsPtr rnormsPtr optionsPtr\n unless (status == 0) $ throwPrimmeError status\n evals' <- V.unsafeFreeze evals\n evecs' <- Block (dim, numEvals) dim <$> V.unsafeFreeze evecs\n rnorms' <- V.unsafeFreeze rnorms\n return (evals', evecs', rnorms')\n\nmkEmptyBlock :: Storable a => Int -> Int -> IO (MBlock RealWorld a)\nmkEmptyBlock rows columns\n | rows <= 0 || columns <= 0 = error $ \"invalid shape specified: \" <> show (rows, columns)\n | otherwise = MBlock (rows, columns) rows <$> MV.new (rows * columns)\n\ncopyBlock :: Storable a => MBlock RealWorld a -> Block a -> IO ()\ncopyBlock dest@(MBlock (r, c) _ _) src@(Block (r', c') _ _)\n | r /= r' || c /= c' = error $ \"block shape mismatch: \" <> show (r, c) <> \" != \" <> show (r', c')\n | otherwise = do\n src' <- unsafeThaw src\n forM_ [0 .. (c - 1)] $ \\i ->\n MV.copy (getColumn i dest) (getColumn i src')\n where\n getColumn :: Storable a => Int -> MBlock RealWorld a -> MVector RealWorld a\n getColumn i (MBlock (rows, _) stride v) = MV.slice (i * stride) rows v\n\nunsafeThaw :: Storable a => Block a -> IO (MBlock RealWorld a)\nunsafeThaw (Block shape stride v) = MBlock shape stride <$> V.unsafeThaw v\n\nunsafeFreeze :: Storable a => MBlock RealWorld a -> IO (Block a)\nunsafeFreeze (MBlock shape stride v) = Block shape stride <$> V.unsafeFreeze v\n\nsliceBlock1 :: Storable a => Int -> Int -> MBlock s a -> MBlock s a\nsliceBlock1 i n (MBlock (r, c) stride v)\n | i < 0 || n < 0 || i + n > c = error $ \"invalid slice: [\" <> show i <> \", \" <> show (i + n) <> \")\"\n | otherwise = MBlock (r, n) stride $ MV.slice (i * stride) (n * stride) v\n\neigh' ::\n forall a.\n BlasDatatype a =>\n PrimmeOptions ->\n MBlock RealWorld a ->\n PrimmeOperator a ->\n IO (Vector (BlasRealPart a), Block a, Vector (BlasRealPart a))\neigh' options init@(MBlock (dim', initSize) _ _) matrix\n | pDim options /= dim' =\n error $\n \"'init' has wrong shape: \"\n <> show (dim', initSize)\n <> \"; expected a block with \"\n <> show (pDim options)\n <> \" rows\"\n | otherwise = do\n let dim = pDim options\n numEvals = pNumEvals options\n evecs@(MBlock (_, _) evecsStride evecsData) <- case initSize < numEvals of\n True -> do\n temp <- mkEmptyBlock dim numEvals\n copyBlock (sliceBlock1 0 initSize temp) =<< unsafeFreeze init\n return temp\n False -> return init\n (evals :: MVector RealWorld (BlasRealPart a)) <- MV.new numEvals\n (rnorms :: MVector RealWorld (BlasRealPart a)) <- MV.new numEvals\n status <-\n MV.unsafeWith evals $ \\evalsPtr ->\n MV.unsafeWith evecsData $ \\evecsPtr ->\n MV.unsafeWith rnorms $ \\rnormsPtr ->\n withOptions options matrix $ \\optionsPtr -> do\n let c_initSize = fromIntegral initSize\n c_evecsStride = fromIntegral evecsStride\n [C.block| void {\n $(primme_params* optionsPtr)->initSize = $(int c_initSize);\n $(primme_params* optionsPtr)->ldevecs = $(PRIMME_INT c_evecsStride);\n } |]\n cPrimme evalsPtr evecsPtr rnormsPtr optionsPtr\n unless (status == 0) $ throwPrimmeError status\n evals' <- V.unsafeFreeze evals\n evecs' <- unsafeFreeze $ sliceBlock1 0 numEvals evecs\n rnorms' <- V.unsafeFreeze rnorms\n return (evals', evecs', rnorms')\n\nthrowPrimmeError :: CInt -> IO a\nthrowPrimmeError c = case (- c) of\n 0 -> error \"no error\"\n 3 -> throw PrimmeMaximumIterationsReached\n 40 -> throw PrimmeLapackFailure\n 41 -> throw PrimmeUserFailure\n _ -> throw $ PrimmeOtherFailure c\n\nforeign import ccall \"sprimme\"\n sprimme :: Ptr Float -> Ptr Float -> Ptr Float -> Ptr Cprimme_params -> IO CInt\n\nforeign import ccall \"dprimme\"\n dprimme :: Ptr Double -> Ptr Double -> Ptr Double -> Ptr Cprimme_params -> IO CInt\n\nforeign import ccall \"cprimme\"\n cprimme :: Ptr Float -> Ptr (Complex Float) -> Ptr Float -> Ptr Cprimme_params -> IO CInt\n\nforeign import ccall \"zprimme\"\n zprimme :: Ptr Double -> Ptr (Complex Double) -> Ptr Double -> Ptr Cprimme_params -> IO CInt\n\ncPrimme ::\n forall a.\n (BlasDatatype a) =>\n Ptr (BlasRealPart a) ->\n Ptr a ->\n Ptr (BlasRealPart a) ->\n Ptr Cprimme_params ->\n IO CInt\ncPrimme = case blasTag (Proxy :: Proxy a) of\n FloatTag -> sprimme\n DoubleTag -> dprimme\n ComplexFloatTag -> cprimme\n ComplexDoubleTag -> zprimme\n\ngetPrimmeVersion :: (Int, Int)\ngetPrimmeVersion =\n ( fromIntegral [CU.pure| int { PRIMME_VERSION_MAJOR } |],\n fromIntegral [CU.pure| int { PRIMME_VERSION_MINOR } |]\n )\n", "meta": {"hexsha": "2dd207ee059f6d8831b5e66664bed69b190962d9", "size": 8485, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/PRIMME.hs", "max_stars_repo_name": "twesterhout/primme-hs", "max_stars_repo_head_hexsha": "c5e7ad4fd650cf88324861fcad2c591f84f8ea5f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-30T12:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T12:18:33.000Z", "max_issues_repo_path": "src/Numeric/PRIMME.hs", "max_issues_repo_name": "twesterhout/primme-hs", "max_issues_repo_head_hexsha": "c5e7ad4fd650cf88324861fcad2c591f84f8ea5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/PRIMME.hs", "max_forks_repo_name": "twesterhout/primme-hs", "max_forks_repo_head_hexsha": "c5e7ad4fd650cf88324861fcad2c591f84f8ea5f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7316017316, "max_line_length": 101, "alphanum_fraction": 0.6663523866, "num_tokens": 2443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2367841702786077}} {"text": "{-# LANGUAGE AllowAmbiguousTypes, CPP, ConstraintKinds, DataKinds,\n FlexibleInstances, GADTs, MultiParamTypeClasses, PolyKinds,\n QuantifiedConstraints, TypeFamilyDependencies, TypeOperators,\n UndecidableInstances #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n-- | The class defining dual components of dual numbers and related classes,\n-- type families, constraints and instances. This is a low-level API\n-- used to define types and operations in \"HordeAd.Core.DualNumber\"\n-- that is the high-level API.\nmodule HordeAd.Core.DualClass\n ( IsPrimalWithScalar, IsPrimalAndHasFeatures, IsScalar, HasDelta\n , DMode(..), Dual, IsPrimal(..), HasRanks(..)\n , HasVariables(..) -- use sparringly\n ) where\n\nimport Prelude\n\nimport qualified Data.Array.Convert\nimport qualified Data.Array.Dynamic as OTB\nimport qualified Data.Array.DynamicS as OT\nimport qualified Data.Array.Shaped as OSB\nimport qualified Data.Array.ShapedS as OS\nimport Data.MonoTraversable (Element, MonoFunctor)\nimport Data.Proxy (Proxy)\nimport qualified Data.Strict.Vector as Data.Vector\nimport qualified Data.Vector.Generic as V\nimport GHC.TypeLits (KnownNat, natVal, type (+))\nimport Numeric.LinearAlgebra (Matrix, Numeric, Vector)\nimport qualified Numeric.LinearAlgebra as HM\n\nimport HordeAd.Internal.Delta\n\n-- * Abbreviations to export (not used anywhere below)\n\n-- | The intended semantics (not fully enforced by the constraint in isolation)\n-- is that the second type is the primal component of a dual number type\n-- at an unknown rank, with the given differentiation mode\n-- and underlying scalar.\ntype IsPrimalWithScalar (d :: DMode) a r =\n (ScalarOf a ~ r, IsPrimal d a, HasVariables a)\n\n-- | A shorthand for a useful set of constraints.\ntype IsPrimalAndHasFeatures (d :: DMode) a r =\n (IsPrimalWithScalar d a r, RealFloat a, MonoFunctor a, Element a ~ r)\n\n-- | A mega-shorthand for a bundle of connected type constraints.\n-- The @Scalar@ in the name means that the second argument is the underlying\n-- scalar type of a well behaved (wrt the differentiation mode in the first\n-- argument) collection of primal and dual components of dual numbers.\ntype IsScalar (d :: DMode) r =\n ( HasRanks d r, Ord r, Numeric r, Show r\n , IsPrimalAndHasFeatures d r r\n , IsPrimalAndHasFeatures d (Vector r) r\n , IsPrimalAndHasFeatures d (Matrix r) r\n , IsPrimalAndHasFeatures d (OT.Array r) r\n -- This fragment is for @OS.Array@ and it's irregular, because we can't\n -- mention @sh@ and so fully apply the type constructor.\n , IsPrimalS d r -- TODO: Floating (OS.Array sh r), MonoFunctor\n )\n\n-- | Is a scalar and will be used to compute gradients via delta-expressions.\ntype HasDelta r = ( IsScalar 'DModeGradient r\n , Dual 'DModeGradient r ~ Delta0 r )\n\n\n-- * Class definitions\n\n-- | The enumeration of all possible differentiation (and more generally,\n-- computation with dual numbers) schemes.\ndata DMode =\n DModeGradient\n | DModeDerivative\n\n-- | The type family that enumerates all possible \"ranks\"\n-- for each differentiation mode.\n-- The second type argument is meant to be the primal component\n-- of dual numbers. The result is the dual component.\n--\n-- Rank 0 is special because, in derivatives mode, the dual component\n-- is not the primal component wrapped in a datatype or newtype constructor.\n-- This makes impossible a representation of primal and dual components as\n-- the primal plus the type constructor for creating the dual.\n--\n-- Rank S is special, because of the extra type parameter @sh@ representing\n-- a shape. This is another obstacle to a dual number representation via\n-- a single-argument type constructor.\ntype family Dual (d :: DMode) a = result | result -> d a where\n Dual 'DModeGradient Double = Delta0 Double\n Dual 'DModeGradient Float = Delta0 Float\n Dual 'DModeGradient (Vector r) = Delta1 r\n Dual 'DModeGradient (Matrix r) = Delta2 r\n Dual 'DModeGradient (OT.Array r) = DeltaX r\n Dual 'DModeGradient (OS.Array sh r) = DeltaS sh r\n-- not injective: Dual 'DModeDerivative r = r\n Dual 'DModeDerivative Double = Double\n Dual 'DModeDerivative Float = Float\n Dual 'DModeDerivative (Vector r) = Vector r\n Dual 'DModeDerivative (Matrix r) = Matrix r\n Dual 'DModeDerivative (OT.Array r) = OT.Array r\n Dual 'DModeDerivative (OS.Array sh r) = OS.Array sh r\n\n-- | The underlying scalar of a given primal component of a dual number.\n-- A long name to remember not to use, unless necessary, and not to export.\ntype family ScalarOf a where\n ScalarOf Double = Double\n ScalarOf Float = Float\n ScalarOf (Vector r) = r\n ScalarOf (Matrix r) = r\n ScalarOf (OT.Array r) = r\n ScalarOf (OS.Array sh r) = r\n\n-- | Second argument is a primal component of dual numbers at some rank\n-- wrt the differentiation mode given in the first argument.\nclass IsPrimal d a where\n dZero :: Dual d a\n dScale :: a -> Dual d a -> Dual d a\n dAdd :: Dual d a -> Dual d a -> Dual d a\n dDelay :: Dual d a -> Dual d a\n\n-- | Part 1/2 of a hack to squeeze the shaped tensors rank,\n-- with its extra @sh@ parameter, into the 'IsPrimal' class.\nclass IsPrimalS d r where\n dZeroS :: forall sh. OS.Shape sh => Dual d (OS.Array sh r)\n dScaleS :: forall sh. OS.Shape sh\n => OS.Array sh r -> Dual d (OS.Array sh r) -> Dual d (OS.Array sh r)\n dAddS :: forall sh. OS.Shape sh\n => Dual d (OS.Array sh r) -> Dual d (OS.Array sh r)\n -> Dual d (OS.Array sh r)\n dDelayS :: forall sh. OS.Shape sh\n => Dual d (OS.Array sh r) -> Dual d (OS.Array sh r)\n\n-- | Part 2/2 of a hack to squeeze the shaped tensors rank,\n-- with its extra @sh@ parameter, into the 'IsPrimal' class.\ninstance (IsPrimalS d r, OS.Shape sh) => IsPrimal d (OS.Array sh r) where\n dZero = dZeroS\n dScale = dScaleS\n dAdd = dAddS\n dDelay = dDelayS\n\n-- | Assuming that the first argument is the primal component of dual numbers\n-- with the underyling scalar in the second argument and with differentiation\n-- mode `DModeGradient`, it additionally admits delta-variable\n-- introduction and binding as defined by the methods of the class.\nclass HasVariables a where\n dVar :: DeltaId a -> Dual 'DModeGradient a\n bindInState :: Dual 'DModeGradient a\n -> DeltaState (ScalarOf a)\n -> (DeltaState (ScalarOf a), DeltaId a )\n dOutline :: CodeOut -> [a] -> [Dual 'DModeGradient a]\n -> Dual 'DModeGradient a\n\n-- | The class provides methods required for the second type parameter\n-- to be the underlying scalar of a well behaved collection of dual numbers\n-- of various ranks wrt the differentation mode given in the first argument.\nclass HasRanks (d :: DMode) r where\n dSumElements0 :: Dual d (Vector r) -> Int -> Dual d r\n dIndex0 :: Dual d (Vector r) -> Int -> Int -> Dual d r\n dDot0 :: Vector r -> Dual d (Vector r) -> Dual d r\n dFromX0 :: Dual d (OT.Array r) -> Dual d r\n dFromS0 :: Dual d (OS.Array '[] r) -> Dual d r\n\n dSeq1 :: Data.Vector.Vector (Dual d r) -> Dual d (Vector r)\n dKonst1 :: Dual d r -> Int -> Dual d (Vector r)\n dAppend1 :: Dual d (Vector r) -> Int -> Dual d (Vector r) -> Dual d (Vector r)\n dSlice1 :: Int -> Int -> Dual d (Vector r) -> Int -> Dual d (Vector r)\n dSumRows1 :: Dual d (Matrix r) -> Int -> Dual d (Vector r)\n dSumColumns1 :: Dual d (Matrix r) -> Int -> Dual d (Vector r)\n dM_VD1 :: Matrix r -> Dual d (Vector r) -> Dual d (Vector r)\n dMD_V1 :: Dual d (Matrix r) -> Vector r -> Dual d (Vector r)\n dFromX1 :: Dual d (OT.Array r) -> Dual d (Vector r)\n dFromS1 :: KnownNat len\n => Dual d (OS.Array '[len] r) -> Dual d (Vector r)\n dReverse1 :: Dual d (Vector r) -> Dual d (Vector r)\n dFlatten1 :: Int -> Int -> Dual d (Matrix r) -> Dual d (Vector r)\n dFlattenX1 :: OT.ShapeL -> Dual d (OT.Array r) -> Dual d (Vector r)\n dFlattenS1 :: OS.Shape sh\n => Dual d (OS.Array sh r) -> Dual d (Vector r)\n\n dFromRows2 :: Data.Vector.Vector (Dual d (Vector r)) -> Dual d (Matrix r)\n dFromColumns2 :: Data.Vector.Vector (Dual d (Vector r)) -> Dual d (Matrix r)\n dKonst2 :: Dual d r -> (Int, Int) -> Dual d (Matrix r)\n dTranspose2 :: Dual d (Matrix r) -> Dual d (Matrix r)\n dM_MD2 :: Matrix r -> Dual d (Matrix r) -> Dual d (Matrix r)\n dMD_M2 :: Dual d (Matrix r) -> Matrix r -> Dual d (Matrix r)\n dRowAppend2 :: Dual d (Matrix r) -> Int -> Dual d (Matrix r) -> Dual d (Matrix r)\n dColumnAppend2 :: Dual d (Matrix r) -> Int -> Dual d (Matrix r) -> Dual d (Matrix r)\n dRowSlice2 :: Int -> Int -> Dual d (Matrix r) -> Int -> Dual d (Matrix r)\n dColumnSlice2 :: Int -> Int -> Dual d (Matrix r) -> Int -> Dual d (Matrix r)\n dAsRow2 :: Dual d (Vector r) -> Dual d (Matrix r)\n dAsColumn2 :: Dual d (Vector r) -> Dual d (Matrix r)\n dFromX2 :: Dual d (OT.Array r) -> Dual d (Matrix r)\n dFromS2 :: (KnownNat rows, KnownNat cols)\n => Dual d (OS.Array '[rows, cols] r) -> Dual d (Matrix r)\n\n dFlipud2 :: Dual d (Matrix r) -> Dual d (Matrix r)\n dFliprl2 :: Dual d (Matrix r) -> Dual d (Matrix r)\n dReshape2 :: Int -> Dual d (Vector r) -> Dual d (Matrix r)\n dConv2 :: Matrix r -> Dual d (Matrix r) -> Dual d (Matrix r)\n\n dKonstX :: Dual d r -> OT.ShapeL -> Dual d (OT.Array r)\n dAppendX :: Dual d (OT.Array r) -> Int -> Dual d (OT.Array r) -> Dual d (OT.Array r)\n dSliceX :: Int -> Int -> Dual d (OT.Array r) -> Int -> Dual d (OT.Array r)\n dIndexX :: Dual d (OT.Array r) -> Int -> Int -> Dual d (OT.Array r)\n dRavelFromListX :: [Dual d (OT.Array r)] -> Dual d (OT.Array r)\n dReshapeX :: OT.ShapeL -> OT.ShapeL -> Dual d (OT.Array r) -> Dual d (OT.Array r)\n dFrom0X :: Dual d r -> Dual d (OT.Array r)\n dFrom1X :: Dual d (Vector r) -> Dual d (OT.Array r)\n dFrom2X :: Dual d (Matrix r) -> Int -> Dual d (OT.Array r)\n dFromSX :: OS.Shape sh\n => Dual d (OS.Array sh r) -> Dual d (OT.Array r)\n\n dKonstS :: OS.Shape sh\n => Dual d r -> Dual d (OS.Array sh r)\n dAppendS :: (OS.Shape sh, KnownNat m, KnownNat n)\n => Dual d (OS.Array (m ': sh) r) -> Dual d (OS.Array (n ': sh) r)\n -> Dual d (OS.Array ((m + n) ': sh) r)\n dSliceS :: (KnownNat i, KnownNat n, KnownNat k, OS.Shape rest)\n => Proxy i -> Proxy n -> Dual d (OS.Array (i + n + k ': rest) r)\n -> Dual d (OS.Array (n ': rest) r)\n dIndexS :: (KnownNat ix, KnownNat k, OS.Shape rest)\n => Dual d (OS.Array (ix + 1 + k ': rest) r)\n -> Proxy ix -> Dual d (OS.Array rest r)\n dRavelFromListS :: (KnownNat k, OS.Shape rest)\n => [Dual d (OS.Array rest r)]\n -> Dual d (OS.Array (k : rest) r)\n dReshapeS :: (OS.Shape sh, OS.Shape sh', OS.Size sh ~ OS.Size sh')\n => Dual d (OS.Array sh r) -> Dual d (OS.Array sh' r)\n dFrom0S :: Dual d r -> Dual d (OS.Array '[] r)\n dFrom1S :: KnownNat n => Dual d (Vector r) -> Dual d (OS.Array '[n] r)\n dFrom2S :: (KnownNat rows, KnownNat cols)\n => Proxy cols\n -> Dual d (Matrix r) -> Dual d (OS.Array '[rows, cols] r)\n dFromXS :: OS.Shape sh => Dual d (OT.Array r) -> Dual d (OS.Array sh r)\n\n\n-- * Backprop gradient method instances\n\ninstance IsPrimal 'DModeGradient Double where\n dZero = Zero0\n dScale = Scale0\n dAdd = Add0\n dDelay = Delay0\n\ninstance IsPrimal 'DModeGradient Float where\n -- Identical as above:\n dZero = Zero0\n dScale = Scale0\n dAdd = Add0\n dDelay = Delay0\n\ninstance IsPrimal 'DModeGradient (Vector r) where\n dZero = Zero1\n dScale = Scale1\n dAdd = Add1\n dDelay = Delay1\n\ninstance IsPrimal 'DModeGradient (Matrix r) where\n dZero = Zero2\n dScale = Scale2\n dAdd = Add2\n dDelay = Delay2\n\ninstance IsPrimal 'DModeGradient (OT.Array r) where\n dZero = ZeroX\n dScale = ScaleX\n dAdd = AddX\n dDelay = DelayX\n\ninstance IsPrimalS 'DModeGradient r where\n dZeroS = ZeroS\n dScaleS = ScaleS\n dAddS = AddS\n dDelayS = DelayS\n\ninstance HasVariables Double where\n dVar = Var0\n {-# INLINE bindInState #-}\n bindInState = bindInState0\n dOutline = Outline0\n\ninstance HasVariables Float where\n dVar = Var0\n {-# INLINE bindInState #-}\n bindInState = bindInState0\n dOutline = Outline0\n\ninstance HasVariables (Vector r) where\n dVar = Var1\n {-# INLINE bindInState #-}\n bindInState = bindInState1\n dOutline = Outline1\n\ninstance HasVariables (Matrix r) where\n dVar = Var2\n {-# INLINE bindInState #-}\n bindInState = bindInState2\n dOutline = Outline2\n\ninstance HasVariables (OT.Array r) where\n dVar = VarX\n {-# INLINE bindInState #-}\n bindInState = bindInStateX\n dOutline = OutlineX\n\ninstance OS.Shape sh => HasVariables (OS.Array sh r) where\n dVar = VarS\n {-# INLINE bindInState #-}\n bindInState u' st = let (st2, did) = bindInStateX (FromSX u') st\n in (st2, convertDeltaId did)\n dOutline = OutlineS\n\ninstance Dual 'DModeGradient r ~ Delta0 r\n => HasRanks 'DModeGradient r where\n dSumElements0 = SumElements0\n dIndex0 = Index0\n dDot0 = Dot0\n dFromX0 = FromX0\n dFromS0 = FromS0\n dSeq1 = Seq1\n dKonst1 = Konst1\n dAppend1 = Append1\n dSlice1 = Slice1\n dSumRows1 = SumRows1\n dSumColumns1 = SumColumns1\n dM_VD1 = M_VD1\n dMD_V1 = MD_V1\n dFromX1 = FromX1\n dFromS1 = FromS1\n dReverse1 = Reverse1\n dFlatten1 = Flatten1\n dFlattenX1 = FlattenX1\n dFlattenS1 = FlattenS1\n dFromRows2 = FromRows2\n dFromColumns2 = FromColumns2\n dKonst2 = Konst2\n dTranspose2 = Transpose2\n dM_MD2 = M_MD2\n dMD_M2 = MD_M2\n dRowAppend2 = RowAppend2\n dColumnAppend2 = ColumnAppend2\n dRowSlice2 = RowSlice2\n dColumnSlice2 = ColumnSlice2\n dAsRow2 = AsRow2\n dAsColumn2 = AsColumn2\n dFromX2 = FromX2\n dFromS2 = FromS2\n dFlipud2 = Flipud2\n dFliprl2 = Fliprl2\n dReshape2 = Reshape2\n dConv2 = Conv2\n dKonstX = KonstX\n dAppendX = AppendX\n dSliceX = SliceX\n dIndexX = IndexX\n dRavelFromListX = RavelFromListX\n dReshapeX = ReshapeX\n dFrom0X = From0X\n dFrom1X = From1X\n dFrom2X = From2X\n dFromSX = FromSX\n dKonstS = KonstS\n dAppendS = AppendS\n dSliceS = SliceS\n dIndexS = IndexS\n dRavelFromListS = RavelFromListS\n dReshapeS = ReshapeS\n dFrom0S = From0S\n dFrom1S = From1S\n dFrom2S = From2S\n dFromXS = FromXS\n\n\n-- * Alternative instances: forward derivatives computed on the spot\n\ninstance IsPrimal 'DModeDerivative Double where\n dZero = 0\n dScale k d = k * d\n dAdd d e = d + e\n dDelay = id -- no delaying\n\ninstance IsPrimal 'DModeDerivative Float where\n dZero = 0\n dScale k d = k * d\n dAdd d e = d + e\n dDelay = id\n\n-- These constraints force @UndecidableInstances@.\ninstance Num (Vector r)\n => IsPrimal 'DModeDerivative (Vector r) where\n dZero = 0\n dScale k d = k * d\n dAdd d e = d + e\n dDelay = id\n\ninstance Num (Matrix r)\n => IsPrimal 'DModeDerivative (Matrix r) where\n dZero = 0\n dScale k d = k * d\n dAdd d e = d + e\n dDelay = id\n\ninstance Num (OT.Array r)\n => IsPrimal 'DModeDerivative (OT.Array r) where\n dZero = 0\n dScale k d = k * d\n dAdd d e = d + e\n dDelay = id\n\ninstance (Numeric r, Num (Vector r))\n => IsPrimalS 'DModeDerivative r where\n dZeroS = 0\n dScaleS k d = k * d\n dAddS d e = d + e\n dDelayS = id\n\ninstance ( Numeric r, Num (Vector r)\n , Dual 'DModeDerivative r ~ r )\n => HasRanks 'DModeDerivative r where\n dSumElements0 vd _ = HM.sumElements vd\n dIndex0 d ix _ = d V.! ix\n dDot0 = (HM.<.>)\n dFromX0 = OT.unScalar\n dFromS0 = OS.unScalar\n dSeq1 = V.convert\n dKonst1 = HM.konst\n dAppend1 d _k e = d V.++ e\n dSlice1 i n d _len = V.slice i n d\n dM_VD1 = (HM.#>)\n dMD_V1 = (HM.#>)\n dSumRows1 dm _cols = V.fromList $ map HM.sumElements $ HM.toRows dm\n dSumColumns1 dm _rows = V.fromList $ map HM.sumElements $ HM.toColumns dm\n dFromX1 = OT.toVector\n dFromS1 = OS.toVector\n dReverse1 = V.reverse\n dFlatten1 _rows _cols = HM.flatten\n dFlattenX1 _sh = OT.toVector\n dFlattenS1 = OS.toVector\n dFromRows2 = HM.fromRows . V.toList\n dFromColumns2 = HM.fromColumns . V.toList\n dKonst2 = HM.konst\n dTranspose2 = HM.tr'\n dM_MD2 = (HM.<>)\n dMD_M2 = (HM.<>)\n dAsRow2 = HM.asRow\n dAsColumn2 = HM.asColumn\n dRowAppend2 d _k e = d HM.=== e\n dColumnAppend2 d _k e = d HM.||| e\n dRowSlice2 i n d _rows = HM.takeRows n $ HM.dropRows i d\n dColumnSlice2 i n d _cols = HM.takeColumns n $ HM.dropColumns i d\n dFromX2 d = case OT.shapeL d of\n [_rows, cols] -> HM.reshape cols $ OT.toVector d\n _ -> error \"dFromX2: wrong tensor dimensions\"\n dFromS2 d = case OS.shapeL d of\n [_rows, cols] -> HM.reshape cols $ OS.toVector d\n _ -> error \"dFromS2: wrong tensor dimensions\"\n dFlipud2 = HM.flipud\n dFliprl2 = HM.fliprl\n dReshape2 = HM.reshape\n dConv2 = HM.conv2\n dKonstX d sz = OT.constant sz d\n dAppendX d _k e = d `OT.append` e\n dSliceX i n d _len = OT.slice [(i, n)] d\n dIndexX d ix _len = OT.index d ix\n dRavelFromListX ld =\n let sh = case ld of\n d : _ -> length ld : OT.shapeL d\n [] -> []\n in OT.ravel $ OTB.fromList sh ld\n dReshapeX _sh = OT.reshape\n dFrom0X = OT.scalar\n dFrom1X d = OT.fromVector [V.length d] d\n dFrom2X d cols = OT.fromVector [HM.rows d, cols] $ HM.flatten d\n dFromSX = Data.Array.Convert.convert\n dKonstS = OS.constant\n dAppendS = OS.append\n dSliceS (_ :: Proxy i) (_ :: Proxy n) = OS.slice @'[ '(i, n) ]\n dIndexS d proxyIx = OS.index d (fromInteger $ natVal proxyIx)\n dRavelFromListS = OS.ravel . OSB.fromList\n dReshapeS = OS.reshape\n dFrom0S = OS.scalar\n dFrom1S = OS.fromVector\n dFrom2S _ = OS.fromVector . HM.flatten\n dFromXS = Data.Array.Convert.convert\n", "meta": {"hexsha": "f1aff1c96ccca04ea7c98375fd5a4018e777fcfd", "size": 17363, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Core/DualClass.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HordeAd/Core/DualClass.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "src/HordeAd/Core/DualClass.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8, "max_line_length": 86, "alphanum_fraction": 0.6641709382, "num_tokens": 5552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23246070272938937}} {"text": "{-# LANGUAGE TypeOperators, DeriveDataTypeable, FlexibleInstances, ScopedTypeVariables, ImplicitParams, ViewPatterns #-}\nmodule Target.Regression where\n\nimport Target.Prelude\nimport qualified Data.Record as R\nimport Prelude hiding (scanl,repeat,replicate)\nimport Data.Record.Combinators ((!!!))\nimport Data.Kind\nimport Data.List (transpose)\nimport Data.TypeFun\nimport Numeric.LinearAlgebra hiding (diag, linspace, svd, )\nimport Math.Probably.Sampler hiding (uniform,primOneOf,logNormal,invGamma,binomial,gamma,oneOf,bernoulli, normal, unormal, unit)\nimport qualified Data.Text as T\nimport Foreign.Storable (Storable)\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad (forM, forM_)\nimport qualified Data.Vector.Storable.Mutable as VSM\nimport qualified Data.Vector.Storable as VS\nimport Foreign.Storable.Tuple\n\ntmax :: Double\ntmax = 1.000\n\ndt :: Double\ndt = 1.000e-2\n\n(.==.) :: (Eq a) => (a -> ((a -> Double)))\n(.==.) = \\((x::a)) -> \\((y::a)) -> if (x==y) then 1.000 else 0.000\n\nscanl :: (((a -> ((b -> a)))) -> ((a -> ((([b]) -> ([a]))))))\nscanl = \\(((_arg0)::(a -> ((b -> a))))) -> \\((_arg1)) -> \\(((_arg2)::[b])) -> case (_arg0,((_arg1,_arg2))) of {((op::(a -> ((b -> a)))),(acc,[])) -> acc:[]; ((op::(a -> ((b -> a)))),(acc,(x:(xs::[b])))) -> acc:((scanl op (op acc x)) xs)}\n\nfromTo :: (BayNum a) => (a -> ((a -> ([a]))))\nfromTo = \\((n::a)) -> \\((m::a)) -> if (n ((Int -> ((((Int -> Double)) -> Double)))))\nbigSum = \\((lo::Int)) -> \\((hi::Int)) -> \\((f::(Int -> Double))) -> sum (map f (fromTo lo hi))\n\nreplicate :: (Int -> ((a -> ([a]))))\nreplicate = \\(((_arg0)::Int)) -> \\((_arg1)) -> case (_arg0,_arg1) of {(0,x) -> []; ((n::Int),x) -> x:(replicate (n-1) x)}\n\nneg :: (BayNum a) => (a -> a)\nneg = \\((x::a)) -> 0-x\n\nix :: (Int -> ((([a]) -> a)))\nix = \\(((_arg0)::Int)) -> \\(((_arg1)::[a])) -> case (_arg0,_arg1) of {(0,(x:_)) -> x; ((n::Int),(_:(xs::[a]))) -> ix (n-1) xs}\n\nlinspace :: (Double -> ((Double -> ((Double -> ([Double]))))))\nlinspace = \\((from::Double)) -> \\((to::Double)) -> \\((num::Double)) -> let {(dt::Double) = (to-from)/num;\n (is::[Double]) = fromTo 0 (num-1);\n } in map (\\((i::Double)) -> ((unround i)*dt)+from) is\n\ncountSamples :: ((Prob a) -> (Maybe Int))\ncountSamples = \\(((_arg0)::Prob a)) -> case _arg0 of {Samples (xs::[a]) -> Just (length xs); Sampler _ -> Nothing}\n\nunit :: Prob Double\nunit = Sampler primUnit\n\nprimOneOf :: (([a]) -> ((Seed -> ((a,Seed)))))\nprimOneOf = \\((xs::[a])) -> \\((seed::Seed)) -> let {((u::Double),(nextSeed::Seed)) = primUnit seed;\n (idx::Int) = floor (u*(unround (length xs)));\n } in ((ix idx xs),nextSeed)\n\nappend :: (([a]) -> ((([a]) -> ([a]))))\nappend = \\(((_arg0)::[a])) -> \\(((_arg1)::[a])) -> case (_arg0,_arg1) of {([],(ys::[a])) -> ys; ((x:(xs::[a])),(ys::[a])) -> x:(append xs ys)}\n\ninvlogit :: (Double -> Double)\ninvlogit = \\((x::Double)) -> 1/(1+(exp (0.000-x)))\n\nlogit :: (Double -> Double)\nlogit = \\((x::Double)) -> log (x/(1-x))\n\nboolToReal :: (Bool -> Double)\nboolToReal = \\(((_arg0)::Bool)) -> case _arg0 of {True -> 1.000; False -> 0.000}\n\nfor :: (Int -> ((Int -> ((((Int -> (Prob a))) -> (Prob ([a])))))))\nfor = \\((n::Int)) -> \\((m::Int)) -> \\((s::(Int -> (Prob a)))) -> if (n>=(\\(x) -> ((for (n+1) m) s)>>=(\\((xs::[a])) -> return (x:xs)))) else ((s n)>>=(\\(v) -> return (v:[])))\n\nrepeat :: (Int -> (((Prob a) -> (Prob ([a])))))\nrepeat = \\((n::Int)) -> \\((sam::Prob a)) -> (for 1 n) (\\((i::Int)) -> sam)\n\nsquare :: (BayNum a) => (a -> a)\nsquare = \\((x::a)) -> x*x\n\nstep :: (BayNum a,BayNum b) => (a -> b)\nstep = \\((x::a)) -> if (x<0) then 0 else 1\n\nfac :: (Int -> Int)\nfac = \\(((_arg0)::Int)) -> case _arg0 of {1 -> 1; (n::Int) -> n*(fac (n-1))}\n\nzipWithNats :: (BayNum b) => (([a]) -> ((b -> ([(b,a)]))))\nzipWithNats = \\(((_arg0)::[a])) -> \\(((_arg1)::b)) -> case (_arg0,_arg1) of {([],_) -> []; ((x:(xs::[a])),(n::b)) -> ((n,x)):(zipWithNats xs (n+1))}\n\nunSamples :: ((Prob a) -> ([a]))\nunSamples = \\(Samples (xs::[a])) -> xs\n\nchainPlot :: ((Prob Double) -> Plot)\nchainPlot = \\(Samples (xs::[Double])) -> Plot [] (return ((Points (zipWithNats xs 0)):[]))\n\nstyle :: (([(T.Text,T.Text)]) -> ((Plot -> Plot)))\nstyle = \\((opts::[(T.Text,T.Text)])) -> \\(Plot (pos::[(T.Text,T.Text)]) (plr::Prob ([Radian]))) -> Plot pos (fmap (\\((lrs::[Radian])) -> (Options opts lrs):[]) plr)\n\ndistPlot0 :: ((Prob Double) -> Plot)\ndistPlot0 = \\(((_arg0)::Prob Double)) -> case _arg0 of {Samples (xs::[Double]) -> Plot ((((T.pack \"range-y\"),(T.pack \"0\"))):[]) (return ((Histogram xs):[])); (sampler::Prob Double) -> Plot ((((T.pack \"range-y\"),(T.pack \"0\"))):[]) ((repeat 2000 sampler)>>=(\\((xs::[Double])) -> return ((Histogram xs):[])))}\n\ndistPlot :: ((Prob Double) -> Plot)\ndistPlot = \\((p::Prob Double)) -> style ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"fill-opacity\"),(T.pack \"0.3\"))):((((T.pack \"stroke\"),(T.pack \"none\"))):((((T.pack \"bar-width\"),(T.pack \"0.8\"))):[])))) (distPlot0 p)\n\nhistogram :: (BayNum a) => (([a]) -> Plot)\nhistogram = \\((xs::[a])) -> Plot [] (return ((Options ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"fill-opacity\"),(T.pack \"0.3\"))):((((T.pack \"stroke\"),(T.pack \"none\"))):((((T.pack \"bar-width\"),(T.pack \"0.8\"))):[])))) ((Histogram (map unround xs)):[])):[]))\n\nunPlot :: (Plot -> (Prob ([Radian])))\nunPlot = \\(Plot _ (x::Prob ([Radian]))) -> x\n\nover :: (([Plot]) -> Plot)\nover = \\((plots::[Plot])) -> Plot [] ((mapM unPlot plots)>>=(\\((items::[[Radian]])) -> return (map (\\((Plot (os::[(T.Text,T.Text)]) _,(rdns::[Radian]))) -> Options os rdns) (zip plots items))))\n\nscatterPlot :: (BayNum a,BayNum b) => (([(a,b)]) -> Plot)\nscatterPlot = \\((xys::[(a,b)])) -> style ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"marker-size\"),(T.pack \"30\"))):((((T.pack \"marker\"),(T.pack \"circle\"))):((((T.pack \"stroke\"),(T.pack \"none\"))):[])))) (Plot [] (return ((Points (map (\\(((x::a),(y::b))) -> ((unround x),(unround y))) xys)):[])))\n\nlinePlot :: (BayNum a,BayNum b) => (([(a,b)]) -> Plot)\nlinePlot = \\((xys::[(a,b)])) -> style ((((T.pack \"stroke\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[])) (Plot [] (return ((Lines (map (\\(((x::a),(y::b))) -> ((unround x),(unround y))) xys)):[])))\n\nplines :: (BayNum a,BayNum b) => ((Prob ([(a,b)])) -> Plot)\nplines = \\((plns::Prob ([(a,b)]))) -> style ((((T.pack \"stroke-opacity\"),(T.pack \"0.2\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[])) (Plot [] (repeat 50 (fmap (\\((xys::[(a,b)])) -> Lines (map (\\(((x::a),(y::b))) -> ((unround x),(unround y))) xys)) plns)))\n\nppoints :: ((Prob ([(Double,Double)])) -> Plot)\nppoints = \\((ppts::Prob ([(Double,Double)]))) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):[]) (repeat 50 (fmap Points ppts))\n\nsigPlot :: (((Double -> Double)) -> Plot)\nsigPlot = \\((sig::(Double -> Double))) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[])) (return ((Timeseries sig):[]))\n\nthin :: (Int -> ((([a]) -> ([a]))))\nthin = \\((skip::Int)) -> \\((xs::[a])) -> map snd (filter (\\(((i::Int),x)) -> (mod i (skip+1))==0) (zip (fromTo 0 ((length xs)-1)) xs))\n\nthinTo :: (Int -> ((([a]) -> ([a]))))\nthinTo = \\((n::Int)) -> \\((xs::[a])) -> let {(nxs::Int) = length xs;\n (ratio::Int) = round ((unround nxs)/(unround n));\n } in thin ratio xs\n\npsigPlot :: ((Prob ((Double -> Double))) -> Plot)\npsigPlot = \\(((_arg0)::Prob ((Double -> Double)))) -> case _arg0 of {Samples (sigs::[(Double -> Double)]) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-opacity\"),(T.pack \"0.2\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[]))) (return (map Timeseries (thinTo 20 sigs))); Sampler (f::(Seed -> ((((Double -> Double)),Seed)))) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-opacity\"),(T.pack \"0.2\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[]))) ((repeat 20 (Sampler f))>>=(\\((sigs::[(Double -> Double)])) -> return (map Timeseries sigs)))}\n\npsigNPlot :: (Int -> (((Prob ((Double -> Double))) -> Plot)))\npsigNPlot = \\(((_arg0)::Int)) -> \\(((_arg1)::Prob ((Double -> Double)))) -> case (_arg0,_arg1) of {((n::Int),Samples (sigs::[(Double -> Double)])) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-opacity\"),(T.pack \"0.2\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[]))) (return (map Timeseries (thinTo n sigs))); ((n::Int),Sampler (f::(Seed -> ((((Double -> Double)),Seed))))) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-opacity\"),(T.pack \"0.1\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[]))) ((repeat n (Sampler f))>>=(\\((sigs::[(Double -> Double)])) -> return (map Timeseries sigs)))}\n\nprobBoolToP :: ((Prob Bool) -> (Prob Double))\nprobBoolToP = \\(((_arg0)::Prob Bool)) -> case _arg0 of {Sampler (f::(Seed -> ((Bool,Seed)))) -> (repeat 200 (Sampler f))>>=(\\((bs::[Bool])) -> probBoolToP (Samples bs)); Samples (bs::[Bool]) -> let {(yeas::[Bool]) = filter id bs;\n } in return ((unround (length yeas))/(unround (length bs)))}\n\npcurve :: (([(Double,(Prob Bool))]) -> Plot)\npcurve = \\((xps::[(Double,(Prob Bool))])) -> Plot [] (let {(xs::[Double]) = map fst xps;\n } in (mapM (probBoolToP.snd) xps)>>=(\\((ps::[Double])) -> return ((Lines (zip xs ps)):[])))\n\nplotStyle :: (([(T.Text,T.Text)]) -> ((Plot -> Plot)))\nplotStyle = \\((opts::[(T.Text,T.Text)])) -> \\(Plot (pos::[(T.Text,T.Text)]) (plr::Prob ([Radian]))) -> Plot (append opts pos) plr\n\naxisLabels :: (T.Text -> ((T.Text -> ((Plot -> Plot)))))\naxisLabels = \\((xlab::T.Text)) -> \\((ylab::T.Text)) -> \\(Plot (popts::[(T.Text,T.Text)]) (plns::Prob ([Radian]))) -> Plot ((((T.pack \"axis-x-label\"),xlab)):((((T.pack \"axis-y-label\"),ylab)):popts)) plns\n\nunPlotOpts :: (Plot -> ([(T.Text,T.Text)]))\nunPlotOpts = \\(Plot (os::[(T.Text,T.Text)]) (x::Prob ([Radian]))) -> os\n\nsigLast :: (((Double -> Double)) -> Double)\nsigLast = \\((sig::(Double -> Double))) -> case observeSig sig of {ObservedSignal (dt::Double) (t0::Double) (pts::Vector Double) -> pts@>((dim pts)-1); ObservedXYSignal (pts::Vector ((Double,Double))) -> snd (pts@>((dim pts)-1))}\n\nsigTail :: (((Double -> Double)) -> ([Double]))\nsigTail = \\((sig::(Double -> Double))) -> case observeSig sig of {ObservedSignal (dt::Double) (t0::Double) (pts::Vector Double) -> vecToList pts}\n\nbetween :: (BayNum a) => (a -> ((a -> ((a -> Bool)))))\nbetween = \\((lo::a)) -> \\((hi::a)) -> \\((x::a)) -> (x>lo)&&(x ((((a -> ((c,d)))) -> c)))\nrunP = \\(xs) -> \\((my::(a -> ((c,d))))) -> fst (my xs)\n\nrunP1 :: (((a -> ((b,c)))) -> ((a -> b)))\nrunP1 = \\((my::(a -> ((b,c))))) -> \\(xs) -> fst (my xs)\n\nreturnP :: (a -> ((b -> ((a,b)))))\nreturnP = \\(x) -> \\(xs) -> (x,xs)\n\nbindP :: (((a -> ((b,c)))) -> ((((b -> ((c -> f)))) -> ((a -> f)))))\nbindP = \\((f::(a -> ((b,c))))) -> \\((g::(b -> ((c -> f))))) -> \\(xs) -> let {(x,xs') = f xs;\n } in g x xs'\n\nheadP :: (([a]) -> ((a,([a]))))\nheadP = \\(((_arg0)::[a])) -> case _arg0 of {(x:(xs::[a])) -> (x,xs); [] -> bayError (T.pack \"headP: empty list\")}\n\ntakeP :: (Int -> ((([a]) -> ((([a]),([a]))))))\ntakeP = \\((n::Int)) -> \\((xs::[a])) -> ((take n xs),(drop n xs))\n\nforP :: (([a]) -> ((((a -> ((c -> ((d,c)))))) -> ((c -> ((([d]),c)))))))\nforP = \\(((_arg0)::[a])) -> \\(((_arg1)::(a -> ((c -> ((d,c))))))) -> \\((_arg2)) -> case (_arg0,((_arg1,_arg2))) of {([],((f::(a -> ((c -> ((d,c)))))),xs)) -> ([],xs); ((a:(as::[a])),((f::(a -> ((c -> ((d,c)))))),xs)) -> (bindP (f a) (\\(y) -> bindP (forP as f) (\\((ys::[d])) -> returnP (y:ys)))) xs}\n\nnoP :: (a -> (((),a)))\nnoP = \\(xs) -> ((),xs)\n\nfmapP :: (((a -> b)) -> ((((c -> ((a,e)))) -> ((c -> ((b,e)))))))\nfmapP = \\((f::(a -> b))) -> \\((mx::(c -> ((a,e))))) -> bindP mx (\\(x) -> returnP (f x))\n\nfixP :: (Int -> (((Prob a) -> (Prob (Prob a)))))\nfixP = \\(((_arg0)::Int)) -> \\(((_arg1)::Prob a)) -> case (_arg0,_arg1) of {((n::Int),Sampler (f::(Seed -> ((a,Seed))))) -> (repeat n (Sampler f))>>=(\\((xs::[a])) -> return (Samples xs)); ((n::Int),Samples (xs::[a])) -> return (Samples (thinTo n xs))}\n\ndiag :: ((Vector Double) -> (Matrix Double))\ndiag = \\((v::Vector Double)) -> fillM (((dim v),(dim v))) (\\(((i::Int),(j::Int))) -> if (i==j) then (v@>i) else 0.000)\n\ndiagL :: (([Double]) -> (Matrix Double))\ndiagL = diag.listToVec\n\nmmap :: (BayNum a,BayNum b) => (((a -> b)) -> (((Matrix a) -> (Matrix b))))\nmmap = \\((f::(a -> b))) -> \\((m::Matrix a)) -> fillM (mdims m) (\\(((i::Int),(j::Int))) -> f (m@@>((i,j))))\n\ntransM :: (BayNum a) => ((Matrix a) -> (Matrix a))\ntransM = \\((m::Matrix a)) -> fillM (mdims m) (\\(((i::Int),(j::Int))) -> m@@>((j,i)))\n\nmeanL :: (([Double]) -> Double)\nmeanL = \\((xs::[Double])) -> (sum xs)/(unround (length xs))\n\nvarL :: (([Double]) -> Double)\nvarL = \\((xs::[Double])) -> let {(mu::Double) = meanL xs;\n } in (sum (map (\\((x::Double)) -> (x-mu)*(x-mu)) xs))/(unround ((length xs)-1))\n\npopvarL :: (([Double]) -> Double)\npopvarL = \\((xs::[Double])) -> let {(mu::Double) = meanL xs;\n } in (sum (map (\\((x::Double)) -> (x-mu)*(x-mu)) xs))/(unround (length xs))\n\nminL :: (([Double]) -> Double)\nminL = \\(((x::Double):(xs::[Double]))) -> (foldl min x) xs\n\nmaxL :: (([Double]) -> Double)\nmaxL = \\(((x::Double):(xs::[Double]))) -> (foldl max x) xs\n\ngetT :: ((a) -> (((b) -> ((a,b)))))\ngetT = \\(dt) -> \\(tmax) -> (dt,tmax)\n\npearson :: (([(Double,Double)]) -> Double)\npearson = \\((xys::[(Double,Double)])) -> let {(xs::[Double]) = map fst xys;\n (ys::[Double]) = map snd xys;\n (mx::Double) = meanL xs;\n (my::Double) = meanL ys;\n (sx::Double) = sqrt (varL xs);\n (sy::Double) = sqrt (varL ys);\n (invN::Double) = 1.000/(unround ((length xys)-1));\n } in invN*(sum (map (\\(((x::Double),(y::Double))) -> ((x-mx)/sx)*((y-my)/sy)) xys))\n\ndata Strategy a = \n GStrategy (((((Vector Double) -> ((Double,(Vector Double))))) -> (((Vector Double) -> ((a -> ((((Double,(Vector Double))) -> (Prob (((((Vector Double),a)),((Double,(Vector Double)))))))))))))) (((Vector Double) -> a))\n |VStrategy (((((Vector Double) -> Double)) -> (((Vector Double) -> ((a -> ((Double -> (Prob (((((Vector Double),a)),Double))))))))))) (((Vector Double) -> a))\nintBetweenLogPdf :: (BayNum d) => (a -> ((b -> ((c -> d)))))\nintBetweenLogPdf = \\(lo) -> \\(hi) -> \\(x) -> 1\n\nanyLogPdf :: (a -> Double)\nanyLogPdf = \\(x) -> 1.000\n\nd :: ((Double) -> ((((Double -> Double)) -> ((Double -> Double)))))\nd = \\((dt::Double)) -> \\((w::(Double -> Double))) -> \\((t::Double)) -> ((w t)-(w (t-dt)))/dt\n\nunormal :: Prob Double\nunormal = unit>>=(\\((u1::Double)) -> unit>>=(\\((u2::Double)) -> return ((sqrt ((0.000-2.000)*(log u1)))*(cos ((2.000*pi)*u2)))))\n\ngammaAux :: (Double -> ((Double -> (Prob Double))))\ngammaAux = \\((a::Double)) -> \\((b::Double)) -> let {(d::Double) = a-(1.000/3.000);\n (c::Double) = 1.000/(3.000*(sqrt d));\n } in unormal>>=(\\((x::Double)) -> let {(cx::Double) = c*x;\n (v::Double) = (1.000+cx)**3.000;\n (x_2::Double) = x*x;\n (x_4::Double) = x_2*x_2;\n } in if (cx<(-1.000)) then (gammaAux a b) else (unit>>=(\\((u::Double)) -> if ((u<(1.000-(3.310e-2*x_4)))||((log u)<((0.500*x_2)+(d*((1.000-v)+(log v)))))) then (return ((b*d)*v)) else (gammaAux a b))))\n\ngamma :: (Double -> ((Double -> (Prob Double))))\ngamma = \\((k::Double)) -> \\((theta::Double)) -> if (k<1.000) then (unit>>=(\\((u::Double)) -> (gamma (1.000+k) theta)>>=(\\((x::Double)) -> return (x*(u**(1.000/k)))))) else (gammaAux k theta)\n\nimproper_uniform :: Prob Double\nimproper_uniform = gamma 1 0.100\n\nimproper_uniformLogPdf :: (a -> Double)\nimproper_uniformLogPdf = \\(_) -> 1.000\n\nimproper_uniform_positive :: Prob Double\nimproper_uniform_positive = gamma 1 1\n\nunfoldN :: (Int -> ((Int -> ((a -> ((((Int -> ((a -> (Prob a))))) -> (Prob ([a])))))))))\nunfoldN = \\((n::Int)) -> \\((m::Int)) -> \\(lastx) -> \\((s::(Int -> ((a -> (Prob a)))))) -> if (n>=(\\(x) -> (((unfoldN (n+1) m) x) s)>>=(\\((xs::[a])) -> return (x:xs)))) else ((s n lastx)>>=(\\(v) -> return (v:[])))\n\nunfold :: (Int -> ((a -> ((((a -> (Prob a))) -> (Prob ([a])))))))\nunfold = \\((n::Int)) -> \\(x0) -> \\((s::(a -> (Prob a)))) -> ((unfoldN 1 n) x0) (\\((i::Int)) -> s)\n\nimproper_uniformInit :: Double\nimproper_uniformInit = 1.000\n\nser :: Double\nser = 1.000\n\nnormal :: (Double -> ((Double -> (Prob Double))))\nnormal = \\((mean::Double)) -> \\((variance::Double)) -> unormal>>=(\\((u::Double)) -> return ((u*(sqrt variance))+mean))\n\nrwmTrans :: (BayNum a) => ((((Vector Double) -> Double)) -> (((Vector Double) -> ((((Double,((Double,a)))) -> ((Double -> (Prob (((((Vector Double),((Double,((Double,a)))))),Double))))))))))\nrwmTrans = \\((posterior::((Vector Double) -> Double))) -> \\((xi::Vector Double)) -> \\(((sigma::Double),((i::Double),(iaccept::a)))) -> \\((pi::Double)) -> (fmap listToVec (mapM (\\((x::Double)) -> normal x sigma) (vecToList xi)))>>=(\\((xstar::Vector Double)) -> let {(pstar::Double) = posterior xstar;\n (ratio::Double) = exp (pstar-pi);\n } in unit>>=(\\((u::Double)) -> let {(accept::Bool) = u ((Double,((Double,Double)))))\nrwmIni = \\(_) -> (0.100,((1.000,0.000)))\n\nrwm :: Strategy ((Double,((Double,Double))))\nrwm = VStrategy rwmTrans rwmIni\n\nmalaTrans :: ((((Vector Double) -> ((Double,a)))) -> (((Vector Double) -> ((Double -> ((((Double,a)) -> (Prob (((((Vector Double),Double)),((Double,a))))))))))))\nmalaTrans = \\((postgrad::((Vector Double) -> ((Double,a))))) -> \\((xi::Vector Double)) -> \\((sigma::Double)) -> \\(((pi::Double),gradienti)) -> let {(xstarMean::Vector Double) = xi;\n } in (fmap listToVec (mapM (\\((x::Double)) -> normal x sigma) (vecToList xi)))>>=(\\((xstar::Vector Double)) -> let {((pstar::Double),gradientStar) = postgrad xstar;\n (ratio::Double) = exp (pstar-pi);\n } in unit>>=(\\((u::Double)) -> let {(accept::Bool) = u (a -> b)\nmalaIni = \\(vini) -> 1\n\nmala :: Strategy Double\nmala = GStrategy malaTrans malaIni\n\nuniform :: (Double -> ((Double -> (Prob Double))))\nuniform = \\((lo::Double)) -> \\((hi::Double)) -> unit>>=(\\((x::Double)) -> return ((x*(hi-lo))+lo))\n\noneOf :: (([a]) -> (Prob a))\noneOf = \\((xs::[a])) -> (fmap floor (uniform 0.000 (unround (length xs))))>>=(\\((idx::Int)) -> return (ix idx xs))\n\noneOfLogPdf :: (([a]) -> ((b -> Double)))\noneOfLogPdf = \\((xs::[a])) -> \\(_) -> 1.000/(unround (length xs))\n\nuniformLogPdf :: (Double -> ((Double -> ((Double -> Double)))))\nuniformLogPdf = \\((lo::Double)) -> \\((hi::Double)) -> \\((x::Double)) -> if ((xlo)) then ((log 1)-(log (hi-lo))) else (0.000-1.000e20)\n\nintBetween :: (BayNum a) => (a -> ((a -> (Prob Int))))\nintBetween = \\((lo::a)) -> \\((hi::a)) -> unit>>=(\\((x::Double)) -> return (floor ((x*(unround ((hi+1)-lo)))+(unround lo))))\n\nany :: Prob a\nany = undefined\n\nimproper_uniform_positiveLogPdf :: (BayNum a) => (a -> Double)\nimproper_uniform_positiveLogPdf = \\((x::a)) -> if (x>0) then 1.000 else (0.000-1.000e20)\n\noneTo :: (BayNum a) => (a -> (Prob Int))\noneTo = \\((n::a)) -> (uniform 0.500 ((unround n)+0.500))>>=(\\((x::Double)) -> return (round x))\n\noneToLogPdf :: (BayNum a) => (a -> ((a -> Double)))\noneToLogPdf = \\((hi::a)) -> \\((x::a)) -> if ((x<(hi+1))&&(x>0)) then 1.000 else (0.000-1.000e10)\n\nnormalLogPdf :: (Double -> ((Double -> ((Double -> Double)))))\nnormalLogPdf = \\((mean::Double)) -> \\((variance::Double)) -> \\((x::Double)) -> ((log 1)-(0.500*(log ((2.000*pi)*variance))))-(((x-mean)**2)/(2*variance))\n\nlogNormal :: (Double -> ((Double -> (Prob Double))))\nlogNormal = \\((mean::Double)) -> \\((variance::Double)) -> fmap exp (normal mean variance)\n\nlogNormalLogPdf :: (Double -> ((Double -> ((Double -> Double)))))\nlogNormalLogPdf = \\((mean::Double)) -> \\((variance::Double)) -> \\((x::Double)) -> (log (1/(sqrt ((2.000*pi)*variance))))+(0.000-((((log x)-mean)*((log x)-mean))/(2*variance)))\n\nnormalLines :: (Double -> ((Double -> ([(Double,Double)]))))\nnormalLines = \\((mean::Double)) -> \\((v::Double)) -> let {(f::(Double -> ((Double,Double)))) = \\((x::Double)) -> (x,(exp ((normalLogPdf mean v) x)));\n } in map f ((linspace (mean-(3*(sqrt v))) (mean+(3*(sqrt v)))) 50)\n\nbinomialProb :: (Int -> ((Double -> ((Int -> Double)))))\nbinomialProb = \\((n::Int)) -> \\((p::Double)) -> \\((k::Int)) -> ((choose n k)*(p^k))*((1.000-p)^(n-k))\n\nbinomialLogProb :: (Int -> ((Double -> ((Int -> Double)))))\nbinomialLogProb = \\((n::Int)) -> \\((p::Double)) -> \\((k::Int)) -> ((log (choose n k))+((unround k)*(log p)))+((unround (n-k))*(log (1.000-p)))\n\nbernoulli :: (Double -> (Prob Bool))\nbernoulli = \\((p::Double)) -> unit>>=(\\((u::Double)) -> return (u (Prob Int))\nbernoulli01 = \\((p::Double)) -> unit>>=(\\((u::Double)) -> if (u ((Bool -> Double)))\nbernoulliLogPdf = \\(((_arg0)::Double)) -> \\(((_arg1)::Bool)) -> case (_arg0,_arg1) of {((p::Double),True ) -> log p; ((p::Double),False ) -> log (1-p)}\n\nbernoulli01LogPdf :: (Double -> ((Int -> Double)))\nbernoulli01LogPdf = \\(((_arg0)::Double)) -> \\(((_arg1)::Int)) -> case (_arg0,_arg1) of {((p::Double),1) -> log p; ((p::Double),0) -> log (1-p)}\n\ncountTrue :: (BayNum a) => (([Bool]) -> a)\ncountTrue = \\(((_arg0)::[Bool])) -> case _arg0 of {[] -> 0; (True :(bs::[Bool])) -> 1+(countTrue bs); (False :(bs::[Bool])) -> countTrue bs}\n\nbinomial :: (BayNum a) => (Int -> ((Double -> (Prob a))))\nbinomial = \\((n::Int)) -> \\((p::Double)) -> (repeat n (unit>>=(\\((u::Double)) -> return (u>=(\\((bools::[Bool])) -> return (countTrue bools))\n\nexponential :: (Double -> (Prob Double))\nexponential = \\((lam::Double)) -> unit>>=(\\((u::Double)) -> return (neg ((log u)/lam)))\n\nexponentialLogPdf :: (Double -> ((Double -> Double)))\nexponentialLogPdf = \\((lam::Double)) -> \\((x::Double)) -> lam*(exp ((0.000-lam)*x))\n\npoissonAux :: (BayNum a) => (Double -> ((a -> ((Double -> (Prob a))))))\npoissonAux = \\((bigl::Double)) -> \\((k::a)) -> \\((p::Double)) -> if (p>bigl) then (unit>>=(\\((u::Double)) -> (poissonAux bigl (k+1)) (p*u))) else (return (k-1))\n\npoisson :: (Double -> (Prob Int))\npoisson = \\((lam::Double)) -> (poissonAux (exp (0.000-lam)) 0) 1\n\npoissonLogPdf :: (Double -> ((Int -> Double)))\npoissonLogPdf = \\((lam::Double)) -> \\((x::Int)) -> ((lam**(unround x))*(exp (0.000-lam)))/(unround (fac x))\n\nbetaAux :: (Int -> (Prob Double))\nbetaAux = \\((n::Int)) -> (repeat n unit)>>=(\\((us::[Double])) -> return (log (product us)))\n\nbeta :: (Int -> ((Int -> (Prob Double))))\nbeta = \\((a::Int)) -> \\((b::Int)) -> (betaAux a)>>=(\\((g1::Double)) -> (betaAux b)>>=(\\((g2::Double)) -> return (g1/(g1+g2))))\n\ncof :: [Double]\ncof = 76.180:((-86.505):(24.014:((-1.232):(1.209e-3:((-5.395e-6):[])))))\n\ngammaln :: (Double -> Double)\ngammaln = \\((xx::Double)) -> let {(tmp'::Double) = (xx+5.500)-((xx+0.500)*(log (xx+5.500)));\n (ser'::Double) = ser+(sum (map (\\(((y::Double),(c::Double))) -> c/(xx+y)) (zip (fromTo 1 7) cof)));\n } in (0.000-tmp')+(log ((2.507*ser')/xx))\n\nbetaf :: (Double -> ((Double -> Double)))\nbetaf = \\((z::Double)) -> \\((w::Double)) -> exp (((gammaln z)+(gammaln w))-(gammaln (z+w)))\n\nbetaLogPdf :: (Int -> ((Int -> ((Double -> Double)))))\nbetaLogPdf = \\((a::Int)) -> \\((b::Int)) -> \\((x::Double)) -> log (((1.000/(betaf (unround a) (unround b)))*(x^(a-1)))*((1.000-x)^(b-1)))\n\ninvGamma :: (Double -> ((Double -> (Prob Double))))\ninvGamma = \\((a::Double)) -> \\((b::Double)) -> (gamma a (1.000/b))>>=(\\((g::Double)) -> return (1.000/g))\n\nwiener :: ((Double) -> (((Double) -> (Prob ((Double -> Double))))))\nwiener = \\((dt::Double)) -> \\((tmax::Double)) -> let {(n::Int) = (round (tmax/dt))+1;\n } in (repeat n unormal)>>=(\\((ns::[Double])) -> let {(etas::[Double]) = map (\\((u::Double)) -> u*(sqrt dt)) ns;\n } in return ((pack dt (0.000-dt)) (listToVec ((scanl (\\((x::Double)) -> \\((y::Double)) -> x+y) 0.000) etas))))\n\ndiff :: ((Double) -> ((((Double -> Double)) -> ((Double -> Double)))))\ndiff = \\((dt::Double)) -> \\((w::(Double -> Double))) -> \\((t::Double)) -> ((w t)-(w (t-dt)))/dt\n\ndecide :: (Double -> (((Vector Double) -> (((Prob a) -> (((((Vector Double) -> ((a -> Double)))) -> (Vector Double))))))))\ndecide = \\((tol::Double)) -> \\((ini::Vector Double)) -> \\((dist::Prob a)) -> \\((util::((Vector Double) -> ((a -> Double))))) -> (optimise tol ini) (\\((vaction::Vector Double)) -> expect (fmap (util vaction) dist))\n\nnsig :: (((Double -> Double)) -> ((Double -> (Prob ((Double -> Double))))))\nnsig = \\((sig::(Double -> Double))) -> \\((v::Double)) -> case observeSig sig of {ObservedSignal (dt::Double) (t0::Double) (vpts::Vector Double) -> (repeat (dim vpts) (normal 0 v))>>=(\\((ns::[Double])) -> return ((pack dt t0) (listToVec (map (\\(((x::Double),(y::Double))) -> x+y) (zip ns (vecToList vpts))))))}\n\nquantile :: (Double -> (((Prob Double) -> Double)))\nquantile = \\((x::Double)) -> \\(Samples (xs::[Double])) -> let {(total::Int) = length xs;\n (under::Int) = length (filter (\\((y::Double)) -> x ((Double -> ((Double -> Double)))))\ngammaLogPdf = \\((k::Double)) -> \\((theta::Double)) -> \\((x::Double)) -> ((((k-1)*(log x))+((0.000-x)/theta))-(k*(log theta)))-(gammaln k)\n\ninvGammaLogPdf :: (Double -> ((Double -> ((Double -> Double)))))\ninvGammaLogPdf = \\((a::Double)) -> \\((b::Double)) -> \\((x::Double)) -> log ((((b**a)/(exp (gammaln a)))*(x**((0.000-a)-1)))*(exp ((0.000-b)/x)))\n\ncookAssert :: ((Prob Double) -> SamplerDensity)\ncookAssert = \\((s::Prob Double)) -> SamplerDensity s (uniformLogPdf 0 1)\n\nmultiNormalLogPdf :: (a -> ((b -> c)))\nmultiNormalLogPdf = \\(vmean) -> \\(cov) -> undefined\n\nmultiNormal :: ((Vector Double) -> (((Matrix Double) -> (Prob (Vector Double)))))\nmultiNormal = \\((vmean::Vector Double)) -> \\((cov::Matrix Double)) -> (repeat (dim vmean) (normal 0 1))>>=(\\((ns::[Double])) -> let {((u::Matrix Double):((s::Matrix Double):((v::Matrix Double):[]))) = svd cov;\n (j::Matrix Double) = mXm (mXm v (mmap sqrt s)) (transM v);\n } in return (vmean+(mXv j (listToVec ns))))\n\nscandyn' :: (BayNum a) => (((Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes)))))))))) -> ((a -> ((Int -> ((sdes -> ((odes -> ((([odes]) -> ((([sdes]) -> ((a,([odes]))))))))))))))))\nscandyn' = \\(((_arg0)::(Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes))))))))))) -> \\(((_arg1)::a)) -> \\(((_arg2)::Int)) -> \\((_arg3)) -> \\((_arg4)) -> \\(((_arg5)::[odes])) -> \\(((_arg6)::[sdes])) -> case (_arg0,((_arg1,((_arg2,((_arg3,((_arg4,((_arg5,_arg6))))))))))) of {((f::(Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes)))))))))),((p::a),(_,(_,(_,((odeacc::[odes]),[])))))) -> (p,(reverse odeacc)); ((f::(Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes)))))))))),((p0::a),((i::Int),(sdelast,(odecurr,((odeacc::[odes]),(sde:(sdes::[sdes])))))))) -> let {((p1::a),odenext) = ((f i odecurr) sdelast) sde;\n } in (((((scandyn' f (p0+p1)) (i+1)) sde) odenext) (odenext:odeacc)) sdes}\n\nscandyn :: (BayNum a) => (((Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes)))))))))) -> ((odes -> ((sdes -> ((([sdes]) -> ((a,([odes]))))))))))\nscandyn = \\((f::(Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes))))))))))) -> \\(initode) -> \\(initsde) -> \\((sdes::[sdes])) -> (((((scandyn' f 0) 0) initsde) initode) []) sdes\n\nsamples :: (BayNum a) => a\nsamples = 10000\n\nregress :: Prob ([((R.X R.:& Y R.::: Double R.:& W R.::: Double) (Id KindStar))])\nregress = (normal 0 1)>>=(\\((offset::Double)) -> (gamma 1 1)>>=(\\((sigma::Double)) -> (normal 0 1)>>=(\\((slope::Double)) -> repeat 50 ((normal 0 1)>>=(\\((w::Double)) -> (normal (offset+(slope*w)) sigma)>>=(\\((y::Double)) -> return (R.X R.:& Y R.:= (y) R.:& W R.:= (w))))))))\n\nregress1 :: Prob ([((R.X R.:& Y R.::: Double R.:& W R.::: Double) (Id KindStar))])\nregress1 = repeat 50 ((uniform 0.000 1.000)>>=(\\((w::Double)) -> (normal ((1*w)-0.500) 0.100)>>=(\\((y::Double)) -> return (R.X R.:& Y R.:= (y) R.:& W R.:= (w)))))\n\ndata W = W deriving Show\ninstance R.Name W where\n name = W\ndata Y = Y deriving Show\ninstance R.Name Y where\n name = Y\ndata Posterior = Posterior deriving Show\ninstance R.Name Posterior where\n name = Posterior\ndata Postgrad = Postgrad deriving Show\ninstance R.Name Postgrad where\n name = Postgrad\ndata VToRec = VToRec deriving Show\ninstance R.Name VToRec where\n name = VToRec\ndata Inisam = Inisam deriving Show\ninstance R.Name Inisam where\n name = Inisam\ndata Offset = Offset deriving Show\ninstance R.Name Offset where\n name = Offset\ndata Sigma = Sigma deriving Show\ninstance R.Name Sigma where\n name = Sigma\ndata Slope = Slope deriving Show\ninstance R.Name Slope where\n name = Slope\n\ntarget = do\n ((fakedata::[((R.X R.:& Y R.::: Double R.:& W R.::: Double) (Id KindStar))]))::[((R.X R.:& Y R.::: Double R.:& W R.::: Double) (Id KindStar))] <- sample (regress1::Prob ([((R.X R.:& Y R.::: Double R.:& W R.::: Double) (Id KindStar))]))\n let prims :: ((R.X R.:& Inisam R.::: Prob ([Double]) R.:& VToRec R.::: ((Vector Double) -> ((R.X R.:& Slope R.::: Double R.:& Sigma R.::: Double R.:& Offset R.::: Double) (Id KindStar))) R.:& Postgrad R.::: ((Vector Double) -> ((Double,(Vector Double)))) R.:& Posterior R.::: (([Double]) -> Double)) (Id KindStar))\n prims = let {(final0::[((R.X R.:& Y R.::: Double R.:& W R.::: Double) (Id KindStar))]) = fakedata;\n posterior = runP1 (bindP headP (\\(offset) -> bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(sigma) -> bindP headP (\\(slope) -> bindP (forP final0 (\\((R.X R.:& Y R.:= (y::Double) R.:& W R.:= (w::Double))) -> returnP ())) (\\(final0_pars) -> returnP (((normalLogPdf 0 1) offset)+(((gammaLogPdf 1 1) sigma)+(((normalLogPdf 0 1) slope)+((sum (map (\\(((R.X R.:& Y R.:= (y::Double) R.:& W R.:= (w::Double)),(()))) -> ((normalLogPdf 0 1) w)+(((normalLogPdf (offset+(slope*w)) sigma) y)+0)) (zip final0 final0_pars)))+0)))))))));\n postgrad = \\((_v)) -> runST ((newSTRef 0)>>=(\\(postref) -> (VSM.replicate (dim _v) 0)>>=(\\(gradref) -> (newSTRef (0::Int))>>=(\\(countref) -> let {post_incr = addSTRef postref;\n grad_incr = addMV gradref;\n count_incr = incrSTRef countref;\n } in (count_incr 1)>>=(\\((_offset_pos)) -> let {offset = _v@>_offset_pos;\n } in (((post_incr ((\\(x) -> ((log 1)-(0.500*(log ((2.000*pi)*1))))-(((x-0)**2)/(2*1))) offset))>>(grad_incr _offset_pos (0-((0+((2*1)*((2*(offset-0))*(1-0))))/((2*1)*(2*1))))))>>(return ()))>>((count_incr 1)>>=(\\((_sigma_pos)) -> let {sigma = exp (_v@>_sigma_pos);\n } in (((post_incr ((\\(x) -> ((((1-1)*(log x))+((0.000-x)/1))-(1*(log 1)))-(gammaln 1)) sigma))>>(grad_incr _sigma_pos (((\\((_x)) -> (exp _x)*1) (_v@>_sigma_pos))*((((0+((1-1)*((1/sigma)*1)))+((0+(1*(0-1)))/(1*1)))-0)-0))))>>(return ()))>>((count_incr 1)>>=(\\((_slope_pos)) -> let {slope = _v@>_slope_pos;\n } in (((post_incr ((\\(x) -> ((log 1)-(0.500*(log ((2.000*pi)*1))))-(((x-0)**2)/(2*1))) slope))>>(grad_incr _slope_pos (0-((0+((2*1)*((2*(slope-0))*(1-0))))/((2*1)*(2*1))))))>>(return ()))>>((forM final0 (\\((R.X R.:& Y R.:= (y::Double) R.:& W R.:= (w::Double))) -> ((post_incr ((\\(x) -> ((log 1)-(0.500*(log ((2.000*pi)*1))))-(((x-0)**2)/(2*1))) w))>>(return ()))>>(((post_incr ((\\(x) -> ((log 1)-(0.500*(log ((2.000*pi)*sigma))))-(((x-(offset+(slope*w)))**2)/(2*sigma))) y))>>((((return ())>>(grad_incr _slope_pos (1*(0-((0+((2*sigma)*((2*(y-(offset+(slope*w))))*(0-(0+(0+(w*1)))))))/((2*sigma)*(2*sigma)))))))>>(grad_incr _sigma_pos (((\\((_x)) -> (exp _x)*1) (_v@>_sigma_pos))*((0-(0+(0.500*((1/((2.000*pi)*sigma))*(0+((2.000*pi)*1))))))-((0+(0-(((y-(offset+(slope*w)))**2)*(0+(2*1)))))/((2*sigma)*(2*sigma)))))))>>(grad_incr _offset_pos (1*(0-((0+((2*sigma)*((2*(y-(offset+(slope*w))))*(0-(1+0)))))/((2*sigma)*(2*sigma))))))))>>(return (R.X R.:& Y R.:= (y) R.:& W R.:= (w))))))>>=(\\((final0::[((R.X R.:& Y R.::: Double R.:& W R.::: Double) (Id KindStar))])) -> (readSTRef postref)>>=(\\(postval) -> (VS.unsafeFreeze gradref)>>=(\\(gradval) -> return ((postval,gradval)))))))))))))));\n vToRec = \\(theta) -> runP (toList theta) (bindP headP (\\(offset) -> bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(sigma) -> bindP headP (\\(slope) -> bindP (forP final0 (\\((R.X R.:& Y R.:= (y::Double) R.:& W R.:= (w::Double))) -> returnP ())) (\\(final0_pars) -> returnP (R.X R.:& Slope R.:= (slope) R.:& Sigma R.:= (sigma) R.:& Offset R.:= (offset)))))));\n inisam = (normal 0 1)>>=(\\(offset) -> (gamma 1 1)>>=(\\(sigma) -> (normal 0 1)>>=(\\(slope) -> (repeat (length final0) ((normal 0 1)>>=(\\(w) -> (normal (offset+(slope*w)) sigma)>>=(\\(y) -> return (((R.X R.:& Y R.:= (y) R.:& W R.:= (w)),(concat [])))))))>>=(\\(final0_ret) -> let {(final0::[((R.X R.:& Y R.::: Double R.:& W R.::: Double) (Id KindStar))]) = map fst final0_ret;\n final0_iniret = map snd final0_ret;\n } in return (concat ((offset:[]):(((log sigma):[]):((slope:[]):((concat final0_iniret):[])))))))));\n } in R.X R.:& Inisam R.:= (inisam) R.:& VToRec R.:= (vToRec) R.:& Postgrad R.:= (postgrad) R.:& Posterior R.:= (posterior)\n let post :: (Vector Double -> Double)\n post = (prims!!!Posterior) . VS.toList\n let postgrad :: ((Vector Double) -> ((Double,(Vector Double))))\n postgrad = prims!!!Postgrad\n let vtorec :: ((Vector Double) -> ((R.X R.:& Slope R.::: Double R.:& Sigma R.::: Double R.:& Offset R.::: Double) (Id KindStar)))\n vtorec = prims!!!VToRec\n let inisam :: Prob (Vector Double)\n inisam = fmap (VS.fromList) $ prims!!!Inisam\n return (post, postgrad,vtorec,inisam)\n", "meta": {"hexsha": "e03a7ecc2b66e532fb8e9824df899ba23112ab38", "size": 33317, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Target/Regression.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Target/Regression.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Target/Regression.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 62.5084427767, "max_line_length": 1184, "alphanum_fraction": 0.5191343758, "num_tokens": 12075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.23083409903895866}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DeriveGeneric #-}\nmodule Lib where\n -- ( someFunc\n -- ) where\n\nimport Statistics.Distribution (probability)\nimport Statistics.Distribution.Binomial (binomial)\nimport Data.List\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Text.Lazy as TL\nimport Web.Scotty as S\nimport Text.Blaze.Html5 as H\nimport Text.Blaze.Html5.Attributes as A\nimport Text.Blaze.Html.Renderer.Pretty\nimport Text.Blaze.Internal (customAttribute)\nimport Network.Wai.Middleware.Static\n\n\nimport Data.Aeson\nimport GHC.Generics\nimport Views (indexPage)\n\n\nsomeFunc :: IO ()\nsomeFunc = scotty 5000 $ do\n middleware $ staticPolicy (noDots >-> addBase \"Static\")\n get \"/\" indexPage\n post \"/data\" postRoute\n\npostRoute :: ActionM ()\npostRoute = do\n shippy <- S.body\n maybeShip shippy\n \n\nmaybeShip param = let shippy = decode param :: Maybe Parameters\n in case (shippy) of\n (Just fleet) -> S.json $ calcFleet fleet\n Nothing -> S.json $ calcFleet testParam\n\ndata ShipPart = Empty\n | IonCannon\n | ElectronComputer\n | Hull\n | NuclearDrive\n | NuclearSource\n | PlasmaCannon\n | AntimatterCannon\n | PlasmaMissile\n | PositronComputer\n | GluonComputer\n | GaussShield\n | PhaseShield\n | ImprovedHull\n | FusionDrive\n | TachyonDrive\n | FusionSource\n | TachyonSource\n deriving (Show, Generic)\n\ninstance ToJSON ShipPart\ninstance FromJSON ShipPart\n\ndata Parameters = Parameters {ships :: [([ShipPart], Count)], enemyShield :: Count}\n deriving (Show, Generic)\n\ninstance ToJSON Parameters\ninstance FromJSON Parameters\n\n\npartsToShip :: [ShipPart] -> Ship\npartsToShip xs = foldr (\\x acc -> sumShips acc (partToShip x)) (Ship 0 0 0 0 0) xs\n where sumShips (Ship i p a c m) (Ship i' p' a' c' m') =\n Ship {ions = i + i'\n , plasmas = p + p'\n , antis = a + a'\n , computers = c + c'\n , missiles = m + m'}\n\npartToShip :: ShipPart -> Ship\npartToShip IonCannon = Ship 1 0 0 0 0\npartToShip ElectronComputer = Ship 0 0 0 1 0\npartToShip PlasmaCannon = Ship 0 1 0 0 0 \npartToShip AntimatterCannon = Ship 0 0 1 0 0\npartToShip PlasmaMissile = Ship 0 0 0 0 1\npartToShip PositronComputer = Ship 0 0 0 2 0\npartToShip GluonComputer = Ship 0 0 0 3 0\npartToShip _ = Ship 0 0 0 0 0\n \n\ntype Damage = Int\ntype Dices = Int\ntype ToHit = Int\ntype Count = Int\ntype Percentage = Double\n\ntype ResMap = Map.Map Int Percentage\n\n\ndata Probability = Prob [(Damage, Percentage)] deriving Show\ndata Hits = Hits [(Count, Percentage)] deriving Show\ntype Damages = [(Damage, Percentage)] \ndata Results = Results {labels :: [Damage], probs:: [Percentage],\n mprobs :: [Percentage]}\n deriving (Show, Generic)\n\ninstance ToJSON Results\ninstance FromJSON Results\n\n\ntestParam :: Parameters\ntestParam = Parameters {ships = [([IonCannon, IonCannon, ElectronComputer, Empty], 2),\n ([IonCannon, PlasmaCannon, Hull, Empty], 1)]\n , enemyShield = 0}\n\n\ndata Ship = Ship {ions :: Count,\n plasmas :: Count,\n antis :: Count,\n computers:: ToHit,\n missiles :: Count} deriving (Generic, Show)\n\ninstance ToJSON Ship \n\ninstance FromJSON Ship\n\ntype EnemyShields = Count\n\n\ncalcHits :: Dices -> ToHit -> Hits\ncalcHits k hit\n | k < 1 || hit < 1 || hit > 6 = Hits []\n | otherwise = Hits $ fmap (\\x -> (x, probability binom x)) [0..k]\n where binom = binomial k p\n p = if hit <= 2 then fromIntegral 5 /6 else fromIntegral (6 - hit + 1) / 6 \n\ncalcDmgs :: Ship -> EnemyShields -> Damages\ncalcDmgs ship shield = combineDmgs [ionDmg,plasmaDmg,antiDmg]\n where ionDmg = hitsToDmgs 1 $ calcHits (ions ship) toHit\n plasmaDmg = hitsToDmgs 2 $ calcHits (plasmas ship) toHit\n antiDmg = hitsToDmgs 4 $ calcHits (antis ship) toHit\n toHit | shield - (computers ship) > 0 = 6\n | otherwise = 6 - (computers ship) + shield\n\ncalcMissiles :: Ship -> EnemyShields -> Damages\ncalcMissiles ship shield = hitsToDmgs 2 $ calcHits (missiles ship * 2) toHit\n where toHit | shield - (computers ship) > 0 = 6\n | otherwise = 6 - (computers ship) + shield\n\nhitsToDmgs :: Damage -> Hits -> Damages\nhitsToDmgs d (Hits xs) = fmap (\\x -> (fst x * d, snd x)) xs\n \ncombineDmgs :: [Damages] -> Damages\ncombineDmgs [] = []\ncombineDmgs dmgs = foldr1 combine dmgs\n where combine xs [] = xs\n combine [] ys = ys\n combine xs ys = func <$> xs <*> ys \n func = \\x y -> (fst x + (fst y), snd x * (snd y))\n\n\nsortMerge :: Damages -> ResMap\nsortMerge xs = foldr helper startMap xs\n where largest = foldr (\\x acc -> if fst x > acc then fst x else acc) 0 xs\n startMap = Map.fromList [(k, 0::Percentage) | k<-[0..largest]]\n helper x acc = Map.insertWith (+) (fst x) (snd x) acc\n\n\ncalcFleet :: Parameters -> Results\ncalcFleet (Parameters fleet shields) = \n Results {labels = labels', probs = probs', mprobs = mprobs'}\n where mergedShips = uncurry mergeShip <$> fmap (\\x -> (partsToShip (fst x), snd x)) fleet\n cannonsDmgs = flip calcDmgs shields <$> mergedShips\n missileDmgs = flip calcMissiles shields <$> mergedShips\n otherDmgs = sortMerge $ combineDmgs cannonsDmgs\n misDmg = sortMerge $ combineDmgs missileDmgs\n len = Prelude.max (Map.size otherDmgs) (Map.size misDmg)\n labels' = [0..len - 1] \n probs' = Map.elems $ Map.map (*100) $ fillMap otherDmgs labels'\n mprobs' = Map.elems $ Map.map (*100) $ fillMap misDmg labels' \n\nmergeShip :: Ship -> Count -> Ship\nmergeShip ship k = Ship {ions = ions ship * k\n , plasmas = plasmas ship * k\n , antis = antis ship * k\n , missiles = missiles ship * k\n , computers = computers ship}\n\nfillMap mp l = foldr fun mp l\n where fun x acc = if Map.notMember x mp then Map.insert x 0 acc else acc\n \n \n\n\n\n\n", "meta": {"hexsha": "4a61c24ed9b04a365b248ed4dbb99e78ad13464b", "size": 6217, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "traunio/eclipse-bg", "max_stars_repo_head_hexsha": "b3d54e56960509fda13bdba59c98daf0585481e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "traunio/eclipse-bg", "max_issues_repo_head_hexsha": "b3d54e56960509fda13bdba59c98daf0585481e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lib.hs", "max_forks_repo_name": "traunio/eclipse-bg", "max_forks_repo_head_hexsha": "b3d54e56960509fda13bdba59c98daf0585481e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.398989899, "max_line_length": 91, "alphanum_fraction": 0.6105838829, "num_tokens": 1760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.22659551455995938}} {"text": "{-# LANGUAGE TypeOperators, DeriveDataTypeable, FlexibleInstances, ScopedTypeVariables, ImplicitParams, PackageImports, ViewPatterns #-}\nmodule Target.Heston where\n\nimport Target.Prelude\nimport qualified Data.Record as R\nimport Prelude hiding (scanl,repeat,replicate)\nimport Data.Record.Combinators ((!!!))\nimport Data.Kind\nimport Data.List (transpose)\nimport Data.TypeFun\nimport Numeric.LinearAlgebra hiding (diag, linspace, svd, )\nimport Math.Probably.Sampler hiding (uniform,primOneOf,logNormal,invGamma,binomial,gamma,oneOf,bernoulli, normal, unit, unormal,multiNormal)\nimport qualified Data.Text as T\nimport Foreign.Storable (Storable)\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad (forM, forM_)\nimport qualified Data.Vector.Storable.Mutable as VSM\nimport qualified Data.Vector.Storable as VS\nimport Foreign.Storable.Tuple\n\n(.==.) :: (Eq a) => (a -> ((a -> Double)))\n(.==.) = \\((x::a)) -> \\((y::a)) -> if (x==y) then 1.000 else 0.000\n\nscanl :: (((a -> ((b -> a)))) -> ((a -> ((([b]) -> ([a]))))))\nscanl = \\(((_arg0)::(a -> ((b -> a))))) -> \\((_arg1)) -> \\(((_arg2)::[b])) -> case (_arg0,((_arg1,_arg2))) of {((op::(a -> ((b -> a)))),(acc,[])) -> acc:[]; ((op::(a -> ((b -> a)))),(acc,(x:(xs::[b])))) -> acc:((scanl op (op acc x)) xs)}\n\nfromTo :: (BayNum a) => (a -> ((a -> ([a]))))\nfromTo = \\((n::a)) -> \\((m::a)) -> if (n ((Int -> ((((Int -> Double)) -> Double)))))\nbigSum = \\((lo::Int)) -> \\((hi::Int)) -> \\((f::(Int -> Double))) -> sum (map f (fromTo lo hi))\n\nreplicate :: (Int -> ((a -> ([a]))))\nreplicate = \\(((_arg0)::Int)) -> \\((_arg1)) -> case (_arg0,_arg1) of {(0,x) -> []; ((n::Int),x) -> x:(replicate (n-1) x)}\n\nneg :: (BayNum a) => (a -> a)\nneg = \\((x::a)) -> 0-x\n\nix :: (Int -> ((([a]) -> a)))\nix = \\(((_arg0)::Int)) -> \\(((_arg1)::[a])) -> case (_arg0,_arg1) of {(0,(x:_)) -> x; ((n::Int),(_:(xs::[a]))) -> ix (n-1) xs}\n\nlinspace :: (Double -> ((Double -> ((Double -> ([Double]))))))\nlinspace = \\((from::Double)) -> \\((to::Double)) -> \\((num::Double)) -> let {(dt::Double) = (to-from)/num;\n (is::[Double]) = fromTo 0 (num-1);\n } in map (\\((i::Double)) -> ((unround i)*dt)+from) is\n\ncountSamples :: ((Prob a) -> (Maybe Int))\ncountSamples = \\(((_arg0)::Prob a)) -> case _arg0 of {Samples (xs::[a]) -> Just (length xs); Sampler _ -> Nothing}\n\nunit :: Prob Double\nunit = Sampler primUnit\n\nprimOneOf :: (([a]) -> ((Seed -> ((a,Seed)))))\nprimOneOf = \\((xs::[a])) -> \\((seed::Seed)) -> let {((u::Double),(nextSeed::Seed)) = primUnit seed;\n (idx::Int) = floor (u*(unround (length xs)));\n } in ((ix idx xs),nextSeed)\n\nappend :: (([a]) -> ((([a]) -> ([a]))))\nappend = \\(((_arg0)::[a])) -> \\(((_arg1)::[a])) -> case (_arg0,_arg1) of {([],(ys::[a])) -> ys; ((x:(xs::[a])),(ys::[a])) -> x:(append xs ys)}\n\ninvlogit :: (Double -> Double)\ninvlogit = \\((x::Double)) -> 1/(1+(exp (0.000-x)))\n\nlogit :: (Double -> Double)\nlogit = \\((x::Double)) -> log (x/(1-x))\n\nboolToReal :: (Bool -> Double)\nboolToReal = \\(((_arg0)::Bool)) -> case _arg0 of {True -> 1.000; False -> 0.000}\n\nfor :: (Int -> ((Int -> ((((Int -> (Prob a))) -> (Prob ([a])))))))\nfor = \\((n::Int)) -> \\((m::Int)) -> \\((s::(Int -> (Prob a)))) -> if (n>=(\\(x) -> ((for (n+1) m) s)>>=(\\((xs::[a])) -> return (x:xs)))) else ((s n)>>=(\\(v) -> return (v:[])))\n\nrepeat :: (Int -> (((Prob a) -> (Prob ([a])))))\nrepeat = \\((n::Int)) -> \\((sam::Prob a)) -> (for 1 n) (\\((i::Int)) -> sam)\n\nsquare :: (BayNum a) => (a -> a)\nsquare = \\((x::a)) -> x*x\n\nstep :: (BayNum a,BayNum b) => (a -> b)\nstep = \\((x::a)) -> if (x<0) then 0 else 1\n\nfac :: (Int -> Int)\nfac = \\(((_arg0)::Int)) -> case _arg0 of {1 -> 1; (n::Int) -> n*(fac (n-1))}\n\nzipWithNats :: (BayNum b) => (([a]) -> ((b -> ([(b,a)]))))\nzipWithNats = \\(((_arg0)::[a])) -> \\(((_arg1)::b)) -> case (_arg0,_arg1) of {([],_) -> []; ((x:(xs::[a])),(n::b)) -> ((n,x)):(zipWithNats xs (n+1))}\n\nunSamples :: ((Prob a) -> ([a]))\nunSamples = \\(Samples (xs::[a])) -> xs\n\nchainPlot :: ((Prob Double) -> Plot)\nchainPlot = \\(Samples (xs::[Double])) -> Plot [] (return ((Points (zipWithNats xs 0)):[]))\n\nstyle :: (([(T.Text,T.Text)]) -> ((Plot -> Plot)))\nstyle = \\((opts::[(T.Text,T.Text)])) -> \\(Plot (pos::[(T.Text,T.Text)]) (plr::Prob ([Radian]))) -> Plot pos (fmap (\\((lrs::[Radian])) -> (Options opts lrs):[]) plr)\n\ndistPlot0 :: ((Prob Double) -> Plot)\ndistPlot0 = \\(((_arg0)::Prob Double)) -> case _arg0 of {Samples (xs::[Double]) -> Plot ((((T.pack \"range-y\"),(T.pack \"0\"))):[]) (return ((Histogram xs):[])); (sampler::Prob Double) -> Plot ((((T.pack \"range-y\"),(T.pack \"0\"))):[]) ((repeat 2000 sampler)>>=(\\((xs::[Double])) -> return ((Histogram xs):[])))}\n\ndistPlot :: ((Prob Double) -> Plot)\ndistPlot = \\((p::Prob Double)) -> style ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"fill-opacity\"),(T.pack \"0.3\"))):((((T.pack \"stroke\"),(T.pack \"none\"))):((((T.pack \"bar-width\"),(T.pack \"0.8\"))):[])))) (distPlot0 p)\n\nhistogram :: (BayNum a) => (([a]) -> Plot)\nhistogram = \\((xs::[a])) -> Plot [] (return ((Options ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"fill-opacity\"),(T.pack \"0.3\"))):((((T.pack \"stroke\"),(T.pack \"none\"))):((((T.pack \"bar-width\"),(T.pack \"0.8\"))):[])))) ((Histogram (map unround xs)):[])):[]))\n\nunPlot :: (Plot -> (Prob ([Radian])))\nunPlot = \\(Plot _ (x::Prob ([Radian]))) -> x\n\nover :: (([Plot]) -> Plot)\nover = \\((plots::[Plot])) -> Plot [] ((mapM unPlot plots)>>=(\\((items::[[Radian]])) -> return (map (\\((Plot (os::[(T.Text,T.Text)]) _,(rdns::[Radian]))) -> Options os rdns) (zip plots items))))\n\nscatterPlot :: (BayNum a,BayNum b) => (([(a,b)]) -> Plot)\nscatterPlot = \\((xys::[(a,b)])) -> style ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"marker-size\"),(T.pack \"30\"))):((((T.pack \"marker\"),(T.pack \"circle\"))):((((T.pack \"stroke\"),(T.pack \"none\"))):[])))) (Plot [] (return ((Points (map (\\(((x::a),(y::b))) -> ((unround x),(unround y))) xys)):[])))\n\nlinePlot :: (BayNum a,BayNum b) => (([(a,b)]) -> Plot)\nlinePlot = \\((xys::[(a,b)])) -> style ((((T.pack \"stroke\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[])) (Plot [] (return ((Lines (map (\\(((x::a),(y::b))) -> ((unround x),(unround y))) xys)):[])))\n\nplines :: (BayNum a,BayNum b) => ((Prob ([(a,b)])) -> Plot)\nplines = \\((plns::Prob ([(a,b)]))) -> style ((((T.pack \"stroke-opacity\"),(T.pack \"0.2\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[])) (Plot [] (repeat 50 (fmap (\\((xys::[(a,b)])) -> Lines (map (\\(((x::a),(y::b))) -> ((unround x),(unround y))) xys)) plns)))\n\nppoints :: ((Prob ([(Double,Double)])) -> Plot)\nppoints = \\((ppts::Prob ([(Double,Double)]))) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):[]) (repeat 50 (fmap Points ppts))\n\nsigPlot :: (((Double -> Double)) -> Plot)\nsigPlot = \\((sig::(Double -> Double))) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[])) (return ((Timeseries sig):[]))\n\nthin :: (Int -> ((([a]) -> ([a]))))\nthin = \\((skip::Int)) -> \\((xs::[a])) -> map snd (filter (\\(((i::Int),x)) -> (mod i (skip+1))==0) (zip (fromTo 0 ((length xs)-1)) xs))\n\nthinTo :: (Int -> ((([a]) -> ([a]))))\nthinTo = \\((n::Int)) -> \\((xs::[a])) -> let {(nxs::Int) = length xs;\n (ratio::Int) = round ((unround nxs)/(unround n));\n } in thin ratio xs\n\npsigPlot :: ((Prob ((Double -> Double))) -> Plot)\npsigPlot = \\(((_arg0)::Prob ((Double -> Double)))) -> case _arg0 of {Samples (sigs::[(Double -> Double)]) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-opacity\"),(T.pack \"0.2\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[]))) (return (map Timeseries (thinTo 20 sigs))); Sampler (f::(Seed -> ((((Double -> Double)),Seed)))) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-opacity\"),(T.pack \"0.2\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[]))) ((repeat 20 (Sampler f))>>=(\\((sigs::[(Double -> Double)])) -> return (map Timeseries sigs)))}\n\npsigNPlot :: (Int -> (((Prob ((Double -> Double))) -> Plot)))\npsigNPlot = \\(((_arg0)::Int)) -> \\(((_arg1)::Prob ((Double -> Double)))) -> case (_arg0,_arg1) of {((n::Int),Samples (sigs::[(Double -> Double)])) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-opacity\"),(T.pack \"0.2\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[]))) (return (map Timeseries (thinTo n sigs))); ((n::Int),Sampler (f::(Seed -> ((((Double -> Double)),Seed))))) -> Plot ((((T.pack \"fill\"),(T.pack \"pop_colour\"))):((((T.pack \"stroke-opacity\"),(T.pack \"0.1\"))):((((T.pack \"stroke-width\"),(T.pack \"2\"))):[]))) ((repeat n (Sampler f))>>=(\\((sigs::[(Double -> Double)])) -> return (map Timeseries sigs)))}\n\nprobBoolToP :: ((Prob Bool) -> (Prob Double))\nprobBoolToP = \\(((_arg0)::Prob Bool)) -> case _arg0 of {Sampler (f::(Seed -> ((Bool,Seed)))) -> (repeat 200 (Sampler f))>>=(\\((bs::[Bool])) -> probBoolToP (Samples bs)); Samples (bs::[Bool]) -> let {(yeas::[Bool]) = filter id bs;\n } in return ((unround (length yeas))/(unround (length bs)))}\n\npcurve :: (([(Double,(Prob Bool))]) -> Plot)\npcurve = \\((xps::[(Double,(Prob Bool))])) -> Plot [] (let {(xs::[Double]) = map fst xps;\n } in (mapM (probBoolToP.snd) xps)>>=(\\((ps::[Double])) -> return ((Lines (zip xs ps)):[])))\n\nplotStyle :: (([(T.Text,T.Text)]) -> ((Plot -> Plot)))\nplotStyle = \\(((_arg0)::[(T.Text,T.Text)])) -> \\(((_arg1)::Plot)) -> case (_arg0,_arg1) of {((opts::[(T.Text,T.Text)]),Plot (pos::[(T.Text,T.Text)]) (plr::Prob ([Radian]))) -> Plot (append opts pos) plr; ((opts::[(T.Text,T.Text)]),PlotRow (pos::[(T.Text,T.Text)]) (plr::[Plot])) -> PlotRow (append opts pos) plr; ((opts::[(T.Text,T.Text)]),PlotColumn (pos::[(T.Text,T.Text)]) (plr::[Plot])) -> PlotColumn (append opts pos) plr; ((opts::[(T.Text,T.Text)]),PlotStack (pos::[(T.Text,T.Text)]) (plr::[(T.Text,Plot)])) -> PlotStack (append opts pos) plr; ((opts::[(T.Text,T.Text)]),PlotGrid (pos::[(T.Text,T.Text)]) (x::Int) (y::Int) (plr::[(T.Text,Plot)])) -> ((PlotGrid (append opts pos) x) y) plr}\n\nwide :: (Plot -> Plot)\nwide = plotStyle ((((T.pack \"width\"),(T.pack \"750\"))):[])\n\naspect :: (Double -> ((Plot -> Plot)))\naspect = \\((x::Double)) -> plotStyle ((((T.pack \"aspect\"),(showReal x))):[])\n\nbesides :: (([Plot]) -> Plot)\nbesides = PlotRow []\n\nabove :: (([Plot]) -> Plot)\nabove = PlotColumn []\n\naxisLabels :: (T.Text -> ((T.Text -> ((Plot -> Plot)))))\naxisLabels = \\((xlab::T.Text)) -> \\((ylab::T.Text)) -> \\(Plot (popts::[(T.Text,T.Text)]) (plns::Prob ([Radian]))) -> Plot ((((T.pack \"axis-x-label\"),xlab)):((((T.pack \"axis-y-label\"),ylab)):popts)) plns\n\nunPlotOpts :: (Plot -> ([(T.Text,T.Text)]))\nunPlotOpts = \\(Plot (os::[(T.Text,T.Text)]) (x::Prob ([Radian]))) -> os\n\nsigLast :: (((Double -> Double)) -> Double)\nsigLast = \\((sig::(Double -> Double))) -> case observeSig sig of {ObservedSignal (dt::Double) (t0::Double) (pts::Vector Double) -> pts@>((dim pts)-1); ObservedXYSignal (pts::Vector ((Double,Double))) -> snd (pts@>((dim pts)-1))}\n\nsigTail :: (((Double -> Double)) -> ([Double]))\nsigTail = \\((sig::(Double -> Double))) -> case observeSig sig of {ObservedSignal (dt::Double) (t0::Double) (pts::Vector Double) -> vecToList pts}\n\nsigNPts :: (((Double -> Double)) -> Int)\nsigNPts = \\((sig::(Double -> Double))) -> case observeSig sig of {ObservedSignal (dt::Double) (t0::Double) (pts::Vector Double) -> dim pts; ObservedXYSignal (pts::Vector ((Double,Double))) -> dim pts}\n\nbetween :: (BayNum a) => (a -> ((a -> ((a -> Bool)))))\nbetween = \\((lo::a)) -> \\((hi::a)) -> \\((x::a)) -> (x>lo)&&(x ((((a -> ((c,d)))) -> c)))\nrunP = \\(xs) -> \\((my::(a -> ((c,d))))) -> fst (my xs)\n\nrunP1 :: (((a -> ((b,c)))) -> ((a -> b)))\nrunP1 = \\((my::(a -> ((b,c))))) -> \\(xs) -> fst (my xs)\n\nreturnP :: (a -> ((b -> ((a,b)))))\nreturnP = \\(x) -> \\(xs) -> (x,xs)\n\nbindP :: (((a -> ((b,c)))) -> ((((b -> ((c -> f)))) -> ((a -> f)))))\nbindP = \\((f::(a -> ((b,c))))) -> \\((g::(b -> ((c -> f))))) -> \\(xs) -> let {(x,xs') = f xs;\n } in g x xs'\n\nheadP :: (([a]) -> ((a,([a]))))\nheadP = \\(((_arg0)::[a])) -> case _arg0 of {(x:(xs::[a])) -> (x,xs); [] -> bayError (T.pack \"headP: empty list\")}\n\ntakeP :: (Int -> ((([a]) -> ((([a]),([a]))))))\ntakeP = \\((n::Int)) -> \\((xs::[a])) -> ((take n xs),(drop n xs))\n\nforP :: (([a]) -> ((((a -> ((c -> ((d,c)))))) -> ((c -> ((([d]),c)))))))\nforP = \\(((_arg0)::[a])) -> \\(((_arg1)::(a -> ((c -> ((d,c))))))) -> \\((_arg2)) -> case (_arg0,((_arg1,_arg2))) of {([],((f::(a -> ((c -> ((d,c)))))),xs)) -> ([],xs); ((a:(as::[a])),((f::(a -> ((c -> ((d,c)))))),xs)) -> (bindP (f a) (\\(y) -> bindP (forP as f) (\\((ys::[d])) -> returnP (y:ys)))) xs}\n\nnoP :: (a -> (((),a)))\nnoP = \\(xs) -> ((),xs)\n\nfmapP :: (((a -> b)) -> ((((c -> ((a,e)))) -> ((c -> ((b,e)))))))\nfmapP = \\((f::(a -> b))) -> \\((mx::(c -> ((a,e))))) -> bindP mx (\\(x) -> returnP (f x))\n\nfixP :: (Int -> (((Prob a) -> (Prob (Prob a)))))\nfixP = \\(((_arg0)::Int)) -> \\(((_arg1)::Prob a)) -> case (_arg0,_arg1) of {((n::Int),Sampler (f::(Seed -> ((a,Seed))))) -> (repeat n (Sampler f))>>=(\\((xs::[a])) -> return (Samples xs)); ((n::Int),Samples (xs::[a])) -> return (Samples (thinTo n xs))}\n\ndiag :: ((Vector Double) -> (Matrix Double))\ndiag = \\((v::Vector Double)) -> fillM (((dim v),(dim v))) (\\(((i::Int),(j::Int))) -> if (i==j) then (v@>i) else 0.000)\n\ndiagL :: (([Double]) -> (Matrix Double))\ndiagL = diag.listToVec\n\nmmap :: (BayNum a,BayNum b) => (((a -> b)) -> (((Matrix a) -> (Matrix b))))\nmmap = \\((f::(a -> b))) -> \\((m::Matrix a)) -> fillM (mdims m) (\\(((i::Int),(j::Int))) -> f (m@@>((i,j))))\n\ntransM :: (BayNum a) => ((Matrix a) -> (Matrix a))\ntransM = \\((m::Matrix a)) -> fillM (mdims m) (\\(((i::Int),(j::Int))) -> m@@>((j,i)))\n\nident :: (BayNum a) => (a -> (Matrix Double))\nident = \\((n::a)) -> diagL (map (const 1) (fromTo 1 n))\n\nmeanL :: (([Double]) -> Double)\nmeanL = \\((xs::[Double])) -> (sum xs)/(unround (length xs))\n\nvarL :: (([Double]) -> Double)\nvarL = \\((xs::[Double])) -> let {(mu::Double) = meanL xs;\n } in (sum (map (\\((x::Double)) -> (x-mu)*(x-mu)) xs))/(unround ((length xs)-1))\n\npopvarL :: (([Double]) -> Double)\npopvarL = \\((xs::[Double])) -> let {(mu::Double) = meanL xs;\n } in (sum (map (\\((x::Double)) -> (x-mu)*(x-mu)) xs))/(unround (length xs))\n\nminL :: (([Double]) -> Double)\nminL = \\(((x::Double):(xs::[Double]))) -> (foldl min x) xs\n\nmaxL :: (([Double]) -> Double)\nmaxL = \\(((x::Double):(xs::[Double]))) -> (foldl max x) xs\n\ngetT :: ((a) -> (((b) -> ((a,b)))))\ngetT = \\(dt) -> \\(tmax) -> (dt,tmax)\n\npearson :: (([(Double,Double)]) -> Double)\npearson = \\((xys::[(Double,Double)])) -> let {(xs::[Double]) = map fst xys;\n (ys::[Double]) = map snd xys;\n (mx::Double) = meanL xs;\n (my::Double) = meanL ys;\n (sx::Double) = sqrt (varL xs);\n (sy::Double) = sqrt (varL ys);\n (invN::Double) = 1.000/(unround ((length xys)-1));\n } in invN*(sum (map (\\(((x::Double),(y::Double))) -> ((x-mx)/sx)*((y-my)/sy)) xys))\n\ndata Strategy a = \n GStrategy (((((Vector Double) -> ((Double,(Vector Double))))) -> (((Vector Double) -> ((a -> ((((Double,(Vector Double))) -> (Prob (((((Vector Double),a)),((Double,(Vector Double)))))))))))))) (((Vector Double) -> a))\n |VStrategy (((((Vector Double) -> Double)) -> (((Vector Double) -> ((a -> ((Double -> (Prob (((((Vector Double),a)),Double))))))))))) (((Vector Double) -> a))\nintBetweenLogPdf :: (BayNum d) => (a -> ((b -> ((c -> d)))))\nintBetweenLogPdf = \\(lo) -> \\(hi) -> \\(x) -> 1\n\nanyLogPdf :: (a -> Double)\nanyLogPdf = \\(x) -> 1.000\n\nd :: ((Double) -> ((((Double -> Double)) -> ((Double -> Double)))))\nd = \\((dt::Double)) -> \\((w::(Double -> Double))) -> \\((t::Double)) -> ((w t)-(w (t-dt)))/dt\n\nunormal :: Prob Double\nunormal = unit>>=(\\((u1::Double)) -> unit>>=(\\((u2::Double)) -> return ((sqrt ((0.000-2.000)*(log u1)))*(cos ((2.000*pi)*u2)))))\n\ngammaAux :: (Double -> ((Double -> (Prob Double))))\ngammaAux = \\((a::Double)) -> \\((b::Double)) -> let {(d::Double) = a-(1.000/3.000);\n (c::Double) = 1.000/(3.000*(sqrt d));\n } in unormal>>=(\\((x::Double)) -> let {(cx::Double) = c*x;\n (v::Double) = (1.000+cx)**3.000;\n (x_2::Double) = x*x;\n (x_4::Double) = x_2*x_2;\n } in if (cx<(-1.000)) then (gammaAux a b) else (unit>>=(\\((u::Double)) -> if ((u<(1.000-(3.310e-2*x_4)))||((log u)<((0.500*x_2)+(d*((1.000-v)+(log v)))))) then (return ((b*d)*v)) else (gammaAux a b))))\n\ngamma :: (Double -> ((Double -> (Prob Double))))\ngamma = \\((k::Double)) -> \\((theta::Double)) -> if (k<1.000) then (unit>>=(\\((u::Double)) -> (gamma (1.000+k) theta)>>=(\\((x::Double)) -> return (x*(u**(1.000/k)))))) else (gammaAux k theta)\n\nimproper_uniform :: Prob Double\nimproper_uniform = gamma 1 0.100\n\nimproper_uniformLogPdf :: (a -> Double)\nimproper_uniformLogPdf = \\(_) -> 1.000\n\nimproper_uniform_positive :: Prob Double\nimproper_uniform_positive = gamma 1 1\n\nunfoldN :: (Int -> ((Int -> ((a -> ((((Int -> ((a -> (Prob a))))) -> (Prob ([a])))))))))\nunfoldN = \\((n::Int)) -> \\((m::Int)) -> \\(lastx) -> \\((s::(Int -> ((a -> (Prob a)))))) -> if (n>=(\\(x) -> (((unfoldN (n+1) m) x) s)>>=(\\((xs::[a])) -> return (x:xs)))) else ((s n lastx)>>=(\\(v) -> return (v:[])))\n\nunfold :: (Int -> ((a -> ((((a -> (Prob a))) -> (Prob ([a])))))))\nunfold = \\((n::Int)) -> \\(x0) -> \\((s::(a -> (Prob a)))) -> ((unfoldN 1 n) x0) (\\((i::Int)) -> s)\n\nimproper_uniformInit :: Double\nimproper_uniformInit = 1.000\n\nser :: Double\nser = 1.000\n\nnormal :: (Double -> ((Double -> (Prob Double))))\nnormal = \\((mean::Double)) -> \\((variance::Double)) -> unormal>>=(\\((u::Double)) -> return ((u*(sqrt variance))+mean))\n\nrwmTrans :: (BayNum a) => ((((Vector Double) -> Double)) -> (((Vector Double) -> ((((Double,((Double,a)))) -> ((Double -> (Prob (((((Vector Double),((Double,((Double,a)))))),Double))))))))))\nrwmTrans = \\((posterior::((Vector Double) -> Double))) -> \\((xi::Vector Double)) -> \\(((sigma::Double),((i::Double),(iaccept::a)))) -> \\((pi::Double)) -> (fmap listToVec (mapM (\\((x::Double)) -> normal x sigma) (vecToList xi)))>>=(\\((xstar::Vector Double)) -> let {(pstar::Double) = posterior xstar;\n (ratio::Double) = exp (pstar-pi);\n } in unit>>=(\\((u::Double)) -> let {(accept::Bool) = u ((Double,((Double,Double)))))\nrwmIni = \\(_) -> (0.100,((1.000,0.000)))\n\nrwm :: Strategy ((Double,((Double,Double))))\nrwm = VStrategy rwmTrans rwmIni\n\nmalaTrans :: ((((Vector Double) -> ((Double,a)))) -> (((Vector Double) -> ((Double -> ((((Double,a)) -> (Prob (((((Vector Double),Double)),((Double,a))))))))))))\nmalaTrans = \\((postgrad::((Vector Double) -> ((Double,a))))) -> \\((xi::Vector Double)) -> \\((sigma::Double)) -> \\(((pi::Double),gradienti)) -> let {(xstarMean::Vector Double) = xi;\n } in (fmap listToVec (mapM (\\((x::Double)) -> normal x sigma) (vecToList xi)))>>=(\\((xstar::Vector Double)) -> let {((pstar::Double),gradientStar) = postgrad xstar;\n (ratio::Double) = exp (pstar-pi);\n } in unit>>=(\\((u::Double)) -> let {(accept::Bool) = u (a -> b)\nmalaIni = \\(vini) -> 1\n\nmala :: Strategy Double\nmala = GStrategy malaTrans malaIni\n\nuniform :: (Double -> ((Double -> (Prob Double))))\nuniform = \\((lo::Double)) -> \\((hi::Double)) -> unit>>=(\\((x::Double)) -> return ((x*(hi-lo))+lo))\n\noneOf :: (([a]) -> (Prob a))\noneOf = \\((xs::[a])) -> (fmap floor (uniform 0.000 (unround (length xs))))>>=(\\((idx::Int)) -> return (ix idx xs))\n\noneOfLogPdf :: (([a]) -> ((b -> Double)))\noneOfLogPdf = \\((xs::[a])) -> \\(_) -> 1.000/(unround (length xs))\n\nuniformLogPdf :: (Double -> ((Double -> ((Double -> Double)))))\nuniformLogPdf = \\((lo::Double)) -> \\((hi::Double)) -> \\((x::Double)) -> if ((xlo)) then ((log 1)-(log (hi-lo))) else (0.000-1.000e20)\n\nintBetween :: (BayNum a) => (a -> ((a -> (Prob Int))))\nintBetween = \\((lo::a)) -> \\((hi::a)) -> unit>>=(\\((x::Double)) -> return (floor ((x*(unround ((hi+1)-lo)))+(unround lo))))\n\nany :: Prob a\nany = undefined\n\nimproper_uniform_positiveLogPdf :: (BayNum a) => (a -> Double)\nimproper_uniform_positiveLogPdf = \\((x::a)) -> if (x>0) then 1.000 else (0.000-1.000e20)\n\noneTo :: (BayNum a) => (a -> (Prob Int))\noneTo = \\((n::a)) -> (uniform 0.500 ((unround n)+0.500))>>=(\\((x::Double)) -> return (round x))\n\noneToLogPdf :: (BayNum a) => (a -> ((a -> Double)))\noneToLogPdf = \\((hi::a)) -> \\((x::a)) -> if ((x<(hi+1))&&(x>0)) then 1.000 else (0.000-1.000e10)\n\nnormalLogPdf :: (Double -> ((Double -> ((Double -> Double)))))\nnormalLogPdf = \\((mean::Double)) -> \\((variance::Double)) -> \\((x::Double)) -> ((log 1)-(0.500*(log ((2.000*pi)*variance))))-(((x-mean)**2)/(2*variance))\n\nlogNormal :: (Double -> ((Double -> (Prob Double))))\nlogNormal = \\((mean::Double)) -> \\((variance::Double)) -> fmap exp (normal mean variance)\n\nlogNormalLogPdf :: (Double -> ((Double -> ((Double -> Double)))))\nlogNormalLogPdf = \\((mean::Double)) -> \\((variance::Double)) -> \\((x::Double)) -> (log (1/(sqrt ((2.000*pi)*variance))))+(0.000-((((log x)-mean)*((log x)-mean))/(2*variance)))\n\nnormalLines :: (Double -> ((Double -> ([(Double,Double)]))))\nnormalLines = \\((mean::Double)) -> \\((v::Double)) -> let {(f::(Double -> ((Double,Double)))) = \\((x::Double)) -> (x,(exp ((normalLogPdf mean v) x)));\n } in map f ((linspace (mean-(3*(sqrt v))) (mean+(3*(sqrt v)))) 50)\n\nbinomialProb :: (Int -> ((Double -> ((Int -> Double)))))\nbinomialProb = \\((n::Int)) -> \\((p::Double)) -> \\((k::Int)) -> ((choose n k)*(p^k))*((1.000-p)^(n-k))\n\nbinomialLogProb :: (Int -> ((Double -> ((Int -> Double)))))\nbinomialLogProb = \\((n::Int)) -> \\((p::Double)) -> \\((k::Int)) -> ((log (choose n k))+((unround k)*(log p)))+((unround (n-k))*(log (1.000-p)))\n\nbernoulli :: (Double -> (Prob Bool))\nbernoulli = \\((p::Double)) -> unit>>=(\\((u::Double)) -> return (u (Prob Int))\nbernoulli01 = \\((p::Double)) -> unit>>=(\\((u::Double)) -> if (u ((Bool -> Double)))\nbernoulliLogPdf = \\((p::Double)) -> \\((b::Bool)) -> log (((p*((2*(boolToReal b))-1))+1)-(boolToReal b))\n\nbernoulli01LogPdf :: (Double -> ((Double -> Double)))\nbernoulli01LogPdf = \\((p::Double)) -> \\((b::Double)) -> log (((p*((2*b)-1))+1)-b)\n\ncountTrue :: (BayNum a) => (([Bool]) -> a)\ncountTrue = \\(((_arg0)::[Bool])) -> case _arg0 of {[] -> 0; (True :(bs::[Bool])) -> 1+(countTrue bs); (False :(bs::[Bool])) -> countTrue bs}\n\nbinomial :: (BayNum a) => (Int -> ((Double -> (Prob a))))\nbinomial = \\((n::Int)) -> \\((p::Double)) -> (repeat n (unit>>=(\\((u::Double)) -> return (u>=(\\((bools::[Bool])) -> return (countTrue bools))\n\nexponential :: (Double -> (Prob Double))\nexponential = \\((lam::Double)) -> unit>>=(\\((u::Double)) -> return (neg ((log u)/lam)))\n\nexponentialLogPdf :: (Double -> ((Double -> Double)))\nexponentialLogPdf = \\((lam::Double)) -> \\((x::Double)) -> lam*(exp ((0.000-lam)*x))\n\npoissonAux :: (BayNum a) => (Double -> ((a -> ((Double -> (Prob a))))))\npoissonAux = \\((bigl::Double)) -> \\((k::a)) -> \\((p::Double)) -> if (p>bigl) then (unit>>=(\\((u::Double)) -> (poissonAux bigl (k+1)) (p*u))) else (return (k-1))\n\npoisson :: (Double -> (Prob Int))\npoisson = \\((lam::Double)) -> (poissonAux (exp (0.000-lam)) 0) 1\n\npoissonLogPdf :: (Double -> ((Int -> Double)))\npoissonLogPdf = \\((lam::Double)) -> \\((x::Int)) -> ((lam**(unround x))*(exp (0.000-lam)))/(unround (fac x))\n\nbetaAux :: (Int -> (Prob Double))\nbetaAux = \\((n::Int)) -> (repeat n unit)>>=(\\((us::[Double])) -> return (log (product us)))\n\nbeta :: (Int -> ((Int -> (Prob Double))))\nbeta = \\((a::Int)) -> \\((b::Int)) -> (betaAux a)>>=(\\((g1::Double)) -> (betaAux b)>>=(\\((g2::Double)) -> return (g1/(g1+g2))))\n\ncof :: [Double]\ncof = 76.180:((-86.505):(24.014:((-1.232):(1.209e-3:((-5.395e-6):[])))))\n\ngammaln :: (Double -> Double)\ngammaln = \\((xx::Double)) -> let {(tmp'::Double) = (xx+5.500)-((xx+0.500)*(log (xx+5.500)));\n (ser'::Double) = ser+(sum (map (\\(((y::Double),(c::Double))) -> c/(xx+y)) (zip (fromTo 1 7) cof)));\n } in (0.000-tmp')+(log ((2.507*ser')/xx))\n\nbetaf :: (Double -> ((Double -> Double)))\nbetaf = \\((z::Double)) -> \\((w::Double)) -> exp (((gammaln z)+(gammaln w))-(gammaln (z+w)))\n\nbetaLogPdf :: (Int -> ((Int -> ((Double -> Double)))))\nbetaLogPdf = \\((a::Int)) -> \\((b::Int)) -> \\((x::Double)) -> log (((1.000/(betaf (unround a) (unround b)))*(x^(a-1)))*((1.000-x)^(b-1)))\n\ninvGamma :: (Double -> ((Double -> (Prob Double))))\ninvGamma = \\((a::Double)) -> \\((b::Double)) -> (gamma a (1.000/b))>>=(\\((g::Double)) -> return (1.000/g))\n\nwiener :: ((Double) -> (((Double) -> (Prob ((Double -> Double))))))\nwiener = \\((dt::Double)) -> \\((tmax::Double)) -> let {(n::Int) = (round (tmax/dt))+1;\n } in (repeat n unormal)>>=(\\((ns::[Double])) -> let {(etas::[Double]) = map (\\((u::Double)) -> u*(sqrt dt)) ns;\n } in return ((pack dt (0.000-dt)) (listToVec ((scanl (\\((x::Double)) -> \\((y::Double)) -> x+y) 0.000) etas))))\n\nmultiNormal :: ((Vector Double) -> (((Matrix Double) -> (Prob (Vector Double)))))\nmultiNormal = \\((vmean::Vector Double)) -> \\((cov::Matrix Double)) -> (repeat (dim vmean) (normal 0 1))>>=(\\((ns::[Double])) -> let {((u::Matrix Double):((s::Matrix Double):((v::Matrix Double):[]))) = svd cov;\n (j::Matrix Double) = mXm (mXm v (mmap sqrt s)) (transM v);\n } in return (vmean+(mXv j (listToVec ns))))\n\nwieners :: ((Double) -> (((Double) -> (((Matrix Double) -> (Prob ([(Double -> Double)])))))))\nwieners = \\((dt::Double)) -> \\((tmax::Double)) -> \\((cov::Matrix Double)) -> let {(n_time_pts::Int) = (round (tmax/dt))+2;\n (n_dims::Int) = fst (mdims cov);\n (zeroV::Vector Double) = fillV n_dims (const 0.000);\n (scale_cov::Matrix Double) = dt*%cov;\n } in ((unfold n_time_pts zeroV) (\\((vlast::Vector Double)) -> (multiNormal zeroV scale_cov)>>=(\\((etas::Vector Double)) -> return (vlast+etas))))>>=(\\((vs::[Vector Double])) -> let {(ll::[[Double]]) = transL (map vecToList vs);\n } in return (map (\\((ys::[Double])) -> (pack dt (0.000-dt)) (listToVec ys)) ll))\n\ndiff :: ((Double) -> ((((Double -> Double)) -> ((Double -> Double)))))\ndiff = \\((dt::Double)) -> \\((w::(Double -> Double))) -> \\((t::Double)) -> ((w t)-(w (t-dt)))/dt\n\ndecide :: (Double -> (((Vector Double) -> (((Prob a) -> (((((Vector Double) -> ((a -> Double)))) -> (Vector Double))))))))\ndecide = \\((tol::Double)) -> \\((ini::Vector Double)) -> \\((dist::Prob a)) -> \\((util::((Vector Double) -> ((a -> Double))))) -> (optimise tol ini) (\\((vaction::Vector Double)) -> expect (fmap (util vaction) dist))\n\nnsig :: (((Double -> Double)) -> ((Double -> (Prob ((Double -> Double))))))\nnsig = \\((sig::(Double -> Double))) -> \\((v::Double)) -> case observeSig sig of {ObservedSignal (dt::Double) (t0::Double) (vpts::Vector Double) -> (repeat (dim vpts) (normal 0 v))>>=(\\((ns::[Double])) -> return ((pack dt t0) (listToVec (map (\\(((x::Double),(y::Double))) -> x+y) (zip ns (vecToList vpts))))))}\n\nquantile :: (Double -> (((Prob Double) -> Double)))\nquantile = \\((x::Double)) -> \\(Samples (xs::[Double])) -> let {(total::Int) = length xs;\n (under::Int) = length (filter (\\((y::Double)) -> x ((Double -> ((Double -> Double)))))\ngammaLogPdf = \\((k::Double)) -> \\((theta::Double)) -> \\((x::Double)) -> ((((k-1)*(log x))+((0.000-x)/theta))-(k*(log theta)))-(gammaln k)\n\ninvGammaLogPdf :: (Double -> ((Double -> ((Double -> Double)))))\ninvGammaLogPdf = \\((a::Double)) -> \\((b::Double)) -> \\((x::Double)) -> log ((((b**a)/(exp (gammaln a)))*(x**((0.000-a)-1)))*(exp ((0.000-b)/x)))\n\ncookAssert :: ((Prob Double) -> SamplerDensity)\ncookAssert = \\((s::Prob Double)) -> SamplerDensity s (uniformLogPdf 0 1)\n\nmultiNormalLogPdf :: (a -> ((b -> c)))\nmultiNormalLogPdf = \\(vmean) -> \\(cov) -> undefined\n\ninvWishart :: (Double -> (((Matrix Double) -> (Prob (Matrix Double)))))\ninvWishart = \\((nu::Double)) -> \\((s::Matrix Double)) -> undefined\n\ninvWishartLogPdf :: (a -> ((b -> ((c -> d)))))\ninvWishartLogPdf = \\(nu) -> \\(s) -> \\(w) -> undefined\n\nscandyn' :: (BayNum a) => (((Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes)))))))))) -> ((a -> ((Int -> ((sdes -> ((odes -> ((([odes]) -> ((([sdes]) -> ((a,([odes]))))))))))))))))\nscandyn' = \\(((_arg0)::(Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes))))))))))) -> \\(((_arg1)::a)) -> \\(((_arg2)::Int)) -> \\((_arg3)) -> \\((_arg4)) -> \\(((_arg5)::[odes])) -> \\(((_arg6)::[sdes])) -> case (_arg0,((_arg1,((_arg2,((_arg3,((_arg4,((_arg5,_arg6))))))))))) of {((f::(Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes)))))))))),((p::a),(_,(_,(_,((odeacc::[odes]),[])))))) -> (p,(reverse odeacc)); ((f::(Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes)))))))))),((p0::a),((i::Int),(sdelast,(odecurr,((odeacc::[odes]),(sde:(sdes::[sdes])))))))) -> let {((p1::a),odenext) = ((f i odecurr) sdelast) sde;\n } in (((((scandyn' f (p0+p1)) (i+1)) sde) odenext) (odenext:odeacc)) sdes}\n\nscandyn :: (BayNum a) => (((Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes)))))))))) -> ((odes -> ((sdes -> ((([sdes]) -> ((a,([odes]))))))))))\nscandyn = \\((f::(Int -> ((odes -> ((sdes -> ((sdes -> ((a,odes))))))))))) -> \\(initode) -> \\(initsde) -> \\((sdes::[sdes])) -> (((((scandyn' f 0) 0) initsde) initode) []) sdes\n\ntmax :: Double\ntmax = 10.000\n\ndt :: Double\ndt = 1.000e-2\n\nsamples :: (BayNum a) => a\nsamples = 2000\n\nheston :: Prob ((R.X R.:& V R.::: (Double -> Double) R.:& S R.::: (Double -> Double)) (Id KindStar))\nheston = (gamma 1 1)>>=(\\((k::Double)) -> (gamma 1 0.100)>>=(\\((th::Double)) -> (gamma 1 0.100)>>=(\\((eta::Double)) -> (normal 0 0.100)>>=(\\((mu::Double)) -> (wiener dt tmax)>>=(\\((w1::(Double -> Double))) -> (wiener dt tmax)>>=(\\((w2::(Double -> Double))) -> (gamma 1 0.100)>>=(\\((v_0::Double)) -> (uniform 0.000 2.000)>>=(\\((s_0::Double)) -> let {v = solveODE (\\v-> \\((t::Double)) -> (k*(th-v))+((eta*(sqrt v))*((d dt w1) t))) tmax dt v_0;\ns = solveODE (\\s-> \\((t::Double)) -> (mu*s)+(((sqrt (v t))*s)*((d dt w2) t))) tmax dt s_0;\n} in return (R.X R.:& V R.:= (v) R.:& S R.:= (s))))))))))\n\nheston1 :: Prob ((R.X R.:& V R.::: (Double -> Double) R.:& S R.::: (Double -> Double)) (Id KindStar))\nheston1 = (return (R.X R.:& S_0 R.:= (1.000) R.:& V_0 R.:= (2.000e-2) R.:& Mu R.:= (5.000e-2) R.:& Eta R.:= (0.100) R.:& Th R.:= (2.000e-2) R.:& K R.:= (1.000))::Prob ((R.X R.:& S_0 R.::: Double R.:& V_0 R.::: Double R.:& Mu R.::: Double R.:& Eta R.::: Double R.:& Th R.::: Double R.:& K R.::: Double) (Id KindStar)))>>=(\\(((_pars)::((R.X R.:& S_0 R.::: Double R.:& V_0 R.::: Double R.:& Mu R.::: Double R.:& Eta R.::: Double R.:& Th R.::: Double R.:& K R.::: Double) (Id KindStar)))) -> let {(k::Double) = _pars!!!K;\n } in let {(th::Double) = _pars!!!Th;\n } in let {(eta::Double) = _pars!!!Eta;\n } in let {(mu::Double) = _pars!!!Mu;\n } in let {(v_0::Double) = _pars!!!V_0;\n } in let {(s_0::Double) = _pars!!!S_0;\n } in (wiener dt tmax)>>=(\\((_w_v)) -> (wiener dt tmax)>>=(\\((_w_s)) -> let {v = solveODE (\\v-> \\((t::Double)) -> (k*(th-v))+((eta*(sqrt v))*((d dt _w_v) t))) tmax dt v_0;\ns = solveODE (\\s-> \\((t::Double)) -> (mu*s)+(((sqrt (v t))*s)*((d dt _w_s) t))) tmax dt s_0;\n} in return (R.X R.:& V R.:= (v) R.:& S R.:= (s)))))\n\ndata S = S deriving Show\ninstance R.Name S where\n name = S\ndata V = V deriving Show\ninstance R.Name V where\n name = V\ndata K = K deriving Show\ninstance R.Name K where\n name = K\ndata Th = Th deriving Show\ninstance R.Name Th where\n name = Th\ndata Eta = Eta deriving Show\ninstance R.Name Eta where\n name = Eta\ndata Mu = Mu deriving Show\ninstance R.Name Mu where\n name = Mu\ndata V_0 = V_0 deriving Show\ninstance R.Name V_0 where\n name = V_0\ndata S_0 = S_0 deriving Show\ninstance R.Name S_0 where\n name = S_0\ndata Posterior = Posterior deriving Show\ninstance R.Name Posterior where\n name = Posterior\ndata Postgrad = Postgrad deriving Show\ninstance R.Name Postgrad where\n name = Postgrad\ndata VToRec = VToRec deriving Show\ninstance R.Name VToRec where\n name = VToRec\ndata Inisam = Inisam deriving Show\ninstance R.Name Inisam where\n name = Inisam\n\ntarget = do\n ((fakedata::((R.X R.:& V R.::: (Double -> Double) R.:& S R.::: (Double -> Double)) (Id KindStar))))::((R.X R.:& V R.::: (Double -> Double) R.:& S R.::: (Double -> Double)) (Id KindStar)) <- sample (heston1::Prob ((R.X R.:& V R.::: (Double -> Double) R.:& S R.::: (Double -> Double)) (Id KindStar)))\n --fail \"done\" \n let prims :: ((R.X R.:& Inisam R.::: Prob ([Double]) R.:& VToRec R.::: ((Vector Double) -> ((R.X R.:& V R.::: (Double -> Double) R.:& V_0 R.::: Double R.:& Mu R.::: Double R.:& Eta R.::: Double R.:& Th R.::: Double R.:& K R.::: Double) (Id KindStar))) R.:& Postgrad R.::: ((Vector Double) -> ((Double,(Vector Double)))) R.:& Posterior R.::: (([Double]) -> Double)) (Id KindStar))\n prims = let {s::(Double -> Double) = (fakedata!!!S);\n posterior = runP1 (bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(k) -> bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(th) -> bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(eta) -> bindP headP (\\(mu) -> bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(v_0) -> bindP (fmapP (\\(s) -> v_0:(map (\\(_x ) -> exp _x) s)) (takeP$((round (tmax/dt))-1))) (\\(v__obsSig) -> bindP (returnP ((packL dt 0) v__obsSig)) (\\(v) -> returnP (((gammaLogPdf 1 1) k)+(((gammaLogPdf 1 0.100) th)+(((gammaLogPdf 1 0.100) eta)+(((normalLogPdf 0 0.100) mu)+(((gammaLogPdf 1 0.100) v_0)+(((uniformLogPdf 0.000 2.000) (s 0))+(let {scanfun = \\(i) -> \\([]) -> \\((v_last:(s_last:[]))) -> \\((v_next:(s_next:[]))) -> let {t = (unround i)*dt;\n v = const v_last;\n s = const s_last;\n pthis = (0+((normalLogPdf (v_last+(dt*(k*(th-(v t))))) (dt*((eta*(sqrt (v t)))*(eta*(sqrt (v t)))))) v_next))+((normalLogPdf (s_last+(dt*(mu*(s t)))) (dt*(((sqrt (v t))*(s t))*((sqrt (v t))*(s t))))) s_next);\n } in (pthis,[]);\n (pdynsys,dynsysres) = ((scandyn scanfun []) ((v 0):((s 0):[]))) (transL ((tail v__obsSig):((sigTail s):[])));\n } in pdynsys+0)))))))))))))));\n postgrad = \\(_v ) -> runST$((newSTRef 0)>>=(\\(postref) -> (VSM.replicate (dim _v) 0)>>=(\\(gradref) -> (newSTRef (0::Int))>>=(\\(countref) -> let {post_incr = addSTRef postref;\n grad_incr = addMV gradref;\n count_incr = incrSTRef countref;\n } in (count_incr 1)>>=(\\((_k_pos)) -> let {k = exp (_v@>_k_pos);\n } in (((post_incr ((\\((x::Double)) -> ((((1-1)*(log x))+((0.000-x)/1))-(1*(log 1)))-(gammaln 1)) k))>>(grad_incr _k_pos (((\\((_x)) -> (exp _x)*1) (_v@>_k_pos))*((((0+((1-1)*((1/k)*1)))+((0+(1*(0-1)))/(1*1)))-0)-0))))>>(return ()))>>((count_incr 1)>>=(\\((_th_pos)) -> let {th = exp (_v@>_th_pos);\n } in (((post_incr ((\\((x::Double)) -> ((((1-1)*(log x))+((0.000-x)/0.100))-(1*(log 0.100)))-(gammaln 1)) th))>>(grad_incr _th_pos (((\\((_x)) -> (exp _x)*1) (_v@>_th_pos))*((((0+((1-1)*((1/th)*1)))+((0+(0.100*(0-1)))/(0.100*0.100)))-0)-0))))>>(return ()))>>((count_incr 1)>>=(\\((_eta_pos)) -> let {eta = exp (_v@>_eta_pos);\n } in (((post_incr ((\\((x::Double)) -> ((((1-1)*(log x))+((0.000-x)/0.100))-(1*(log 0.100)))-(gammaln 1)) eta))>>(grad_incr _eta_pos (((\\((_x)) -> (exp _x)*1) (_v@>_eta_pos))*((((0+((1-1)*((1/eta)*1)))+((0+(0.100*(0-1)))/(0.100*0.100)))-0)-0))))>>(return ()))>>((count_incr 1)>>=(\\((_mu_pos)) -> let {mu = _v@>_mu_pos;\n } in (((post_incr ((\\((x::Double)) -> ((log 1)-(0.500*(log ((2.000*pi)*0.100))))-(((x-0)**2)/(2*0.100))) mu))>>(grad_incr _mu_pos (0-((0+((2*0.100)*((2*(mu-0))*(1-0))))/((2*0.100)*(2*0.100))))))>>(return ()))>>((count_incr 1)>>=(\\((_v_0_pos)) -> let {v_0 = exp (_v@>_v_0_pos);\n } in (((post_incr ((\\((x::Double)) -> ((((1-1)*(log x))+((0.000-x)/0.100))-(1*(log 0.100)))-(gammaln 1)) v_0))>>(grad_incr _v_0_pos (((\\((_x)) -> (exp _x)*1) (_v@>_v_0_pos))*((((0+((1-1)*((1/v_0)*1)))+((0+(0.100*(0-1)))/(0.100*0.100)))-0)-0))))>>(return ()))>>(((post_incr ((\\(_) -> (log 1)-(log (2.000-0.000))) (s 0.000)))>>(return ()))>>((count_incr ((round (tmax/dt))-1))>>=(\\(v__startpos) -> let {v__obsSig = vcons v_0 (vmap (\\((_x)) -> exp _x) ((slice v__startpos ((round (tmax/dt))-1)) _v));\n v = (pack dt 0) v__obsSig;\n } in (forM (fromTo 1 ((round (tmax/dt))-1)) (\\((_timeix)) -> let {t = (unround _timeix)*dt;\n t__last = (unround (_timeix-1))*dt;\n v__last = v t__last;\n s__last = s t__last;\n } in ((return ())>>(let {v__next = v t;\n v__mean = v__last+(dt*(k*(th-v__last)));\n v__var = dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)));\n } in (post_incr (((log 1)-(0.500*(log ((2*pi)*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last))))))))-(((v__next-(v__last+(dt*(k*(th-v__last)))))**2)/(2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last))))))))>>((((((return ())>>(let {(_v__next_pos) = v__startpos+(_timeix-1);\n } in grad_incr _v__next_pos (((\\((_x)) -> (exp _x)*1) (_v@>_v__next_pos))*(0-((0+((2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))*((2*(v__next-(v__last+(dt*(k*(th-v__last))))))*(1-0))))/((2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))*(2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))))))))>>(grad_incr _eta_pos (((\\((_x)) -> (exp _x)*1) (_v@>_eta_pos))*((0-(0+(0.500*((1/((2*pi)*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last))))))*(0+((2*pi)*(0+(dt*((0+((eta*(sqrt v__last))*(0+((sqrt v__last)*1))))+((eta*(sqrt v__last))*(0+((sqrt v__last)*1))))))))))))-((0+(0-(((v__next-(v__last+(dt*(k*(th-v__last)))))**2)*(0+(2*(0+(dt*((0+((eta*(sqrt v__last))*(0+((sqrt v__last)*1))))+((eta*(sqrt v__last))*(0+((sqrt v__last)*1)))))))))))/((2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))*(2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))))))))>>(grad_incr _th_pos (((\\((_x)) -> (exp _x)*1) (_v@>_th_pos))*(0-((0+((2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))*((2*(v__next-(v__last+(dt*(k*(th-v__last))))))*(0-(0+(0+(dt*(0+(k*(1-0))))))))))/((2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))*(2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))))))))>>(grad_incr _k_pos (((\\((_x)) -> (exp _x)*1) (_v@>_k_pos))*(0-((0+((2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))*((2*(v__next-(v__last+(dt*(k*(th-v__last))))))*(0-(0+(0+(dt*(0+((th-v__last)*1)))))))))/((2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))*(2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))))))))>>(let {(_v__last_pos) = if (_timeix==1) then _v_0_pos else (v__startpos+(_timeix-2));\n } in grad_incr _v__last_pos (((\\((_x)) -> (exp _x)*1) (_v@>_v__last_pos))*((0-(0+(0.500*((1/((2*pi)*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last))))))*(0+((2*pi)*(0+(dt*((0+((eta*(sqrt v__last))*(0+(eta*((0.500*(1/(sqrt v__last)))*1)))))+((eta*(sqrt v__last))*(0+(eta*((0.500*(1/(sqrt v__last)))*1)))))))))))))-(((0+((2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))*((2*(v__next-(v__last+(dt*(k*(th-v__last))))))*(0-(1+(0+(dt*(0+(k*(0-1))))))))))+(0-(((v__next-(v__last+(dt*(k*(th-v__last)))))**2)*(0+(2*(0+(dt*((0+((eta*(sqrt v__last))*(0+(eta*((0.500*(1/(sqrt v__last)))*1)))))+((eta*(sqrt v__last))*(0+(eta*((0.500*(1/(sqrt v__last)))*1))))))))))))/((2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))*(2*(dt*((eta*(sqrt v__last))*(eta*(sqrt v__last)))))))))))))>>(let {s__next = s t;\n s__mean = s__last+(dt*(mu*s__last));\n s__var = dt*(((sqrt v__last)*s__last)*((sqrt v__last)*s__last));\n } in (post_incr (((log 1)-(0.500*(log ((2*pi)*s__var))))-(((s__next-s__mean)**2)/(2*s__var))))>>(((return ())>>(grad_incr _mu_pos (1*(0-((0+((2*(dt*(((sqrt v__last)*s__last)*((sqrt v__last)*s__last))))*((2*(s__next-(s__last+(dt*(mu*s__last)))))*(0-(0+(0+(dt*(0+(s__last*1)))))))))/((2*(dt*(((sqrt v__last)*s__last)*((sqrt v__last)*s__last))))*(2*(dt*(((sqrt v__last)*s__last)*((sqrt v__last)*s__last))))))))))>>(let {(_v__last_pos) = if (_timeix==1) then _v_0_pos else (v__startpos+(_timeix-2));\n } in grad_incr _v__last_pos (((\\((_x)) -> (exp _x)*1) (_v@>_v__last_pos))*((0-(0+(0.500*((1/((2*pi)*(dt*(((sqrt v__last)*s__last)*((sqrt v__last)*s__last)))))*(0+((2*pi)*(0+(dt*((0+(((sqrt v__last)*s__last)*(0+(s__last*((0.500*(1/(sqrt v__last)))*1)))))+(((sqrt v__last)*s__last)*(0+(s__last*((0.500*(1/(sqrt v__last)))*1)))))))))))))-((0+(0-(((s__next-(s__last+(dt*(mu*s__last))))**2)*(0+(2*(0+(dt*((0+(((sqrt v__last)*s__last)*(0+(s__last*((0.500*(1/(sqrt v__last)))*1)))))+(((sqrt v__last)*s__last)*(0+(s__last*((0.500*(1/(sqrt v__last)))*1))))))))))))/((2*(dt*(((sqrt v__last)*s__last)*((sqrt v__last)*s__last))))*(2*(dt*(((sqrt v__last)*s__last)*((sqrt v__last)*s__last)))))))))))))>>((readSTRef postref)>>=(\\(postval) -> (unsafeFreeze gradref)>>=(\\(gradval) -> return ((postval,gradval)))))))))))))))))))));\n vToRec = \\(theta) -> runP (toList theta) (bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(k) -> bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(th) -> bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(eta) -> bindP headP (\\(mu) -> bindP (fmapP (\\((_x)) -> exp _x) headP) (\\(v_0) -> bindP (fmapP (\\(s) -> v_0:(map (\\(_x ) -> exp _x) s)) (takeP$((round (tmax/dt))-1))) (\\(v__obsSig) -> bindP (returnP ((packL dt 0) v__obsSig)) (\\(v) -> returnP (R.X R.:& V R.:= (v) R.:& V_0 R.:= (v_0) R.:& Mu R.:= (mu) R.:& Eta R.:= (eta) R.:& Th R.:= (th) R.:& K R.:= (k))))))))));\n inisam = (gamma 1 1)>>=(\\(k) -> (gamma 1 0.100)>>=(\\(th) -> (gamma 1 0.100)>>=(\\(eta) -> (normal 0 0.100)>>=(\\(mu) -> (gamma 1 0.100)>>=(\\(v_0) -> (uniform 0.000 2.000)>>=(\\(s_0) -> (wiener dt tmax)>>=(\\(w2) -> (wiener dt tmax)>>=(\\(w1) -> let {v = solveODE (\\v-> \\((t::Double)) -> (k*(th-v))+((eta*(sqrt v))*((d dt w1) t))) tmax dt v_0;\ns = solveODE (\\s-> \\((t::Double)) -> (mu*s)+(((sqrt (v t))*s)*((d dt w2) t))) tmax dt s_0;\n} in return (concat (((log k):[]):(((log th):[]):(((log eta):[]):((mu:[]):(((log v_0):[]):((map (\\((_x)) -> log _x) (sigTail v)):[])))))))))))))));\n\n\n\n } in R.X R.:& Inisam R.:= (inisam) R.:& VToRec R.:= (vToRec) R.:& Postgrad R.:= (postgrad) R.:& Posterior R.:= (posterior)\n let post :: ((Vector Double) -> Double)\n post = (prims!!!Posterior) . VS.toList\n let postgrad :: ((Vector Double) -> ((Double,(Vector Double))))\n postgrad = prims!!!Postgrad\n let vtorec :: ((Vector Double) -> ((R.X R.:& V R.::: (Double -> Double) R.:& V_0 R.::: Double R.:& Mu R.::: Double R.:& Eta R.::: Double R.:& Th R.::: Double R.:& K R.::: Double) (Id KindStar)))\n vtorec = prims!!!VToRec\n let inisam :: Prob (Vector Double)\n inisam = fmap (VS.fromList) $ prims!!!Inisam\n return (post, postgrad,vtorec,inisam)\n", "meta": {"hexsha": "664dd566fd6ce9a5e6679bf188471110cc1da914", "size": 42096, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Target/Heston.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Target/Heston.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Target/Heston.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 68.8968903437, "max_line_length": 1577, "alphanum_fraction": 0.5227812619, "num_tokens": 15763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.2167464523859084}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_HADDOCK show-extensions #-}\n\nmodule NQS.Internal.Types\n ( -- * Numeric types\n ℂ\n , ℝ\n\n -- , Estimate(..)\n -- , NormalError(..)\n -- , EnergyMeasurement(..)\n , RealOf\n -- , SRMeasurement(..)\n {-\n , withRbm\n , withRbmPure\n , withMRbm\n , withMRbmPure\n -}\n -- * Vectors and matrices\n , DenseVector\n , DenseMatrix\n , MDenseVector\n , MDenseMatrix\n , slice\n , withForeignPtrPrim\n , newVectorAligned\n , newDenseVector\n , newDenseMatrix\n\n , unsafeRow\n , unsafeColumn\n , unsafeWriteVector\n\n , Mutable(..)\n , Variant(..)\n , Orientation(..)\n , Transpose(..)\n , MatUpLo(..)\n , Sing(..)\n\n , CheckValid(..)\n , isValidVector\n , isValidMatrix\n , badVectorInfo\n , HasBuffer(..)\n , HasStride(..)\n , HasDim(..)\n\n , orientationOf\n , ToNative(..)\n\n , DenseWorkspace(..)\n , MCConfig(..)\n , defaultMCConfig\n , CGConfig(..)\n , SRConfig(..)\n\n , HasMc(..)\n , HasCg(..)\n , HasSteps(..)\n , HasRuns(..)\n , HasRate(..)\n , HasRestarts(..)\n , HasRegulariser(..)\n , HasMaxIter(..)\n , HasMagnetisation(..)\n\n , mapVectorM\n , mapMatrixM\n , zipWithVectorM\n , zipWithMatrixM\n -- , asTuple\n -- , fromTuple\n , FreezeThaw(..)\n\n , HasMean(..)\n , HasVar(..)\n -- , HasEnergy(..)\n -- , HasForce(..)\n -- , HasDerivatives(..)\n ) where\n\nimport Foreign.Storable\nimport Foreign.ForeignPtr\n\nimport Control.DeepSeq\nimport Control.Exception (assert)\nimport Control.Monad ((>=>), unless)\nimport Control.Monad.Primitive\nimport Control.Monad.ST.Strict\nimport Data.Complex\nimport Debug.Trace\nimport GHC.Generics (Generic)\nimport GHC.ForeignPtr (mallocPlainForeignPtrAlignedBytes)\n\nimport Data.Semigroup ((<>))\nimport Lens.Micro\nimport Lens.Micro.TH\n\nimport System.IO.Unsafe\nimport Data.Coerce\nimport Data.Bits\n\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.ForeignPtr.Unsafe\n\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Storable.Mutable as MV\nimport Data.Vector.Storable (Vector, MVector(..))\n\nimport qualified Data.Vector.Generic as GV\nimport qualified Data.Vector as Boxed\nimport Data.Aeson\nimport qualified Data.Aeson.Types as Aeson\n\nimport Data.Singletons\n\nimport qualified Numerical.HBLAS.MatrixTypes as HBLAS\nimport Numerical.HBLAS.MatrixTypes ( Variant(..)\n , Orientation(..)\n , Transpose(..)\n , MatUpLo(..)\n )\nimport Numerical.HBLAS.BLAS.FFI ( CBLAS_UPLOT(..) )\n\nimport Data.Kind\nimport Data.Proxy\n\nderiving instance Generic Variant\nderiving instance NFData Variant\n\nderiving instance Generic Orientation\nderiving instance NFData Orientation\n\nclass ToNative a b where\n encode :: a -> b\n\ndata family Mutable (v :: * -> *) :: * -> * -> *\n\n-- | After some prototyping, I've concluded (possibly incorrectly) that a\n-- single-precision 'Float' is enough for our purposes.\n--\n-- [This answer](https://stackoverflow.com/a/40538415) also mentions that 32-bit\n-- floats should be enought for most neural network applications.\ntype ℝ = Float\ntype ℂ = Complex ℝ\n\ndata instance Sing (orient :: Orientation) where\n SRow :: Sing 'Row\n SColumn :: Sing 'Column\n\ninstance SingI 'Row where sing = SRow\ninstance SingI 'Column where sing = SColumn\n\ninstance SingKind Orientation where\n type Demote Orientation = Orientation\n fromSing SRow = Row\n fromSing SColumn = Column\n toSing x = case x of\n Row -> SomeSing SRow\n Column -> SomeSing SColumn\n\ndata DenseVector (variant :: Variant) (a :: *) = DenseVector\n { _denseVectorDim :: {-# UNPACK #-}!Int\n , _denseVectorStride :: {-# UNPACK #-}!Int\n , _denseVectorBuffer :: {-# UNPACK #-}!(Vector a)\n } deriving (Show, Generic, NFData)\n\ndata DenseMatrix (orientation :: Orientation) (a :: *) = DenseMatrix\n { _denseMatrixRows :: {-# UNPACK #-}!Int\n , _denseMatrixCols :: {-# UNPACK #-}!Int\n , _denseMatrixStride :: {-# UNPACK #-}!Int\n , _denseMatrixBuffer :: {-# UNPACK #-}!(Vector a)\n } deriving (Show, Generic, NFData)\n\ndata instance Mutable (DenseVector variant) s a = MDenseVector\n { _mDenseVectorDim :: {-# UNPACK #-}!Int\n , _mDenseVectorStride :: {-# UNPACK #-}!Int\n , _mDenseVectorBuffer :: {-# UNPACK #-}!(MVector s a)\n } deriving (Generic, NFData)\n\ntype MDenseVector variant = Mutable (DenseVector variant)\n\ndata instance Mutable (DenseMatrix orientation) s a = MDenseMatrix\n { _mDenseMatrixRows :: {-# UNPACK #-}!Int\n , _mDenseMatrixCols :: {-# UNPACK #-}!Int\n , _mDenseMatrixStride :: {-# UNPACK #-}!Int\n , _mDenseMatrixBuffer :: {-# UNPACK #-}!(MVector s a)\n } deriving (Generic, NFData)\n\ntype MDenseMatrix orientation = Mutable (DenseMatrix orientation)\n\nmakeFields ''DenseVector\nmakeFields ''DenseMatrix\n\n\nunsafeIndexVector :: Storable a => DenseVector 'Direct a -> Int -> a\n{-# INLINE unsafeIndexVector #-}\nunsafeIndexVector !(DenseVector _ stride buff) !i = V.unsafeIndex buff (i * stride)\n\nunsafeIndexMatrix :: forall a orient. (Storable a, SingI orient)\n => DenseMatrix orient a -> (Int, Int) -> a\n{-# INLINE unsafeIndexMatrix #-}\nunsafeIndexMatrix !(DenseMatrix _ _ stride buff) !(r, c) = V.unsafeIndex buff i\n where i = case (sing :: Sing orient) of\n SRow -> r * stride + c\n SColumn -> r + c * stride\n\nunsafeReadVector :: (Storable a, PrimMonad m)\n => MDenseVector 'Direct (PrimState m) a -> Int -> m a\n{-# INLINE unsafeReadVector #-}\nunsafeReadVector !(MDenseVector _ stride buff) !i = MV.unsafeRead buff (i * stride)\n\nunsafeReadMatrix :: forall a m orient. (Storable a, PrimMonad m, SingI orient)\n => MDenseMatrix orient (PrimState m) a -> (Int, Int) -> m a\n{-# INLINE unsafeReadMatrix #-}\nunsafeReadMatrix !(MDenseMatrix _ _ stride buff) !(r, c) = MV.unsafeRead buff i\n where i = case (sing :: Sing orient) of\n SRow -> r * stride + c\n SColumn -> r + c * stride\n\nunsafeWriteVector :: (Storable a, PrimMonad m)\n => MDenseVector 'Direct (PrimState m) a -> Int -> a -> m ()\n{-# INLINE unsafeWriteVector #-}\nunsafeWriteVector !(MDenseVector _ stride buff) !i !x = MV.unsafeWrite buff (i * stride) x\n\nunsafeWriteMatrix :: forall a m orient. (Storable a, PrimMonad m, SingI orient)\n => MDenseMatrix orient (PrimState m) a -> (Int, Int) -> a -> m ()\n{-# INLINE unsafeWriteMatrix #-}\nunsafeWriteMatrix !(MDenseMatrix _ _ stride buff) !(r, c) !x = MV.unsafeWrite buff i x\n where i = case (sing :: Sing orient) of\n SRow -> r * stride + c\n SColumn -> r + c * stride\n\n-- | Returns a row of a matrix.\nunsafeRow\n :: forall orient s a\n . (Storable a, SingI orient)\n => Int\n -> MDenseMatrix orient s a\n -> MDenseVector 'Direct s a\n{-# INLINE unsafeRow #-}\nunsafeRow !i !(MDenseMatrix rows cols stride buff) = assert False $\n assert (i < rows) $ case (sing :: Sing orient) of\n SRow -> MDenseVector cols 1 (MV.slice (i * stride) cols buff)\n SColumn -> MDenseVector cols stride (MV.slice i (cols * stride) buff)\n\n\n\n\n-- | Returns a column of a matrix.\nunsafeColumn\n :: forall orient s a\n . (Storable a, SingI orient)\n => Int\n -> MDenseMatrix orient s a\n -> MDenseVector 'Direct s a\n{-# INLINE unsafeColumn #-}\nunsafeColumn !i !(MDenseMatrix rows cols stride buff) =\n assert (i < cols) $ case (sing :: Sing orient) of\n SRow -> if rows == 1\n then MDenseVector 1 1 (MV.slice i 1 buff)\n else MDenseVector rows stride (MV.slice i ((rows - 1)* stride + 1) buff)\n SColumn -> MDenseVector rows 1 (MV.slice (i * stride) rows buff)\n\n\n\n\ndata DenseWorkspace s a = DenseWorkspace\n { _denseWorkspaceForce :: !(MDenseVector 'Direct s a) -- ^ Force\n , _denseWorkspaceDerivatives :: !(MDenseMatrix 'Row s a) -- ^ Derivatives\n , _denseWorkspaceDelta :: !(MDenseVector 'Direct s a) -- ^ Old delta\n } deriving (Generic, NFData)\n\n\n-- | Configuration for Monte-Carlo sampling.\ndata MCConfig =\n MCConfig\n { _mCConfigSteps :: {-# UNPACK #-}!(Int, Int, Int)\n -- ^ A range of steps for a single run. It is very similar to Python's\n -- [range](). @(low, high, step)@ corresponds to [low, low + step, low +\n -- 2 * step, ..., high).\n --\n -- /Note:/ only positive @step@s are supported.\n , _mCConfigThreads :: {-# UNPACK #-}!(Int, Int, Int)\n , _mCConfigRuns :: {-# UNPACK #-}!Int\n -- ^ Number of Monte-Carlo runs to perform.\n --\n -- /Note:/ for optimal work scheduling, make that the total number of\n -- threads is divisible by the number of runs.\n , _mCConfigFlips :: {-# UNPACK #-}!Int\n -- ^ Number of spin-flips to do at each step.\n , _mCConfigRestarts :: {-# UNPACK #-}!Int\n -- ^ Allowed number of restarts.\n --\n -- A restart happens when the function computing local energy notices\n -- that a particular spin-flip results in a spin configuration with\n -- significantly higher probability. Monte-Carlo sampler is then reset\n -- and this new spin configuration is used as the initial one.\n , _mCConfigMagnetisation :: !(Maybe Int)\n -- ^ Specifies the magnetisation over which to sample.\n }\n\nmakeFields ''MCConfig\n\ndefaultMCConfig :: MCConfig\ndefaultMCConfig = MCConfig (1000, 11000, 1) (4, 1, 1) 4 2 5 Nothing\n\n-- | Configuration for the Conjugate Gradient solver.\ndata CGConfig a =\n CGConfig { _cGConfigMaxIter :: {-# UNPACK #-}!Int\n -- ^ Maximum number of iterations.\n , _cGConfigTol :: !a\n -- ^ Tolerance.\n }\n\nmakeFields ''CGConfig\n\n-- | Configuration for the Stochastic Reconfiguration algorithm.\ndata SRConfig a =\n SRConfig\n { _sRConfigMaxIter :: !Int\n -- ^ Maximum number of iterations to perform.\n , _sRConfigRegulariser :: !(Maybe (Int -> ℂ))\n -- ^ Regulariser for the S matrix. If it is @'Just' f@,\n -- then @λ = f i@ where @i@ is the currect iteration is used to\n -- regularise the matrix S according to @S <- S + λ1@.\n , _sRConfigRate :: !(Int -> ℂ)\n -- ^ Learning rate as a function of the iteration.\n , _sRConfigCg :: !(CGConfig ℝ)\n -- ^ Configuration for the Monte-Carlo sampling.\n , _sRConfigMc :: !MCConfig\n -- ^ Configuration for the Conjugate Gradient solver.\n }\n\n-- | Returns a slice of the vector.\nslice\n :: forall a s\n . Storable a\n => Int -- ^ Start index\n -> Int -- ^ Length\n -> MDenseVector 'Direct s a -- ^ Source vector\n -> MDenseVector 'Direct s a -- ^ Slice\nslice !i !n !(MDenseVector size stride buff) =\n MDenseVector n stride (MV.slice (stride * i) (stride * n) buff)\n\nmakeFields ''SRConfig\n\ntype family RealOf a :: *\n\ntype instance RealOf Float = Float\ntype instance RealOf Double = Double\ntype instance RealOf (Complex a) = a\n\nmallocVectorAligned :: forall a. Storable a => Int -> Int -> IO (ForeignPtr a)\nmallocVectorAligned n alignment =\n mallocPlainForeignPtrAlignedBytes (n * sizeOf (undefined :: a)) alignment\n\nnewVectorAligned\n :: (Storable a, PrimMonad m) => Int -> Int -> m (MVector (PrimState m) a)\nnewVectorAligned n alignment =\n unsafePrimToPrim $! MVector n <$> mallocVectorAligned n alignment\n\nnewDenseVector\n :: (Storable a, PrimMonad m) => Int -> m (MDenseVector 'Direct (PrimState m) a)\nnewDenseVector n = MDenseVector n 1 <$> newVectorAligned n 64\n\n-- | Default alignment used when allocating new vectors and matrices.\ndefaultAlignment :: Int\ndefaultAlignment = 64\n\nroundUpTo :: Int -> Int -> Int\n{-# INLINE roundUpTo #-}\nroundUpTo !alignment !n = assert (isValidAlignment alignment && n >= 0) $\n (n + alignment - 1) .&. complement (alignment - 1)\n where isValidAlignment !x = x > 0 && (x .&. (x - 1) == 0)\n\nnewDenseMatrix\n :: forall orient a m. (Storable a, SingI orient, PrimMonad m)\n => Int\n -> Int\n -> m (MDenseMatrix orient (PrimState m) a)\nnewDenseMatrix rows cols = case (sing :: Sing orient) of\n SRow ->\n let ldim = assert (defaultAlignment `mod` sizeOf (undefined :: a) == 0) $\n roundUpTo (defaultAlignment `div` sizeOf (undefined :: a)) cols\n in MDenseMatrix rows cols ldim\n <$> newVectorAligned (rows * ldim) defaultAlignment\n SColumn ->\n let ldim = roundUpTo defaultAlignment rows\n in MDenseMatrix rows cols ldim\n <$> newVectorAligned (ldim * cols) defaultAlignment\n\nclass HasOrientation s a | s -> a where\n orientationOf :: s -> a\n\ninstance SingI orient\n => HasOrientation (DenseMatrix orient a) Orientation where\n orientationOf _ = fromSing (sing :: Sing orient)\n\ninstance SingI orient\n => HasOrientation (Mutable (DenseMatrix orient) s a) Orientation where\n orientationOf _ = fromSing (sing :: Sing orient)\n\n\n\nisValidMatrix :: Orientation -- ^ Row- vs. column-major layout\n -> Int -- ^ Number of rows\n -> Int -- ^ Number of columns\n -> Int -- ^ Stride\n -> Int -- ^ Buffer size\n -> Bool\nisValidMatrix orient rows cols i size =\n i >= 0 && (rows == 0 && cols == 0 || rows > 0 && cols > 0 && validAccesses orient)\n where validAccesses Row = (rows - 1) * i < size && cols <= i\n validAccesses Column = (cols - 1) * i < size && rows <= i\n\n-- | Constructs a nice message describing the problem in the BLAS vector.\nbadMatrixInfo :: String -- ^ Function name\n -> String -- ^ Argument name\n -> Int -- ^ Number of rows\n -> Int -- ^ Number of columns\n -> Int -- ^ Stride\n -> Int -- ^ Size of the underlying buffer\n -> String -- ^ Error message\nbadMatrixInfo funcName argName rows cols i size\n | rows < 0 = preamble <> \" has a negative number of rows: \" <> show rows <> \".\"\n | cols < 0 = preamble <> \" has a negative number of columns: \" <> show cols <> \".\"\n | i < 0 = preamble <> \" has a negative stride: \" <> show i <> \".\"\n | otherwise = preamble <> \" has invalid range of accesses: #rows = \" <> show rows <>\n \", #cols = \" <> show cols <> \", stride = \" <> show i <> \", bufferSize = \" <> show size <> \".\"\n where preamble = funcName <> \": \" <> argName\n\n-- | Returns whether strides and dimensions are consistent.\nisValidVector :: Int -- ^ Logical dimension\n -> Int -- ^ Stride\n -> Int -- ^ Buffer size\n -> Bool\nisValidVector n i size = i >= 0 && (n == 0 || n > 0 && (n - 1) * i < size)\n\n-- | Constructs a nice message describing the problem in the BLAS vector.\nbadVectorInfo :: String -- ^ Function name\n -> String -- ^ Argument name\n -> Int -- ^ Logical vector dimension\n -> Int -- ^ Vector stride\n -> Int -- ^ Size of the underlying buffer\n -> String -- ^ Error message\nbadVectorInfo funcName argName n i size\n | n < 0 = preamble <> \" has a negative logical dimension: \" <> show n <> \".\"\n | i < 0 = preamble <> \" has a negative stride: \" <> show i <> \".\"\n | otherwise = preamble <> \" has invalid range of accesses: dim = \" <> show n <>\n \", stride = \" <> show i <> \", bufferSize = \" <> show size <> \".\"\n where preamble = funcName <> \": \" <> argName\n\nclass CheckValid a where\n assertValid :: String -> String -> a -> b -> b\n\ninstance Storable a => CheckValid (DenseVector variant a) where\n assertValid funcName argName !(DenseVector dim stride (V.length -> size))\n | isValidVector dim stride size = id\n | otherwise = error $! badVectorInfo funcName argName dim stride size\n\ninstance Storable a => CheckValid (Mutable (DenseVector variant) s a) where\n assertValid funcName argName !(MDenseVector dim stride (MV.length -> size))\n | isValidVector dim stride size = id\n | otherwise = error $! badVectorInfo funcName argName dim stride size\n\ninstance (Storable a, SingI orient) => CheckValid (DenseMatrix orient a) where\n assertValid funcName argName !m@(DenseMatrix rows cols stride (V.length -> size))\n | isValidMatrix (orientationOf m) rows cols stride size = id\n | otherwise = error $! badMatrixInfo funcName argName rows cols stride size\n\ninstance (Storable a, SingI orient) => CheckValid (Mutable (DenseMatrix orient) s a) where\n assertValid funcName argName !m@(MDenseMatrix rows cols stride (MV.length -> size))\n | isValidMatrix (orientationOf m) rows cols stride size = id\n | otherwise = error $! badMatrixInfo funcName argName rows cols stride size\n\ninstance Storable a => HasBuffer (MDenseVector variant s a) (MVector s a) where\n buffer inj (MDenseVector dim stride buf) = MDenseVector dim stride <$> inj buf\n\ninstance Storable a => HasBuffer (MDenseMatrix orientation s a) (MVector s a) where\n buffer inj (MDenseMatrix rows cols stride buf) = MDenseMatrix rows cols stride <$> inj buf\n\ninstance Storable a => HasStride (MDenseVector variant s a) Int where\n stride inj (MDenseVector dim stride buf) = (\\x -> MDenseVector dim x buf) <$> inj stride\n\ninstance Storable a => HasStride (MDenseMatrix orientation s a) Int where\n stride inj (MDenseMatrix rows cols stride buf) = (\\x -> MDenseMatrix rows cols x buf) <$> inj stride\n\ninstance Storable a => HasDim (MDenseVector variant s a) Int where\n dim inj (MDenseVector dim stride buf) = (\\x -> MDenseVector x stride buf) <$> inj dim\n\ninstance Storable a => HasDim (MDenseMatrix orientation s a) (Int, Int) where\n dim inj (MDenseMatrix rows cols stride buf) =\n (\\(x, y) -> MDenseMatrix x y stride buf) <$> inj (rows, cols)\n\ninstance Storable a => HasDim (DenseMatrix orientation a) (Int, Int) where\n dim inj (DenseMatrix rows cols stride buf) =\n (\\(x, y) -> DenseMatrix x y stride buf) <$> inj (rows, cols)\n\nclass FreezeThaw (v :: * -> *) a where\n unsafeFreeze :: PrimMonad m => (Mutable v) (PrimState m) a -> m (v a)\n unsafeThaw :: PrimMonad m => v a -> m ((Mutable v) (PrimState m) a)\n\ninstance Storable a => FreezeThaw (DenseVector variant) a where\n unsafeFreeze (MDenseVector dim stride mv) = DenseVector dim stride <$> V.unsafeFreeze mv\n unsafeThaw (DenseVector dim stride mv) = MDenseVector dim stride <$> V.unsafeThaw mv\n\ninstance Storable a => FreezeThaw (DenseMatrix orientation) a where\n unsafeFreeze (MDenseMatrix rows cols stride mv) = DenseMatrix rows cols stride <$> V.unsafeFreeze mv\n unsafeThaw (DenseMatrix rows cols stride v) = MDenseMatrix rows cols stride <$> V.unsafeThaw v\n\n\ntouchForeignPtrPrim :: PrimMonad m => ForeignPtr a -> m ()\n{-# NOINLINE touchForeignPtrPrim #-}\ntouchForeignPtrPrim fp = unsafeIOToPrim $! touchForeignPtr fp\n\nwithForeignPtrPrim :: PrimMonad m => ForeignPtr a -> (Ptr a -> m b) -> m b\n{-# INLINE withForeignPtrPrim #-}\nwithForeignPtrPrim p func = do r <- func (unsafeForeignPtrToPtr p)\n touchForeignPtrPrim p\n return r\n\nmapVectorM ::\n (PrimMonad m, Storable a, Storable b)\n => (a -> m b)\n -> MDenseVector 'Direct (PrimState m) a\n -> MDenseVector 'Direct (PrimState m) b\n -> m ()\nmapVectorM f x y =\n assertValid \"NQS.Rbm.zipWithVectorM\" \"x\" x $\n assertValid \"NQS.Rbm.zipWithVectorM\" \"x\" y $\n assert (x ^. dim == y ^. dim) $ go 0\n where\n n = x ^. dim\n go !i\n | i == n = return ()\n | otherwise = do\n xi <- unsafeReadVector x i\n yi <- f xi\n unsafeWriteVector y i yi\n go (i + 1)\n\nzipWithVectorM ::\n (PrimMonad m, Storable a, Storable b, Storable c)\n => (a -> b -> m c)\n -> MDenseVector 'Direct (PrimState m) a\n -> MDenseVector 'Direct (PrimState m) b\n -> MDenseVector 'Direct (PrimState m) c\n -> m ()\nzipWithVectorM f x y z =\n assertValid \"NQS.Rbm.zipWithVectorM\" \"x\" x $\n assertValid \"NQS.Rbm.zipWithVectorM\" \"x\" y $\n assertValid \"NQS.Rbm.zipWithVectorM\" \"x\" z $\n assert (y ^. dim == n && z ^. dim == n) $ go 0\n where\n n = x ^. dim\n go !i\n | i == n = return ()\n | otherwise = do\n xi <- unsafeReadVector x i\n yi <- unsafeReadVector y i\n zi <- f xi yi\n unsafeWriteVector z i zi\n go (i + 1)\n\nmapMatrixM ::\n forall m a b orientX orientY.\n (PrimMonad m, Storable a, Storable b, SingI orientX, SingI orientY)\n => (a -> m b)\n -> MDenseMatrix orientX (PrimState m) a\n -> MDenseMatrix orientY (PrimState m) b\n -> m ()\nmapMatrixM f x y =\n assertValid \"NQS.Rbm.zipWithMatrixM\" \"x\" x $\n assertValid \"NQS.Rbm.zipWithMatrixM\" \"y\" y $\n assert (x ^. dim == y ^. dim) $\n case (sing :: Sing orientY) of\n SRow -> stepperRow 0 0\n SColumn -> stepperColumn 0 0\n where\n !(n, m) = x ^. dim\n stepperRow !i !j\n | j < m && i < n = go i j >> stepperRow i (j + 1)\n | i < n = stepperRow (i + 1) 0\n | otherwise = return ()\n stepperColumn !i !j\n | i < n && j < m = go i j >> stepperColumn (i + 1) j\n | j < m = stepperColumn 0 (j + 1)\n | otherwise = return ()\n go !i !j = do\n xij <- unsafeReadMatrix x (i, j)\n yij <- f xij\n unsafeWriteMatrix y (i, j) yij\n\nzipWithMatrixM :: forall m a b c orientX orientY orientZ.\n (PrimMonad m, Storable a, Storable b, Storable c, SingI orientX, SingI orientY, SingI orientZ)\n => (a -> b -> m c)\n -> MDenseMatrix orientX (PrimState m) a\n -> MDenseMatrix orientY (PrimState m) b\n -> MDenseMatrix orientZ (PrimState m) c\n -> m ()\nzipWithMatrixM f x y z =\n assertValid \"NQS.Rbm.zipWithMatrixM\" \"x\" x $\n assertValid \"NQS.Rbm.zipWithMatrixM\" \"y\" y $\n assertValid \"NQS.Rbm.zipWithMatrixM\" \"z\" z $\n assert (y ^. dim == (n, m) && z ^. dim == (n, m)) $\n case (sing :: Sing orientZ) of\n SRow -> stepperRow 0 0\n SColumn -> stepperColumn 0 0\n where\n !(n, m) = x ^. dim\n stepperRow !i !j\n | j < m && i < n = go i j >> stepperRow i (j + 1)\n | i < n = stepperRow (i + 1) 0\n | otherwise = return ()\n stepperColumn !i !j\n | i < n && j < m = go i j >> stepperColumn (i + 1) j\n | j < m = stepperColumn 0 (j + 1)\n | otherwise = return ()\n go !i !j = do\n xij <- unsafeReadMatrix x (i, j)\n yij <- unsafeReadMatrix y (i, j)\n zij <- f xij yij\n unsafeWriteMatrix z (i, j) zij\n\n{-\nwithRbm :: PrimMonad m => Rbm a -> (Ptr (RbmCore a) -> m b) -> m b\nwithRbm (Rbm p) func = withForeignPtrPrim p func\n\nwithRbmPure :: Rbm a -> (Ptr (RbmCore a) -> b) -> b\nwithRbmPure (Rbm p) func = unsafePerformIO $! withForeignPtrPrim p (return . func)\n\nwithMRbm :: PrimMonad m => MRbm (PrimState m) a -> (Ptr (RbmCore a) -> m b) -> m b\nwithMRbm (MRbm p) func = withForeignPtrPrim p func\n\nwithMRbmPure :: MRbm s a -> (Ptr (RbmCore a) -> b) -> b\nwithMRbmPure (MRbm p) func = unsafePerformIO $! withForeignPtr p (return . func)\n-}\n\n\ndata Estimate e a = Estimate\n { estPoint :: !a\n , estError :: !(e a)\n } deriving (Generic, NFData)\n\nnewtype NormalError a = NormalError a\n deriving (Eq, Ord, Read, Show, Generic, NFData)\n\ndata EnergyMeasurement a = EnergyMeasurement\n { _energyMeasurementMean :: !a\n , _energyMeasurementVar :: !a\n } deriving (Generic)\n\nmakeFields ''EnergyMeasurement\n\n-- | Simple for loop. Counts from /start/ to /end/-1.\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor !start !end f = assert (start <= end) $ loop start\n where\n loop !i | i == end = return ()\n | otherwise = f i >> loop (i + 1)\n{-# INLINE for #-}\n\n\nfor' :: Monad m => a -> Int -> (a -> Int -> m a) -> m a\nfor' !x0 !n f = assert (n >= 0) $ loop x0 0\n where\n loop !x !i | i == n = return x\n | otherwise = f x i >>= \\x' -> loop x' (i + 1)\n{-# INLINE for' #-}\n\n\n\ngenerateVectorM\n :: forall a m\n . (Monad m, Storable a)\n => Int\n -> (Int -> m a)\n -> m (DenseVector 'Direct a)\n{-# NOINLINE generateVectorM #-}\ngenerateVectorM !n f\n | n < 0 = error $! \"generateVectorM: Invalid dimension: \" <> show n\n | n == 0 = return $! DenseVector 0 0 V.empty\n | otherwise = go (runST $ newDenseVector n >>= unsafeFreeze)\n where\n go :: DenseVector 'Direct a -> m (DenseVector 'Direct a)\n go !v' = for' v' n $ \\v i -> f i >>= \\x -> return (set v i x)\n set !v !i !x = runST $ do\n !v' <- unsafeThaw v\n unsafeWriteVector v' i x\n unsafeFreeze v'\n\ngenerateMatrixM\n :: forall orient m a. (Monad m, Storable a, SingI orient)\n => Int\n -> Int\n -> (Int -> Int -> m a)\n -> m (DenseMatrix orient a)\n{-# NOINLINE generateMatrixM #-}\ngenerateMatrixM !rows !cols f\n | rows < 0 || cols < 0 = error $! \"generateMatrixM: Invalid dimensions: \" <> show (rows, cols)\n | rows == 0 || cols == 0 = return $! DenseMatrix 0 0 0 V.empty\n | otherwise = go (runST $ newDenseMatrix rows cols >>= unsafeFreeze)\n where\n go :: DenseMatrix orient a -> m (DenseMatrix orient a)\n go !m'' = case (sing :: Sing orient) of\n SRow -> for' m'' rows $ \\m' i -> for' m' cols $ \\m j ->\n f i j >>= \\x -> return (set m i j x)\n SColumn -> for' m'' cols $ \\m' j -> for' m' rows $ \\m i ->\n f i j >>= \\x -> return (set m i j x)\n set !m !i !j !x = runST $ do\n !m' <- unsafeThaw m\n unsafeWriteMatrix m' (i, j) x\n unsafeFreeze m'\n\ninstance (Storable a, FromJSON a) => FromJSON (DenseVector 'Direct a) where\n parseJSON = withArray \"vector elements (i.e. Array)\" $ \\v -> do\n generateVectorM (GV.length v) $ \\i -> parseJSON (v `GV.unsafeIndex` i)\n\ninstance ToJSON a => ToJSON (Complex a) where\n toJSON (x :+ y) = toJSON [x, y]\n toEncoding (x :+ y) = toEncoding [x, y]\n\ninstance FromJSON a => FromJSON (Complex a) where\n parseJSON = withArray \"Complex\" $ \\v ->\n (:+) <$> parseJSON (v GV.! 0)\n <*> parseJSON (v GV.! 1)\n\ninstance (Storable a, FromJSON a, SingI orient) => FromJSON (DenseMatrix orient a) where\n parseJSON = withArray \"Matrix rows\" $ \\matrix -> do\n (n, m) <- checkDimensions matrix\n generateMatrixM n m $ \\i j ->\n flip (withArray \"a matrix row\") (matrix `GV.unsafeIndex` i) $ \\row ->\n parseJSON (row `GV.unsafeIndex` j)\n where\n checkDimensions x@(GV.length -> n)\n | n == 0 = return (0, 0)\n | otherwise = do\n !m <- withArray \"first row (i.e. Array)\" (return . GV.length) (GV.unsafeHead x)\n for 0 n $ \\i ->\n flip (withArray \"a matrix row (i.e. Array)\") (x `GV.unsafeIndex` i) $ \\row ->\n unless (GV.length row == m) $ fail $! \"Matrix row #\" <> show i <> \" has wrong dimension.\"\n return (n, m)\n\nvectorAsVector :: Storable a => DenseVector 'Direct a -> Boxed.Vector a\nvectorAsVector !(DenseVector n stride buff) =\n Boxed.generate n (\\i -> buff `V.unsafeIndex` (i * stride))\n\n-- | Returns a row of a matrix.\nunsafeRowAsVector\n :: forall orient a\n . (Storable a, SingI orient)\n => Int\n -> DenseMatrix orient a\n -> Boxed.Vector a\nunsafeRowAsVector !i !(DenseMatrix rows cols stride buff) =\n assert (i < rows) $ case (sing :: Sing orient) of\n SRow -> GV.generate cols (\\j -> buff `V.unsafeIndex` (i * stride + j))\n SColumn -> GV.generate cols (\\j -> buff `V.unsafeIndex` (i + j * stride))\n\ninstance (Storable a, ToJSON a) => ToJSON (DenseVector 'Direct a) where\n toEncoding = toEncoding . vectorAsVector\n\ninstance (Storable a, ToJSON a, SingI orient) => ToJSON (DenseMatrix orient a) where\n toEncoding x = toEncoding $ Boxed.generate (x ^. dim . _1) (\\i -> unsafeRowAsVector i x)\n\n\n\n", "meta": {"hexsha": "813fcf1167e183e159349a96b919c629208dc74e", "size": 27577, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NQS/Internal/Types.hs", "max_stars_repo_name": "twesterhout/tcm-swarm", "max_stars_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NQS/Internal/Types.hs", "max_issues_repo_name": "twesterhout/tcm-swarm", "max_issues_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NQS/Internal/Types.hs", "max_forks_repo_name": "twesterhout/tcm-swarm", "max_forks_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8634639697, "max_line_length": 103, "alphanum_fraction": 0.6261377235, "num_tokens": 7983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.20441216878528065}}