{"text": "{-# LANGUAGE Safe #-}\n-- | Import all modules from prelude that should be safe\nmodule Main where\n\nimport Numeric\nimport Prelude\n-- import Foreign\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Category\n\n-- import Control.ST\n-- import Control.ST.Lazy\n-- import Control.ST.Strict\n\nimport Control.Concurrent\nimport Control.Concurrent.Chan\nimport Control.Concurrent.MVar\n\nimport Control.Exception\nimport Control.Exception.Base\n\nimport Control.Monad\nimport Control.Monad.Fix\nimport Control.Monad.Zip\n\nimport Data.Bits\nimport Data.Bool\nimport Data.Char\nimport Data.Complex\nimport Data.Either\nimport Data.Eq\nimport Data.Fixed\nimport Data.Foldable\nimport Data.Function\nimport Data.Functor\nimport Data.IORef\nimport Data.Int\nimport Data.Ix\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\nimport Data.Typeable\nimport Data.Unique\nimport Data.Version\nimport Data.Word\n\nimport Data.STRef\nimport Data.STRef.Lazy\nimport Data.STRef.Strict\n\n-- import Debug.Trace\n\nimport Foreign.Concurrent\n-- import Foreign.ForeignPtr\nimport Foreign.Ptr\nimport Foreign.StablePtr\nimport Foreign.Storable\n\nimport Foreign.C\nimport Foreign.C.Error\nimport Foreign.C.String\nimport Foreign.C.Types\n\n-- import Foreign.Marshal\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Error\nimport Foreign.Marshal.Pool\nimport Foreign.Marshal.Utils\n\nimport System.CPUTime\nimport System.Environment\nimport System.Exit\nimport System.Info\nimport System.Mem\nimport System.Timeout\n\nimport System.Console.GetOpt\n\nimport System.IO\nimport System.IO.Error\n\nimport System.Mem.StableName\nimport System.Mem.Weak\n\nimport System.Posix.Internals\nimport System.Posix.Types\n\nimport Text.Printf\n\nimport Text.Read\nimport Text.Read.Lex\n\nimport Text.Show\nimport Text.Show.Functions\n\nimport Text.ParserCombinators.ReadP\nimport Text.ParserCombinators.ReadPrec\n\n-- import Unsafe.Coerce\n\nf :: Int\nf = 2\n\nmain :: IO ()\nmain = putStrLn $ \"X is: \" ++ show f\n\n", "meta": {"hexsha": "6533e18b7d8545ff73b84239e0f9d8f6962a98b1", "size": 2028, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "testsuite/tests/safeHaskell/unsafeLibs/GoodImport03.hs", "max_stars_repo_name": "ocharles/ghc", "max_stars_repo_head_hexsha": "f0fcc41d755876a1b02d1c7c79f57515059f6417", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-01-20T19:27:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-10T17:54:29.000Z", "max_issues_repo_path": "testsuite/tests/safeHaskell/unsafeLibs/GoodImport03.hs", "max_issues_repo_name": "ocharles/ghc", "max_issues_repo_head_hexsha": "f0fcc41d755876a1b02d1c7c79f57515059f6417", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 98, "max_issues_repo_issues_event_min_datetime": "2015-01-09T07:00:35.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-22T12:32:57.000Z", "max_forks_repo_path": "testsuite/tests/safeHaskell/unsafeLibs/GoodImport03.hs", "max_forks_repo_name": "ocharles/ghc", "max_forks_repo_head_hexsha": "f0fcc41d755876a1b02d1c7c79f57515059f6417", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-05T16:00:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-05T16:00:07.000Z", "avg_line_length": 17.6347826087, "max_line_length": 56, "alphanum_fraction": 0.8126232742, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24993408376257822}}
{"text": "{-# LANGUAGE RecordWildCards #-}\n\nmodule Arpack.Foreign.Class where\n\nimport Data.Vector.Storable.Mutable (IOVector)\nimport Numeric.LinearAlgebra (Matrix, Vector)\n\nimport Arpack.Options\n\nclass Arpack t where\n  arpack :: Options t -> Int -> (IOVector t -> IOVector t -> IO ())\n         -> IO (Vector t, Matrix t)\n", "meta": {"hexsha": "c2fb6feb03e6bc89b90f711b9ce8dd0ec5e0721f", "size": 311, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Arpack/Foreign/Class.hs", "max_stars_repo_name": "ttuegel/arpack", "max_stars_repo_head_hexsha": "004b7b4444f2ab7b2b1c07ed6aecf279e330f9a5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-17T01:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-17T01:05:40.000Z", "max_issues_repo_path": "src/Arpack/Foreign/Class.hs", "max_issues_repo_name": "ttuegel/arpack", "max_issues_repo_head_hexsha": "004b7b4444f2ab7b2b1c07ed6aecf279e330f9a5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-09-30T09:59:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-30T19:56:06.000Z", "max_forks_repo_path": "src/Arpack/Foreign/Class.hs", "max_forks_repo_name": "ttuegel/arpack", "max_forks_repo_head_hexsha": "004b7b4444f2ab7b2b1c07ed6aecf279e330f9a5", "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": 23.9230769231, "max_line_length": 67, "alphanum_fraction": 0.7009646302, "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24945148725570082}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\nmodule Statistics.BBVI.Observed\n  ( Obs(..)\n  , defaultObs\n  )\nwhere\n\nimport qualified Data.Vector                   as V\nimport           Statistics.BBVI.Class\nimport           Statistics.BBVI.Propagator     ( DistCell(..)\n                                                , SampleVector\n                                                , SampleDouble\n                                                )\nimport           System.Random.MWC              ( uniformR )\n\n-- | Dummy distribution representing a vector of observations, for use\n-- with building \"observation\" distribution cells.  these can be used\n-- to easily/selectively subsample (and resample) observations using\n-- existing typeclass methods (useful with stochatic gradient\n-- updates).\nnewtype Obs a = O (V.Vector a) deriving (Show, Eq, Ord, Read)\n\n-- | helper function to build a distribution cell of observations\ndefaultObs\n  :: V.Vector a -- ^ observations\n  -> DistCell (Obs a)\ndefaultObs d = (Node 1 V.empty (O d))\n\ninstance DistUtil (Obs Double) where\n  nParams _x = 0\n  toParamVector _ = V.empty\n  fromParamVector _ = O V.empty\n\ninstance Dist (Obs Double) SampleDouble where\n  resample (O d) gen = return . (d V.!) =<< uniformR (0, (V.length d - 1)) gen\n  logProb _d _x = 0\n  paramGradOfLogQ _d _x = V.empty\n\ninstance DistUtil (Obs SampleVector) where\n  nParams _x = 0\n  toParamVector _ = V.empty\n  fromParamVector _ = O V.empty\n\ninstance Dist (Obs SampleVector) SampleVector where\n  resample (O d) gen = return . (d V.!) =<< uniformR (0, (V.length d - 1)) gen\n  logProb _d _x = 0\n  paramGradOfLogQ _d _x = V.empty\n", "meta": {"hexsha": "302b5a43ca2dde4008b8b4edd648dbd60a4821bf", "size": 1701, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/BBVI/Observed.hs", "max_stars_repo_name": "massma/propagator-bbvi", "max_stars_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "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/Statistics/BBVI/Observed.hs", "max_issues_repo_name": "massma/propagator-bbvi", "max_issues_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "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/Statistics/BBVI/Observed.hs", "max_forks_repo_name": "massma/propagator-bbvi", "max_forks_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "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.02, "max_line_length": 78, "alphanum_fraction": 0.6308054086, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24781554514906318}}
{"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": "-- Copyright (c) 1982-1999 Lennart Augustsson, Thomas Johnsson\n-- See LICENSE for the full license.\n--\nmodule Hash(Hash(..), combineHash, emptyHash, hashToInt, hashToMax, Hashable(..)) where\n\n--\n-- Hash a value.  Hashing produces an Int of\n-- unspecified range.\n--\nimport Data.Array\nimport Data.Complex\nimport Data.Ratio\n\n-- #define HASH(x) (case hash (x) of H h -> h)\nhASH x = case hash (x) of H h -> h\n\nnewtype Hash = H Int deriving (Eq)\n\ninstance Show Hash where\n    --showsType _ = showString \"Hash\"\n    show _ = \"<<Hash>>\"\n\ncombineHash :: Hash -> Hash -> Hash\ncombineHash (H x) (H y) = H (x+y)\n\nemptyHash :: Hash\nemptyHash = H 0\n\nclass Hashable a where\n    hash :: a -> Hash\n\ninstance Hashable Char where\n    hash x = H $ fromEnum x\n\ninstance Hashable Int where\n    hash x = H $ x\n\ninstance Hashable Integer where\n    hash x = H $ fromInteger x\n\ninstance Hashable Float where\n    hash x = H $ truncate x\n\ninstance Hashable Double where\n    hash x = H $ truncate x\n\ninstance Hashable (IO a) where\n    hash x = H 0\n\ninstance Hashable () where\n    hash x = H 0\n\ninstance Hashable (a -> b) where\n    hash x = H 0\n\ninstance (Hashable a) => Hashable (Maybe a) where\n    hash Nothing = H 0\n    hash (Just x) = hash x\n\ninstance (Hashable a, Hashable b) => Hashable (Either a b) where\n    hash (Left x) = hash x\n    hash (Right y) = hash y\n\ninstance Hashable a => Hashable [a] where\n    hash l = H $ f l 0\n        where f :: (Hashable a') => [a'] -> Int -> Int\n              f [] r = r\n              f (c:cs) r = f cs (3*r + hASH(c))\n\n{-\n#ifndef __HBCC__\ninstance Hashable [Char] where\n    hash l = H $ f l 0\n        where f :: String -> Int -> Int\n              f [] r = r\n              f (c:cs) r = f cs (3*r + fromEnum c)\n#endif\n-}\n\ninstance (Hashable a, Hashable b) => Hashable (a,b) where\n    hash (a,b) = H $ hASH(a) + 3 * hASH(b)\n\ninstance (Hashable a, Hashable b, Hashable c) => Hashable (a,b,c) where\n    hash (a,b,c) = H $ hASH(a) + 3 * hASH(b) + 5 * hASH(c)\n\ninstance (Hashable a, Hashable b, Hashable c, Hashable d) => Hashable (a,b,c,d) where\n    hash (a,b,c,d) = H $ hASH(a) + 3 * hASH(b) + 5 * hASH(c) + 7 * hASH(d)\n\ninstance (Hashable a, Hashable b, Hashable c, Hashable d, Hashable e) => Hashable (a,b,c,d,e) where\n    hash (a,b,c,d,e) = H $ hASH(a) + 3 * hASH(b) + 5 * hASH(c) + 7 * hASH(d) + 9 * hASH(e)\n\ninstance Hashable Bool where\n    hash False = H 0\n    hash True = H 1\n\ninstance (Integral a, Hashable a) => Hashable (Ratio a) where\n    hash x = H $ hASH (denominator x) + hASH (numerator x)\n\ninstance (RealFloat a, Hashable a) => Hashable (Complex a) where\n    hash (x :+ y) = H $ hASH(x) + hASH(y)\n\ninstance (Ix a) => Hashable (Array a b) where\n    hash x = H $ 0 -- !!!\n\nhashToInt :: Int -> Hash -> Int\nhashToInt maxhash x =\n    case x of\n    H h ->\n        if h < 0 then\n            if -h < 0 then 0\n            else (-h) `rem` maxhash\n        else h `rem` maxhash\n\nhashToMax maxhash x =\n    case hash x of\n    H h ->\n        if h < 0 then\n            if -h < 0 then 0\n            else (-h) `rem` maxhash\n        else h `rem` maxhash\n", "meta": {"hexsha": "86a2167b58e174f90606c436ae472f4571d74d9f", "size": 3058, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/comp/Libs/Hash.hs", "max_stars_repo_name": "GaloisInc/BESSPIN-BSC", "max_stars_repo_head_hexsha": "21a0a8cba9e643ef5afcb87eac164cc33ea83e94", "max_stars_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-11T01:52:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:52:42.000Z", "max_issues_repo_path": "src/comp/Libs/Hash.hs", "max_issues_repo_name": "GaloisInc/BESSPIN-BSC", "max_issues_repo_head_hexsha": "21a0a8cba9e643ef5afcb87eac164cc33ea83e94", "max_issues_repo_licenses": ["BSD-2-Clause", "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/comp/Libs/Hash.hs", "max_forks_repo_name": "GaloisInc/BESSPIN-BSC", "max_forks_repo_head_hexsha": "21a0a8cba9e643ef5afcb87eac164cc33ea83e94", "max_forks_repo_licenses": ["BSD-2-Clause", "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": 25.2727272727, "max_line_length": 99, "alphanum_fraction": 0.5853499019, "num_tokens": 1025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2474388945535826}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Grenade.Layers.Internal.Pad (\n    pad\n  , crop\n  ) where\n\nimport qualified Data.Vector.Storable        as U (unsafeFromForeignPtr0,\n                                                   unsafeToForeignPtr0)\n\nimport           Foreign                     (mallocForeignPtrArray, withForeignPtr)\nimport           Foreign.Ptr                 (Ptr)\nimport           Numeric.LinearAlgebra       (Matrix, flatten)\nimport qualified Numeric.LinearAlgebra.Devel as U\nimport           System.IO.Unsafe            (unsafePerformIO)\n\nimport           Grenade.Types\n\npad :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum\npad channels padLeft padTop padRight padBottom rows cols rows' cols' m\n = let outMatSize      = rows' * cols' * channels\n       vec             = flatten m\n   in unsafePerformIO $ do\n     outPtr        <- mallocForeignPtrArray outMatSize\n     let (inPtr, _) = U.unsafeToForeignPtr0 vec\n\n     withForeignPtr inPtr $ \\inPtr' ->\n       withForeignPtr outPtr $ \\outPtr' ->\n         pad_cpu inPtr' channels rows cols padLeft padTop padRight padBottom outPtr'\n\n     let matVec = U.unsafeFromForeignPtr0 outPtr outMatSize\n     return (U.matrixFromVector U.RowMajor (rows' * channels) cols' matVec)\n{-# INLINE pad #-}\n\nforeign import ccall unsafe\n    pad_cpu\n      :: Ptr RealNum -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr RealNum -> IO ()\n\ncrop :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum\ncrop channels padLeft padTop padRight padBottom rows cols _ _ m\n = let outMatSize      = rows * cols * channels\n       vec             = flatten m\n   in unsafePerformIO $ do\n     outPtr        <- mallocForeignPtrArray outMatSize\n     let (inPtr, _) = U.unsafeToForeignPtr0 vec\n\n     withForeignPtr inPtr $ \\inPtr' ->\n       withForeignPtr outPtr $ \\outPtr' ->\n         crop_cpu inPtr' channels rows cols padLeft padTop padRight padBottom outPtr'\n\n     let matVec = U.unsafeFromForeignPtr0 outPtr outMatSize\n     return (U.matrixFromVector U.RowMajor (rows * channels) cols matVec)\n\nforeign import ccall unsafe\n    crop_cpu\n      :: Ptr RealNum -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr RealNum -> IO ()\n\n\n", "meta": {"hexsha": "55e785c4e2c6ec3aeeeccdd11b531753e0974f13", "size": 2271, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Internal/Pad.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Layers/Internal/Pad.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-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/Grenade/Layers/Internal/Pad.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 39.1551724138, "max_line_length": 103, "alphanum_fraction": 0.6257155438, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24703296844699485}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n\n{-|\nModule      : Data.Picture\nDescription : picture manipulation functions\nCopyright   : (c) Mahdi Dibaiee, 2016\nLicense     : GPL-3\nMaintainer  : mdibaiee@aol.com\nStability   : experimental\nPortability : POSIX\n-}\nmodule Data.Picture ( Picture\n                    -- * Manipulation functions\n                    , grayscale\n                    , fade\n                    , rotate\n                    , contrast\n                    , brightness\n                    , gamma\n                    , invert\n                    , compress\n                    , embed\n                    , resize\n                    , Data.Picture.scale\n                    -- * Converting between Image and Picture\n                    , fromImage\n                    , toImage\n                    -- * IO operations\n                    , readPicture\n                    , writePicturePng\n                    )\n  where\n\n    import Codec.Picture\n    import Numeric.LinearAlgebra\n    import qualified Data.Vector.Storable as V\n    import System.IO\n    import Data.Maybe\n    import Debug.Trace\n    import Data.List (zipWith4)\n\n    -- | (R, G, B, A) color channels\n    type Picture = (Matrix Double, Matrix Double, Matrix Double, Matrix Double)\n\n    -- | Converts a JuicyPixel 'Image PixelRGBA8' to 'Picture'\n    fromImage :: Image PixelRGBA8 -> Picture\n    fromImage Image { imageWidth = w, imageHeight = h, imageData = vec } =\n     let [r, g, b, a] = map (reshape w . V.fromList . reverse) (snd $ V.foldl' gp (0, [[],[],[],[]]) (V.map fromIntegral vec))\n     in (r, g, b, a)\n     where\n       gp acc x =\n         case acc of\n           (0, [r, g, b, a]) -> (1, [x:r, g, b, a])\n           (1, [r, g, b, a]) -> (2, [r, x:g, b, a])\n           (2, [r, g, b, a]) -> (3, [r, g, x:b, a])\n           (3, [r, g, b, a]) -> (0, [r, g, b, x:a])\n\n    -- | Converts a 'Picture' to JuicyPixel 'Image PixelRGBA8'\n    toImage :: Picture -> Image PixelRGBA8\n    toImage (r, g, b, a) = \n      let (fr, fg, fb, fa) = (toList $ flatten r, toList $ flatten g, toList $ flatten b, toList $ flatten a)\n          img = V.map (fromIntegral . floor) . V.concat $ zipWith4 (\\a b c d -> vector [a, b, c, d]) fr fg fb fa\n      in Image { imageWidth = cols r, imageHeight = rows r, imageData = img }\n\n\n    -- | Reads a 'Picture' from specified path\n    readPicture :: FilePath -> IO (Either String Picture)\n    readPicture path = do\n      img <- readImage path\n      return $ case img of \n        Left err -> Left err\n        Right im -> Right $ fromImage (convertRGBA8 im)\n\n    -- | Write the specified 'Picture' to a PNG file\n    writePicturePng :: FilePath -> Picture -> IO ()\n    writePicturePng path pic = writePng path (toImage pic)\n\n    -- | Turn the 'Picture' grayscale\n    grayscale :: Picture -> Picture\n    grayscale (r, g, b, a) =\n      let (fr, fg, fb) = (flatten r, flatten g, flatten b)\n          mean = reshape (cols r) $ V.map (/ 3) (fr + fg + fb)\n      in (mean, mean, mean, a)\n\n    -- | Fade the 'Picture' by a number between 0 and 1\n    fade :: Double -> Picture -> Picture\n    fade opacity (r, g, b, a) = (r, g, b, f a)\n      where\n        f = cmap (*opacity)\n\n    -- | Set contrast level of 'Picture', a number between -255 and 255\n    contrast :: Double -> Picture -> Picture\n    contrast level (r, g, b, a) = (f r, f g, f b, a)\n      where\n        cfactor = (259 * (level + 255)) / (255 * (259 - level))\n        f = cmap (\\x -> pixelBound $ cfactor * (x - 128) + 128)\n\n    -- | Set brightness level of 'Picture', a number between -255 and 255\n    brightness :: Double -> Picture -> Picture\n    brightness level (r, g, b, a) = (f r, f g, f b, a)\n      where\n        f = cmap (pixelBound . (+level))\n\n    -- | Set gamma level of 'Picture'\n    gamma :: Int -> Picture -> Picture\n    gamma level (r, g, b, a) = (f r, f g, f b, a)\n      where\n        f = cmap (\\x -> pixelBound $ 255 * (x / 255) ^ level)\n\n    -- | Inverts the 'Picture'\n    invert :: Picture -> Picture\n    invert (r, g, b, a) = (f r, f g, f b, a)\n      where\n        f = cmap (`subtract` 255)\n\n    -- | Rotate 'Picture' for the specified degrees, around the specified origin.\n    -- If the origin is `Nothing`, rotates around the center\n    rotate :: Double -> Maybe (Int, Int) -> Picture -> Picture\n    rotate deg orig (r, g, b, a) = (f r, f g, f b, f a)\n      where\n        -- rotation in radians\n        rad = deg * pi / 180\n\n        -- rotation matrix (clockwise)\n        rm = fromLists [[cos rad, sin rad],\n                        [negate $ sin rad, cos rad]]\n\n        -- origin of rotation\n        (originX, originY) = if isJust orig then fromJust orig else (cols r `div` 2, rows r `div` 2)\n\n        -- all index pairs\n        indices = [vector [fromIntegral x - fromIntegral originX, fromIntegral y - fromIntegral originY] | y <- [0..rows r - 1], x <- [0..cols r - 1]]\n\n        -- rotate them using rotation matrix\n        rotatedIndices :: [[Int]] = map (\\r -> toList . V.map (fromIntegral . round) $ rm #> r) indices\n\n        -- move them back to the origin\n        movedIndices = map (\\[x, y] -> [x + originX, y + originY]) rotatedIndices\n\n        f m = reshape (cols m) $ fromList $ map (\\[x, y] -> if y < 0 || y >= rows r || x < 0 || x >= cols r then 0 else m `atIndex` (y, x)) movedIndices\n\n    -- | Compress the image using SVD\n    -- note: this is not size compression, it's just a k-rank approximation of the image\n    compress :: Int -> Picture -> Picture\n    compress rate (r, g, b, a) = (f r, f g, f b, a)\n      where\n        k = cols r - rate\n        f m =\n          let (u, s, v) = svd m\n              si = diagRect 0 s (rows m) (cols m)\n              (mu, ms, mv) = (u ?? (All, Take k), si ?? (Take k, Take k), (tr v) ?? (Take k, All))\n          in mu <> ms <> mv\n\n    -- | Embed a 'Picture' into another one, in the specified position-}\n    embed :: Picture -> (Int, Int) -> Picture -> Picture\n    embed (br, bg, bb, ba) (x, y) (lr, lg, lb, la) = (f br lmr, f bg lmg, f bb lmb, maxAlpha)\n      where\n        (lmr, lmg, lmb, lma) = (fit lr, fit lg, fit lb, fit la)\n        scaledAlpha = cmap (/255) lma\n      \n        fit m =\n          let distance = y * cols br\n              total = rows br * cols br\n              xPush = (rows m><x) (repeat 0)\n              xPast = (rows m><(cols br - x - cols m)) (repeat 0)\n              positioned = xPush ||| m ||| xPast\n              flat = toList $ flatten positioned\n          in (rows br><cols br) $ replicate distance 0 ++ flat ++ repeat 0\n\n        f b lm = (b * (cmap (1-) scaledAlpha)) + (lm * scaledAlpha)\n        maxAlpha = (rows ba><cols ba) $ zipWith max (toList . flatten $ ba) (toList . flatten . fit $ la)\n\n    -- | Resize an image using nearest-neighbor interpolation\n    resize :: (Int, Int) -> Picture -> Picture\n    resize (sWidth, sHeight) (r, g, b, a) = (f r, f g, f b, f a)\n      where\n        initial = vector [0..fromIntegral sWidth * fromIntegral sHeight - 1]\n        (width, height) = (cols r, rows r)\n        factor = 2 ^ 16\n        (xRatio, yRatio) = (width * factor `div` sWidth + 1, height * factor `div` sHeight + 1)\n        f m = reshape sWidth $ V.map replace initial\n          where\n            v = flatten m\n            replace index =\n              let (x, y) = (floor index `mod` sWidth, floor index `div` sWidth)\n                  (px, py) = (x * xRatio `div` factor, y * yRatio `div` factor)\n              in v ! (py * width + px)\n\n    -- | Scale an image using the resize function\n    scale :: Double -> Picture -> Picture\n    scale 1 p = p\n    scale s (r, g, b, a) = resize (floor $ s * width, floor $ s * height) (r, g, b, a)\n      where\n        (width, height) = (fromIntegral $ cols r, fromIntegral $ rows r)\n\n\n    bound (l, u) x = max l $ min u x\n    pixelBound = bound (0, 255)\n", "meta": {"hexsha": "6769d95c7ba23d798f39f2ff24f848f7ce3da09f", "size": 7820, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Picture.hs", "max_stars_repo_name": "mdibaiee/picedit", "max_stars_repo_head_hexsha": "ffdf17c84ef5fb625fe70ed23753a11afcdae880", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-10-09T06:06:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-27T13:15:36.000Z", "max_issues_repo_path": "src/Data/Picture.hs", "max_issues_repo_name": "mdibaiee/picedit", "max_issues_repo_head_hexsha": "ffdf17c84ef5fb625fe70ed23753a11afcdae880", "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/Data/Picture.hs", "max_forks_repo_name": "mdibaiee/picedit", "max_forks_repo_head_hexsha": "ffdf17c84ef5fb625fe70ed23753a11afcdae880", "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": 38.9054726368, "max_line_length": 152, "alphanum_fraction": 0.5274936061, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2469533556692104}}
{"text": "{-# LANGUAGE ConstraintKinds       #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE Rank2Types            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeApplications      #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n-- |\n-- This module provides function for working with product types and\n-- comes in two variants. First works with plain product, types like\n-- @(a,b)@ or @data Prod = Prod A B@, etc. Second one is for\n-- parameterized products (it seems there's no standard name for\n-- them), that is types like: @data ProdF f = ProdF (f Int) (f Char)@.\n--\n-- Most examples in this module use tuple but library is not limited\n-- to them in any way. They're just in base and convenient to work\n-- with.\nmodule Data.Vector.HFixed (\n    -- * HVector type classes\n    HVector(..)\n  , tupleSize\n  , HVectorF(..)\n  , tupleSizeF\n  , ContVec\n  , ContVecF(..)\n  , asCVec\n  , asCVecF\n    -- * Plain product types\n    -- ** Construction\n    -- *** Simple constructor\n    -- $construction\n  , mk0\n  , mk1\n  , mk2\n  , mk3\n  , mk4\n  , mk5\n    -- *** Unfoldr & replicate\n  , unfoldr\n  , replicate\n  , replicateM\n  -- ** Position based functions\n  , convert\n  , head\n  , tail\n  , cons\n  , concat\n    -- *** Indexing\n  , ValueAt\n  , Index\n  , index\n  , set\n  , element\n  , elementCh\n  , tyLookup\n  , tyLookupF\n    -- ** Folds & unfolds\n  , foldr\n  , foldl\n  , foldMap\n  , mapM_\n    -- ** Zips\n  , zipWith\n  , zipFold\n    -- ** Specializations\n  , eq\n  , compare\n  , rnf\n    -- * Parametrized products\n    -- ** Construction\n    -- *** Simple constructors\n    -- $construction_F\n  , mk0F\n  , mk1F\n  , mk2F\n  , mk3F\n  , mk4F\n  , mk5F\n    -- *** Unfoldr & replicate\n  , unfoldrF\n  , replicateF\n  , replicateNatF\n    -- ** Conversion to\\/from products\n  , wrap\n  , unwrap\n  , monomorphize\n  , monomorphizeF\n    -- ** Functor\\/Applicative like\n  , map\n  , mapNat\n  , sequence\n  , sequence_\n  , sequenceF\n  , distribute\n  , distributeF\n    -- ** Folds and unfolds\n  , foldrF\n  , foldlF\n  , foldMapF\n  , foldrNatF\n  , foldlNatF\n  , foldMapNatF\n    -- ** Zips\n  , zipWithF\n  , zipWithNatF\n  , zipFoldF\n    -- ** Reexports\n  , Arity\n  , ArityC\n  , Proxy(..)\n  ) where\n\nimport Control.Applicative  (Applicative(..),(<$>))\nimport qualified Control.DeepSeq as NF\n\nimport Data.Coerce           (coerce)\nimport Data.Functor.Compose  (Compose(..))\nimport Data.Functor.Identity (Identity(..))\nimport Data.Monoid           (Monoid,All(..))\nimport Prelude ( Functor(..),Eq(..),Ord,Bool,Ordering\n               , id,(.),($),seq)\nimport qualified Prelude\n\nimport           Data.Vector.HFixed.Class hiding (cons,consF)\nimport           Data.Vector.Fixed.Cont       (Peano)\nimport qualified Data.Vector.Fixed          as F\nimport qualified Data.Vector.HFixed.Cont    as C\n\n\n----------------------------------------------------------------\n-- Generic API\n----------------------------------------------------------------\n\n-- | Restrict type of vector to 'ContVec'. This function is useful for\n--   resolving type ambiguity when composing functions. For example\n--   following code would not compile because intermediate type is\n--   ambiguous:\n--\n-- > cons 'a' . tail\n--\n--   GHC cannot guess what type should be produced by @tail@. However\n--   we can fix type of intermediate vector with @asCVec@, so code\n--   below will work just fine:\n--\n-- > cons 'a' . asCVec . tail\nasCVec :: ContVec xs -> ContVec xs\nasCVec = id\n\nasCVecF :: ContVecF f xs -> ContVecF f xs\nasCVecF = id\n\n-- | We can convert between any two vector which have same\n--   structure but different representations.\n--\n-- >>> convert (1 :+ 2) :: (Double,Double)\n-- (1.0,2.0)\nconvert :: (HVector v, HVector w, Elems v ~ Elems w)\n        => v -> w\n{-# INLINE convert #-}\nconvert v = inspect v construct\n\n-- | Tail of the vector. Note that in the example we only tell GHC\n--   that resulting value is 2-tuple via pattern matching and let\n--   typechecker figure out the rest.\n--\n-- >>> case tail ('a',\"aa\",()) of x@(_,_) -> x\n-- (\"aa\",())\ntail :: (HVector v, HVector w, (a : Elems w) ~ Elems v)\n     => v -> w\n{-# INLINE tail #-}\ntail = C.vector . C.tail . C.cvec\n\n\n-- | Head of the vector\n--\n-- >>> head ('a',\"ABC\")\n-- 'a'\nhead :: (HVector v, Elems v ~ (a : as), Arity as)\n     => v -> a\n{-# INLINE head #-}\nhead = C.head . C.cvec\n\n-- | Prepend element to the product.\n--\n-- >>> cons 'c' ('d','e') :: (Char,Char,Char)\n-- ('c','d','e')\ncons :: (HVector v, HVector w, Elems w ~ (a : Elems v))\n     => a -> v -> w\n{-# INLINE cons #-}\ncons a = C.vector . C.cons a . C.cvec\n\n-- | Concatenate two vectors\n--\n-- >>> concat ('c','d') ('e','f') :: (Char,Char,Char,Char)\n-- ('c','d','e','f')\nconcat :: ( HVector v, HVector u, HVector w\n          , Elems w ~ (Elems v ++ Elems u)\n          )\n       => v -> u -> w\nconcat v u = C.vector $ C.concat (C.cvec v) (C.cvec u)\n{-# INLINE concat #-}\n\n\n\n----------------------------------------------------------------\n-- Indexing\n----------------------------------------------------------------\n\n-- | Index heterogeneous vector.\n--\n-- >>> index (Proxy @0) ('c',\"str\")\n-- 'c'\n-- >>> index (Proxy @1) ('c',\"str\")\n-- \"str\"\nindex\n  :: forall n v proxy. (Index (Peano n) (Elems v), HVector v)\n  => proxy n                     -- ^ Type level index\n  -> v                           -- ^ Vector to index\n  -> ValueAt (Peano n) (Elems v)\n{-# INLINE index #-}\nindex _ v = C.index (C.cvec v) (Proxy @(Peano n))\n\n\n-- | Set element in the vector\n--\n-- >>> set (Proxy @0) 'X' ('_',\"str\")\n-- ('X',\"str\")\nset :: forall n v proxy. (Index (Peano n) (Elems v), HVector v)\n    => proxy n                     -- ^ Type level index\n    -> ValueAt (Peano n) (Elems v) -- ^ New value at index\n    -> v\n    -> v\n{-# INLINE set #-}\nset _ x = C.vector\n        . C.set (Proxy @(Peano n)) x\n        . C.cvec\n\n-- | Twan van Laarhoven's lens for i'th element.\nelement :: forall n v proxy.\n           ( Index (Peano n) (Elems v)\n           , HVector v\n           )\n        => proxy n              -- ^ Type level index\n        -> Lens' v (ValueAt (Peano n) (Elems v))\n{-# INLINE element #-}\nelement _ f v = inspect v\n              $ lensF (Proxy @(Peano n)) f construct\n\n-- | Type changing Twan van Laarhoven's lens for i'th element.\nelementCh :: forall n v w a b proxy.\n             ( Index   (Peano n) (Elems v)\n             , ValueAt (Peano n) (Elems v) ~ a\n             , HVector v\n             , HVector w\n             , Elems w ~ NewElems (Peano n) (Elems v) b\n             )\n          => proxy n            -- ^ Type level index\n          -> Lens v w a b\n{-# INLINE elementCh #-}\nelementCh _ f v = inspect v\n                $ lensChF (Proxy @(Peano n)) f construct\n\n\n-- | Lookup field from product by its type. Product must contain one\n--   and only one field of type @a@\n--\n-- >>> tyLookup ('c',\"str\") :: Char\n-- 'c'\n--\n-- >>> tyLookup ('c',\"str\") :: Int\n-- ...\n--     \u2022 Cannot find type:\n--       Int\n--     \u2022 In the expression: tyLookup ('c', \"str\") :: Int\n--       In an equation for \u2018it\u2019: it = tyLookup ('c', \"str\") :: Int\n--\n-- >>> tyLookup ('c','c') :: Char\n-- ...\n--     \u2022 Duplicate type found:\n--       Char\n--     \u2022 In the expression: tyLookup ('c', 'c') :: Char\n--       In an equation for \u2018it\u2019: it = tyLookup ('c', 'c') :: Char\ntyLookup :: (HVector v, TyLookup a (Elems v)) => v -> a\ntyLookup = C.tyLookup . C.cvec\n{-# INLINE tyLookup #-}\n\n-- | Analog of 'tyLookup' for @HVectorF@\ntyLookupF :: (HVectorF v, TyLookup a (ElemsF v)) => v f -> f a\ntyLookupF = C.tyLookupF . C.cvecF\n{-# INLINE tyLookupF #-}\n\n\n----------------------------------------------------------------\n-- Folds over vector\n----------------------------------------------------------------\n\n-- | Right fold over heterogeneous vector\n--\n-- >>> foldr (Proxy @Show) (\\x str -> show x : str) [] (12,'c')\n-- [\"12\",\"'c'\"]\nfoldr :: (HVector v, ArityC c (Elems v))\n      => Proxy c -> (forall a. c a => a -> b -> b) -> b -> v -> b\n{-# INLINE foldr #-}\nfoldr c f b0 = C.foldrF c (\\(Identity a) b -> f a b) b0 . C.cvec\n\n-- | Left fold over heterogeneous vector\nfoldl :: (HVector v, ArityC c (Elems v))\n      => Proxy c -> (forall a. c a => b -> a -> b) -> b -> v -> b\n{-# INLINE foldl #-}\nfoldl c f b0 = C.foldlF c (\\b (Identity a) -> f b a) b0 . C.cvec\n\n-- | Monoidal fold over heterogeneuous vector\n--\n-- >>> foldMap (Proxy @Show) show (12,'c',\"str\")\n-- \"12'c'\\\"str\\\"\"\nfoldMap\n  :: (HVector v, ArityC c (Elems v), Monoid m)\n  => Proxy c -> (forall a. c a => a -> m) -> v -> m\n{-# INLINE foldMap #-}\nfoldMap c f = C.foldMapF c (\\(Identity a) -> f a) . C.cvec\n\n-- | Right fold over heterogeneous vector\nfoldrF :: (HVectorF v, ArityC c (ElemsF v))\n       => Proxy c -> (forall a. c a => f a -> b -> b) -> b -> v f -> b\n{-# INLINE foldrF #-}\nfoldrF c f b0 = C.foldrF c f b0 . C.cvecF\n\n-- | Left fold over heterogeneous vector\nfoldlF :: (HVectorF v, ArityC c (ElemsF v))\n       => Proxy c -> (forall a. c a => b -> f a -> b) -> b -> v f -> b\n{-# INLINE foldlF #-}\nfoldlF c f b0 = C.foldlF c f b0 . C.cvecF\n\n-- | Monoidal fold over heterogeneous vector\n--\n-- >>> foldMapF (Proxy @Show) show (mk2F (Just 1) Nothing :: HVecF '[Int,Char] Maybe)\n-- \"Just 1Nothing\"\nfoldMapF :: (HVectorF v, ArityC c (ElemsF v), Monoid m)\n         => Proxy c -> (forall a. c a => f a -> m) -> v f -> m\n{-# INLINE foldMapF #-}\nfoldMapF c f = C.foldMapF c f . C.cvecF\n\n-- | Right fold over heterogeneous vector\nfoldrNatF :: (HVectorF v)\n          => (forall a. f a -> b -> b) -> b -> v f -> b\n{-# INLINE foldrNatF #-}\nfoldrNatF f b0 = C.foldrNatF f b0 . C.cvecF\n\n-- | Left fold over heterogeneous vector\nfoldlNatF :: (HVectorF v)\n          => (forall a. b -> f a -> b) -> b -> v f -> b\n{-# INLINE foldlNatF #-}\nfoldlNatF f b0 = C.foldlNatF f b0 . C.cvecF\n\n-- | Monoidal fold over heterogeneous vector\n--\n-- >>> foldMapNatF (Sum . getConst) (mk2F (Const 1) (Const 2) :: HVecF '[Char,String] (Const Int))\n-- Sum {getSum = 3}\nfoldMapNatF :: (HVectorF v, Monoid m)\n            => (forall a. f a -> m) -> v f -> m\n{-# INLINE foldMapNatF #-}\nfoldMapNatF f = C.foldMapNatF f . C.cvecF\n\n-- | Apply monadic action to every element in the vector\nmapM_ :: (HVector v, ArityC c (Elems v), Applicative f)\n      => Proxy c -> (forall a. c a => a -> f ()) -> v -> f ()\n{-# INLINE mapM_ #-}\nmapM_ c f = foldl c (\\m a -> m *> f a) (pure ())\n\n-- | Unfold vector.\nunfoldr :: (HVector v, ArityC c (Elems v))\n        => Proxy c -> (forall a. c a => b -> (a,b)) -> b -> v\n{-# INLINE unfoldr #-}\nunfoldr c f = C.vector . C.unfoldrF c (\\b -> let (a,b') = f b in (Identity a, b'))\n\n-- | Unfold vector.\nunfoldrF :: (HVectorF v, ArityC c (ElemsF v))\n        => Proxy c -> (forall a. c a => b -> (f a,b)) -> b -> v f\n{-# INLINE unfoldrF #-}\nunfoldrF c f = C.vectorF . C.unfoldrF c f\n\n\n\n----------------------------------------------------------------\n-- Constructors\n----------------------------------------------------------------\n\n-- $construction\n--\n-- Functions below allow to construct products up to 5 elements. Here\n-- are example for product types from base:\n--\n-- >>> mk0 :: ()\n-- ()\n--\n-- >>> mk3 12 'x' \"xyz\" :: (Int,Char,String)\n-- (12,'x',\"xyz\")\n--\n-- >>> mk2 0 1 :: Complex Double\n-- 0.0 :+ 1.0\n\nmk0 :: forall v. (HVector v, Elems v ~ '[]) => v\nmk0 = coerce (construct :: Fun '[] v)\n{-# INLINE mk0 #-}\n\nmk1 :: forall v a. (HVector v, Elems v ~ '[a])\n    => a -> v\nmk1 = coerce (construct :: Fun '[a] v)\n{-# INLINE mk1 #-}\n\nmk2 :: forall v a b. (HVector v, Elems v ~ '[a,b])\n    => a -> b -> v\nmk2 = coerce (construct :: Fun '[a,b] v)\n{-# INLINE mk2 #-}\n\nmk3 :: forall v a b c. (HVector v, Elems v ~ '[a,b,c])\n    => a -> b -> c -> v\nmk3 = coerce (construct :: Fun '[a,b,c] v)\n{-# INLINE mk3 #-}\n\nmk4 :: forall v a b c d. (HVector v, Elems v ~ '[a,b,c,d])\n    => a -> b -> c -> d -> v\nmk4 = coerce (construct :: Fun '[a,b,c,d] v)\n{-# INLINE mk4 #-}\n\nmk5 :: forall v a b c d e. (HVector v, Elems v ~ '[a,b,c,d,e])\n    => a -> b -> c -> d -> e -> v\nmk5 = coerce (construct :: Fun '[a,b,c,d,e] v)\n{-# INLINE mk5 #-}\n\n\n-- $construction_F\n--\n-- Construction function for parametrized products are fully\n-- analogous to plain products:\n--\n-- >>>mk2F (Identity 'c') (Identity 1) :: HVecF '[Char, Int] Identity\n-- [Identity 'c',Identity 1]\n--\n-- >>>mk2F (Nothing) (Just 1) :: HVecF '[Char, Int] Maybe\n-- [Nothing,Just 1]\n\nmk0F :: forall f v. (HVectorF v, ElemsF v ~ '[]) => v f\nmk0F = coerce (constructF :: TFun f '[] (v f))\n{-# INLINE mk0F #-}\n\nmk1F :: forall f v a. (HVectorF v, ElemsF v ~ '[a])\n     => f a -> v f\nmk1F = coerce (constructF :: TFun f '[a] (v f))\n{-# INLINE mk1F #-}\n\nmk2F :: forall f v a b. (HVectorF v, ElemsF v ~ '[a,b])\n     => f a -> f b -> v f\nmk2F = coerce (constructF :: TFun f '[a,b] (v f))\n{-# INLINE mk2F #-}\n\nmk3F :: forall f v a b c. (HVectorF v, ElemsF v ~ '[a,b,c])\n     => f a -> f b -> f c -> v f\nmk3F = coerce (constructF :: TFun f '[a,b,c] (v f))\n{-# INLINE mk3F #-}\n\nmk4F :: forall f v a b c d. (HVectorF v, ElemsF v ~ '[a,b,c,d])\n     => f a -> f b -> f c -> f d -> v f\nmk4F = coerce (constructF :: TFun f '[a,b,c,d] (v f))\n{-# INLINE mk4F #-}\n\nmk5F :: forall f v a b c d e. (HVectorF v, ElemsF v ~ '[a,b,c,d,e])\n     => f a -> f b -> f c -> f d -> f e -> v f\nmk5F = coerce (constructF :: TFun f '[a,b,c,d,e] (v f))\n{-# INLINE mk5F #-}\n\n\n\n----------------------------------------------------------------\n-- Collective operations\n----------------------------------------------------------------\n\n-- | Apply function to every value of parametrized product.\n--\n-- >>> map (Proxy @Num) (Identity . fromMaybe 0) (mk2F (Just 12) Nothing :: HVecF '[Double, Int] Maybe)\n-- [Identity 12.0,Identity 0]\nmap :: (HVectorF v, ArityC c (ElemsF v))\n    => Proxy c -> (forall a. c a => f a -> g a) -> v f -> v g\n{-# INLINE map #-}\nmap cls f = C.vectorF . C.map cls f . C.cvecF\n\n-- | Apply natural transformation to every element of the tuple.\n--\n-- >>> mapNat (Just . runIdentity) (mk2F (pure 'c') (pure 1) :: HVecF '[Char, Int] Identity)\n-- [Just 'c',Just 1]\nmapNat :: (HVectorF v)\n       => (forall a. f a -> g a) -> v f -> v g\n{-# INLINE mapNat #-}\nmapNat f = C.vectorF . C.mapNat f . C.cvecF\n\n-- | Sequence effects for every element in the vector\n--\n-- >>> sequence (mk2F [1,2] \"ab\" :: HVecF '[Int,Char] []) :: [(Int,Char)]\n-- [(1,'a'),(1,'b'),(2,'a'),(2,'b')]\nsequence\n  :: ( Applicative f, HVectorF v, HVector w, ElemsF v ~ Elems w )\n  => v f -> f w\n{-# INLINE sequence #-}\nsequence\n  = fmap C.vector\n  . C.sequenceF\n  . C.mapNat (Compose . fmap Identity)\n  . C.cvecF\n\n-- | Sequence effects for every element in the vector\nsequence_ :: (Applicative f, HVectorF v) => v f -> f ()\n{-# INLINE sequence_ #-}\nsequence_ = foldlNatF (\\m a -> m <* a) (pure ())\n\n-- | Sequence effects for every element in the vector\nsequenceF :: ( Applicative f, HVectorF v) => v (f `Compose` g) -> f (v g)\n{-# INLINE sequenceF #-}\nsequenceF v = C.vectorF <$> C.sequenceF (C.cvecF v)\n\n-- | Wrap every value in the vector into type constructor.\nwrap :: ( HVector v, HVectorF w, Elems v ~ ElemsF w )\n     => (forall a. a -> f a) -> v -> w f\n{-# INLINE wrap #-}\nwrap f = C.vectorF . C.mapNat (f . runIdentity) . C.cvec\n\n-- | Unwrap every value in the vector from the type constructor.\nunwrap :: ( HVectorF v, HVector w, ElemsF v ~ Elems w )\n       => (forall a. f a -> a) -> v f -> w\n{-# INLINE unwrap #-}\nunwrap  f = C.vector . C.mapNat (Identity . f) . C.cvecF\n\n-- | Analog of /distribute/ from /Distributive/ type class.\ndistribute\n  :: ( Functor f, HVector v, HVectorF w,  Elems v ~ ElemsF w )\n  => f v -> w f\n{-# INLINE distribute #-}\ndistribute\n  = C.vectorF\n  . mapNat (fmap runIdentity . getCompose)\n  . C.distributeF\n  . fmap C.cvec\n\n-- | Analog of /distribute/ from /Distributive/ type class.\ndistributeF\n  :: ( Functor f, HVectorF v)\n  => f (v g) -> v (f `Compose` g)\n{-# INLINE distributeF #-}\ndistributeF = C.vectorF . C.distributeF . fmap C.cvecF\n\n\n\n----------------------------------------------------------------\n-- Type class based ops\n----------------------------------------------------------------\n\n-- | Replicate polymorphic value n times. Concrete instance for every\n--   element is determined by their respective types.\n--\n-- >>> replicate (Proxy :: Proxy Monoid) mempty :: ((),String)\n-- ((),\"\")\n--\n-- Or a bit contrived example which illustrate what how to call\n-- function that require multiple type class constraints:\n--\n-- >>> replicate (Proxy @(Monoid :&&: Num)) (mempty * 10) :: (Product Int, Sum Int)\n-- (Product {getProduct = 10},Sum {getSum = 0})\nreplicate :: (HVector v, ArityC c (Elems v))\n          => Proxy c -> (forall x. c x => x) -> v\n{-# INLINE replicate #-}\nreplicate c x = C.vector $ C.replicateF c (Identity x)\n\n-- | Replicate monadic action n times. Example below is a bit awkward does convey what's\n--\n-- >>> :{\n--   Prelude.mapM_ print\n--     (replicateM (Proxy @(Monoid :&&: Num)) [mempty+1, mempty * 10] :: [(Product Int, Sum Int)])\n-- :}\n-- (Product {getProduct = 2},Sum {getSum = 1})\n-- (Product {getProduct = 2},Sum {getSum = 0})\n-- (Product {getProduct = 10},Sum {getSum = 1})\n-- (Product {getProduct = 10},Sum {getSum = 0})\nreplicateM :: (HVector v, Applicative f, ArityC c (Elems v))\n           => Proxy c -> (forall a. c a => f a) -> f v\n{-# INLINE replicateM #-}\nreplicateM c x\n  = fmap C.vector\n  $ C.sequenceF\n  $ C.replicateF c (Compose $ fmap Identity x)\n\n-- | Replicate value @f a@ which is valid for every type a n times.\n--\n-- >>> replicateNatF Nothing :: HVecF '[Char,Int] Maybe\n-- [Nothing,Nothing]\nreplicateNatF :: (HVectorF v, Arity (ElemsF v))\n           => (forall a. f a) -> v f\n{-# INLINE replicateNatF #-}\nreplicateNatF x = C.vectorF $ C.replicateNatF x\n\n-- | Replicate polymorphic value n times:\n--\n-- >>> replicateF (Proxy @Num) (Just 0) :: HVecF '[Double,Int] Maybe\n-- [Just 0.0,Just 0]\nreplicateF :: (HVectorF v, ArityC c (ElemsF v))\n            => Proxy c -> (forall a. c a => f a) -> v f\n{-# INLINE replicateF #-}\nreplicateF c x = C.vectorF $ C.replicateF c x\n\n\n\n----------------------------------------------------------------\n-- Zipping of vectors\n----------------------------------------------------------------\n\n-- | Zip two heterogeneous vectors\n--\n-- >>> zipWith (Proxy @Num) (+) (0, 1.2) (1, 10) :: (Int,Double)\n-- (1,11.2)\nzipWith :: (HVector v, ArityC c (Elems v))\n        => Proxy c -> (forall a. c a => a -> a -> a) -> v -> v -> v\n{-# INLINE zipWith #-}\nzipWith c f v u\n  = C.vector\n  $ C.zipWithF c (\\(Identity a) (Identity b) -> Identity (f a b)) (C.cvec v) (C.cvec u)\n\n-- | Zip two heterogeneous vectors\nzipWithF :: (HVectorF v, ArityC c (ElemsF v))\n         => Proxy c -> (forall a. c a => f a -> g a -> h a) -> v f -> v g -> v h\n{-# INLINE zipWithF #-}\nzipWithF c f v u\n  = C.vectorF $ C.zipWithF c f (C.cvecF v) (C.cvecF u)\n\n-- | Zip two heterogeneous vectors\nzipWithNatF :: (HVectorF v)\n        => (forall a. f a -> g a -> h a) -> v f -> v g -> v h\n{-# INLINE zipWithNatF #-}\nzipWithNatF f v u\n  = C.vectorF $ C.zipWithNatF f (C.cvecF v) (C.cvecF u)\n\n-- | Zip two heterogeneous vectors and immediately fold resulting\n--   value.\n--\n-- >>> zipFold (Proxy @Show) (\\a b -> show (a,b)) ((),'c',10) ((),'D',1)\n-- \"((),())('c','D')(10,1)\"\nzipFold :: (HVector v, ArityC c (Elems v), Monoid m)\n        => Proxy c -> (forall a. c a => a -> a -> m) -> v -> v -> m\n{-# INLINE zipFold #-}\nzipFold c f v u\n  = C.zipFoldF c (\\(Identity a) (Identity b) -> f a b) (C.cvec v) (C.cvec u)\n\nzipFoldF :: (HVectorF v, ArityC c (ElemsF v), Monoid m)\n        => Proxy c -> (forall a. c a => f a -> f a -> m) -> v f -> v f -> m\n{-# INLINE zipFoldF #-}\nzipFoldF c f v u\n  = C.zipFoldF c f (C.cvecF v) (C.cvecF u)\n\n-- | Convert heterogeneous vector to homogeneous\nmonomorphize :: ( HVector v\n                , Peano n ~ Len (Elems v)\n                , ArityC c (Elems v))\n             => Proxy c -> (forall a. c a => a -> x)\n             -> v -> F.ContVec n x\n{-# INLINE monomorphize #-}\nmonomorphize c f = C.monomorphizeF c (f . runIdentity) . C.cvec\n\n-- | Convert heterogeneous vector to homogeneous\nmonomorphizeF :: ( HVectorF v\n                 , Peano n ~ Len (ElemsF v)\n                 , ArityC c (ElemsF v)\n                 )\n             => Proxy c -> (forall a. c a => f a -> x)\n             -> v f -> F.ContVec n x\n{-# INLINE monomorphizeF #-}\nmonomorphizeF c f = C.monomorphizeF c f . C.cvecF\n\n\n-- | Generic equality for heterogeneous vectors\n--\n-- >>> data A = A Int Char deriving Generic\n-- >>> instance HVector A\n-- >>> eq (A 1 'c') (A 2 'c')\n-- False\neq :: (HVector v, ArityC Eq (Elems v)) => v -> v -> Bool\neq v u = getAll $ zipFold (Proxy :: Proxy Eq) (\\x y -> All (x == y)) v u\n{-# INLINE eq #-}\n\n-- | Generic comparison for heterogeneous vectors. It works same way\n--   as Ord instance for tuples.\n--\n-- >>> data A = A Int Char deriving Generic\n-- >>> instance HVector A\n-- >>> compare (A 1 'c') (A 2 'c')\n-- LT\ncompare :: (HVector v, ArityC Ord (Elems v)) => v -> v -> Ordering\ncompare = zipFold (Proxy :: Proxy Ord) Prelude.compare\n{-# INLINE compare #-}\n\n-- | Reduce vector to normal form\nrnf :: (HVector v, ArityC NF.NFData (Elems v)) => v -> ()\nrnf = foldl (Proxy :: Proxy NF.NFData) (\\r a -> NF.rnf a `seq` r) ()\n{-# INLINE rnf #-}\n\n\n----------------------------------------------------------------\n-- Doctest\n----------------------------------------------------------------\n\n-- $setup\n--\n-- >>> :set -XDeriveGeneric\n-- >>> :set -XTypeApplications\n-- >>> :set -XTypeOperators\n-- >>> :set -XDataKinds\n-- >>> import Prelude (Int,Double,String,Char,IO,(++),Maybe(..))\n-- >>> import Prelude (Show(..),Read(..),read,Num(..),Monoid(..))\n-- >>> import Prelude (print)\n-- >>> import Control.Applicative     (Const(..))\n-- >>> import Data.Complex            (Complex(..))\n-- >>> import Data.Monoid             (Sum(..),Product(..))\n-- >>> import Data.Maybe              (fromMaybe)\n-- >>> import Data.Vector.HFixed.HVec (HVec,HVecF)\n-- >>> import GHC.Generics            (Generic)\n", "meta": {"hexsha": "f986bcee0079779a82090510a03e28f9e01bff66", "size": 21967, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Vector/HFixed.hs", "max_stars_repo_name": "Shimuuar/fixed-vector-hetero", "max_stars_repo_head_hexsha": "37ba6fccb900dc8bb9a87dac2d965c22ab598729", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-02-06T19:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T13:42:50.000Z", "max_issues_repo_path": "Data/Vector/HFixed.hs", "max_issues_repo_name": "Shimuuar/fixed-vector-hetero", "max_issues_repo_head_hexsha": "37ba6fccb900dc8bb9a87dac2d965c22ab598729", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-01-03T08:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-07T12:50:57.000Z", "max_forks_repo_path": "Data/Vector/HFixed.hs", "max_forks_repo_name": "Shimuuar/fixed-vector-hetero", "max_forks_repo_head_hexsha": "37ba6fccb900dc8bb9a87dac2d965c22ab598729", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2015-01-02T19:37:06.000Z", "max_forks_repo_forks_event_max_datetime": "2015-01-02T19:37:06.000Z", "avg_line_length": 30.2159559835, "max_line_length": 103, "alphanum_fraction": 0.538352984, "num_tokens": 6902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24570009184480024}}
{"text": "{-# LANGUAGE GADTs                      #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ScopedTypeVariables        #-}\n{-# LANGUAGE RankNTypes                #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE ConstraintKinds #-}\nmodule CodeGen.Type where\n\nimport           Data.Bits\nimport           Data.Typeable\nimport           Data.List\nimport           Foreign.Storable               ( Storable )\nimport           Data.Complex\n\ntype Serialise a = (Repr a, Show a, Read a)\ntype CVal a = Serialise a\n\ntype Complex a = (a, a)\n\n-- need to find a way to represent recursive single type \ndata SingleType a where\n    NumSingleType :: NumType a -> SingleType a\n    LabelSingleType :: SingleType Label\n    SumSingleType :: SingleType a -> SingleType b -> SingleType (Either a b)\n    UnitSingleType :: SingleType ()\n    ProductSingleType :: SingleType a -> SingleType b -> SingleType (a, b)\n    ListSingleType :: SingleType a -> SingleType [a]\n    FuncSingleType :: SingleType a -> SingleType b -> SingleType (a -> b)\n\ndata ASingleType where\n    ASingleType :: forall a. SingleType a -> ASingleType\n\nequal :: SingleType a -> SingleType b -> Bool\nequal (NumSingleType (IntegralNumType _)) (NumSingleType (IntegralNumType _)) =\n    True\nequal (NumSingleType (FloatingNumType _)) (NumSingleType (FloatingNumType _)) =\n    True\nequal LabelSingleType     LabelSingleType       = True\nequal (SumSingleType a b) (SumSingleType a' b') = equal a a' && equal b b'\nequal (ProductSingleType a b) (ProductSingleType a' b') =\n    equal a a' && equal b b'\nequal UnitSingleType       UnitSingleType         = True\nequal (ListSingleType a  ) (ListSingleType b    ) = a `equal` b\nequal (FuncSingleType a b) (FuncSingleType a' b') = equal a a' && equal b b'\nequal _                    _                      = False\n\nsTypeHeight :: SingleType a -> Int\nsTypeHeight (NumSingleType _)       = 0\nsTypeHeight LabelSingleType         = 0\nsTypeHeight (SumSingleType     a b) = 1 + max (sTypeHeight a) (sTypeHeight b)\nsTypeHeight (ProductSingleType a b) = 1 + max (sTypeHeight a) (sTypeHeight b)\nsTypeHeight (UnitSingleType       ) = 0\nsTypeHeight (ListSingleType a     ) = 1 + sTypeHeight a\nsTypeHeight (FuncSingleType _ _   ) = error \"Func not height\"\n\ncompareSingleType :: SingleType a -> SingleType b -> Ordering\ncompareSingleType a b\n    | a `equal` b = EQ\n    | otherwise = case (sTypeHeight a) `compare` (sTypeHeight b) of\n        EQ -> LT\n        x  -> x\n\ninstance Show (SingleType a) where\n    show (NumSingleType (IntegralNumType _)) = \"int\"\n    show (NumSingleType (FloatingNumType _)) = \"float\"\n    show UnitSingleType                      = \"unit\"\n    show LabelSingleType                     = \"Label\"\n    show (SumSingleType a b) = intercalate \"_\" [\"Sum\", show a, show b]\n    show (ProductSingleType a b) = intercalate \"_\" [\"Prod\", show a, show b]\n    show (ListSingleType a     )             = intercalate \"_\" [\"List\", show a]\n\ninstance Show ASingleType where\n    show (ASingleType s) = show s\n\ntoASingleType :: SingleType a -> ASingleType\ntoASingleType stype = ASingleType stype\n\ninstance Eq (SingleType a) where\n    (==) = equal\n\ninstance Ord (SingleType a) where\n    compare a b = compareSingleType a b\n\ninstance Eq (ASingleType) where\n    (ASingleType left) == (ASingleType right) = equal left right\n\ninstance Ord ASingleType where\n    compare (ASingleType left) (ASingleType right) =\n        compareSingleType left right\n\ndata NumType a where\n    IntegralNumType :: IntegralType a -> NumType a\n    FloatingNumType :: FloatingType a -> NumType a\n\ndata IntegralType a where\n    TypeInt     :: IntegralDict Int     -> IntegralType Int\n\ndata FloatingType a where\n    TypeFloat   :: FloatingDict Float   -> FloatingType Float\n\n\ndata IntegralDict a where\n    IntegralDict :: ( Typeable a, Bounded a, Eq a, Ord a, Show a\n                    , Bits a, FiniteBits a, Integral a, Num a, Real a, Storable a )\n                    => IntegralDict a\n\ndata FloatingDict a where\n    FloatingDict :: ( Typeable a, Eq a, Ord a, Show a\n                    , Floating a, Fractional a, Num a, Real a, RealFrac a\n                    , RealFloat a, Storable a )\n                    => FloatingDict a\n\ndata Label = Le | Ri\n    deriving (Eq, Show, Typeable)\n\ntypeInt :: IntegralType Int\ntypeInt = TypeInt (IntegralDict @Int)\n\ntypeFloat :: FloatingType Float\ntypeFloat = TypeFloat (FloatingDict @Float)\n\nnumTypeInt :: NumType Int\nnumTypeInt = IntegralNumType typeInt\n\nnumTypeFloat :: NumType Float\nnumTypeFloat = FloatingNumType typeFloat\n\nsingleTypeInt :: SingleType Int\nsingleTypeInt = NumSingleType numTypeInt\n\nsingleTypeLabel :: SingleType Label\nsingleTypeLabel = LabelSingleType\n\nsingleTypeUnionInt :: SingleType (Either Int Int)\nsingleTypeUnionInt = SumSingleType singleTypeInt singleTypeInt\n\nclass Typeable a => Repr a where\n    singleType :: SingleType a\n\ninstance Repr () where\n    singleType = UnitSingleType\n\ninstance Repr Int where\n    singleType = singleTypeInt\n\ninstance Repr Label where\n    singleType = LabelSingleType\n\ninstance Repr Float where\n    singleType = NumSingleType numTypeFloat\n\ninstance (Repr a, Repr b) => Repr (Either a b) where\n    singleType = SumSingleType singleType singleType\n\ninstance (Repr a, Repr b) => Repr (a, b) where\n    singleType = ProductSingleType singleType singleType\n\ninstance Repr a => Repr [a] where\n    singleType = ListSingleType singleType\n\ninstance (Repr a, Repr b) => Repr (a -> b) where\n    singleType = FuncSingleType singleType singleType\n", "meta": {"hexsha": "f277f0f36445b1b37a7da9fa05205583f5ff0703", "size": 5541, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CodeGen/Type.hs", "max_stars_repo_name": "Richard-zhang/SPar", "max_stars_repo_head_hexsha": "ba5af0a3fa97ecdb974777ed05f529e7a74e7b00", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-09-09T12:37:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T00:17:34.000Z", "max_issues_repo_path": "src/CodeGen/Type.hs", "max_issues_repo_name": "Richard-zhang/SPar", "max_issues_repo_head_hexsha": "ba5af0a3fa97ecdb974777ed05f529e7a74e7b00", "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/CodeGen/Type.hs", "max_forks_repo_name": "Richard-zhang/SPar", "max_forks_repo_head_hexsha": "ba5af0a3fa97ecdb974777ed05f529e7a74e7b00", "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": 33.5818181818, "max_line_length": 83, "alphanum_fraction": 0.6742465259, "num_tokens": 1466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2453118435562797}}
{"text": "import Graphics.UI.SDL.General (withInit, InitFlag(InitVideo, InitEventthread))\nimport Graphics.UI.SDL.Types (Surface, surfaceGetPixels, surfaceGetPixelFormat, SurfaceFlag(SWSurface))\nimport Graphics.UI.SDL.Video (setVideoMode, mapRGB)\nimport qualified Graphics.UI.SDL.Video as V (flip)\nimport Graphics.UI.SDL.WindowManagement (setCaption)\nimport Graphics.UI.SDL.Events (Event(Quit, KeyDown), waitEvent)\nimport Graphics.UI.SDL.Keysym (Keysym(Keysym), SDLKey(SDLK_SPACE))\nimport Foreign.Ptr (castPtr)\nimport Data.Array (elems)\nimport Foreign.Marshal.Array (pokeArray)\nimport Control.Monad (liftM)\n\nimport Control.Applicative ((<*>))\n\nimport Data.Maybe (fromJust, isJust)\nimport Data.List (intersperse)\n\nimport Numeric.LinearAlgebra.Data ((|>))\n\nimport Raytracer.Geometry (cube)\nimport Raytracer.Camera (Camera(Camera), calculate_rays, fire_rays)\n\nwres = 400\nhres = 300\ncolor_depth = 32\n\ntest_camera = Camera 4 3 wres hres (Just 1)\ntest_positions = map (3 |>) [[1, 1, -1], [2, 1, -1], [2, 2, -1], [2, 2, -2]]\ntest_directions = map (3 |>) [[0,0,1], [-1, 0, 1], [0,1,1], [0,-1,1]]\n\ntest_cube = cube (3 |> [2, 0, 0]) (3 |> [0, 2, 0]) (3 |> [0, 0, 2]) (3 |> [0, 0, 0])\n\ntranspose (a, b) (c, d) v = (((v-c) * (b-a)) / (d-c)) + a\n\ncompute_pixels surface array = mapM (pixel (minimum just_list, maximum just_list)) list\n\twhere\n\tlist = elems array\n\tjust_list = map fromJust $ filter isJust list\n\tpixel_format = surfaceGetPixelFormat surface\n\tpixel range (Just n) = greyscale $ round $ transpose (200, 100) range n\n\tpixel _ Nothing = greyscale 0\n\tgreyscale a = mapRGB pixel_format a a a\n\narray_to_surface surface array = array_ptr >>= ((flip pokeArray) array)\n\twhere\n\tarray_ptr = liftM castPtr $ surfaceGetPixels surface\n\nwait_to_quit _ = waitEvent >>= handle\n\twhere\n\thandle Quit = return ()\n\thandle _ = wait_to_quit ()\n\nwait_to_space _ = waitEvent >>= handle\n\twhere\n\thandle (KeyDown (Keysym SDLK_SPACE _ _)) = return ()\n\thandle _ = wait_to_space ()\n\nrender _ = do\n\tscreen <- setVideoMode wres hres color_depth [SWSurface]\n\tpixels <- mapM (compute_pixels screen) $ fmap ((flip fire_rays) test_cube) $ fmap calculate_rays $ fmap test_camera test_positions <*> test_directions\n\tputStrLn \"Images Rendered\"\n\tsequence $ intersperse (V.flip screen >>= wait_to_space) $ map (array_to_surface screen) pixels\n\tV.flip screen\n\nmain = withInit [InitVideo, InitEventthread] $ setCaption \"SDL Test\" \"\" >>= render >> putStrLn \"Ready To Quit\" >>= wait_to_quit\n\n", "meta": {"hexsha": "02e38480b89646c91cd7e83834063f7db3abddd3", "size": 2434, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "sdl_test.hs", "max_stars_repo_name": "psycotica0/ray-tracer", "max_stars_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "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": "sdl_test.hs", "max_issues_repo_name": "psycotica0/ray-tracer", "max_issues_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "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": "sdl_test.hs", "max_forks_repo_name": "psycotica0/ray-tracer", "max_forks_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "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": 36.328358209, "max_line_length": 151, "alphanum_fraction": 0.7181594084, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.24531184355627966}}
{"text": "{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TemplateHaskell #-}\nmodule Myelin.Neuron where\n\nimport Control.Lens hiding ((.=), (*~))\nimport Data.Aeson\nimport Numeric.LinearAlgebra\n\n{--| NeuronType corresponds to the different point neuron\ntypes that are constructible in SNN. Many of them\nare back end specific.\n\nThings that can be improved:\n\n- Currently none of the parameters have any units,\n  instead their units are indicated by their names\n\n  - tau_* are time constants\n  - v_* are voltages\n  - i_* are currents\n  - cm is a capacitance\n\n- There is no restriction to \"biological\" ranges of\n  parameters in place and no check of consistency\n\n- In the case of the Heidelberg Hardware system additionally\n  every neuron on the chip has analog parameter variation,\n  and finite (much coarser than floating point) precision\n  in parameter adjustment.\n\nTODO:\n\nHH_cond_exp\nGIF_cond_exp\n\nSpikeSourceGamma\nSpikeSourceArray\nSpikeSourcePoisson\nSpikeSourcePoissonRefractory\n--}\ndata NeuronType =\n    IFCurrentAlpha {\n        _tau_m :: Float, -- ^ membrane time constant\n        _tau_refrac :: Float, -- ^ refractory time\n        _v_thresh :: Float, -- ^ threshhold potential\n        _tau_syn_E :: Float, -- ^ excitatory synaptic time constant\n        _v_rest :: Float, -- ^ resting potential\n        _cm :: Float, -- ^ membrane capactitance\n        _v_reset :: Float, -- ^ reset potential\n        _tau_syn_I :: Float, -- ^ inhibitory synaptic time constant\n        _i_offset :: Float -- ^ offset current\n    }\n    | IFCondAlpha {\n        _v_rest :: Float, -- ^ resting membrane potential\n        _cm :: Float, -- ^ capacity of the membrane\n        _tau_m :: Float, -- ^ membrane time constant\n        _tau_refrac :: Float, -- ^ duration of refractory period\n        _tau_syn_E :: Float, -- ^ rise time of the excitatory synaptic alpha function\n        _tau_syn_I :: Float, -- ^ rise time of the inhibitory synaptic alpha function\n        _e_rev_E :: Float, -- ^ reversal potential for excitatory input\n        _e_rev_I :: Float, -- ^ reversal potential for inhibitory input\n        _v_thresh :: Float, -- ^ spike threshold\n        _v_reset :: Float, -- ^ reset potential after a spike\n        _i_offset :: Float -- ^ offset current\n    }\n    | IFSpikey {\n        _e_rev_I :: Float, -- ^ excitatory reversal current\n        _g_leak :: Float, -- ^ leak conductance\n        _tau_refrac :: Float, -- ^ refractory time\n        _v_reset :: Float, -- ^ reset potential\n        _v_rest :: Float, -- ^ resting potential\n        _v_thresh :: Float -- ^ threshhold potential\n    }\n    | IFCurrExp {\n        _cm :: Float, -- ^ membrane capacitance\n        _tau_m :: Float, -- ^ membrane time constant\n        _tau_syn_E :: Float, -- ^ excitatory synaptic time constant\n        _tau_syn_I :: Float, -- ^ inhibitory synaptic time constant\n        _tau_refrac :: Float, -- ^ refractory time\n        _v_thresh :: Float, -- ^ threshhold voltage\n        _v_rest :: Float, -- ^ resting potential\n        _v_reset :: Float, -- ^ reset potential\n        _i_offset :: Float -- ^ offset current\n    }\n    | IFCondExp {\n        _v_rest :: Float, -- ^ resting potential\n        _cm :: Float, -- ^ membrane capacitance\n        _tau_m :: Float, -- ^ membrane time constant\n        _tau_refrac :: Float, -- ^ refractory time\n        _tau_syn_E :: Float, -- ^ excitatory synaptic time constant\n        _tau_syn_I :: Float, -- ^ inhibitory synaptic time constant\n        _e_rev_E :: Float, -- ^ excitatory reversal potential\n        _e_rev_I :: Float, -- ^ inhibitory reversal potential\n        _v_thresh :: Float, -- ^ spike initiation threshold\n        _v_reset :: Float, -- ^ reset value for membrane potential after a spike\n        _i_offset :: Float -- ^ offset current\n    }\n    | Izhikevich {\n        _a :: Float,\n        _i_offset :: Float,\n        _c :: Float,\n        _d :: Float,\n        _b :: Float\n    }\n    | EIFCondExp {\n        _v_reset :: Float,\n        _i_offset :: Float,\n        _tau_w :: Float,\n        _tau_syn_I :: Float,\n        _e_rev_E :: Float,\n        _v_rest :: Float,\n        _cm :: Float,\n        _tau_syn_E :: Float,\n        _tau_m :: Float,\n        _a :: Float,\n        _delta_T :: Float,\n        _v_thresh :: Float,\n        _b :: Float,\n        _v_spike :: Float,\n        _e_rev_I :: Float,\n        _tau_refrac :: Float\n    }\n    | EIFCondAlpha {\n        _cm :: Float, -- ^ capacity of the membrane\n        _tau_refrac :: Float, -- ^ duration of the refractory period\n        _v_spike :: Float, -- ^ spike detection threshold\n        _v_reset :: Float, -- ^ reset value for membrane potential after a spike\n        _v_rest :: Float, -- ^ resting membrane potential (Leak reversal potential)\n        _tau_m :: Float, -- ^ membrane time constant\n        _i_offset :: Float, -- ^ offset current\n        _a :: Float, -- ^ subthreshold adaptation conductance\n        _b :: Float, -- ^ spike-triggered adaptation\n        _delta_T :: Float, -- ^ slope factor\n        _tau_w :: Float, -- ^ adaptation time constant\n        _v_thresh :: Float, -- ^ spike initiation threshold\n        _e_rev_E :: Float, -- ^ excitatory reversal potential\n        _tau_syn_E :: Float, -- ^ rise time of excitatory synaptic conductance (alpha function)\n        _e_rev_I :: Float, -- ^ inhibitory reversal potential\n        _tau_syn_I :: Float -- ^ rise time of the inhibitory synaptic conductance (alpha function)\n    }\n    | HHCondExp {\n        _cm :: Float, -- ^ capacity of the membrane\n        _e_rev_E :: Float, -- ^ excitatory reversal potential\n        _e_rev_I :: Float, -- ^ inhibitory reversal potential\n        _e_rev_K :: Float,\n        _e_rev_Na :: Float,\n        _e_rev_leak :: Float,\n        _g_leak :: Float,\n        _gbar_K :: Float,\n        _gbar_Na :: Float,\n        _i_offset :: Float,\n        _tau_syn_E :: Float,\n        _tau_syn_I :: Float,\n        _v_offset :: Float\n    } deriving (Eq, Show)\n\nmakeLenses ''NeuronType\nmakePrisms ''NeuronType\n\n-- ^  Defaults taken from http://neuralensemble.org/docs/PyNN/standardmodels.html\nif_cond_exp :: NeuronType\nif_cond_exp = IFCondExp {\n    _v_rest = -65.0,\n    _cm = 1.0,\n    _tau_m = 20.0,\n    _tau_refrac = 0.0,\n    _tau_syn_E = 5.0,\n    _tau_syn_I = 5.0,\n    _e_rev_E = 0.0,\n    _e_rev_I = -70.0,\n    _v_thresh = -50.0,\n    _v_reset = -65.0,\n    _i_offset = 0.0\n}\n\nif_current_alpha :: NeuronType\nif_current_alpha = IFCurrentAlpha {\n    _tau_m = 20.0,\n    _tau_refrac = 0.1,\n    _v_thresh = -50.0,\n    _tau_syn_E =  0.5,\n    _tau_syn_I = 0.5,\n    _v_rest = -65.0,\n    _cm = 1.0,\n    _v_reset = -65.0,\n    _i_offset = 0.0\n}\n\nif_cond_alpha :: NeuronType\nif_cond_alpha = IFCondAlpha {\n    _v_rest = -65.0,\n    _cm = 1.0,\n    _tau_m = 20.0,\n    _tau_refrac = 0.0,\n    _tau_syn_E = 5.0,\n    _tau_syn_I = 5.0,\n    _e_rev_E = 0.0,\n    _e_rev_I = -70.0,\n    _v_thresh = -50.0,\n    _v_reset = -65.0,\n    _i_offset = 0.0\n}\n\nif_spikey :: NeuronType\nif_spikey = IFSpikey {\n    _e_rev_I = -80.0,\n    _g_leak = 20.0,\n    _tau_refrac = 1.0,\n    _v_reset = -80.0,\n    _v_rest = -75.0,\n    _v_thresh = -55.0\n}\n\nif_current_exponential :: NeuronType\nif_current_exponential = IFCurrExp {\n    _cm = 1.0,\n    _tau_m = 20.0,\n    _tau_syn_E = 5.0,\n    _tau_syn_I = 5.0,\n    _tau_refrac = 0.1,\n    _v_thresh = -50.0,\n    _v_rest = -65.0,\n    _v_reset = -65.0,\n    _i_offset = 0.0\n}\n\nizhikevich :: NeuronType\nizhikevich = Izhikevich {\n    _a = 0.02,\n    _i_offset = 0.0,\n    _c = -65.0,\n    _d = 2.0,\n    _b = 0.2\n}\n\neif_cond_exp :: NeuronType\neif_cond_exp = EIFCondExp {\n    _v_reset = -70.6,\n    _i_offset = 0.0,\n    _tau_w = 144.0,\n    _tau_syn_I = 5.0,\n    _e_rev_E = 0.0,\n    _v_rest = -70.6,\n    _cm = 0.281,\n    _tau_syn_E = 5.0,\n    _tau_m = 9.3667,\n    _a = 4.0,\n    _delta_T = 2.0,\n    _v_thresh = -50.4,\n    _b = 0.0805,\n    _v_spike = -40.0,\n    _e_rev_I = -80.0,\n    _tau_refrac = 0.1\n}\n\neif_cond_alpha :: NeuronType\neif_cond_alpha = EIFCondAlpha {\n    _v_reset = -70.6,\n    _i_offset = 0.0,\n    _tau_w = 144.0,\n    _tau_syn_I = 5.0,\n    _e_rev_E = 0.0,\n    _v_rest = -70.6,\n    _cm = 0.281,\n    _tau_syn_E = 5.0,\n    _tau_m = 9.3667,\n    _a = 4.0,\n    _delta_T = 2.0,\n    _v_thresh = -50.4,\n    _b = 0.0805,\n    _v_spike = -40.0,\n    _e_rev_I = -80.0,\n    _tau_refrac = 0.1\n}\n\ninstance ToJSON NeuronType where\n    toJSON IFCondExp {..} = object [\n            \"type\" .= (\"IFCondExp\" :: String),\n            \"tau_m\" .= _tau_m,\n            \"tau_refrac\" .= _tau_refrac,\n            \"v_thresh\" .= _v_thresh,\n            \"tau_syn_E\" .= _tau_syn_E,\n            \"v_rest\" .= _v_rest,\n            \"cm\" .= _cm,\n            \"v_reset\" .= _v_reset,\n            \"tau_syn_I\" .= _tau_syn_I,\n            \"i_offset\" .= _i_offset,\n            \"e_rev_E\" .= _e_rev_E,\n            \"e_rev_I\" .= _e_rev_I\n        ]\n    toJSON IFCurrentAlpha {..} = object [\n            \"type\" .= (\"IFCurrentAlpha\" :: String),\n            \"tau_m\" .= _tau_m,\n            \"tau_refrac\" .= _tau_refrac,\n            \"v_thresh\" .= _v_thresh,\n            \"tau_syn_E\" .= _tau_syn_E,\n            \"v_rest\" .= _v_rest,\n            \"cm\" .= _cm,\n            \"v_reset\" .= _v_reset,\n            \"tau_syn_I\" .= _tau_syn_I,\n            \"i_offset\" .= _i_offset\n        ]\n    toJSON IFCondAlpha {..} = object [\n            \"type\" .= (\"IFCondAlpha\" :: String),\n            \"v_rest\" .= _v_rest,\n            \"cm\" .= _cm,\n            \"tau_m\" .= _tau_m,\n            \"tau_refrac\" .= _tau_refrac,\n            \"tau_syn_E\" .= _tau_syn_E,\n            \"tau_syn_I\" .= _tau_syn_I,\n            \"e_rev_E\" .= _e_rev_E,\n            \"e_rev_I\" .= _e_rev_I,\n            \"v_thresh\" .= _v_thresh,\n            \"v_reset\" .= _v_reset,\n            \"i_offset\" .= _i_offset\n        ]\n    toJSON IFSpikey {..} = object [\n            \"type\" .= (\"IFSpikey\" :: String),\n            \"e_rev_I\" .= _e_rev_I,\n            \"g_leak\" .= _g_leak,\n            \"tau_refrac\" .= _tau_refrac,\n            \"v_reset\" .= _v_reset,\n            \"v_rest\" .= _v_rest,\n            \"v_thresh\" .= _v_thresh\n        ]\n    toJSON IFCurrExp {..} = object [\n            \"type\" .= (\"IFCurrentExp\" :: String),\n            \"cm\" .= _cm,\n            \"tau_m\" .= _tau_m,\n            \"tau_syn_E\" .= _tau_syn_E,\n            \"tau_syn_I\" .= _tau_syn_I,\n            \"tau_refrac\" .= _tau_refrac,\n            \"v_thresh\" .= _v_thresh,\n            \"v_rest\" .= _v_rest,\n            \"v_reset\" .= _v_reset,\n            \"i_offset\" .= _i_offset\n        ]\n    toJSON Izhikevich {..} = object [\n            \"type\" .= (\"Izhikevich\" :: String),\n            \"a\" .= _a,\n            \"i_offset\" .= _i_offset,\n            \"c\" .= _c,\n            \"d\" .= _d,\n            \"b\" .= _b\n        ]\n    toJSON EIFCondExp {..} = object [\n            \"type\" .= (\"EIFCondExp\" :: String),\n            \"v_reset\" .= _v_reset,\n            \"i_offset\" .= _i_offset,\n            \"tau_w\" .= _tau_w,\n            \"tau_syn_I\" .= _tau_syn_I,\n            \"e_rev_E\" .= _e_rev_E,\n            \"v_rest\" .= _v_rest,\n            \"cm\" .= _cm,\n            \"tau_syn_E\" .= _tau_syn_E,\n            \"tau_m\" .= _tau_m,\n            \"a\" .= _a,\n            \"delta_T\" .= _delta_T,\n            \"v_thresh\" .= _v_thresh,\n            \"b\" .= _b,\n            \"v_spike\" .= _v_spike,\n            \"e_rev_I\" .= _e_rev_I,\n            \"tau_refrac\" .= _tau_refrac\n        ]\n    toJSON EIFCondAlpha {..} = object [\n            \"type\" .= (\"EIFCondAlpha\" :: String),\n            \"cm\" .= _cm,\n            \"tau_refrac\" .= _tau_refrac,\n            \"v_spike\" .= _v_spike,\n            \"v_reset\" .= _v_reset,\n            \"v_rest\" .= _v_rest,\n            \"tau_m\" .= _tau_m,\n            \"i_offset\" .= _i_offset,\n            \"a\" .= _a,\n            \"b\" .= _b,\n            \"delta_T\" .= _delta_T,\n            \"tau_w\" .= _tau_w,\n            \"v_thresh\" .= _v_thresh,\n            \"e_rev_E\" .= _e_rev_E,\n            \"tau_syn_E\" .= _tau_syn_E,\n            \"e_rev_I\" .= _e_rev_I,\n            \"tau_syn_I\" .= _tau_syn_I\n        ]\n\ninstance FromJSON NeuronType where\n    parseJSON = withObject \"neuron\" $ \\o -> do\n        typ :: String <- o .: \"type\"\n        case typ of\n            \"IFCondExp\" -> IFCondExp <$>\n                o .: \"v_rest\" <*>\n                o .: \"cm\" <*>\n                o .: \"tau_m\" <*>\n                o .: \"tau_refrac\" <*>\n                o .: \"tau_syn_E\" <*>\n                o .: \"tau_syn_I\" <*>\n                o .: \"e_rev_E\" <*>\n                o .: \"e_rev_I\" <*>\n                o .: \"v_thresh\" <*>\n                o .: \"v_reset\" <*>\n                o .: \"i_offset\"\n            \"IFCurrentAlpha\" -> IFCurrentAlpha <$>\n                o .: \"tau_m\" <*>\n                o .: \"tau_refrac\" <*>\n                o .: \"v_thresh\" <*>\n                o .: \"tau_syn_E\" <*>\n                o .: \"v_rest\" <*>\n                o .: \"cm\" <*>\n                o .: \"v_reset\" <*>\n                o .: \"tau_syn_I\" <*>\n                o .: \"i_offset\"\n            \"IFCondAlpha\" -> IFCondAlpha <$>\n                o .: \"v_rest\" <*>\n                o .: \"cm\" <*>\n                o .: \"tau_m\" <*>\n                o .: \"tau_refrac\" <*>\n                o .: \"tau_syn_E\" <*>\n                o .: \"tau_syn_I\" <*>\n                o .: \"e_rev_E\" <*>\n                o .: \"e_rev_I\" <*>\n                o .: \"v_thresh\" <*>\n                o .: \"v_reset\" <*>\n                o .: \"i_offset\"\n            \"IFSpikey\" -> IFSpikey <$>\n                o .: \"e_rev_I\" <*>\n                o .: \"g_leak\" <*>\n                o .: \"tau_refrac\" <*>\n                o .: \"v_reset\" <*>\n                o .: \"v_rest\" <*>\n                o .: \"v_thresh\"\n            \"IFCurrExp\" -> IFCurrExp <$>\n                o .: \"cm\" <*>\n                o .: \"tau_m\" <*>\n                o .: \"tau_syn_E\" <*>\n                o .: \"tau_syn_I\" <*>\n                o .: \"tau_refrac\" <*>\n                o .: \"v_thresh\" <*>\n                o .: \"v_rest\" <*>\n                o .: \"v_reset\" <*>\n                o .: \"i_offset\"\n            \"Izhikevich\" -> Izhikevich <$>\n                o .: \"a\" <*>\n                o .: \"i_offset\"<*>\n                o .: \"c\" <*>\n                o .: \"d\" <*>\n                o .: \"b\"\n            \"EIFCondExp\" -> EIFCondExp <$>\n                o .: \"v_reset\" <*>\n                o .: \"i_offset\" <*>\n                o .: \"tau_w\" <*>\n                o .: \"tau_syn_I\" <*>\n                o .: \"e_rev_E\" <*>\n                o .: \"v_rest\" <*>\n                o .: \"cm\" <*>\n                o .: \"tau_syn_E\" <*>\n                o .: \"tau_m\" <*>\n                o .: \"a\" <*>\n                o .: \"delta_T\" <*>\n                o .: \"v_thresh\" <*>\n                o .: \"b\" <*>\n                o .: \"v_spike\" <*>\n                o .: \"e_rev_I\" <*>\n                o .: \"tau_refrac\"\n            \"EIFCondAlpha\" -> EIFCondAlpha <$>\n                o .: \"cm\" <*>\n                o .: \"tau_refrac\" <*>\n                o .: \"v_spike\" <*>\n                o .: \"v_reset\" <*>\n                o .: \"v_rest\" <*>\n                o .: \"tau_m\" <*>\n                o .: \"i_offset\" <*>\n                o .: \"a\" <*>\n                o .: \"b\" <*>\n                o .: \"delta_T\" <*>\n                o .: \"tau_w\" <*>\n                o .: \"v_thresh\" <*>\n                o .: \"e_rev_E\" <*>\n                o .: \"tau_syn_E\" <*>\n                o .: \"e_rev_I\" <*>\n                o .: \"tau_syn_I\"\n\n\n", "meta": {"hexsha": "e117ae89712ee196b4b9054d2bc724733b2ab85f", "size": 15248, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Myelin/Neuron.hs", "max_stars_repo_name": "volr/myelin", "max_stars_repo_head_hexsha": "aaae7ab6f6db85c60fd7940accbb834e0068752e", "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/Myelin/Neuron.hs", "max_issues_repo_name": "volr/myelin", "max_issues_repo_head_hexsha": "aaae7ab6f6db85c60fd7940accbb834e0068752e", "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/Myelin/Neuron.hs", "max_forks_repo_name": "volr/myelin", "max_forks_repo_head_hexsha": "aaae7ab6f6db85c60fd7940accbb834e0068752e", "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.4391752577, "max_line_length": 98, "alphanum_fraction": 0.4876705142, "num_tokens": 4590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.24529252657582334}}
{"text": "{-# LANGUAGE TemplateHaskell, ScopedTypeVariables, OverloadedLists, BangPatterns, Strict #-}\nmodule Data.Mesh where\n\n\nimport qualified Graphics.Rendering.OpenGL.GL as GL\nimport           Graphics.Rendering.OpenGL.GL (($=))\nimport           Control.Lens      hiding (indices)\nimport qualified Data.Vector.Storable as VS\nimport           Number.Quaternion (T,real,imag)\nimport           Numeric.LinearAlgebra (Vector)\nimport qualified SDL\nimport qualified SDL.Image as SDLImage\nimport           Foreign (sizeOf)\nimport           Foreign.Ptr (intPtrToPtr)\nimport           Data.Shaders\nimport           Utils.Quaternions (qZero)\nimport           Control.Arrow\nimport           Control.Monad (unless)\nimport Control.DeepSeq\nimport Graphics.Rendering.OpenGL.GLU.Errors\n\n\ninstance NFData a => NFData (T a) where\n  rnf q = let !_ = real q\n              (!_,!_,!_) = imag q\n          in ()\n\ninstance NFData Mesh where\n  rnf m = let !_ = _quaternion m\n          in ()\n\ndata Mesh = Mesh { _vertices     :: [Vector Float],\n                   _indices      :: Vector GL.BaseInstance,\n                   _vao          :: GL.VertexArrayObject,\n                   _vbo          :: GL.BufferObject,\n                   _ebo          :: GL.BufferObject,\n                   _shaders      :: Shaders,\n                   _quaternion   :: T Float,\n                   _texture      :: Maybe GL.TextureObject,\n                   _normalMap    :: Maybe GL.TextureObject }\n\nmakeLenses ''Mesh\n\n-- loadAndBindImage :: FilePath -> IO ()\nloadAndBindImage texType fn = do\n  sdlSurf <- SDLImage.load fn\n  SDL.V2 w h <- fmap fromIntegral <$> SDL.surfaceDimensions sdlSurf\n  SDL.lockSurface sdlSurf\n  texturePtr <- SDL.surfacePixels sdlSurf\n  let textureSize = GL.TextureSize2D w h\n      textureData = GL.PixelData GL.RGB GL.UnsignedByte texturePtr\n  GL.texImage2D texType GL.NoProxy 0 GL.RGB' textureSize 0 textureData\n  SDL.unlockSurface sdlSurf\n\nloadTexture :: FilePath -> IO GL.TextureObject\nloadTexture fn = do\n  texName <- GL.genObjectName\n  GL.textureBinding GL.Texture2D $= Just texName\n  loadAndBindImage GL.Texture2D fn\n  GL.textureFilter GL.Texture2D $=\n    ((GL.Linear', Nothing),GL.Linear')\n  return texName\n\ncreateMesh (vdata, indices, verts) shad mtex norm = do\n    vao <- GL.genObjectName\n    GL.bindVertexArrayObject $= Just vao\n    ebo <- createAndBindArrayBuffer GL.ElementArrayBuffer $ indices\n    vbo <- createAndBindArrayBuffer GL.ArrayBuffer $ vdata\n\n    setAttrib 17 3 \"vertexPosition_modelspace\" 0  -- vertex location\n    setAttrib 17 3 \"vertexNormal\" 3  -- vertex normal\n    setAttrib 17 2 \"vertexUV\" 6  -- vertex UV\n    setAttrib 17 3 \"vertex_col\" 8  -- vertex color\n    setAttrib 17 3 \"vertex_tangent\" 11 -- vertex tangent\n    setAttrib 17 3 \"vertex_bitangent\" 14 -- vertex bitangent\n\n    GL.bindVertexArrayObject $= Nothing\n    return $ Mesh verts indices vao vbo ebo shad qZero mtex norm\n  where\n    setAttrib size attrSize name offset = do\n      let glFloatSize = sizeOf (undefined :: GL.GLfloat)\n          glLocation  = fromIntegral $ size * glFloatSize\n          glOffset    = intPtrToPtr $ fromIntegral(offset * glFloatSize)\n      loc@(GL.AttribLocation n) <- GL.get $ GL.attribLocation (shad^.program) name\n      unless (n > 1000000) $ do\n        GL.vertexAttribPointer loc $=\n          (GL.ToFloat,\n           GL.VertexArrayDescriptor attrSize GL.Float glLocation glOffset)\n        GL.vertexAttribArray loc $= GL.Enabled\n\nsendData :: forall a. VS.Storable a => GL.BufferTarget -> VS.Vector a -> IO ()\nsendData t d =\n  VS.unsafeWith d $\n    \\vptr -> GL.bufferData t $=\n               (fromIntegral $ VS.length d * sizeOf (undefined :: a),\n                vptr,\n                GL.StaticDraw)\n\ncreateAndBindArrayBuffer\n  :: forall a. VS.Storable a =>\n  GL.BufferTarget\n  -> VS.Vector a\n  -> IO GL.BufferObject\ncreateAndBindArrayBuffer arrayType arrayData = do\n    bufferObject <- GL.genObjectName\n    GL.bindBuffer arrayType $= Just bufferObject\n    sendData arrayType arrayData\n    return bufferObject\n\n\nvertexBufferData :: (VS.Vector Float, VS.Vector GL.BaseInstance, [VS.Vector Float])\nvertexBufferData =\n  let v = --position        normal         UV        color          tangents\n          [-2.0, 0.0, -2.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.1, 0.0, 0.0, 0.0, 0.0, 1.0,\n            2.0, 0.0, -2.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.1, 0.0, 0.0, 0.0, 0.0, 1.0,\n           -2.0, 0.0,  2.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.1, 0.0, 0.0, 0.0, 0.0, 1.0,\n            2.0, 0.0,  2.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.1, 0.0, 0.0, 0.0, 0.0, 1.0]\n      v3 = [[-2.0, 0.0, -2.0],\n            [ 2.0, 0.0, -2.0],\n            [-2.0, 0.0,  2.0],\n            [ 2.0, 0.0,  2.0]]\n      i = [0,1,2,1,3,2]\n  in (v,i,v3)\n\nflatQuad shad tex norm =\n  createMesh vertexBufferData shad (Just tex) (Just norm)\n\nupdate :: (Float -> Float -> Bool) -> Int -> Float -> Vector Float -> Vector Float\nupdate pred ix f v = if pred f (v VS.! ix) then VS.update_ v [ix] [f] else v\n\nupdatePair pred ix f = update pred ix f *** update ((not .) . pred) ix f\n\n-- getAABB :: Mesh -> (Vector Float, Vector Float)\n-- getAABB = VS.ifoldr inserter ([0,0,0],[0,0,0]) . view vertices\n--   where inserter ix = case mod ix 17 of\n--           1 -> updatePair (<) 0\n--           2 -> updatePair (<) 1\n--           3 -> updatePair (<) 2\n--           _ -> flip const\n", "meta": {"hexsha": "2c1adc25bafb1be909402946ea9d2a0f1bb9ea3c", "size": 5353, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Mesh.hs", "max_stars_repo_name": "Antystenes/CPG", "max_stars_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "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/Data/Mesh.hs", "max_issues_repo_name": "Antystenes/CPG", "max_issues_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "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/Data/Mesh.hs", "max_forks_repo_name": "Antystenes/CPG", "max_forks_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "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": 38.2357142857, "max_line_length": 97, "alphanum_fraction": 0.6125537082, "num_tokens": 1680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.2452046334410795}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n\nimport Debug.Trace\n-- import Control.Monad.State.Lazy\n\nimport System.Environment (getArgs)\nimport System.IO (readFile)\nimport Data.Map.Strict (Map, (!), insert, elems, fromList, toList, findWithDefault, size, empty, member, findMin, findMax, singleton, filter)\nimport qualified Data.Map.Strict as M\nimport Data.Set (Set)\nimport qualified Data.Set as S\n--import qualified Data.Array as A\nimport Data.List (find, intercalate, intersperse, permutations, inits, tails, isPrefixOf)\nimport Data.List.Split (splitOn)\n-- import Data.Complex (Complex((:+)), realPart, imagPart) -- define my own complex\n\nimport UI.NCurses\nimport Data.Char (chr, ord)\n-- import Data.Complex (Complex((:+)))\nimport Data.Maybe (fromJust)\ntype Instructions = Map Integer Integer\n\ndata ComputerState = Ready | Running | Blocked | Done\n  deriving (Show, Eq)\n\ndata Computer = Computer {\n  state :: ComputerState,\n  memory :: Map Integer Integer,\n  iptr :: Integer, -- instruction pointer\n  base :: Integer, -- base offset\n  input :: [Integer],\n  output :: [Integer]}\n\ncomputer0 = Computer { state = Ready, memory = empty, iptr = 0, base = 0, input = [], output = [] }\n\nrun :: Computer -> Computer -- (Integer, Integer) -> Instructions -> [Integer] -> [Integer]\nrun c\n  | state c == Ready = run $ c {state = Running}\n  | state c == Done = c\n  | state c == Blocked = if input c == [] then c else run $ c {state = Running}\n  | otherwise = -- running\n    --traceShow (iptr c, base c, memory c) $ \n    case instr `mod` 100 of\n      1 -> -- add\n        run $ c {iptr = i+4, memory = insert (addr 3) (arg 1 + arg 2) instructions}\n      2 -> -- multiply\n        run $ c {iptr = i+4, memory = insert (addr 3) (arg 1 * arg 2) instructions}\n      3 -> -- read input\n        if (null $ input c)\n        then c {state = Blocked}\n        else run $ c {iptr = i+2, memory = insert (addr 1) (head $ input c) instructions, input = tail $ input c}\n      4 -> -- output\n        --traceShow (arg 1) $ \n        run $ c {iptr = i+2, output = output c ++ [arg 1]}\n      5 -> -- jump-if-true\n        run $ c {iptr = if arg 1 == 0 then i+3 else arg 2}\n      6 -> -- jump-if-false\n        run $ c {iptr = if arg 1 == 0 then arg 2 else i+3}\n      7 -> -- less than\n        run $ c {iptr = i+4, memory = insert (addr 3) (if arg 1 < arg 2 then 1 else 0) instructions}\n      8 -> -- equals\n        run $ c {iptr = i+4, memory = insert (addr 3) (if arg 1 == arg 2 then 1 else 0) instructions}\n      9 -> -- set relative base\n        run $ c {iptr = i+2, base = base c + arg 1}\n      99 -> -- halt\n        run $ c {state = Done}\n      _ -> error \"unknown opcode\"\n  where instructions = memory c\n        i = iptr c\n        instr = instructions!i\n        ii x = findWithDefault 0 x instructions\n        arg :: Integer -> Integer\n        arg n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ ii $ i+n\n          1 -> ii $ i+n\n          2 -> ii ((ii $ i+n) + base c)\n          _ -> error \"bad argument mode\"\n        addr n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ i+n\n          1 -> error \"address in mode 1\"\n          2 -> --trace \"address in mode 2\" $\n            ii (i+n) + base c\n          _ -> error $ \"address in unknown mode\"\n\n-- instance (Show a) => Show (Complex a) where\n--   show (C x y) = \"C \" ++ show x ++ \" \" ++ show y\n  \n-- instance (Eq a) => Eq (Complex a) where\n--   (C a ai) == (C b bi) = a == b && ai == bi\n  \n-- instance (Eq a, Ord a) => Ord (Complex a) where\n--   compare (C a ai) (C b bi) | a < b || a == b && ai < bi = LT\n--                             | a > b || a == b && ai > bi = GT\n--                             | otherwise = EQ\n\n-- -- Note that we are using a plane where imaginary (y-axis) numbers\n-- -- increase downward. I think this means that right and left are\n-- -- reversed.\n\n-- data Complex a = C a a\n\n-- -- instance Num (Complex Int) where\n-- --   abs c = error \"Can't take abs of Complex Int\"\n\n-- instance Num a => Num (Complex a) where\n--   (C x y) + (C u v) = C (x+u) (y+v)\n--   (C x y) * (C u v) = C (x*u-y*v) (x*v+y*u)\n--   fromInteger n = C (fromInteger n) 0\n--   abs (C x y) = C (abs x) y -- sqrt $ x*x + y*y\n--   signum (C x y) = C (signum x) 0\n--   negate (C x y) = C (negate x) (negate y)\n\nmain = do\n  -- [instructionFile] <- getArgs\n  instructionStrings <- readFile \"21.input.txt\" -- instructionFile\n  let instructions = fromList . zip [0 ..] $ map read $ splitOn \",\" instructionStrings\n\n  putStrLn \"Part 1\"\n  let linesToAscii = map (fromIntegral . ord) . unlines\n  -- Jumps are 4 spaces. Jump on an island if you can. # = ground, . = hole, _ = don't care\n  -- Jump if any of the three spaces in front of you have holes and the fourth space is solid.\n  -- @ A B C D\n  -- _ . _ _ #\n  -- _ _ . _ #\n  -- _ _ _ . #\n  -- ~(ABC)D -> ~((ABC)+D)\n  let ls = [ \"OR A J\"\n           , \"AND B J\"\n           , \"AND C J\"\n           , \"NOT J J\"\n           , \"AND D J\"\n           , \"WALK\"]\n  \n  -- let c = run $ computer0{memory = instructions, input=ls}\n  let c = run $ computer0{memory = instructions}\n  putStrLn $ map (chr . fromIntegral) $ output c\n  putStrLn $ \"Running with input: \\n\" ++ unlines ls\n  let c2 = run $ c {input=linesToAscii ls, output=[]}\n  let (msg, result) = span (< 128) $ output c2\n  putStrLn $ map (chr . fromIntegral) msg ++ concatMap show result\n\n  putStrLn \"\\n\\nPart 2\"\n  -- Jump as before . . .\n  -- @ABCD  EFGHI \n  -- _.__#  \n  -- __._#  \n  -- ___.#\n  -- But check that you are not blocked after the jump.\n  --        EFGHI \n  --        .__#_\n  --        #___#\n  --        ##___\n  -- ~(ABC)D -> ~((ABC)+D)\n  -- (~E)H + EI + EF = (~E)H + E(I+F) = E(F+I) + H\n  \n  let ls2 = [\n              -- jump if a hole is ahead and the landing is open\n              \"OR A J\"\n            , \"AND B J\"\n            , \"AND C J\"\n            , \"NOT J J\"\n            , \"AND D J\"\n              -- and if the future looks ok\n            , \"OR F T\"\n            , \"OR I T\"\n            , \"AND E T\"\n            , \"OR H T\"\n            , \"AND T J\"\n            , \"RUN\"\n            ]\n  let c3 = run $ computer0{memory = instructions}\n  putStrLn $ map (chr . fromIntegral) $ output c3\n  putStrLn $ \"Running with input: \\n\" ++ unlines ls2\n  let c4 = run $ c3 {input=linesToAscii ls2, output=[]}\n  let (msg, result) = span (< 128) $ output c4\n  putStrLn $ map (chr . fromIntegral) msg ++ concatMap show result\n", "meta": {"hexsha": "1b30fe30e26c7956981d4c1bf71dfdc6854b4eaa", "size": 6359, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "21.hs", "max_stars_repo_name": "dpatru/aoc2019", "max_stars_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-30T21:19:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T21:19:29.000Z", "max_issues_repo_path": "21.hs", "max_issues_repo_name": "dpatru/aoc2019", "max_issues_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "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": "21.hs", "max_forks_repo_name": "dpatru/aoc2019", "max_forks_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "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": 35.9265536723, "max_line_length": 141, "alphanum_fraction": 0.5426953924, "num_tokens": 1993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24443762986146805}}
{"text": "import Debug.Trace\n-- import Control.Monad.State.Lazy\n\nimport System.Environment (getArgs)\nimport System.IO (readFile)\nimport Data.Map.Strict (Map, (!), insert, elems, fromList, toList, findWithDefault, size, empty, member, findMin, findMax, singleton, filter)\nimport qualified Data.Map.Strict as M\n--import qualified Data.Array as A\nimport Data.List (permutations)\nimport Data.List.Split (splitOn)\nimport Data.Complex (Complex((:+)), realPart, imagPart)\n\nimport UI.NCurses\n\n\ntype Instructions = Map Integer Integer\n\ndata ComputerState = Ready | Running | Blocked | Done\n  deriving (Show, Eq)\n\ndata Computer = Computer {\n  state :: ComputerState,\n  memory :: Map Integer Integer,\n  iptr :: Integer, -- instruction pointer\n  base :: Integer, -- base offset\n  input :: [Integer],\n  output :: [Integer]}\n\ncomputer0 = Computer { state = Ready, memory = empty, iptr = 0, base = 0, input = [], output = [] }\n\nrun :: Computer -> Computer -- (Integer, Integer) -> Instructions -> [Integer] -> [Integer]\nrun c\n  | state c == Ready = run $ c {state = Running}\n  | state c == Done = c\n  | state c == Blocked = if input c == [] then c else run $ c {state = Running}\n  | otherwise = -- running\n    --traceShow (iptr c, base c, memory c) $ \n    case instr `mod` 100 of\n      1 -> -- add\n        run $ c {iptr = i+4, memory = insert (addr 3) (arg 1 + arg 2) instructions}\n      2 -> -- multiply\n        run $ c {iptr = i+4, memory = insert (addr 3) (arg 1 * arg 2) instructions}\n      3 -> -- read input\n        if (null $ input c)\n        then c {state = Blocked}\n        else run $ c {iptr = i+2, memory = insert (addr 1) (head $ input c) instructions, input = tail $ input c}\n      4 -> -- output\n        --traceShow (arg 1) $ \n        run $ c {iptr = i+2, output = output c ++ [arg 1]}\n      5 -> -- jump-if-true\n        run $ c {iptr = if arg 1 == 0 then i+3 else arg 2}\n      6 -> -- jump-if-false\n        run $ c {iptr = if arg 1 == 0 then arg 2 else i+3}\n      7 -> -- less than\n        run $ c {iptr = i+4, memory = insert (addr 3) (if arg 1 < arg 2 then 1 else 0) instructions}\n      8 -> -- equals\n        run $ c {iptr = i+4, memory = insert (addr 3) (if arg 1 == arg 2 then 1 else 0) instructions}\n      9 -> -- set relative base\n        run $ c {iptr = i+2, base = base c + arg 1}\n      99 -> -- halt\n        run $ c {state = Done}\n      _ -> error \"unknown opcode\"\n  where instructions = memory c\n        i = iptr c\n        instr = instructions!i\n        ii x = findWithDefault 0 x instructions\n        arg :: Integer -> Integer\n        arg n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ ii $ i+n\n          1 -> ii $ i+n\n          2 -> ii ((ii $ i+n) + base c)\n          _ -> error \"bad argument mode\"\n        addr n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ i+n\n          1 -> error \"address in mode 1\"\n          2 -> --trace \"address in mode 2\" $\n            ii (i+n) + base c\n          _ -> error $ \"address in unknown mode\"\n\ninstance Ord a => Ord (Complex a) where\n  compare a b | ar < br || ar == br && ai < bi = LT\n              | ar > br || ar == br && ai > bi = GT\n              | otherwise = EQ\n    where (ar, ai) = toParts a\n          (br, bi) = toParts b\n\ntoParts :: Complex a -> (a, a)\ntoParts c = (realPart c, imagPart c)\n\ntoIntParts :: RealFrac a => Complex a -> (Int, Int)\ntoIntParts c = (round $ realPart c, round $ imagPart c)\n\nfromParts :: (a, a) -> Complex a\nfromParts (a,b) = a :+ b\n\ndata Game = Game {\n  m :: Map (Integer, Integer) Integer, -- map\n  b :: [(Integer, Integer)], -- ball\n  p :: [(Integer, Integer)]} -- paddle\n  deriving (Show)\n\ngame0 = Game { m = empty, b = [], p = [] }\nupdateGame :: Game -> [Integer] -> Game\nupdateGame g [] = g\nupdateGame g (x:y:t:r) = updateGame (g' { m = insert (x,y) t $ m g}) r\n  where g' | t == 4 = g { b = (x,y): b g }\n           | t == 3 = g { p = (x,y): p g }\n           | otherwise = g\nupdateGame g _ = error \"bad input\"\n\nrecommendMove :: Game -> Integer\nrecommendMove g =\n  if null (p g) || null (b g) then 0\n  else if x == x' && (y == y' || y - 1 == y') then 0\n       else case length (b g) of\n              0 -> 0\n              1 -> signum $ (fst $ head $ b g) - x\n              _ -> let [x2, x1] = map fst $ take 2 $ b g\n                in signum $ x2 + signum (x2 - x1) - x\n  where (x,y) = head $ p g\n        (x',y') = head $ b g\n\n\n  \ndisplay :: [Integer] -> IO ()\ndisplay drawCommands = runCurses $ do\n    setEcho False\n    w <- defaultWindow\n    updateWindow w $ do\n        draw drawCommands\n    render\n    waitFor w (\\ev -> ev == EventCharacter 'q' || ev == EventCharacter 'Q')\n      where draw [] = do\n              moveCursor 0 10\n              drawString \"Done\"\n            draw (x:y:t:r) =\n              if (x,y) == (-1, 0)\n              then do \n                moveCursor 0 0\n                drawString $ show t\n                draw r\n              else do\n                moveCursor (y+5) x \n                drawString (case t of\n                              0 -> \" \"\n                              1 -> \"W\"\n                              2 -> \"B\"\n                              3 -> \"_\"\n                              4 -> \"*\")\n                draw r\n\nwaitFor :: Window -> (Event -> Bool) -> Curses ()\nwaitFor w p = loop where\n    loop = do\n        ev <- getEvent w Nothing\n        case ev of\n            Nothing -> loop\n            Just ev' -> if p ev' then return () else loop\n\nplay :: Game -> Computer -> IO (Game)\nplay game c = runCurses $ do\n  setEcho False\n  w <- defaultWindow\n  loop w game $ run c\n    where loop :: Window -> Game -> Computer -> Curses(Game)\n          loop w g c\n            | state c == Done = do\n                processDrawCommands w g' $ output c\n                updateWindow w $ do\n                  moveCursor 0 10\n                  drawString \"Press q to quit\"\n                render\n                let qloop = do\n                      ev <- getEvent w Nothing\n                      case ev of\n                        Nothing -> qloop\n                        Just (EventCharacter 'q') -> return g'\n                        Just (EventCharacter 'Q') -> return g'\n                        _ -> qloop\n                qloop\n            | state c == Blocked = do -- waiting for input\n                processDrawCommands w g' $ output c\n                moveEvent <- getEvent w (Just 20)\n                let joystick = case moveEvent of\n                                 Just (EventSpecialKey KeyLeftArrow) -> -1\n                                 Just (EventSpecialKey KeyRightArrow) -> 1\n                                 Nothing -> recommendMove g'\n                                 Just (EventCharacter 'j') -> -1\n                                 Just (EventCharacter 'J') -> -1\n                                 Just (EventCharacter 'k') -> 1\n                                 Just (EventCharacter 'K') -> 1\n                                 _ -> 0\n                updateWindow w $ do\n                  moveCursor 0 10\n                  drawString $ case joystick of\n                    -1 -> \"move left\"\n                    0 -> \"no move\"\n                    1 -> \"move right\"\n                render\n                loop w g' $ run $ c {state = Running, output = [], input = [joystick]}\n            | otherwise = loop w game $ run c\n              where g' = updateGame g $ output c\n          processDrawCommands :: Window -> Game -> [Integer] -> Curses()\n          processDrawCommands w g [] = render\n          processDrawCommands w g (x:y:t:r) = do\n            updateWindow w $ do\n              if (x,y) == (-1, 0)\n              then do \n              moveCursor 0 0\n              drawString $ show t\n              else do\n              moveCursor 1 0\n              drawString $ show $ take 25 $ b g\n              moveCursor 2 0\n              drawString $ show $ take 25 $ p g\n              moveCursor (y+5) x\n              drawString (case t of\n                             0 -> \" \"\n                             1 -> \"W\"\n                             2 -> \"B\"\n                             3 -> \"_\"\n                             4 -> \"*\"\n                             _ -> error (\"Unknown input \" ++ show t)\n                         )\n            processDrawCommands w g r\n\nmain = do\n  [instructionFile] <- getArgs\n  instructionStrings <- readFile instructionFile\n  let instructions = fromList . zip [0 ..] $ map read $ splitOn \",\" instructionStrings\n\n  -- putStrLn \"Part 1\"\n  -- let c = run $ computer0 {memory = instructions}\n  -- -- putStrLn $ show (\"state\", state c, \"drawCommands\", output c)\n  -- let game = updateGame game0 $ output c\n  -- putStrLn $ show $ size $ M.filter (== 2) $ m game\n  -- putStrLn \"Part 1b\"\n  -- display $ output c\n  putStrLn \"Part 2\"\n  let instructions2 = insert 0 2 instructions -- play for free by setting memory address 0 to 2\n  game <- play game0 $ computer0 {memory = instructions2}\n  putStrLn $ show $ head $ p game\n  -- let moves = moves >>= (play . run (0,0) instructions2)\n  -- -- moves <- play $ run (0,0) instructions2 $ repeat 0\n  -- moves' <- moves\n  -- putStrLn $ show $ length moves'\n  \n  -- let moves = moves >>= (play . run (0,0) instructions2)\n  -- moves' <- moves\n  -- putStrLn $ show moves'\n  -- moves' <- play $ run (0,0) instructions2 []\n  -- putStrLn $ show (\"moves\", moves')\n  -- let moves = run (0,0) instructions2 $ repeat 0\n  -- putStrLn $ show (\"moves\", moves)\n  -- display moves\n  \n  \n  -- let out = run (0,0) instructions $ (startColors!origin) : processOutput\n  --     (processOutput, finalp, finald, colors) = process (origin,up, startColors) $ out\n  -- putStrLn\n  --   $ unlines\n  --   $ [\"done Part 1\"\n  --     , show $ (\"tiles painted: \", size colors)\n  --     , show $ (\"finalp\", finalp, \"finald\", robot finald)\n  --     ]\n  -- putStr $ showColors finalp finald colors\n\n  -- putStrLn \"Part 2\"\n  -- let out = run (0,0) instructions $ (startColors2!origin) : processOutput\n  --     (processOutput, finalp, finald, colors) = process (origin,up, startColors2) $ out\n  -- putStrLn\n  --   $ unlines\n  --   $ [\"done Part 2\"\n  --     , show $ (\"tiles painted: \", size colors)\n  --     , show $ (\"finalp\", finalp, \"finald\", robot finald)\n  --     ]\n  -- putStr $ showColors finalp finald colors\n\n", "meta": {"hexsha": "547713aebfe29954e9a1ac56d6e0e29fb4b6c7fa", "size": 10205, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "13b.hs", "max_stars_repo_name": "dpatru/aoc2019", "max_stars_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-30T21:19:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T21:19:29.000Z", "max_issues_repo_path": "13b.hs", "max_issues_repo_name": "dpatru/aoc2019", "max_issues_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "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": "13b.hs", "max_forks_repo_name": "dpatru/aoc2019", "max_forks_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "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": 36.5770609319, "max_line_length": 141, "alphanum_fraction": 0.4963253307, "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.24394972689275343}}
{"text": "{-# LANGUAGE DerivingStrategies #-}\n{-# LANGUAGE DerivingVia #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE UndecidableInstances #-}\nmodule DerivingViaCompile where\n\nimport Data.Void\nimport Data.Complex\nimport Data.Functor.Const\nimport Data.Functor.Identity\nimport Data.Ratio\nimport Control.Monad.Reader\nimport Control.Monad.State\nimport Control.Monad.Writer\nimport Control.Applicative hiding (WrappedMonad(..))\n\nimport Data.Bifunctor\nimport Data.Monoid\nimport Data.Kind\n\ntype f ~> g = forall xx. f xx -> g xx\n\n-----\n-- Simple example\n-----\n\ndata Foo a = MkFoo a a\n  deriving Show\n       via (Identity (Foo a))\n\n-----\n-- Eta reduction at work\n-----\n\nnewtype Flip p a b = Flip { runFlip :: p b a }\n\ninstance Bifunctor p => Bifunctor (Flip p) where\n  bimap f g = Flip . bimap g f . runFlip\n\ninstance Bifunctor p => Functor (Flip p a) where\n  fmap f = Flip . first f . runFlip\n\nnewtype Bar a = MkBar (Either a Int)\n  deriving Functor\n       via (Flip Either Int)\n\n-----\n-- Monad transformers\n-----\n\ntype MTrans = (Type -> Type) -> (Type -> Type)\n\n-- From `constraints'\ndata Dict c where\n  Dict :: c => Dict c\n\nnewtype a :- b = Sub (a => Dict b)\n\ninfixl 1 \\\\\n(\\\\) :: a => (b => r) -> (a :- b) -> r\nr \\\\ Sub Dict = r\n\n-- With `-XQuantifiedConstraints' this just becomes\n--\n--    type Lifting cls  trans = forall mm. cls mm => cls (trans mm)\n--\n--    type LiftingMonad trans = Lifting Monad trans\n--\nclass LiftingMonad (trans :: MTrans) where\n  proof :: Monad m :- Monad (trans m)\n\ninstance LiftingMonad (StateT s :: MTrans) where\n  proof :: Monad m :- Monad (StateT s m)\n  proof = Sub Dict\n\ninstance Monoid w => LiftingMonad (WriterT w :: MTrans) where\n  proof :: Monad m :- Monad (WriterT w m)\n  proof = Sub Dict\n\ninstance (LiftingMonad trans, LiftingMonad trans') => LiftingMonad (ComposeT trans trans' :: MTrans) where\n  proof :: forall m. Monad m :- Monad (ComposeT trans trans' m)\n  proof = Sub (Dict \\\\ proof @trans @(trans' m) \\\\ proof @trans' @m)\n\nnewtype Stack :: MTrans where\n  Stack :: ReaderT Int (StateT Bool (WriterT String m)) a -> Stack m a\n  deriving newtype\n    ( Functor\n    , Applicative\n    , Monad\n    , MonadReader Int\n    , MonadState Bool\n    , MonadWriter String\n    )\n  deriving (MonadTrans, MFunctor)\n       via (ReaderT Int `ComposeT` StateT Bool `ComposeT` WriterT String)\n\nclass MFunctor (trans :: MTrans) where\n  hoist :: Monad m => (m ~> m') -> (trans m ~> trans m')\n\ninstance MFunctor (ReaderT r :: MTrans) where\n  hoist :: Monad m => (m ~> m') -> (ReaderT r m ~> ReaderT r m')\n  hoist nat = ReaderT . fmap nat . runReaderT\n\ninstance MFunctor (StateT s :: MTrans) where\n  hoist :: Monad m => (m ~> m') -> (StateT s m ~> StateT s m')\n  hoist nat = StateT . fmap nat . runStateT\n\ninstance MFunctor (WriterT w :: MTrans) where\n  hoist :: Monad m => (m ~> m') -> (WriterT w m ~> WriterT w m')\n  hoist nat = WriterT . nat . runWriterT\n\ninfixr 9 `ComposeT`\nnewtype ComposeT :: MTrans -> MTrans -> MTrans where\n  ComposeT :: { getComposeT :: f (g m) a } -> ComposeT f g m a\n  deriving newtype (Functor, Applicative, Monad)\n\ninstance (MonadTrans f, MonadTrans g, LiftingMonad g) => MonadTrans (ComposeT f g) where\n  lift :: forall m. Monad m => m ~> ComposeT f g m\n  lift = ComposeT . lift . lift\n    \\\\ proof @g @m\n\ninstance (MFunctor f, MFunctor g, LiftingMonad g) => MFunctor (ComposeT f g) where\n  hoist :: forall m m'. Monad m => (m ~> m') -> (ComposeT f g m ~> ComposeT f g m')\n  hoist f = ComposeT . hoist (hoist f) . getComposeT\n    \\\\ proof @g @m\n\n-----\n-- Using tuples in a `via` type\n-----\n\nnewtype X a = X (a, a)\n  deriving (Semigroup, Monoid)\n       via (Product a, Sum a)\n\n  deriving (Show, Eq)\n       via (a, a)\n\n-----\n-- Abstract data types\n-----\n\nclass C f where\n  c :: f a -> Int\n\nnewtype X2 f a = X2 (f a)\n\ninstance C (X2 f) where\n  c = const 0\n\nderiving via (X2 IO) instance C IO\n\n----\n-- Testing parser\n----\n\nnewtype P0 a = P0 a             deriving Show via a\nnewtype P1 a = P1 [a]           deriving Show via [a]\nnewtype P2 a = P2 (a, a)        deriving Show via (a, a)\nnewtype P3 a = P3 (Maybe a)     deriving Show via (First a)\nnewtype P4 a = P4 (Maybe a)     deriving Show via (First $ a)\nnewtype P5 a = P5 a             deriving Show via (Identity $ a)\nnewtype P6 a = P6 [a]           deriving Show via ([] $ a)\nnewtype P7 a = P7 (a, a)        deriving Show via (Identity $ (a, a))\nnewtype P8 a = P8 (Either () a) deriving Functor via (($) (Either ()))\n\nnewtype f $ a = APP (f a) deriving newtype Show deriving newtype Functor\n\n----\n-- From Baldur's notes\n----\n\n----\n-- 1\n----\nnewtype WrapApplicative f a = WrappedApplicative (f a)\n  deriving (Functor, Applicative)\n\ninstance (Applicative f, Num a) => Num (WrapApplicative f a) where\n  (+)         = liftA2 (+)\n  (*)         = liftA2 (*)\n  negate      = fmap negate\n  fromInteger = pure . fromInteger\n  abs         = fmap abs\n  signum      = fmap signum\n\ninstance (Applicative f, Fractional a) => Fractional (WrapApplicative f a) where\n  recip        = fmap recip\n  fromRational = pure . fromRational\n\ninstance (Applicative f, Floating a) => Floating (WrapApplicative f a) where\n  pi    = pure pi\n  sqrt  = fmap sqrt\n  exp   = fmap exp\n  log   = fmap log\n  sin   = fmap sin\n  cos   = fmap cos\n  asin  = fmap asin\n  atan  = fmap atan\n  acos  = fmap acos\n  sinh  = fmap sinh\n  cosh  = fmap cosh\n  asinh = fmap asinh\n  atanh = fmap atanh\n  acosh = fmap acosh\n\ninstance (Applicative f, Semigroup s) => Semigroup (WrapApplicative f s) where\n  (<>) = liftA2 (<>)\n\ninstance (Applicative f, Monoid m) => Monoid (WrapApplicative f m) where\n  mempty = pure mempty\n\n----\n-- 2\n----\nclass Pointed p where\n  pointed :: a -> p a\n\nnewtype WrapMonad f a = WrappedMonad (f a)\n  deriving newtype (Pointed, Monad)\n\ninstance (Monad m, Pointed m) => Functor (WrapMonad m) where\n  fmap = liftM\n\ninstance (Monad m, Pointed m) => Applicative (WrapMonad m) where\n  pure  = pointed\n  (<*>) = ap\n\n-- data\ndata Sorted a = Sorted a a a\n  deriving (Functor, Applicative)\n    via (WrapMonad Sorted)\n  deriving (Num, Fractional, Floating, Semigroup, Monoid)\n    via (WrapApplicative Sorted a)\n\n\ninstance Monad Sorted where\n  (>>=) :: Sorted a -> (a -> Sorted b) -> Sorted b\n  Sorted a b c >>= f = Sorted a' b' c' where\n    Sorted a' _  _  = f a\n    Sorted _  b' _  = f b\n    Sorted _  _  c' = f c\n\ninstance Pointed Sorted where\n  pointed :: a -> Sorted a\n  pointed a = Sorted a a a\n\n----\n-- 3\n----\nclass IsZero a where\n  isZero :: a -> Bool\n\nnewtype WrappedNumEq  a = WrappedNumEq a\nnewtype WrappedShow   a = WrappedShow  a\nnewtype WrappedNumEq2 a = WrappedNumEq2 a\n\ninstance (Num a, Eq a) => IsZero (WrappedNumEq a) where\n  isZero :: WrappedNumEq a -> Bool\n  isZero (WrappedNumEq a) = 0 == a\n\ninstance Show a => IsZero (WrappedShow a) where\n  isZero :: WrappedShow a -> Bool\n  isZero (WrappedShow a) = \"0\" == show a\n\ninstance (Num a, Eq a) => IsZero (WrappedNumEq2 a) where\n  isZero :: WrappedNumEq2 a -> Bool\n  isZero (WrappedNumEq2 a) = a + a == a\n\nnewtype INT = INT Int\n  deriving newtype Show\n  deriving IsZero via (WrappedNumEq Int)\n\nnewtype VOID = VOID Void deriving IsZero via (WrappedShow Void)\n\n----\n-- 4\n----\nclass Bifunctor p => Biapplicative p where\n  bipure :: a -> b -> p a b\n\n  biliftA2\n    :: (a  -> b  -> c)\n    -> (a' -> b' -> c')\n    -> p a a'\n    -> p b b'\n    -> p c c'\n\ninstance Biapplicative (,) where\n  bipure = (,)\n\n  biliftA2 f f' (a, a') (b, b') =\n    (f a b, f' a' b')\n\nnewtype WrapBiapp p a b = WrapBiap (p a b)\n  deriving newtype (Bifunctor, Biapplicative, Eq)\n\ninstance (Biapplicative p, Num a, Num b) => Num (WrapBiapp p a b) where\n  (+) = biliftA2 (+) (+)\n  (-) = biliftA2 (*) (*)\n  (*) = biliftA2 (*) (*)\n  negate = bimap negate negate\n  abs = bimap abs abs\n  signum = bimap signum signum\n  fromInteger n = fromInteger n `bipure` fromInteger n\n\nnewtype INT2 = INT2 (Int, Int)\n  deriving IsZero via (WrappedNumEq2 (WrapBiapp (,) Int Int))\n\n----\n-- 5\n----\nclass Monoid a => MonoidNull a where\n  null :: a -> Bool\n\nnewtype WrpMonNull a = WRM a deriving (Eq, Semigroup, Monoid)\n\ninstance (Eq a, Monoid a) => MonoidNull (WrpMonNull a) where\n  null :: WrpMonNull a -> Bool\n  null = (== mempty)\n\nderiving via (WrpMonNull Any) instance MonoidNull Any\nderiving via ()               instance MonoidNull ()\nderiving via Ordering         instance MonoidNull Ordering\n\n----\n-- 6\n----\n-- https://github.com/mikeizbicki/subhask/blob/f53fd8f465747681c88276c7dabe3646fbdf7d50/src/SubHask/Algebra.hs#L635\n\nclass Lattice a where\n  sup   :: a -> a -> a\n  (.>=) :: a -> a -> Bool\n  (.>)  :: a -> a -> Bool\n\nnewtype WrapOrd a = WrappedOrd a\n  deriving newtype (Eq, Ord)\n\ninstance Ord a => Lattice (WrapOrd a) where\n  sup   = max\n  (.>=) = (>=)\n  (.>)  = (>)\n\nderiving via [a]    instance Ord a          => Lattice [a]\nderiving via (a, b) instance (Ord a, Ord b) => Lattice (a, b)\n--mkLattice_(Bool)\nderiving via Bool instance Lattice Bool\n--mkLattice_(Char)\nderiving via Char instance Lattice Char\n--mkLattice_(Int)\nderiving via Int instance Lattice Int\n--mkLattice_(Integer)\nderiving via Integer instance Lattice Integer\n--mkLattice_(Float)\nderiving via Float instance Lattice Float\n--mkLattice_(Double)\nderiving via Double instance Lattice Double\n--mkLattice_(Rational)\nderiving via Rational instance Lattice Rational\n\n----\n-- 7\n----\n-- https://hackage.haskell.org/package/linear-1.20.7/docs/src/Linear-Affine.html\n\nclass Functor f => Additive f where\n  zero :: Num a => f a\n  (^+^) :: Num a => f a -> f a -> f a\n  (^+^) = liftU2 (+)\n  (^-^) :: Num a => f a -> f a -> f a\n  x ^-^ y = x ^+^ fmap negate y\n  liftU2 :: (a -> a -> a) -> f a -> f a -> f a\n\ninstance Additive [] where\n  zero = []\n  liftU2 f = go where\n    go (x:xs) (y:ys) = f x y : go xs ys\n    go [] ys = ys\n    go xs [] = xs\n\ninstance Additive Maybe where\n  zero = Nothing\n  liftU2 f (Just a) (Just b) = Just (f a b)\n  liftU2 _ Nothing ys = ys\n  liftU2 _ xs Nothing = xs\n\ninstance Applicative f => Additive (WrapApplicative f) where\n  zero   = pure 0\n  liftU2 = liftA2\n\nderiving via (WrapApplicative ((->) a)) instance Additive ((->) a)\nderiving via (WrapApplicative Complex)  instance Additive Complex\nderiving via (WrapApplicative Identity) instance Additive Identity\n\ninstance Additive ZipList where\n  zero = ZipList []\n  liftU2 f (ZipList xs) (ZipList ys) = ZipList (liftU2 f xs ys)\n\nclass Additive (Diff p) => Affine p where\n  type Diff p :: Type -> Type\n\n  (.-.) :: Num a => p a -> p a -> Diff p a\n  (.+^) :: Num a => p a -> Diff p a -> p a\n  (.-^) :: Num a => p a -> Diff p a -> p a\n  p .-^ v = p .+^ fmap negate v\n\n-- #define ADDITIVEC(CTX,T) instance CTX => Affine T where type Diff T = T ; \\\n--   (.-.) = (^-^) ; {-# INLINE (.-.) #-} ; (.+^) = (^+^) ; {-# INLINE (.+^) #-} ; \\\n--   (.-^) = (^-^) ; {-# INLINE (.-^) #-}\n-- #define ADDITIVE(T) ADDITIVEC((), T)\nnewtype WrapAdditive f a = WrappedAdditive (f a)\n\ninstance Additive f => Affine (WrapAdditive f) where\n  type Diff (WrapAdditive f) = f\n\n  WrappedAdditive a .-. WrappedAdditive b = a ^-^ b\n  WrappedAdditive a .+^ b = WrappedAdditive (a ^+^ b)\n  WrappedAdditive a .-^ b = WrappedAdditive (a ^-^ b)\n\n-- ADDITIVE(((->) a))\nderiving via (WrapAdditive ((->) a)) instance Affine ((->) a)\n-- ADDITIVE([])\nderiving via (WrapAdditive [])       instance Affine []\n-- ADDITIVE(Complex)\nderiving via (WrapAdditive Complex)  instance Affine Complex\n-- ADDITIVE(Maybe)\nderiving via (WrapAdditive Maybe)    instance Affine Maybe\n-- ADDITIVE(ZipList)\nderiving via (WrapAdditive ZipList)  instance Affine ZipList\n-- ADDITIVE(Identity)\nderiving via (WrapAdditive Identity) instance Affine Identity\n\n----\n-- 8\n----\n\nclass C2 a b c where\n  c2 :: a -> b -> c\n\ninstance C2 a b (Const a b) where\n  c2 x _ = Const x\n\nnewtype Fweemp a = Fweemp a\n  deriving (C2 a b)\n       via (Const a (b :: Type))\n\n", "meta": {"hexsha": "b94da99015f2fe3cb1cb80a01044aa2fa9ffacfd", "size": 12180, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/examples/ghc86/deriving-via-compile.hs", "max_stars_repo_name": "expipiplus1/ghc-exactprint", "max_stars_repo_head_hexsha": "91f54d7a7a1d8d2131c5e83d13dee6c9e8b57831", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2015-01-10T23:15:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T19:53:04.000Z", "max_issues_repo_path": "tests/examples/ghc86/deriving-via-compile.hs", "max_issues_repo_name": "expipiplus1/ghc-exactprint", "max_issues_repo_head_hexsha": "91f54d7a7a1d8d2131c5e83d13dee6c9e8b57831", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 82, "max_issues_repo_issues_event_min_datetime": "2015-01-25T20:04:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T18:24:55.000Z", "max_forks_repo_path": "tests/examples/ghc86/deriving-via-compile.hs", "max_forks_repo_name": "expipiplus1/ghc-exactprint", "max_forks_repo_head_hexsha": "91f54d7a7a1d8d2131c5e83d13dee6c9e8b57831", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2015-02-05T10:08:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T00:59:27.000Z", "avg_line_length": 26.420824295, "max_line_length": 115, "alphanum_fraction": 0.6325123153, "num_tokens": 3856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24372687576120297}}
{"text": "{-# LANGUAGE Safe #-}\n{-# OPTIONS_GHC -fno-warn-deprecations #-}\n-- | Import all modules from prelude that should be safe\nmodule Main where\n\nimport Numeric\nimport Prelude\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Category\n\nimport Control.Concurrent\nimport Control.Concurrent.Chan\nimport Control.Concurrent.MVar\nimport Control.Concurrent.QSem\nimport Control.Concurrent.QSemN\n\nimport Control.Exception\nimport Control.Exception.Base\n\nimport Control.Monad\nimport Control.Monad.Fix\nimport Control.Monad.Instances\nimport Control.Monad.Zip\n\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy\nimport Control.Monad.ST.Strict\n\nimport Data.Bifunctor\nimport Data.Bits\nimport Data.Bool\nimport Data.Char\n-- import Data.Coerce\nimport Data.Complex\nimport Data.Data\nimport Data.Dynamic\nimport Data.Either\nimport Data.Eq\nimport Data.Fixed\nimport Data.Foldable\nimport Data.Function\nimport Data.Functor.Identity\nimport Data.Functor\nimport Data.IORef\nimport Data.Int\nimport Data.Ix\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Proxy\nimport Data.Ratio\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\nimport Data.Typeable\nimport Data.Unique\nimport Data.Version\nimport Data.Word\n\nimport Data.STRef\nimport Data.STRef.Lazy\nimport Data.STRef.Strict\n\nimport Data.Type.Bool\n-- import Data.Type.Coercion\n-- import Data.Type.Equality\n\n-- import Debug.Trace\n\nimport Foreign\n\nimport Foreign.Concurrent\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\nimport Foreign.StablePtr\nimport Foreign.Storable\n\nimport Foreign.C\nimport Foreign.C.Error\nimport Foreign.C.String\nimport Foreign.C.Types\n\nimport Foreign.Marshal\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Error\nimport Foreign.Marshal.Pool\nimport Foreign.Marshal.Utils\n\nimport System.CPUTime\nimport System.Console.GetOpt\nimport System.Environment\nimport System.Exit\nimport System.IO\nimport System.IO.Error\nimport System.Info\nimport System.Mem\nimport System.Mem.StableName\nimport System.Mem.Weak\nimport System.Posix.Internals\nimport System.Posix.Types\nimport System.Timeout\n\nimport Text.ParserCombinators.ReadP\nimport Text.ParserCombinators.ReadPrec\nimport Text.Printf\nimport Text.Read\nimport Text.Read.Lex\nimport Text.Show\nimport Text.Show.Functions\n\nimport Type.Reflection\n\n-- import Unsafe.Coerce\n\nf :: Int\nf = 2\n\nmain :: IO ()\nmain = putStrLn $ \"X is: \" ++ show f\n\n", "meta": {"hexsha": "edd6d65fcb4c829094d4f9b28074f06981cc65cc", "size": 2392, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "testsuite/tests/safeHaskell/unsafeLibs/GoodImport03.hs", "max_stars_repo_name": "janpath/ghc", "max_stars_repo_head_hexsha": "caffff1238097821cd2879f7285010a6565afd52", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2018-07-06T18:58:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-16T13:03:19.000Z", "max_issues_repo_path": "testsuite/tests/safeHaskell/unsafeLibs/GoodImport03.hs", "max_issues_repo_name": "janpath/ghc", "max_issues_repo_head_hexsha": "caffff1238097821cd2879f7285010a6565afd52", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-02-21T02:34:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T15:09:01.000Z", "max_forks_repo_path": "testsuite/tests/safeHaskell/unsafeLibs/GoodImport03.hs", "max_forks_repo_name": "janpath/ghc", "max_forks_repo_head_hexsha": "caffff1238097821cd2879f7285010a6565afd52", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-08-04T13:38:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T03:52:36.000Z", "avg_line_length": 19.136, "max_line_length": 56, "alphanum_fraction": 0.8206521739, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24358799464210024}}
{"text": "-- Copyright 2021 Google LLC.\n-- SPDX-License-Identifier: Apache-2.0\n\n-- #region language extensions\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DuplicateRecordFields #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedLabels #-}\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ViewPatterns #-}\n\n-- #endregion\n\nmodule Main where\n\n-- #region imports\n\nimport Control.DeepSeq\nimport Control.Lens (at, each, folded, isn't, ix, traversed, (%~), (&), (.~), (?~), (^.), (^..), (^?), _1, _2, _3, _4)\nimport Control.Lens.Extras (is)\nimport Control.Monad (forM_)\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString.Lazy as LBS\nimport qualified Data.ByteString.Lazy.Char8 as LBS8\nimport Data.Complex (Complex (..), cis, imagPart, realPart)\nimport Data.Functor ((<&>))\nimport Data.Generics.Labels ()\nimport qualified Data.Graph.Inductive as G\nimport Data.Graph.Inductive.PatriciaTree (Gr)\nimport Data.List (elemIndex, scanl', sortOn, transpose, foldl', tails)\nimport Data.List.Split (chunksOf, splitOn)\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\nimport Data.Maybe (catMaybes, fromJust, mapMaybe)\nimport Data.MemoTrie\nimport Data.Sequence (Seq (..))\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.Lazy as LT\nimport Data.Vector (Vector)\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Unboxed as UV\nimport qualified Data.Vector.Unboxed.Mutable as MUV\nimport Debug.Trace (trace, traceShow, traceShowId)\nimport GHC.Generics (Generic)\nimport GHC.IO (unsafePerformIO)\nimport Linear (V2 (..), angle, (*^), _x, _y)\nimport QuickSpec\nimport Safe hiding (at)\nimport Test.QuickCheck (Arbitrary (..), NonNegative (NonNegative), chooseInt, vectorOf, (==>), quickCheckResult)\nimport Test.QuickCheck.Modifiers (Positive (Positive, getPositive))\nimport qualified Text.Megaparsec as P\nimport qualified Text.Megaparsec.Char as P\nimport qualified Text.Megaparsec.Char.Lexer as L\nimport Text.Pretty.Simple (pPrint, pShow)\nimport Text.Regex.PCRE ((=~))\nimport Util\n\n-- #endregion\n\ntype Input = UV.Vector Int\n\nparse :: String -> Input\nparse = UV.fromList . map (read . (: [])) . head . lines\n\ninput :: Input\ninput = parse (unsafePerformIO (readFile \"/home/polux/projects/aoc/2019/day16-2/input.txt\"))\n\nvecSize :: Int\nvecSize = UV.length input * 10_000\n\noffset :: Int\noffset = UV.take 7 input & UV.toList & concatMap show & read\n\ninputFromOffset :: [Int]\ninputFromOffset = [input UV.! (i `mod` UV.length input) | i <- [offset..vecSize-1]]\n\nmultFromOffset :: [Int] -> [Int]\nmultFromOffset vec = scanr (+) 0 vec & map (`mod` 10)\n\nresult :: [Int]\nresult = take 8 (iterate multFromOffset inputFromOffset !! 100)\n\nmain :: IO ()\nmain = print result", "meta": {"hexsha": "d71b6ed2afbc524c9ea6c5e9f97ffe3c3732a078", "size": 3015, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "2019/day16-2/src/Main.hs", "max_stars_repo_name": "polux/advent-of-code", "max_stars_repo_head_hexsha": "0db7feebab40497ed566a88aa3e6fcba488adc72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-07T15:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T15:57:10.000Z", "max_issues_repo_path": "2019/day16-2/src/Main.hs", "max_issues_repo_name": "polux/advent-of-code", "max_issues_repo_head_hexsha": "0db7feebab40497ed566a88aa3e6fcba488adc72", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2019/day16-2/src/Main.hs", "max_forks_repo_name": "polux/advent-of-code", "max_forks_repo_head_hexsha": "0db7feebab40497ed566a88aa3e6fcba488adc72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0744680851, "max_line_length": 118, "alphanum_fraction": 0.7343283582, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.24295081462946147}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Grenade.Layers.Internal.Pooling (\n    poolForward\n  , poolBackward\n  ) where\n\nimport qualified Data.Vector.Storable as U ( unsafeToForeignPtr0, unsafeFromForeignPtr0 )\n\nimport           Foreign ( mallocForeignPtrArray, withForeignPtr )\nimport           Foreign.Ptr ( Ptr )\n\nimport           Numeric.LinearAlgebra ( Matrix , flatten )\nimport qualified Numeric.LinearAlgebra.Devel as U\n\nimport           System.IO.Unsafe ( unsafePerformIO )\n\npoolForward :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double\npoolForward channels height width kernelRows kernelColumns strideRows strideColumns dataIm =\n  let vec             = flatten dataIm\n      rowOut          = (height - kernelRows) `div` strideRows + 1\n      colOut          = (width - kernelColumns) `div` strideColumns + 1\n      numberOfPatches = rowOut * colOut\n  in unsafePerformIO $ do\n    outPtr <- mallocForeignPtrArray (numberOfPatches * channels)\n    let (inPtr, _) = U.unsafeToForeignPtr0 vec\n\n    withForeignPtr inPtr $ \\inPtr' ->\n      withForeignPtr outPtr $ \\outPtr' ->\n        pool_forwards_cpu inPtr' channels height width kernelRows kernelColumns strideRows strideColumns outPtr'\n\n    let matVec = U.unsafeFromForeignPtr0 outPtr (numberOfPatches * channels)\n    return $ U.matrixFromVector U.RowMajor (rowOut * channels) colOut matVec\n\nforeign import ccall unsafe\n    pool_forwards_cpu\n      :: Ptr Double -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr Double -> IO ()\n\npoolBackward :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double -> Matrix Double\npoolBackward channels height width kernelRows kernelColumns strideRows strideColumns dataIm dataGrad =\n  let vecIm     = flatten dataIm\n      vecGrad   = flatten dataGrad\n  in unsafePerformIO $ do\n    outPtr <- mallocForeignPtrArray (height * width * channels)\n    let (imPtr, _) = U.unsafeToForeignPtr0 vecIm\n    let (gradPtr, _) = U.unsafeToForeignPtr0 vecGrad\n\n    withForeignPtr imPtr $ \\imPtr' ->\n      withForeignPtr gradPtr $ \\gradPtr' ->\n        withForeignPtr outPtr $ \\outPtr' ->\n          pool_backwards_cpu imPtr' gradPtr' channels height width kernelRows kernelColumns strideRows strideColumns outPtr'\n\n    let matVec = U.unsafeFromForeignPtr0 outPtr (height * width * channels)\n    return $ U.matrixFromVector U.RowMajor (height * channels) width matVec\n\nforeign import ccall unsafe\n    pool_backwards_cpu\n      :: Ptr Double -> Ptr Double -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr Double -> IO ()\n", "meta": {"hexsha": "3d21e78d61709dd35c827191e1aa717b36b94058", "size": 2565, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Internal/Pooling.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1527, "max_stars_repo_stars_event_min_datetime": "2016-06-23T13:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T05:22:00.000Z", "max_issues_repo_path": "src/Grenade/Layers/Internal/Pooling.hs", "max_issues_repo_name": "Alien-Inc/grenade", "max_issues_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2016-06-27T22:16:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-20T17:50:09.000Z", "max_forks_repo_path": "src/Grenade/Layers/Internal/Pooling.hs", "max_forks_repo_name": "Alien-Inc/grenade", "max_forks_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2016-06-28T02:24:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:17:29.000Z", "avg_line_length": 44.224137931, "max_line_length": 124, "alphanum_fraction": 0.6951267057, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2429404898682933}}
{"text": "module Type\n    (\n      -- * Types\n      LispVal(..)\n    , LispError(..)\n    , LispEnv\n      -- * Monads\n    , ThrowsError\n    ) where\n\nimport Data.Array (Array, elems)\nimport Data.Complex (Complex(..), imagPart, realPart)\nimport Data.Ratio (numerator, denominator)\n\nimport Data.IORef (IORef)\nimport Text.ParserCombinators.Parsec (ParseError)\n\n-- | Values and code structures for lisp.\ndata LispVal\n    = Symbol String\n    | Integer Integer\n    | Rational Rational\n    | Real Float\n    | Complex (Complex Integer)\n    | Character Char\n    | String String\n    | Boolean Bool\n    | List [LispVal]\n    | DottedList [LispVal] LispVal\n    | Vector (Array Int LispVal)\n    | PrimitiveFunc String\n    | Func [String] (Maybe String) [LispVal] LispEnv\n    deriving (Eq)\n\ninstance Show LispVal where\n    show = showVal\n\n-- | Show the s-expression for LispVal.\nshowVal :: LispVal -> String\nshowVal (Symbol x)        = x\nshowVal (Integer x)       = show x\nshowVal (Rational x)      = show (numerator x) ++ \"/\" ++ show (denominator x)\nshowVal (Real x)          = show x\nshowVal (Complex x)       = show (realPart x) ++ \"+\" ++ show (imagPart x) ++ \"i\"\nshowVal (Character x)     = \"#\\\\\" ++ [x]\nshowVal (String x)        = \"\\\"\" ++ x ++ \"\\\"\"\nshowVal (Boolean True)    = \"#t\"\nshowVal (Boolean False)   = \"#f\"\nshowVal (List xs)         = \"(\" ++ unwordsList xs ++ \")\"\nshowVal (DottedList xs t) = \"(\" ++ unwordsList xs ++ \" . \" ++ showVal t ++ \")\"\nshowVal (Vector xs)       = \"#(\" ++ unwordsList (elems xs) ++ \")\"\nshowVal (PrimitiveFunc n) = \"<primitive \" ++ n ++ \">\"\nshowVal (Func pns vn _ _) =\n    \"(lambda (\" ++ varargText ++ unwords (map show pns) ++ \") ...)\"\n  where\n    varargText = maybe \"\" (\" . \" ++) vn\n\n-- | Errors for evaluating or parsing lisp.\ndata LispError\n    = NumArgs String Integer [LispVal]\n    | TypeMismatch String String LispVal\n    | Parser ParseError\n    | BadSpecialForm String LispVal\n    | NotFunction String String\n    | UnboundVar String String\n    | Default String\n    deriving (Eq)\n\n-- | Show `LispError` as text.\nshowError :: LispError -> String\nshowError (NumArgs fName expected found) =\n    fName ++ \": Expected \" ++ show expected ++ \" arguments, found values \" ++ vs\n  where\n    vs = unwords $ map show found\nshowError (TypeMismatch fName expected found) =\n    fName ++ \": Invalid type: expected \" ++ expected ++ \", found \" ++ show found\nshowError (Parser parseError) = \"Parse error at \" ++ show parseError\nshowError (BadSpecialForm message form) = message ++ \": \" ++ show form\nshowError (NotFunction message fName)   = message ++ \": \" ++ fName\nshowError (UnboundVar message varName)  = message ++ \": \" ++ varName\nshowError (Default message)             = \"Default: \" ++ message\n\ninstance Show LispError where\n    show = showError\n\n-- | Monad for computation with potential `LispError`.\ntype ThrowsError = Either LispError\n\n-- | Environment of mutable `LispVal` bindings.\ntype LispEnv = IORef [(String, IORef LispVal)]\n\n-- | Join the s-expressions of a list of `LispVal` with spaces.\nunwordsList :: [LispVal] -> String\nunwordsList = unwords . map showVal\n", "meta": {"hexsha": "5821d838bb21c8f28f4e5dbe220af2001452a3bd", "size": 3070, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Type.hs", "max_stars_repo_name": "gavinkflam/backspin", "max_stars_repo_head_hexsha": "e1a4e1f2ac7f236c574272fd7d1fcc5fd8c688a2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-08T04:47:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-08T04:47:51.000Z", "max_issues_repo_path": "src/Type.hs", "max_issues_repo_name": "gavinkflam/backspin", "max_issues_repo_head_hexsha": "e1a4e1f2ac7f236c574272fd7d1fcc5fd8c688a2", "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/Type.hs", "max_forks_repo_name": "gavinkflam/backspin", "max_forks_repo_head_hexsha": "e1a4e1f2ac7f236c574272fd7d1fcc5fd8c688a2", "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": 32.3157894737, "max_line_length": 80, "alphanum_fraction": 0.6332247557, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.242835315677398}}
{"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 DeriveDataTypeable, FlexibleContexts, Rank2Types #-}\n{-# OPTIONS_HADDOCK hide #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module     : Numeric.LinearAlgebra.Matrix.STBase\n-- Copyright  : Copyright (c) 2010, Patrick Perry <patperry@gmail.com>\n-- License    : BSD3\n-- Maintainer : Patrick Perry <patperry@gmail.com>\n-- Stability  : asinerimental\n--\n\nmodule Numeric.LinearAlgebra.Matrix.STBase\n    where\n      \nimport Control.Monad( forM_, when )\nimport Control.Monad.ST( ST, RealWorld, runST, unsafeInterleaveST,\n    unsafeIOToST )\nimport Data.Maybe( fromMaybe )\nimport Data.Typeable( Typeable )\nimport Foreign( Ptr, advancePtr, peek, peekElemOff, pokeElemOff,\n    mallocForeignPtrArray )\nimport Text.Printf( printf )\nimport Unsafe.Coerce( unsafeCoerce )\n\nimport Numeric.LinearAlgebra.Types\nimport qualified Foreign.BLAS as BLAS\nimport Numeric.LinearAlgebra.Matrix.Base hiding ( unsafeWith,\n    unsafeToForeignPtr, unsafeFromForeignPtr, )\nimport qualified Numeric.LinearAlgebra.Matrix.Base as M\nimport Numeric.LinearAlgebra.Vector( STVector, RVector )\nimport qualified Numeric.LinearAlgebra.Vector as V\n\n-- | Mutable dense matrices in the 'ST' monad.\nnewtype STMatrix s e = STMatrix { unSTMatrix :: Matrix e }\n    deriving (Typeable)\n\n-- | Mutable dense matrices in the 'IO' monad.\ntype IOMatrix = STMatrix RealWorld\n\n-- | A safe way to create and work with a mutable matrix before returning \n-- an immutable matrix for later perusal. This function avoids copying\n-- the matrix before returning it - it uses 'unsafeFreeze' internally,\n-- but this wrapper is a safe interface to that function. \ncreate :: (Storable e) => (forall s . ST s (STMatrix s e)) -> Matrix e\ncreate mx = runST $ mx >>= unsafeFreeze\n{-# INLINE create #-}\n\n-- | Converts a mutable matrix to an immutable one by taking a complete\n-- copy of it.\nfreeze :: (RMatrix m, Storable e) => m e -> ST s (Matrix e)\nfreeze a = do\n    a' <- newCopy a\n    unsafeFreeze a'\n{-# INLINE freeze #-}\n\n\n-- | Read-only matrices\nclass RMatrix m where\n    -- | Get the dimensions of the matrix (number of rows and columns).\n    getDim :: (Storable e) => m e -> ST s (Int,Int)\n    \n    -- | Same as 'withCol' but does not range-check index.\n    unsafeWithCol :: (Storable e)\n                  => m e\n                  -> Int \n                  -> (forall v. RVector v => v e -> ST s a)\n                  -> ST s a\n\n    -- | Perform an action with a list of views of the matrix columns.\n    withCols :: (Storable e)\n                 => m e\n                 -> (forall v . RVector v => [v e] -> ST s a)\n                 -> ST s a\n\n    -- | Same as 'withSlice' but does not range-check index.\n    unsafeWithSlice :: (Storable e)\n                    => (Int,Int)\n                    -> (Int,Int)\n                    -> m e\n                    -> (forall m'. RMatrix m' => m' e -> ST s a)\n                    -> ST s a\n\n    -- | Possibly view a matrix as a vector and perform an action on the\n    -- view.  This only succeeds if the matrix is stored contiguously in\n    -- memory, i.e. if the matrix contains a single column or the \\\"lda\\\"\n    -- of the matrix is equal to the number of rows.\n    maybeWithVector :: (Storable e)\n                    => m e\n                    -> (forall v . RVector v => v e -> ST s a)\n                    -> Maybe (ST s a)\n\n    -- | Converts a read-only matrix into an immutable matrix. This simply\n    -- casts the matrix from one type to the other without copying.\n    -- Note that because the matrix is possibly not copied, any subsequent\n    -- modifications made to the read-only version of the matrix may be shared\n    -- with the immutable version. It is safe to use, therefore, if the\n    -- read-only version is never modified after the freeze operation.\n    unsafeFreeze :: (Storable e) => m e -> ST s (Matrix e)\n\n    -- | Unsafe cast from a read-only matrix to a mutable matrix.\n    unsafeThaw :: (Storable e)\n               => m e -> ST s (STMatrix s e)\n\n    -- | Execute an 'IO' action with a pointer to the first element in the\n    -- matrix and the leading dimension (lda).\n    unsafeWith :: (Storable e) => m e -> (Ptr e -> Int -> IO a) -> IO a\n\ninstance RMatrix Matrix where\n    getDim = return . dim\n    {-# INLINE getDim #-}\n    unsafeWithCol a j f = f (unsafeCol a j)\n    {-# INLINE unsafeWithCol #-}\n    withCols a f = f (cols a)\n    {-# INLINE withCols #-}\n    unsafeWithSlice ij mn a f = f (unsafeSlice ij mn a)\n    {-# INLINE unsafeWithSlice #-}\n    maybeWithVector a f | isContig a = Just $ f (toVector a)\n                        | otherwise = Nothing\n    {-# INLINE maybeWithVector #-}\n    unsafeWith = M.unsafeWith\n    {-# INLINE unsafeWith #-}\n    unsafeFreeze = return\n    {-# INLINE unsafeFreeze #-}\n    unsafeThaw = return . STMatrix\n    {-# INLINE unsafeThaw #-}\n\n\ninstance RMatrix (STMatrix s) where\n    getDim = return . dim . unSTMatrix\n    {-# INLINE getDim #-}\n    unsafeWithCol = unsafeWithCol . unSTMatrix\n    {-# INLINE unsafeWithCol #-}\n    withCols = withCols . unSTMatrix\n    {-# INLINE withCols #-}\n    unsafeWithSlice ij mn = unsafeWithSlice ij mn . unSTMatrix\n    {-# INLINE unsafeWithSlice #-}\n    maybeWithVector = maybeWithVector . unSTMatrix\n    {-# INLINE maybeWithVector #-}\n    unsafeWith = unsafeWith . unSTMatrix\n    {-# INLINE unsafeWith #-}\n    unsafeFreeze = return . unSTMatrix\n    {-# INLINE unsafeFreeze #-}\n    unsafeThaw v = return $ cast v\n      where\n        cast :: STMatrix s e -> STMatrix s' e\n        cast = unsafeCoerce\n    {-# INLINE unsafeThaw #-}\n\n\n\n-- | Perform an action with a view of a mutable matrix column\n-- (no index checking).\nunsafeWithColM :: (Storable e)\n               => STMatrix s e\n               -> Int\n               -> (STVector s e -> ST s a)\n               -> ST s a\nunsafeWithColM a j f = \n    unsafeWithCol a j $ \\c -> do\n        mc <- V.unsafeThaw c\n        f mc\n{-# INLINE unsafeWithColM #-}\n\n-- | Perform an action with a list of views of the mutable matrix columns. See\n-- also 'withCols'.\nwithColsM :: (Storable e)\n               => STMatrix s e\n               -> ([STVector s e] -> ST s a)\n               -> ST s a\nwithColsM a f =\n    withCols a $ \\cs -> do\n        mcs <- thawVecs cs\n        f mcs\n  where\n    thawVecs [] = return []\n    thawVecs (c:cs) = unsafeInterleaveST $ do\n        mc <- V.unsafeThaw c\n        mcs <- thawVecs cs\n        return $ mc:mcs\n{-# INLINE withColsM #-}\n\n\n-- | Possibly view a matrix as a vector and perform an action on the\n-- view.  This succeeds when the matrix is stored contiguously in memory,\n-- i.e. if the matrix contains a single column or the \\\"lda\\\" of the matrix\n-- is equal to the number of rows.  See also 'maybeWithVector'.\nmaybeWithVectorM :: (Storable e)\n                 => STMatrix s e\n                 -> (STVector s e -> ST s a)\n                 -> Maybe (ST s a)\nmaybeWithVectorM a f = \n    maybeWithVector a $ \\v -> do\n        mv <- V.unsafeThaw v\n        f mv\n{-# INLINE maybeWithVectorM #-}\n\n\n-- | View a vector as a matrix of the given shape and pass it to\n-- the specified function.\nwithFromVector :: (RVector v, Storable e)\n                   => (Int,Int)\n                   -> v e\n                   -> (forall m . RMatrix m => m e -> ST s a)\n                   -> ST s a\nwithFromVector mn@(m,n) v f = do\n    nv <- V.getDim v\n    when (nv /= m*n) $ error $\n        printf (\"withFromVector (%d,%d) <vector with dim %d>:\"\n                ++ \" dimension mismatch\") m n nv\n    iv <- V.unsafeFreeze v\n    f $ fromVector mn iv\n{-# INLINE withFromVector #-}\n\n\n-- | View a mutable vector as a mutable matrix of the given shape and pass it\n-- to the specified function.\nwithFromVectorM :: (Storable e)\n                     => (Int,Int)\n                     -> STVector s e\n                     -> (STMatrix s e -> ST s a)\n                     -> ST s a\nwithFromVectorM mn@(m,n) v f = do\n    nv <- V.getDim v\n    when (nv /= m*n) $ error $\n        printf (\"withFromVectorM (%d,%d) <vector with dim %d>:\"\n                ++ \" dimension mismatch\") m n nv\n    withFromVector mn v $ \\a -> do\n        ma <- unsafeThaw a\n        f ma\n{-# INLINE withFromVectorM #-}\n\n\n-- | View a vector as a matrix with one column and pass it to\n-- the specified function.\nwithFromCol :: (RVector v, Storable e)\n                => v e\n                -> (forall m . RMatrix m => m e -> ST s a)\n                -> ST s a\nwithFromCol v f = do\n    m <- V.getDim v\n    withFromVector (m,1) v f\n{-# INLINE withFromCol #-}\n\n\n-- | View a mutable vector as a mutable matrix with one column and pass it to\n-- the specified function.\nwithFromColM :: (Storable e)\n                  => STVector s e\n                  -> (STMatrix s e -> ST s a)\n                  -> ST s a\nwithFromColM v f = do\n    m <- V.getDim v\n    withFromVectorM (m, 1) v f\n{-# INLINE withFromColM #-}\n\n\n-- | View a vector as a matrix with one row and pass it to\n-- the specified function.\nwithFromRow :: (RVector v, Storable e)\n                => v e\n                -> (forall m . RMatrix m => m e -> ST s a)\n                -> ST s a\nwithFromRow v f = do\n    n <- V.getDim v\n    withFromVector (1,n) v f\n{-# INLINE withFromRow #-}\n\n-- | View a mutable vector as a mutable matrix with one row and pass it to\n-- the specified function.\nwithFromRowM :: (Storable e)\n                  => STVector s e\n                  -> (STMatrix s e -> ST s a)\n                  -> ST s a\nwithFromRowM v f = do\n    n <- V.getDim v\n    withFromVectorM (1,n) v f\n{-# INLINE withFromRowM #-}\n\n-- | Perform an action with a view of a matrix column.\nwithCol :: (RMatrix m, Storable e)\n            => m e\n            -> Int\n            -> (forall v . RVector v => v e -> ST s a)\n            -> ST s a\nwithCol a j f = do\n    (m,n) <- getDim a\n    when (j < 0 || j >= n) $ error $\n        printf (\"withCol <matrix with dim (%d,%d)> %d:\"\n                ++ \" index out of range\") m n j\n\n    unsafeWithCol a j f\n{-# INLINE withCol #-}\n\n-- | Like 'withCol', but perform the action with a mutable view.\nwithColM :: (Storable e)\n         => STMatrix s e\n         -> Int\n         -> (STVector s e -> ST s a)\n         -> ST s a\nwithColM a j f = do\n    (m,n) <- getDim a\n    when (j < 0 || j >= n) $ error $\n        printf (\"withColM <matrix with dim (%d,%d)> %d:\"\n                ++ \" index out of range\") m n j\n\n    unsafeWithColM a j f\n{-# INLINE withColM #-}\n\n-- | Create a new matrix of given shape, but do not initialize the elements.\nnew_ :: (Storable e) => (Int,Int) -> ST s (STMatrix s e)\nnew_ (m,n) \n    | m < 0 || n < 0 = error $\n        printf \"new_ (%d,%d): invalid dimensions\" m n\n    | otherwise = unsafeIOToST $ do\n        f <- mallocForeignPtrArray (m*n)\n        return $ STMatrix $ M.unsafeFromForeignPtr f 0 (m,n) (max 1 m)\n\n-- | Create a matrix with every element initialized to the same value.\nnew :: (Storable e) => (Int,Int) -> e -> ST s (STMatrix s e)\nnew (m,n) e = do\n    a <- new_ (m,n)\n    setElems a $ replicate (m*n) e\n    return a\n\n-- | Creates a new matrix by copying another one.    \nnewCopy :: (RMatrix m, Storable e) => m e -> ST s (STMatrix s e)\nnewCopy a = do\n    mn <- getDim a\n    b <- new_ mn\n    unsafeCopyTo b a\n    return b\n\n-- | @copyTo dst src@ replaces the values in @dst@ with those in\n-- source.  The operands must be the same shape.\ncopyTo :: (RMatrix m, Storable e) => STMatrix s e -> m e -> ST s ()\ncopyTo = checkOp2 \"copyTo\" unsafeCopyTo\n{-# INLINE copyTo #-}\n\n-- | Same as 'copyTo' but does not range-check indices.\nunsafeCopyTo :: (RMatrix m, Storable e) => STMatrix s e -> m e -> ST s ()\nunsafeCopyTo = vectorOp2 V.unsafeCopyTo\n{-# INLINE unsafeCopyTo #-}\n\n-- | Get the indices of the elements in the matrix, in column-major order.\ngetIndices :: (RMatrix m, Storable e) => m e -> ST s [(Int,Int)]\ngetIndices a = do\n    (m,n) <- getDim a\n    return $ [ (i,j) | j <- [ 0..n-1 ], i <- [ 0..m-1 ] ]\n  \n-- | Lazily get the elements of the matrix, in column-major order.  \ngetElems :: (RMatrix m, Storable e) => m e -> ST s [e]\ngetElems a = case maybeWithVector a V.getElems of\n    Just es -> es\n    Nothing -> withCols a $ \\xs ->\n                   concat `fmap` mapM V.getElems xs\n\n-- | Get the elements of the matrix, in column-major order.\ngetElems' :: (RMatrix m, Storable e) => m e -> ST s [e]\ngetElems' a = case maybeWithVector a V.getElems' of\n    Just es -> es\n    Nothing -> withCols a $ \\xs ->\n                   concat `fmap` mapM V.getElems' xs\n\n-- | Lazily get the association list of the matrix, in column-major order.\ngetAssocs :: (RMatrix m, Storable e) => m e -> ST s [((Int,Int),e)]\ngetAssocs a = do\n    is <- getIndices a\n    es <- getElems a\n    return $ zip is es\n\n-- | Get the association list of the matrix, in column-major order.\ngetAssocs' :: (RMatrix m, Storable e) => m e -> ST s [((Int,Int),e)]\ngetAssocs' a = do\n    is <- getIndices a\n    es <- getElems' a\n    return $ zip is es\n\n-- | Set all of the values of the matrix from the elements in the list,\n-- in column-major order.\nsetElems :: (Storable e) => STMatrix s e -> [e] -> ST s ()\nsetElems a es =\n    case maybeWithVectorM a (`V.setElems` es) of\n        Just st  -> st\n        Nothing -> do\n            (m,n) <- getDim a\n            go m n 0 es\n  where\n    go _ n j [] | j == n = return ()\n    go m n j [] | j < n = error $ \n        printf (\"setElems <matrix with dim (%d,%d>\"\n                ++ \"<list with length %d>: not enough elements)\") m n (j*m)\n    go m n j es' =\n        let (es1', es2') = splitAt m es'\n        in do\n            withColM a j (`V.setElems` es1')\n            go m n (j+1) es2'\n\n-- | Set the given values in the matrix.  If an index is repeated twice,\n-- the value is implementation-defined.\nsetAssocs :: (Storable e) => STMatrix s e -> [((Int,Int),e)] -> ST s ()\nsetAssocs a ies =\n    sequence_ [ write a i e | (i,e) <- ies ]\n\n-- | Same as 'setAssocs' but does not range-check indices.\nunsafeSetAssocs :: (Storable e) => STMatrix s e -> [((Int,Int),e)] -> ST s ()\nunsafeSetAssocs a ies =\n    sequence_ [ unsafeWrite a i e | (i,e) <- ies ]\n\n-- | Set the specified row of the matrix to the given vector.\nsetRow :: (RVector v, Storable e)\n       => STMatrix s e -> Int -> v e -> ST s ()\nsetRow a i x = do\n    (m,n) <- getDim a\n    nx <- V.getDim x\n    \n    when (i < 0 || i >= m) $ error $\n        printf (\"setRow <matrix with dim (%d,%d)> %d:\"\n                ++ \" index out of range\") m n i\n    when (nx /= n) $ error $\n        printf (\"setRow <matrix with dim (%d,%d)> _\"\n                ++ \" <vector with dim %d>:\"\n                ++ \" dimension mismatch\") m n nx\n\n    unsafeSetRow a i x\n{-# INLINE setRow #-}\n\n-- | Same as 'setRow' but does not range-check index or check\n-- vector dimension.\nunsafeSetRow :: (RVector v, Storable e)\n             => STMatrix s e -> Int -> v e -> ST s ()\nunsafeSetRow a i x = do\n    jes <- V.getAssocs x\n    sequence_ [ unsafeWrite a (i,j) e | (j,e) <- jes ]\n{-# INLINE unsafeSetRow #-}\n\n-- | Exchange corresponding elements in the given rows.\nswapRows :: (BLAS1 e)\n         => STMatrix s e -> Int -> Int -> ST s ()\nswapRows a i1 i2 = do\n    (m,n) <- getDim a\n    when (i1 < 0 || i1 >= m || i2 < 0 || i2 >= m) $ error $\n        printf (\"swapRows <matrix with dim (%d,%d)> %d %d\"\n                ++ \": index out of range\") m n i1 i2\n    unsafeSwapRows a i1 i2\n\n-- | Same as 'swapRows' but does not range-check indices.\nunsafeSwapRows :: (BLAS1 e)\n               => STMatrix s e -> Int -> Int -> ST s ()\nunsafeSwapRows a i1 i2 = when (i1 /= i2) $ do\n    (_,n) <- getDim a\n    unsafeIOToST $\n        unsafeWith a $ \\pa lda ->\n            let px = pa `advancePtr` i1\n                py = pa `advancePtr` i2\n                incx = lda\n                incy = lda\n            in\n                BLAS.swap n px incx py incy\n\n-- | Exchange corresponding elements in the given columns.\nswapCols :: (BLAS1 e)\n         => STMatrix s e -> Int -> Int -> ST s ()\nswapCols a j1 j2 = do\n    (m,n) <- getDim a\n    when (j1 < 0 || j1 >= n || j2 < 0 || j2 >= n) $ error $\n        printf (\"swapCols <matrix with dim (%d,%d)> %d %d\"\n                ++ \": index out of range\") m n j1 j2\n    unsafeSwapCols a j1 j2\n\n-- | Same as 'swapCols' but does not range-check indices.\nunsafeSwapCols :: (BLAS1 e)\n               => STMatrix s e -> Int -> Int -> ST s ()\nunsafeSwapCols a j1 j2 = when (j1 /= j2) $ do\n    (m,_) <- getDim a\n    unsafeIOToST $\n        unsafeWith a $ \\pa lda ->\n            let px = pa `advancePtr` (j1*lda)\n                py = pa `advancePtr` (j2*lda)\n                incx = 1\n                incy = 1\n            in\n                BLAS.swap m px incx py incy\n\n-- | Copy the specified row of the matrix to the vector.\nrowTo :: (RMatrix m, Storable e)\n         => STVector s e -> m e -> Int -> ST s ()\nrowTo x a i = do\n    (m,n) <- getDim a\n    nx <- V.getDim x\n    when (i < 0 || i >= m) $ error $\n        printf (\"rowTo\"\n               ++ \" _\"\n               ++ \" <matrix with dim (%d,%d)>\"\n               ++ \" %d:\"\n               ++ \": index out of range\"\n               ) m n i\n    when (nx /= n) $ error $\n        printf (\"rowTo\"\n                ++ \" <vector with dim %d>\"\n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \" _\"\n                ++ \": dimension mismatch\") nx m n\n\n    unsafeRowTo x a i\n{-# INLINE rowTo #-}\n\n-- | Same as 'rowTo' but does not range-check index or check dimension.\nunsafeRowTo :: (RMatrix m, Storable e)\n            =>  STVector s e -> m e -> Int ->ST s ()\nunsafeRowTo x a i = do\n    (_,n) <- getDim a\n    forM_ [ 0..n-1 ] $ \\j -> do\n        e <- unsafeRead a (i,j)\n        V.unsafeWrite x j e\n{-# INLINE unsafeRowTo #-}\n\n-- | Set the diagonal of the matrix to the given vector.\nsetDiag :: (RVector v, Storable e)\n        => STMatrix s e -> v e -> ST s ()\nsetDiag a x = do\n    (m,n) <- getDim a\n    nx <- V.getDim x\n    let mn = min m n\n    \n    when (nx /= mn) $ error $\n        printf (\"setRow <matrix with dim (%d,%d)>\"\n                ++ \" <vector with dim %d>:\"\n                ++ \" dimension mismatch\") m n nx\n\n    unsafeSetDiag a x\n{-# INLINE setDiag #-}\n\n-- | Same as 'setDiag' but does not range-check index or check dimension.\nunsafeSetDiag :: (RVector v, Storable e)\n              => STMatrix s e -> v e -> ST s ()\nunsafeSetDiag a x = do\n    ies <- V.getAssocs x\n    sequence_ [ unsafeWrite a (i,i) e | (i,e) <- ies ]\n{-# INLINE unsafeSetDiag #-}\n\n-- | Copy the diagonal of the matrix to the vector.\ndiagTo :: (RMatrix m, Storable e)\n       => STVector s e -> m e -> ST s ()\ndiagTo x a = do\n    nx <- V.getDim x\n    (m,n) <- getDim a\n    let mn = min m n\n    \n    when (nx /= mn) $ error $\n        printf (\"diagTo\"\n                ++ \" <vector with dim %d>\"\n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \": dimension mismatch\") nx m n\n\n    unsafeDiagTo x a\n{-# INLINE diagTo #-}\n\n-- | Same as 'diagTo' but does not range-check index or check dimensions.\nunsafeDiagTo :: (RMatrix m, Storable e)\n             => STVector s e -> m e -> ST s ()\nunsafeDiagTo x a = do\n    (m,n) <- getDim a\n    let mn = min m n\n    forM_ [ 0..mn-1 ] $ \\i -> do\n        e <- unsafeRead a (i,i)\n        V.unsafeWrite x i e\n{-# INLINE unsafeDiagTo #-}\n\n-- | Get the element stored at the given index.\nread :: (RMatrix m, Storable e) => m e -> (Int,Int) -> ST s e\nread a (i,j) = do\n    (m,n) <- getDim a\n    when (i < 0 || i >= m || j < 0 || j >= n) $ error $\n        printf (\"read <matrix with dim (%d,%d)> (%d,%d):\"\n                ++ \" index out of range\") m n i j\n    unsafeRead a (i,j)\n{-# INLINE read #-}\n\n-- | Same as 'read' but does not range-check index.\nunsafeRead :: (RMatrix m, Storable e) => m e -> (Int,Int) -> ST s e\nunsafeRead a (i,j) = unsafeIOToST $\n    unsafeWith a $ \\p lda ->\n        peekElemOff p (i + j * lda)\n{-# INLINE unsafeRead #-}\n\n-- | Set the element stored at the given index.\nwrite :: (Storable e)\n      => STMatrix s e -> (Int,Int) -> e -> ST s ()\nwrite a (i,j) e = do\n    (m,n) <- getDim a\n    when (i < 0 || i >= m || j < 0 || j >= n) $ error $\n        printf (\"write <matrix with dim (%d,%d)> (%d,%d):\"\n                ++ \" index out of range\") m n i j\n    unsafeWrite a (i,j) e\n    \n{-# INLINE write #-}\n\n-- | Same as 'write' but does not range-check index.\nunsafeWrite :: (Storable e)\n            => STMatrix s e -> (Int,Int) -> e -> ST s ()\nunsafeWrite a (i,j) e = unsafeIOToST $\n    unsafeWith a $ \\p lda ->\n        pokeElemOff p (i + j * lda) e\n{-# INLINE unsafeWrite #-}\n\n-- | Modify the element stored at the given index.\nmodify :: (Storable e)\n       => STMatrix s e -> (Int,Int) -> (e -> e) -> ST s ()\nmodify a (i,j) f = do\n    (m,n) <- getDim a\n    when (i < 0 || i >= m || j < 0 || j >= n) $ error $\n        printf (\"modify <matrix with dim (%d,%d)> (%d,%d):\"\n                ++ \" index out of range\") m n i j\n    unsafeModify a (i,j) f\n{-# INLINE modify #-}\n\n-- | Same as 'modify' but does not range-check index.\nunsafeModify :: (Storable e)\n             => STMatrix s e -> (Int,Int) -> (e -> e) -> ST s ()\nunsafeModify a (i,j) f = unsafeIOToST $\n    unsafeWith a $ \\p lda -> \n        let o = i + j * lda\n        in do\n            e <- peekElemOff p o\n            pokeElemOff p o $ f e\n{-# INLINE unsafeModify #-}\n\n-- | @mapTo dst f src@ replaces @dst@ elementwise with @f(src)@.\nmapTo :: (RMatrix m, Storable e, Storable f)\n      => STMatrix s f\n      -> (e -> f)\n      -> m e\n      -> ST s ()\nmapTo dst f src = (checkOp2 \"mapTo _\" $ \\z x -> unsafeMapTo z f x) dst src\n{-# INLINE mapTo #-}\n             \n-- | Same as 'mapTo' but does not check dimensions.\nunsafeMapTo :: (RMatrix m, Storable e, Storable f)\n            => STMatrix s f\n            -> (e -> f)\n            -> m e\n            -> ST s ()\nunsafeMapTo dst f src =\n    fromMaybe colwise $ maybeWithVectorM dst $ \\vdst ->\n    fromMaybe colwise $ maybeWithVector  src $ \\vsrc ->\n        V.unsafeMapTo vdst f vsrc\n  where\n    colwise = withColsM dst $ \\zs ->\n              withCols   src $ \\xs ->\n                  sequence_ [ V.unsafeMapTo z f x\n                            | (z,x) <- zip zs xs\n                            ]\n\n-- | @zipWithTo dst f x y@ replaces @dst@ elementwise with @f(x, y)@.\nzipWithTo :: (RMatrix m1, RMatrix m2, Storable e1, Storable e2, Storable f)\n          => STMatrix s f\n          -> (e1 -> e2 -> f)\n          -> m1 e1\n          -> m2 e2\n          -> ST s ()\nzipWithTo dst f x y = \n    (checkOp3 \"zipWithTo _\" $ \\dst1 x1 y1 -> unsafeZipWithTo dst1 f x1 y1)\n        dst x y\n{-# INLINE zipWithTo #-}\n\n-- | Same as 'zipWithTo' but does not check dimensions.\nunsafeZipWithTo :: (RMatrix m1, RMatrix m2, Storable e1, Storable e2, Storable f)\n                => STMatrix s f\n                -> (e1 -> e2 -> f)\n                -> m1 e1\n                -> m2 e2\n                -> ST s ()\nunsafeZipWithTo dst f x y =\n    fromMaybe colwise $ maybeWithVectorM dst $ \\vdst ->\n    fromMaybe colwise $ maybeWithVector    x $ \\vx ->\n    fromMaybe colwise $ maybeWithVector    y $ \\vy ->\n        V.unsafeZipWithTo vdst f vx vy\n  where\n    colwise = withColsM dst $ \\vdsts ->\n              withCols   x $ \\vxs ->\n              withCols   y $ \\vys ->\n              \n                  sequence_ [ V.unsafeZipWithTo vdst f vx vy\n                            | (vdst,vx,vy) <- zip3 vdsts vxs vys\n                            ]\n\n-- | Set every element in the matrix to a default value.  For\n-- standard numeric types (including 'Double', 'Complex Double', and 'Int'),\n-- the default value is '0'.\nclear :: (Storable e) => STMatrix s e -> ST s ()\nclear a = fromMaybe colwise $ maybeWithVectorM a V.clear\n  where\n    colwise = withColsM a $ mapM_ V.clear\n\n-- | @withSlice (i,j) (m,n) a@ performs an action with a view of the\n-- submatrix of @a@ starting at index @(i,j)@ and having dimension @(m,n)@.\nwithSlice :: (RMatrix m, Storable e)\n          => (Int,Int)\n          -> (Int,Int)\n          -> m e\n          -> (forall m'. RMatrix m' => m' e -> ST s a)\n          -> ST s a\nwithSlice ij mn a f = do\n    ia <- unsafeFreeze a\n    f $ slice ij mn ia\n\n-- | Like 'withSlice', but perform the action with a mutable view.\nwithSliceM :: (Storable e)\n           => (Int,Int)\n           -> (Int,Int)\n           -> STMatrix s e\n           -> (STMatrix s e -> ST s a)\n           -> ST s a\nwithSliceM ij mn a f =\n    withSlice ij mn a $ \\a' -> do\n        ma <- unsafeThaw a'\n        f ma\n\n-- | Perform an action with a view gotten from taking the given number of\n-- rows from the start of the matrix.\nwithTakeRows :: (RMatrix m, Storable e)\n             => Int\n             -> m e\n             -> (forall m'. RMatrix m' => m' e -> ST s a)\n             -> ST s a\nwithTakeRows i a f = do\n    ia <- unsafeFreeze a\n    f $ takeRows i ia\n\n-- | Like 'withTakeRows', but perform the action with a mutable view.\nwithTakeRowsM :: (Storable e)\n              => Int\n              -> STMatrix s e\n              -> (STMatrix s e -> ST s a)\n              -> ST s a\nwithTakeRowsM i a f =\n    withTakeRows i a $ \\a' -> do\n        ma <- unsafeThaw a'\n        f ma\n\n-- | Perform an action with a view gotten from dropping the given number of\n-- rows from the start of the matrix.\nwithDropRows :: (RMatrix m, Storable e)\n             => Int\n             -> m e\n             -> (forall m'. RMatrix m' => m' e -> ST s a)\n             -> ST s a\nwithDropRows n a f = do\n    ia <- unsafeFreeze a\n    f $ dropRows n ia\n\n-- | Like 'withDropRows', but perform the action with a mutable view.\nwithDropRowsM :: (Storable e)\n              => Int\n              -> STMatrix s e\n              -> (STMatrix s e -> ST s a)\n              -> ST s a\nwithDropRowsM i a f =\n    withDropRows i a $ \\a' -> do\n        ma <- unsafeThaw a'\n        f ma\n\n-- | Perform an action with views from splitting the matrix rows at the given\n-- index.\nwithSplitRowsAt :: (RMatrix m, Storable e)\n                => Int\n                -> m e\n                -> (forall m1 m2. (RMatrix m1, RMatrix m2) => m1 e -> m2 e -> ST s a)\n                -> ST s a\nwithSplitRowsAt i a f = do\n    ia <- unsafeFreeze a\n    uncurry f $ splitRowsAt i ia\n\n-- | Like 'withSplitRowsAt', but perform the action with a mutable view.\nwithSplitRowsAtM :: (Storable e)\n                 => Int\n                 -> STMatrix s e\n                 -> (STMatrix s e -> STMatrix s e -> ST s a)\n                 -> ST s a\nwithSplitRowsAtM i a f =\n    withSplitRowsAt i a $ \\a1' a2' -> do\n        ma1 <- unsafeThaw a1'\n        ma2 <- unsafeThaw a2'        \n        f ma1 ma2\n    \n-- | Perform an action with a view gotten from taking the given number of\n-- columns from the start of the matrix.\nwithTakeCols :: (RMatrix m, Storable e)\n             => Int\n             -> m e\n             -> (forall m'. RMatrix m' => m' e -> ST s a)\n             -> ST s a\nwithTakeCols i a f = do\n    ia <- unsafeFreeze a\n    f $ takeCols i ia\n\n-- | Like 'withTakeCols', but perform the action with a mutable view.\nwithTakeColsM :: (Storable e)\n              => Int\n              -> STMatrix s e\n              -> (STMatrix s e -> ST s a)\n              -> ST s a\nwithTakeColsM i a f =\n    withTakeCols i a $ \\a' -> do\n        ma <- unsafeThaw a'\n        f ma\n\n-- | Perform an action with a view gotten from dropping the given number of\n-- columns from the start of the matrix.\nwithDropCols :: (RMatrix m, Storable e)\n             => Int\n             -> m e\n             -> (forall m'. RMatrix m' => m' e -> ST s a)\n             -> ST s a\nwithDropCols n a f = do\n    ia <- unsafeFreeze a\n    f $ dropCols n ia\n\n-- | Like 'withDropCols', but perform the action with a mutable view.\nwithDropColsM :: (Storable e)\n              => Int\n              -> STMatrix s e\n              -> (STMatrix s e -> ST s a)\n              -> ST s a\nwithDropColsM i a f =\n    withDropCols i a $ \\a' -> do\n        ma <- unsafeThaw a'\n        f ma\n\n-- | Perform an action with views from splitting the matrix columns at the given\n-- index.\nwithSplitColsAt :: (RMatrix m, Storable e)\n                => Int\n                -> m e\n                -> (forall m1 m2. (RMatrix m1, RMatrix m2) => m1 e -> m2 e -> ST s a)\n                -> ST s a\nwithSplitColsAt i a f = do\n    ia <- unsafeFreeze a\n    uncurry f $ splitColsAt i ia\n\n-- | Like 'withSplitColsAt', but perform the action with mutable views.    \nwithSplitColsAtM :: (Storable e)\n                 => Int\n                 -> STMatrix s e\n                 -> (STMatrix s e -> STMatrix s e -> ST s a)\n                 -> ST s a\nwithSplitColsAtM i a f =\n    withSplitColsAt i a $ \\a1' a2' -> do\n        ma1 <- unsafeThaw a1'\n        ma2 <- unsafeThaw a2'        \n        f ma1 ma2\n\n\n-- | Add a vector to the diagonal of a matrix.\nshiftDiagM_ :: (RVector v, BLAS1 e)\n              => v e -> STMatrix s e -> ST s ()\nshiftDiagM_ s a = do\n    (m,n) <- getDim a\n    ns <- V.getDim s\n    let mn = min m n\n    \n    when (ns /= mn) $ error $\n        printf (\"shiftDiagM_\"\n                ++ \" <vector with dim %d>\"\n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \": dimension mismatch\")\n                ns\n                m n\n    \n    shiftDiagWithScaleM_ 1 s a\n    \n\n-- | Add a scaled vector to the diagonal of a matrix.\nshiftDiagWithScaleM_ :: (RVector v, BLAS1 e)\n                       => e -> v e -> STMatrix s e -> ST s ()\nshiftDiagWithScaleM_ e s a = do\n    (m,n) <- getDim a\n    ns <- V.getDim s\n    let mn = min m n\n\n    when (ns /= mn) $ error $\n        printf (\"shiftDiagWithScaleM_\"\n                ++ \" _\"\n                ++ \" <vector with dim %d>\"\n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \": dimension mismatch\")\n                ns\n                m n\n\n    unsafeIOToST $\n        V.unsafeWith s $ \\ps ->\n        unsafeWith a $ \\pa lda ->\n            BLAS.axpy mn e ps 1 pa (lda+1)\n\n\n-- | Add two matrices.\naddTo :: (RMatrix m1, RMatrix m2, VNum e)\n      =>  STMatrix s e -> m1 e -> m2 e -> ST s ()\naddTo = checkOp3 \"addTo\" $ vectorOp3 V.addTo\n\n-- | Subtract two matrices.\nsubTo :: (RMatrix m1, RMatrix m2, VNum e)\n      => STMatrix s e -> m1 e -> m2 e -> ST s ()\nsubTo = checkOp3 \"subTo\" $ vectorOp3 V.subTo\n\n-- | Conjugate the entries of a matrix.\nconjugateTo :: (RMatrix m, VNum e)\n            => STMatrix s e -> m e -> ST s ()\nconjugateTo = checkOp2 \"conjugateTo\" $\n    vectorOp2 V.conjugateTo\n\n-- | Negate the entries of a matrix.\nnegateTo :: (RMatrix m, VNum e)\n         => STMatrix s e -> m e -> ST s ()\nnegateTo = checkOp2 \"negateTo\" $\n    vectorOp2 V.negateTo\n\n-- | Scale the entries of a matrix by the given value.\nscaleM_ :: (BLAS1 e)\n          => e -> STMatrix s e -> ST s ()\nscaleM_ e = vectorOp (V.scaleM_ e)\n\n-- | @addWithScaleM_ alpha x y@ sets @y := alpha * x + y@.\naddWithScaleM_ :: (RMatrix m, BLAS1 e)\n               => e -> m e -> STMatrix s e -> ST s ()\naddWithScaleM_ e = checkOp2 \"addWithScaleM_\" $\n    unsafeAddWithScaleM_ e\n\nunsafeAddWithScaleM_ :: (RMatrix m, BLAS1 e)\n                     => e -> m e -> STMatrix s e -> ST s ()\nunsafeAddWithScaleM_ alpha x y =\n    fromMaybe colwise $ maybeWithVector  x $ \\vx ->\n    fromMaybe colwise $ maybeWithVectorM y $ \\vy ->\n        V.unsafeAddWithScaleM_ alpha vx vy\n  where\n    colwise = withCols   x $ \\vxs ->\n              withColsM y $ \\vys ->\n                  sequence_ [ V.unsafeAddWithScaleM_ alpha vx vy\n                            | (vx,vy) <- zip vxs vys ]                \n\n-- | Scale the rows of a matrix; @scaleRowsM_ s a@ sets\n-- @a := diag(s) * a@.\nscaleRowsM_ :: (RVector v, BLAS1 e)\n              => v e -> STMatrix s e -> ST s ()\nscaleRowsM_  s a = do\n    (m,n) <- getDim a\n    ns <- V.getDim s\n    when (ns /= m) $ error $\n        printf (\"scaleRowsM_\"\n                ++ \" <vector with dim %d>\"\n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \": dimension mismatch\")\n                ns\n                m n\n\n    unsafeIOToST $\n        V.unsafeWith s $ \\ps ->\n        unsafeWith a   $ \\pa lda ->\n            go m n lda pa ps 0\n  where\n    go m n lda pa ps i | i == m    = return ()\n                       | otherwise = do\n                             e <- peek ps\n                             BLAS.scal n e pa lda\n                             go m n lda (pa `advancePtr` 1)\n                                        (ps `advancePtr` 1)\n                                        (i+1)\n\n-- | Scale the columns of a matrix; @scaleColBysM_ s a@ sets\n-- @a := a * diag(s)@.\nscaleColsM_ :: (RVector v, BLAS1 e)\n            => v e -> STMatrix s e -> ST s ()\nscaleColsM_ s a = do\n    (m,n) <- getDim a\n    ns <- V.getDim s\n    when (ns /= n) $ error $\n        printf (\"scaleColsM_\"\n                ++ \" <vector with dim %d>\"\n                ++ \" <matrix with dim (%d,%d)>\"        \n                ++ \": dimension mismatch\") \n                ns\n                m n\n\n    es <- V.getElems s\n    withColsM a $ \\xs ->\n        sequence_ [ V.scaleM_ e x\n                  | (e,x) <- zip es xs\n                  ]\n\n\n-- | @rank1UpdateM_ alpha x y a@ sets @a := alpha * x * y^H + a@.\nrank1UpdateM_ :: (RVector v1, RVector v2, BLAS2 e)\n              => e -> v1 e -> v2 e -> STMatrix s e -> ST s ()\nrank1UpdateM_ alpha x y a = do\n    (m,n) <- getDim a    \n    nx <- V.getDim x\n    ny <- V.getDim y\n    \n    when (nx /= m || ny /= n) $ error $\n        printf (\"rank1UpdateTo\"\n                ++ \" _\"\n                ++ \" <vector with dim %d>\"\n                ++ \" <vector with dim %d>\"\n                ++ \": dimension mismatch\"\n                ++ \"<matrix with dim (%d,%d)>\"                )\n                nx\n                ny\n                m n\n    \n    unsafeIOToST $\n        V.unsafeWith x $ \\px ->\n        V.unsafeWith y $ \\py ->\n        unsafeWith a $ \\pa lda ->\n            BLAS.gerc m n alpha px 1 py 1 pa lda\n\n\n-- | @transTo dst a@ sets @dst := trans(a)@.\ntransTo :: (RMatrix m, BLAS1 e)\n        => STMatrix s e\n        -> m e\n        -> ST s ()\ntransTo a' a = do\n    (ma,na) <- getDim a\n    (ma',na') <- getDim a'\n    let (m,n) = (ma,na)\n\n    when ((ma,na) /= (na',ma')) $ error $\n        printf ( \"transTo\"\n               ++ \" <matrix with dim (%d,%d)>\"\n               ++ \" <matrix with dim (%d,%d)>\"\n               ++ \": dimension mismatch\"\n               )\n               ma' na'\n               ma na\n    \n    unsafeIOToST $\n        unsafeWith a' $ \\pa' lda' ->\n        unsafeWith a $ \\pa lda -> let\n            go j px py | j == n = return ()\n                       | otherwise = do\n                           BLAS.copy m px 1 py lda'\n                           go (j+1) (px `advancePtr` lda) (py `advancePtr` 1)\n            in go 0 pa pa'\n\n\n-- | @conjTransTo dst a@ sets @dst := conjugate(trans(a))@.\nconjTransTo :: (RMatrix m, BLAS1 e)\n            => STMatrix s e\n            -> m e\n            -> ST s ()\nconjTransTo a' a = do\n    transTo a' a\n    conjugateTo a' a'\n\n-- | @mulVectorTo dst transa a x@\n-- sets @dst := op(a) * x@, where @op(a)@ is determined by @transa@.                   \nmulVectorTo :: (RMatrix m, RVector v, BLAS2 e)\n            => STVector s e\n            -> Trans -> m e\n            -> v e\n            -> ST s ()\nmulVectorTo dst = mulVectorWithScaleTo dst 1\n\n-- | @mulVectorWithScaleTo dst alpha transa a x@\n-- sets @dst := alpha * op(a) * x@, where @op(a)@ is determined by @transa@.                   \nmulVectorWithScaleTo :: (RMatrix m, RVector v, BLAS2 e)\n                     => STVector s e\n                     -> e\n                     -> Trans -> m e\n                     -> v e\n                     -> ST s ()\nmulVectorWithScaleTo dst alpha t a x =\n    addMulVectorWithScalesM_ alpha t a x 0 dst\n\n-- | @addMulVectorWithScalesM_ alpha transa a x beta y@\n-- sets @y := alpha * op(a) * x + beta * y@, where @op(a)@ is\n-- determined by @transa@.\naddMulVectorWithScalesM_ :: (RMatrix m, RVector v, BLAS2 e)\n                         => e\n                         -> Trans -> m e\n                         -> v e\n                         -> e\n                         -> STVector s e\n                         -> ST s ()\naddMulVectorWithScalesM_ alpha transa a x beta y = do\n    (ma,na) <- getDim a\n    nx <- V.getDim x\n    ny <- V.getDim y\n    let (m,n) = (ny,nx)\n\n    when ((not . and) [ case transa of NoTrans -> (ma,na) == (m,n)\n                                       _       -> (ma,na) == (n,m)\n                      , nx == n\n                      , ny == m\n                      ]) $ error $\n        printf (\"addMulVectorWithScalesTo\"\n                ++ \" _\"\n                ++ \" %s\"\n                ++ \" <matrix with dim (%d,%d)>\" \n                ++ \" <vector with dim %d>\"\n                ++ \" _\"\n                ++ \" <vector with dim %d>\"\n                ++ \": dimension mismatch\")\n               (show transa)\n               ma na\n               nx\n               ny\n\n    unsafeIOToST $\n        unsafeWith a $ \\pa lda ->\n        V.unsafeWith x $ \\px ->\n        V.unsafeWith y $ \\py ->\n            if n == 0\n                then BLAS.scal m beta py 1\n                else BLAS.gemv transa ma na alpha pa lda px 1 beta py 1\n\n-- | @mulMatrixTo dst transa a transb b@\n-- sets @dst := op(a) * op(b)@, where @op(a)@ and @op(b)@ are determined\n-- by @transa@ and @transb@.                   \nmulMatrixTo :: (RMatrix m1, RMatrix m2, BLAS3 e)\n            => STMatrix s e\n            -> Trans -> m1 e\n            -> Trans -> m2 e\n            -> ST s ()\nmulMatrixTo dst = mulMatrixWithScaleTo dst 1\n\n-- | @mulMatrixWithScaleTo alpha transa a transb b c@\n-- sets @c := alpha * op(a) * op(b)@, where @op(a)@ and @op(b)@ are determined\n-- by @transa@ and @transb@.                   \nmulMatrixWithScaleTo :: (RMatrix m1, RMatrix m2, BLAS3 e)\n                     => STMatrix s e\n                     -> e\n                     -> Trans -> m1 e\n                     -> Trans -> m2 e\n                     -> ST s ()\nmulMatrixWithScaleTo dst alpha ta a tb b =\n    addMulMatrixWithScalesM_ alpha ta a tb b 0 dst\n\n-- | @addMulMatrixWithScalesM_ alpha transa a transb b beta c@\n-- sets @c := alpha * op(a) * op(b) + beta * c@, where @op(a)@ and\n-- @op(b)@ are determined by @transa@ and @transb@.\naddMulMatrixWithScalesM_ :: (RMatrix m1, RMatrix m2, BLAS3 e)\n                         => e\n                         -> Trans -> m1 e\n                         -> Trans -> m2 e\n                         -> e\n                         -> STMatrix s e\n                         -> ST s ()\naddMulMatrixWithScalesM_ alpha transa a transb b beta c = do\n    (ma,na) <- getDim a\n    (mb,nb) <- getDim b\n    (mc,nc) <- getDim c\n    let (m,n) = (mc,nc)\n        k = case transa of NoTrans -> na\n                           _       -> ma\n\n    when ((not . and) [ case transa of NoTrans -> (ma,na) == (m,k)\n                                       _       -> (ma,na) == (k,m)\n                      , case transb of NoTrans -> (mb,nb) == (k,n)\n                                       _       -> (mb,nb) == (n,k)\n                      , (mc, nc) == (m,n)\n                      ]) $ error $\n        printf (\"addMulMatrixWithScalesM_\"\n                ++ \" _\"\n                ++ \" %s <matrix with dim (%d,%d)>\" \n                ++ \" %s <matrix with dim (%d,%d)>\"\n                ++ \" _\"\n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \": dimension mismatch\")\n               (show transa) ma na\n               (show transb) mb nb\n               mc nc\n\n    unsafeIOToST $\n        unsafeWith a $ \\pa lda ->\n        unsafeWith b $ \\pb ldb ->\n        unsafeWith c $ \\pc ldc ->\n            BLAS.gemm transa transb m n k alpha pa lda pb ldb beta pc ldc\n\ncheckOp2 :: (RMatrix x, RMatrix y, Storable e, Storable f)\n         => String\n         -> (x e -> y f -> ST s a)\n         -> x e\n         -> y f\n         -> ST s a\ncheckOp2 str f x y = do\n    (m1,n1) <- getDim x\n    (m2,n2) <- getDim y\n    when ((m1,n1) /= (m2,n2)) $ error $\n        printf (\"%s <matrix with dim (%d,%d)> <matrix with dim (%d,%d)>:\"\n                ++ \" dimension mismatch\") str m1 n1 m2 n2\n    f x y\n{-# INLINE checkOp2 #-}\n\ncheckOp3 :: (RMatrix x, RMatrix y, RMatrix z, Storable e, Storable f, Storable g)\n         => String\n         -> (x e -> y f -> z g -> ST s a)\n         -> x e\n         -> y f\n         -> z g\n         -> ST s a\ncheckOp3 str f x y z = do\n    (m1,n1) <- getDim x\n    (m2,n2) <- getDim y\n    (m3,n3) <- getDim z\n    when((m1,n1) /= (m2,n2) || (m1,n1) /= (m3,n3)) $ error $\n        printf (\"%s <matrix with dim (%d,%d)> <matrix with dim (%d,%d)>:\"\n                ++ \" <matrix with dim (%d,%d)> dimension mismatch\")\n               str m1 n1 m2 n2 m3 n3\n    f x y z\n{-# INLINE checkOp3 #-}\n\nvectorOp :: (Storable e)\n         => (STVector s e -> ST s ())\n         -> STMatrix s e -> ST s ()\nvectorOp f x =\n    fromMaybe colwise $ maybeWithVectorM x $ \\vx -> f vx\n  where\n    colwise = withColsM x $ \\vxs ->\n                  sequence_ [ f vx | vx <- vxs ]\n\nvectorOp2 :: (RMatrix m, Storable e, Storable f)\n          => (forall v . RVector v => STVector s f -> v e -> ST s ())\n          -> STMatrix s f -> m e -> ST s ()\nvectorOp2 f dst x =\n    fromMaybe colwise $ maybeWithVectorM dst $ \\vdst ->\n    fromMaybe colwise $ maybeWithVector    x $ \\vx ->\n        f vdst vx\n  where\n    colwise = withColsM dst $ \\vdsts ->\n              withCols   x   $ \\vxs ->\n                  sequence_ [ f vdst vx | (vdst,vx) <- zip vdsts vxs ]\n{-# INLINE vectorOp2 #-}\n\nvectorOp3 :: (RMatrix m1, RMatrix m2, Storable e1, Storable e2, Storable f)\n          => (forall v1 v2 . (RVector v1, RVector v2) => \n                  STVector s f -> v1 e1 -> v2 e2 -> ST s ())\n          -> STMatrix s f -> m1 e1 -> m2 e2 -> ST s ()\nvectorOp3 f dst x y =\n    fromMaybe colwise $ maybeWithVectorM dst $ \\vdst ->\n    fromMaybe colwise $ maybeWithVector    x $ \\vx ->\n    fromMaybe colwise $ maybeWithVector    y $ \\vy ->\n        f vdst vx vy\n  where\n    colwise = withColsM dst $ \\vdsts ->\n              withCols   x   $ \\vxs ->\n              withCols   y   $ \\vys ->\n                  sequence_ [ f vdst vx vy\n                            | (vdst,vx,vy) <- zip3 vdsts vxs vys ]\n{-# INLINE vectorOp3 #-}\n", "meta": {"hexsha": "5154788d9a4174a5fe8a1d401caac78469300d0a", "size": 41765, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Matrix/STBase.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Matrix/STBase.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "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": "lib/Numeric/LinearAlgebra/Matrix/STBase.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 33.3852917666, "max_line_length": 95, "alphanum_fraction": 0.5124386448, "num_tokens": 12243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24201280108417803}}
{"text": "-- \n-- (c) Susumu Katayama\n--\n{-# LANGUAGE UndecidableInstances, OverlappingInstances, TemplateHaskell, CPP, FlexibleInstances #-} \n-- x #define TESTEQ\n\nmodule MagicHaskeller.Classification -- (\n                      -- randomTestFilter, -- ::  Filtrable a => (b->a) -> Matrix b -> Matrix b\n                      -- )\n                      where\nimport Prelude hiding ((/))\n#ifdef TFRANDOM\nimport System.Random.TF.Gen\n#else\nimport System.Random\n#endif\nimport MagicHaskeller.MyCheck\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Monad.Search.Combinatorial\nimport Data.Complex\n\nimport MagicHaskeller.MHTH\nimport MagicHaskeller.TimeOut\nimport MagicHaskeller.T10\n\nimport MagicHaskeller.Instantiate(compareRealFloat)\n\nclass (Search m) => SStrategy m where\n    sfilter :: Relation r =>\n               (k->k->r) -> (Int->Int) -> m ([k],e) -> m ([k],e)\n    ofilter :: Relation r =>\n               (k->k->r) -> m (k,e) -> m (k,e)\n\ninstance SStrategy Matrix where\n    sfilter = sfilterMx\n    ofilter = ofilterMx\n\ninstance SStrategy DBound where\n    sfilter = sfilterDB\n    ofilter = ofilterDB\n\n#ifdef TFRANDOM\narbitraries :: Arbitrary a => [a]\narbitraries = arbs 0 (seedTFGen (12279932681387497184,218462391894233257,1625759680792809304,12756118543158863164))\narbs :: Arbitrary a => Int -> TFGen -> [a]\narbs n stdgen  =  case map (splitn stdgen 8) [0..255] of\n                    g0:gs -> zipWith f [n..] gs ++ arbs (n+255) g0 -- I think 255 seeds is enough, but just in case.\n    where Gen f = arbitrary\n#else\narbitraries :: Arbitrary a => [a]\narbitraries = arbs 0 (mkStdGen 1)\narbs :: Arbitrary a => Int -> StdGen -> [a]\narbs n stdgen  =  case split stdgen of\n                    (g0,g1) -> f n g0 : arbs (n+1) g1\n    where Gen f = arbitrary\n#endif\n\n(/~) :: [a] -> (a->a->Bool) -> [[a]]\n[]      /~  eq  =  []\n(x:xs)  /~  eq  =  case partition (x `eq`) xs of\n                     (same, diff) -> (x:same) : (diff /~ eq)\n{-\n\u001b$B$J$*!$>e5-\u001b(B(/)\u001b$B$*$h$S2<5-\u001b(Bnub\u001b$B$N>l9g!$L58B%j%9%H$G$b$$$1$k!%\u001b(B\n*T10> let {[]     / eq = []; (x:xs) / eq = case partition (x `eq`) xs of (same, diff) -> (x:same) : (diff / eq)}\n*T10> cycle \"hogeha\" / (==)\n[\"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\n(snip)\nhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhInterrupted.\n*T10> map head $ cycle \"hogeha\" / (==)\n\"hogeaInterrupted.\n*T10> Data.List.nub $ cycle \"hogeha\"\n\"hogeaTerminated\n(snip)\n*T10> Data.List.nub $ repeat 'h'\n\"hTerminated\n-}\n\n\n\n\n-- ToDo: deal with timeout\n\n\n\n\n-- complete set of representatives\nnubSortBy :: (a->a->Ordering) -> [a] -> [a]\nnubSortBy = mergesortWithBy const\nnubSortByBot :: (a->a->Maybe Ordering) -> [a] -> [a]\nnubSortByBot = mergesortWithByBot const\n-- quotient set\n(/<) :: [a] -> (a->a->Ordering) -> [[a]]\nxs /< cmp  =  mergesortWithBy (++)\n                (\\x y -> head x `cmp` head y)\n                (map return xs)\n(/<?) :: [a] -> (a->a->Maybe Ordering) -> [[a]]\nxs /<? cmp  =  mergesortWithByBot (++)\n                (\\x y -> head x `cmp` head y)\n                (map return xs)\nclass Eq rel => Relation rel where\n -- remove duplicates, and sort if |rel==Ordering|\n    fromListBy   :: (k->k->rel) -> [k] -> [k]\n    fromListBy cmp = map head . (/cmp)\n-- used to pick up the shallowest expression in |DBound|\n    fromListByDB :: (k->k->rel) -> [(k,Int)] -> [(k,Int)]\n    fromListByDB rel ts =\n          map  (minimumBy (\\x y -> compare (snd y) (snd x)))\n               (ts / (\\x y -> rel (fst x) (fst y)))\n    -- \\NB : |maximumBy| returns the last of the maxima,\n    -- while |minimumBy| the first of the minima.\n -- quotient set\n    (/)          :: [k] -> (k->k->rel) -> [[k]]\n -- merge two lists, \n    appendWithBy :: (k->k->k) -> -- combiner\n                    (k->k->rel) -> [k] -> [k] -> [k]\n    diffBy       :: (k -> k -> rel) -> [k] -> [k] -> [k]\n -- counterpart of EQ\n    cEQ          :: rel\n-- merge two quotient sets\nappendQuotientsBy ::\n  (Relation rel) =>\n  (k -> k -> rel) -> [[k]] -> [[k]] -> [[k]]\nappendQuotientsBy rel =\n   appendWithBy (++) (\\ (x:_) (y:_) -> x `rel` y)\n-- merge two complete sets of representatives\nappendRepresentativesBy ::\n   (Relation rel) =>\n   (k -> k -> rel) -> [k] -> [k] -> [k]\nappendRepresentativesBy = appendWithBy const\n\ninstance Relation Bool where\n    fromListBy    = Data.List.nubBy\n    (/)           = (/~)\n    appendWithBy  = unionWithBy\n    diffBy        = Data.List.deleteFirstsBy\n    cEQ           = True\nunionWithBy combiner eq []      ys = ys\nunionWithBy combiner eq (x:xs)  ys =\n   case break (eq x) ys of\n      (_,   [])    ->  x  :  unionWithBy combiner eq xs ys\n      (ts,  h:ds)  ->  (x `combiner` h)\n                          :  unionWithBy combiner eq xs (ts++ds)\ninstance Relation Ordering where\n    fromListBy    = nubSortBy\n    fromListByDB rel =\n        mergesortWithBy\n                    (\\x y -> if snd x < snd y then y else x)\n                    (\\x y -> fst x `rel` fst y)\n    (/)           = (/<)\n    appendWithBy  = mergeWithBy\n    diffBy        = diffSortedBy\n    cEQ           = EQ\ninstance Relation (Maybe Ordering) where\n    fromListBy    = nubSortByBot\n    fromListByDB rel =\n        mergesortWithByBot\n                    (\\x y -> if snd x < snd y then y else x)\n                    (\\x y -> fst x `rel` fst y)\n    (/)           = (/<?)\n    appendWithBy  = mergeWithByBot\n    diffBy        = diffSortedByBot\n    cEQ           = Just EQ\n\nrandomTestFilter ::  (SStrategy m, Filtrable a) =>\n                     (Int->Int) -> m (e,a) -> m (e,a)\nrandomTestFilter numRandoms = filt numRandoms . fmap (\\ t@(_,a) -> (a,t))\n\nunsafeRandomTestFilter ::  (SStrategy m, Filtrable a) =>\n                           Maybe Int -- ^ microsecs until timeout\n                               -> (Int->Int) -> m (e,a) -> m (e,a)\nunsafeRandomTestFilter mto numRandoms = unsafeFilt mto numRandoms . fmap (\\ t@(_,a) -> (a,t))\n\nmapFst f (a,b) = (f a, b)\n\nclass Filtrable a where\n    filt    :: SStrategy m => (Int->Int) -> m (a,e) -> m e\n    filtFun :: (SStrategy m, Arbitrary b) =>\n               (Int->Int) -> m (b->a,e) -> m e\n    unsafeFilt    :: SStrategy m =>\n                     Maybe Int -> (Int->Int) -> m (a,e) -> m e\n    unsafeFiltFun :: (SStrategy m, Arbitrary b) =>\n                     Maybe Int -> (Int->Int) -> m (b->a,e) -> m e\n\ninstance  (Arbitrary a, Filtrable r) => Filtrable (a->r)\n  where\n    filt      = filtFun\n    filtFun f = filt f . fmap (mapFst uncurry)\n    unsafeFilt    mto f = unsafeFiltFun mto f\n    unsafeFiltFun mto f = unsafeFilt mto f . fmap (mapFst uncurry)\n\n#ifdef TESTEQ\ninstance Eq a => Filtrable a where\n    filt     = filtNullary  (==)\n    filtFun  = filtUnary    (==)\n#else\ninstance Ord a => Filtrable a where\n    filt     = filtNullary  compare\n    filtFun  = filtUnary    compare\n    unsafeFilt    mto = filtNullary  (unsafeOpWithPTO mto compare)\n    unsafeFiltFun mto = filtUnary    (unsafeOpWithPTO mto compare)\ninstance Filtrable Double where\n    filt     = filtNullary  compareRealFloat\n    filtFun  = filtUnary    compareRealFloat\n    unsafeFilt    mto = filtNullary  (unsafeOpWithPTO mto compareRealFloat)\n    unsafeFiltFun mto = filtUnary    (unsafeOpWithPTO mto compareRealFloat)\n#endif\nfiltNullary ::  (SStrategy m, Relation r) =>\n                (k->k->r) -> (Int->Int) -> m (k,e) -> m e\nfiltNullary  op _ =  fmap snd . ofilter op\nfiltUnary    op f =  fmap snd . sfilter op f .\n                      fmap (mapFst (flip map arbitraries))\n\ninstance  (RealFloat a, Ord a) =>\n          Filtrable (Complex a) where\n    filt     = filtNullary  compareCx\n    filtFun  = filtUnary    compareCx\n    unsafeFilt    mto = filtNullary  (unsafeOpWithPTO mto compareCx)\n    unsafeFiltFun mto = filtUnary    (unsafeOpWithPTO mto compareCx)\ncompareCx ::  (RealFloat a, Ord a) =>\n              Complex a -> Complex a -> Ordering\n(a:+b) `compareCx` (c:+d) = case compare a c of\n                              EQ -> compare b d\n                              o  -> o\nofilterMx ::  Relation r =>\n            (k->k->r) -> Matrix (k,e) -> Matrix (k,e)\nofilterMx op (Mx xss)\n        = let\n            (k,_) `rel` (l,_) = k `op` l\n            mapped     = map (fromListBy rel) xss\n            cumulative =\n                 scanl  (appendRepresentativesBy rel)\n                                 [] mapped\n          in Mx $ zipWith (diffBy rel) mapped cumulative\n\nofilterDB :: Relation rel =>\n              (k->k->rel) ->\n               DBound (k,e) -> DBound (k,e)\nofilterDB cmp (DB f) = DB $\n    \\n -> fromListByDB  (\\(k,_) (l,_) -> cmp k l)\n                        (f n)\n\ncumulativeRepresentatives ::\n    Relation rel =>\n   [a->a->rel] -> Matrix a -> Matrix a\ncumulativeRepresentatives relations mx =\n    fmap head (cumulativeQuotients relations mx)\n\nrepresentatives ::\n    Relation rel =>\n   [a->a->rel] -> Matrix a -> Matrix a\nrepresentatives relations mx = \n   unscanlByList relations $\n        cumulativeRepresentatives relations mx\nunscanlByList ::  Relation r =>\n                  [k->k->r] -> Matrix k -> Matrix k\nunscanlByList (_:rels) (Mx (yss@(xs:xss))) =\n    Mx $ xs : zipWith3 diffBy rels xss yss\n\nsfilterMx ::  Relation r =>\n              (k->k->r) -> \n              (Int->Int) ->\n              Matrix ([k],e) -> Matrix ([k],e)\nsfilterMx rel numRands = representatives (map (liftRelation rel . numRands) [0..])\nliftRelation ::  Relation r =>\n                 (k->k->r) -> \n                    Int -> ([k],e) -> ([k],e) -> r\nliftRelation rel len (xs,_) (ys,_) = liftRel rel len xs ys\nliftRel _   0   _      _      = cEQ\nliftRel _   _   []     []     = cEQ\nliftRel rel len (x:xs) (y:ys) =\n    case rel x y of\n           c  | c == cEQ   -> liftRel rel (len-1) xs ys\n              | otherwise  -> c\n\nsfilterDB ::  Relation rel =>\n               (k->k->rel) ->\n              (Int->Int)->\n                DBound ([k],e) -> DBound ([k],e)\nsfilterDB rel numRands (DB f) = DB $ \\n -> fromListByDB  (liftRelation rel (numRands n)) (f n)\n\ncumulativeQuotients relations (Mx xss)\n   =  let yss:ysss = zipWith (/) xss relations\n      in Mx $ scanl  (\\rec (r,z) ->\n                       appendQuotientsBy r (rec>>=(/r)) z)\n                     yss  (zip (tail relations) ysss)\n\nns = [6..]\n", "meta": {"hexsha": "ca30180bdd0d0a89e718145efc5f6a698e65db90", "size": 10304, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "demo/back-end system/MagicHaskeller/MagicHaskeller/Classification.hs", "max_stars_repo_name": "liconoc/MagicWrangler", "max_stars_repo_head_hexsha": "c095c2f7892f33d4ade78beaecd682ec89623ac0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-11-29T04:03:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T16:00:18.000Z", "max_issues_repo_path": "MagicHaskeller/Classification.hs", "max_issues_repo_name": "junjihashimoto/MagicHaskeller", "max_issues_repo_head_hexsha": "a21645d5281ebe5e9862127c15b4fdcdf0dc02bf", "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": "MagicHaskeller/Classification.hs", "max_forks_repo_name": "junjihashimoto/MagicHaskeller", "max_forks_repo_head_hexsha": "a21645d5281ebe5e9862127c15b4fdcdf0dc02bf", "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.5310344828, "max_line_length": 217, "alphanum_fraction": 0.5614324534, "num_tokens": 3322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.24141290125295242}}
{"text": "{-# LANGUAGE BangPatterns #-}\nmodule MnistLoader\n  ( load_data_wrapper\n  , TrainingData\n  , ValidationData\n  ) where\n\nimport           Codec.Compression.GZip (decompress)\nimport           Control.Applicative ((<$>))\nimport           Control.DeepSeq\nimport           Control.Monad (replicateM, unless)\nimport           Data.Binary.Get\nimport qualified Data.ByteString.Lazy as B\nimport           Data.Word (Word8)\nimport           Numeric.LinearAlgebra\nimport           System.FilePath.Posix ((</>))\n\ntype TrainingData   = [(Vector Double, Vector Double)]\ntype ValidationData = [(Vector Double, Word8)]\n\n\nreadImageFile :: FilePath -> IO [[Word8]]\nreadImageFile p = runGet parseImages <$> decompress <$> B.readFile p\n\n\nreadLabelFile :: FilePath -> IO [Word8]\nreadLabelFile p = runGet parseLabels <$> decompress <$> B.readFile p\n\n\nparseImages :: Get [[Word8]]\nparseImages = do\n  magicNum <- getWord32be\n  unless (magicNum == 2051) $ error $\n    \"Not an image file, wrong magic number \" ++ show magicNum\n  nImg <- fromIntegral <$> getWord32be\n  nRow <- fromIntegral <$> getWord32be\n  nCol <- fromIntegral <$> getWord32be\n  img  <- replicateM nImg $ replicateM (nRow * nCol) getWord8\n  unlessM isEmpty $ error \"not all data consumed\"\n  return img\n\n\nparseLabels :: Get [Word8]\nparseLabels = do\n  magicNum <- getWord32be\n  unless (magicNum == 2049) $ error $\n    \"Not a label file, wrong magic number \" ++ show magicNum\n  n <- fromIntegral <$> getWord32be\n  lbl <- replicateM n getWord8\n  unlessM isEmpty $ error \"not all data consumed\"\n  return lbl\n\n\nload_data_wrapper :: FilePath -> IO (TrainingData, ValidationData)\nload_data_wrapper p = do\n  imgTraining    <- readImageFile $ p </> \"train-images-idx3-ubyte.gz\"\n  imgValidation  <- readImageFile $ p </> \"t10k-images-idx3-ubyte.gz\"\n  lblTraining    <- readLabelFile $ p </> \"train-labels-idx1-ubyte.gz\"\n  lblValidation  <- readLabelFile $ p </> \"t10k-labels-idx1-ubyte.gz\"\n  return ( (zip $!! normalizeImg imgTraining)   $!! toUnitVector lblTraining\n         , (zip $!! normalizeImg imgValidation) $!! lblValidation\n         )\n  where\n    normalizeImg = map $ fromList . map ((/ 256) . fromIntegral)\n    toUnitVector = map (fromList . toUnitVector')\n    toUnitVector' 0 = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n    toUnitVector' 1 = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]\n    toUnitVector' 2 = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]\n    toUnitVector' 3 = [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]\n    toUnitVector' 4 = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]\n    toUnitVector' 5 = [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]\n    toUnitVector' 6 = [0, 0, 0, 0, 0, 0, 1, 0, 0, 0]\n    toUnitVector' 7 = [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]\n    toUnitVector' 8 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]\n    toUnitVector' 9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]\n    toUnitVector' x = error $ \"(toUnitVector \" ++ show x ++ \") is undefined\"\n\n\nunlessM :: Monad m => m Bool -> m () -> m ()\nunlessM mp f = (\\p -> unless p f) =<< mp\n", "meta": {"hexsha": "bd7d10439245c8bb4ffb2d7ec85a834c7f0b641e", "size": 2890, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/MnistLoader.hs", "max_stars_repo_name": "KaiHa/NNDigitReader", "max_stars_repo_head_hexsha": "789c502b8dfdb6f867d569132b2c5cfe06aea136", "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": "haskell/src/MnistLoader.hs", "max_issues_repo_name": "KaiHa/NNDigitReader", "max_issues_repo_head_hexsha": "789c502b8dfdb6f867d569132b2c5cfe06aea136", "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": "haskell/src/MnistLoader.hs", "max_forks_repo_name": "KaiHa/NNDigitReader", "max_forks_repo_head_hexsha": "789c502b8dfdb6f867d569132b2c5cfe06aea136", "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": 35.6790123457, "max_line_length": 76, "alphanum_fraction": 0.6252595156, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.24141289539169752}}
{"text": "{-# LANGUAGE TemplateHaskell, OverloadedLists #-}\n{-# LANGUAGE Strict #-}\n\nmodule Data.Scene where\n\nimport           Numeric.LinearAlgebra (Vector, scale)\nimport qualified Graphics.GL as GLRaw\nimport qualified SDL\nimport qualified Graphics.Rendering.OpenGL.GL as GL\nimport           Control.Lens\nimport           Control.Arrow\nimport qualified Data.Vector as V\n\nimport           Data.GameObject ( GameObject(..)\n                                 , drawObject\n                                 , location\n                                 , drawObject2)\nimport           Utils (lookAt, step, norm, remTrans)\nimport           Data.SkyBox\nimport           Tasks.Swarm\nimport           Debug.Trace\n-- import           Data.Traversable (traverse)\n\ndata Objects = Objects {\n  _player :: GameObject,\n  _npc    :: V.Vector GameObject,\n  _area   :: V.Vector GameObject }\n\ndata Scene = Scene {\n  _campos     :: Vector GLRaw.GLfloat,\n  _objects    :: Objects,\n  _projection :: Vector GLRaw.GLfloat,\n  _skyBox :: Maybe SkyBox }\n\nmakeLenses ''Objects\n\nmakeLenses ''Scene\n\nresolveObjectCollisions obs =\n  let v = resolveContacts .\n          V.cons (obs^.player) $\n          (obs^.npc) -- V.++ (obs^.area)\n      newPlayer = V.head v\n      newNpcs =\n        -- V.take (V.length (obs^.npc)) .\n        V.drop 1 $ v\n  in set player newPlayer . set npc newNpcs $ obs\n\ntraverseObjects :: (GameObject -> GameObject) -> Scene -> Scene\ntraverseObjects =\n  over (objects.player) &&& over (objects.npc.traverse) >>> uncurry (.)\n\n\nclass Drawable d where\n  draw :: SDL.Window -> d -> IO ()\n\ninstance Drawable Scene where\n  draw window (Scene pos obj proj msb) =\n    let camMat     = lookAt pos $ obj^.player.location\n        objectDraw = drawObject (msb^?_Just.skyTex) camMat proj\n        objectDraw2 = drawObject2 camMat proj\n        drawSB      = drawSkyBox (remTrans camMat) proj\n    in\n      GL.clear [GL.ColorBuffer, GL.DepthBuffer]\n      >> traverse drawSB msb\n      >> objectDraw (obj^.player)\n      >> V.mapM_ objectDraw (obj^.npc)\n      >> V.mapM_ objectDraw (obj^.area)\n      >> SDL.glSwapWindow window\n\n-- CAMERA\n\nmoveCameraV = over campos . (+)\n\nmoveCamera :: Float -> Float -> Float -> Scene -> Scene\nmoveCamera x y z = moveCameraV [x,y,z]\n\nmoveDepth :: Float -> Scene -> Scene\nmoveDepth = moveCamera 0 0\n\nmoveForwardCamera :: Scene -> Scene\nmoveForwardCamera = moveDepth step\n\nmoveBackCamera :: Scene -> Scene\nmoveBackCamera = moveDepth (-step)\n\nadjustCamera :: Scene -> Scene\nadjustCamera scene =\n  let playPos = scene^.objects.player.location\n      pointer = playPos - scene^.campos\n      dist    = norm pointer\n      maxDist = 10\n      tooFar  = dist > maxDist\n      movement= scale ((dist-maxDist)/dist) pointer\n  in if tooFar then over campos (+movement) scene\n     else scene\n\n\nmoveHor :: Float -> Scene -> Scene\nmoveHor s = moveCamera s 0 0\n\nmoveLeftCamera :: Scene -> Scene\nmoveLeftCamera = moveHor step\n\nmoveRightCamera :: Scene -> Scene\nmoveRightCamera = moveHor (-step)\n", "meta": {"hexsha": "e89e8076d0d4bdf6b73eff57abb989b16a9993e7", "size": 2964, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Scene.hs", "max_stars_repo_name": "Antystenes/CPG", "max_stars_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "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/Data/Scene.hs", "max_issues_repo_name": "Antystenes/CPG", "max_issues_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "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/Data/Scene.hs", "max_forks_repo_name": "Antystenes/CPG", "max_forks_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "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": 27.7009345794, "max_line_length": 71, "alphanum_fraction": 0.6363022942, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.24086018785653646}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE LambdaCase #-}\nmodule Taiji.Utils.Clustering\n    ( evalClusters\n    , computeClusterMetrics\n    , computeReproducibility\n    , readKNNGraph\n    , optimalParam\n    , visualizeCluster\n    , sampleCells\n    , silhouette\n    , confusionTable\n    , batchCorrect\n    , leiden\n    , ari\n    ) where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Binary (encodeFile, decodeFile)\nimport Bio.Utils.Misc\nimport qualified Data.Text as T\nimport qualified Data.HashSet as S\nimport qualified Data.HashMap.Strict as M\nimport Data.Hashable (Hashable)\nimport Control.Arrow (first, second)\nimport Conduit\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as VM\nimport qualified Data.Vector.Unboxed as U\nimport Data.List.Ordered (nubSort)\nimport Shelly (shelly, run_)\nimport Data.Conduit.Zlib (multiple, ungzip)\nimport AI.Clustering.Hierarchical.Types (computeDists, (!))\nimport AI.Clustering.Hierarchical (euclidean)\nimport Statistics.Sample (mean)\nimport System.Random.MWC.Distributions\nimport Language.Javascript.JMacro\nimport System.Random.MWC\n\nimport IGraph.Random\nimport IGraph\nimport qualified IGraph.Algorithms.Community as I\n\nimport Taiji.Prelude\nimport Taiji.Utils.Plot.ECharts\nimport Taiji.Utils.Plot\n   \n-- | Evaluating the clustering results\nevalClusters :: FilePath\n             -> Optimizer  -- ^ Optimizer\n             -> Double     -- ^ Resolution\n             -> FilePath   -- ^ knn\n             -> IO ([FilePath], FilePath)\nevalClusters dir optimizer res knn = do\n    gr <- readKNNGraph knn\n    gen <- create\n\n    perturbed <- forM [1::Int ..5] $ \\i -> do\n        let output' = dir <> \"/perturbed_clustering_result_\" <> show i <> \".bin\"\n        r <- mutateGraph gr gen >>= leiden res optimizer \n        encodeFile output' $ map snd $ sort $ concat $ zipWith (\\a b -> zip a $ repeat b) r [0::Int ..]\n        return output'\n\n    let output = dir <> \"/clustering_result.bin\"\n    (filter ((>100) . length) <$> leiden res optimizer gr) >>= encodeFile output\n    return (perturbed, output)\n  where\n    mutateGraph gr gen = do\n        let n = truncate $ fromIntegral (nEdges gr) * (0.02 :: Double)\n        xs <- take n . V.toList <$> uniformShuffle (V.fromList $ edges gr) gen\n        return $ delEdges xs gr\n\ncomputeReproducibility :: [[Int]] -- ^ cluster\n                       -> [[Int]]  -- ^ perturbed clusters\n                       -> [Double]\ncomputeReproducibility a bs = map (mean . U.fromList) $ transpose $ flip map bs $ \\b ->\n    let b' = U.fromList b\n    in map (reproducibility . map (b' U.!)) a\n\ncomputeClusterMetrics :: ([FilePath], FilePath)\n                      -> FilePath\n                      -> IO (Int, Double, Double)\ncomputeClusterMetrics (perturbed, cl) coordinate = do\n    stability <- (mean . U.fromList . map ari . comb) <$> mapM decodeFile perturbed\n    clusters <- decodeFile cl\n    points <- fmap V.fromList $ runResourceT $ runConduit $ sourceFile coordinate .|\n        multiple ungzip .| linesUnboundedAsciiC .|\n        mapC (U.fromList . map readDouble . B.split '\\t') .| sinkList\n    gen <- create\n\n    let samplingRatio = 10000 / fromIntegral (V.length points) :: Double\n    clusters' <- forM clusters $ \\c -> do\n        let n = max 2 $ truncate $ fromIntegral (length c) * samplingRatio\n        V.toList . V.take n <$> uniformShuffle (V.fromList c) gen\n\n    let sil = silhouette $ (map . map) (points V.!) clusters'\n    return (length clusters, sil, stability)\n  where\n    comb (x:xs) = zip (repeat x) xs ++ comb xs\n    comb _ = []\n\nreadKNNGraph :: FilePath -> IO (Graph 'U () Double)\nreadKNNGraph fl = runResourceT $ runConduit $ sourceFile fl .|\n    multiple ungzip .| linesUnboundedAsciiC .| sink\n  where\n    sink = do\n        n <- headC >>= \\case\n            Nothing -> error \"\"\n            Just x -> return $ readInt x\n        es <- mapC f .| sinkList\n        return $ mkGraph (replicate n ()) $ replaceInf es\n    f x = let (a:b:c:_) = B.split '\\t' x\n          in ((readInt a, readInt b), readDouble' c)\n    readDouble' x | x == \"inf\" = Nothing\n                  | otherwise = Just $ readDouble x\n    replaceInf es = let m = maximum $ mapMaybe snd es\n                    in map (second (fromMaybe m)) es\n\noptimalParam :: FilePath\n             -> [(Double, (Int, Double, Double))]\n             -> IO Double\noptimalParam output input = do\n    savePlots output [] plt\n    return optimal\n  where\n    optimal = fst $ maximumBy (comparing (^._2._2)) $ case filter (\\x -> x^._2._3 >= 0.9) input of\n        [] -> input\n        x -> x\n    (res, dat) = unzip $ flip map (sortBy (comparing fst) input) $ \\(r, (n, sil, stab)) ->\n        (r, (fromIntegral n, sil, stab))\n    (num, sils, stabs) = unzip3 dat\n    plt = map (setDim 400 300 . addAttr toolbox)\n        [ addAttr (yAxisLabel \"number of clusters\") $\n                addAttr (xAxisLabel \"resolution\") $\n                lineplot $ zip res num \n        , addAttr (yAxisLabel \"silhouette width\") $\n                addAttr (xAxisLabel \"resolution\") $\n                lineplot $ zip res sils\n        , addAttr (yAxisLabel \"stability\") $\n                addAttr (xAxisLabel \"resolution\") $\n                lineplot $ zip res stabs ]\n    lineplot input = mkEChart [jmacroE| {\n        grid: { containLabel: true },\n        xAxis: {\n            type: \"value\",\n            axisLine: {onZero: false}\n        },\n        tooltip: {\n            trigger: \"axis\"\n        }, \n        yAxis: {\n            type: \"value\",\n            axisLine: {onZero: false}\n        }, \n        series: [{\n            data: `dataset`,\n            markLine: {symbolSize: 0, precision: 10, data: [{xAxis: `optimal`}]},\n            type: \"line\"\n        }]\n        } |]\n      where\n        dataset = map (\\(x,y) -> [x,y]) input\n    \n\nvisualizeCluster :: [CellCluster] -> [EChart]\nvisualizeCluster cls =\n    [ addAttr toolbox $ scatter' $ flip map cls $ \\(CellCluster nm cells _) ->\n        (B.unpack nm, map _cell_2d cells) ] ++ if noName then [] else\n          [ addAttr toolbox $ scatter' $ map (first head . unzip) $\n              groupBy ((==) `on` fst) $ sortBy (comparing fst) $ concatMap\n              (map (\\x -> (getName $ _cell_barcode x, _cell_2d x)) . _cluster_member) cls\n          ]\n  where\n    noName = null $ getName $ _cell_barcode $ head $\n        _cluster_member $ head cls\n    getName x = let prefix = fst $ B.breakEnd (=='+') x\n                in if B.null prefix then \"\" else B.unpack $ B.init prefix\n\n-- | Random sample 30,000 cells.\nsampleCells :: [CellCluster] -> IO [CellCluster]\nsampleCells clusters\n    | ratio >= 1 = return clusters\n    | otherwise = do\n        gen <- create\n        forM clusters $ \\c -> do\n            s <- sampling gen ratio $ V.fromList $ _cluster_member c\n            return $ c {_cluster_member = V.toList s}\n  where\n    n = foldl1' (+) $ map (length . _cluster_member) clusters\n    ratio = 1 / (fromIntegral n / 30000) :: Double\n    sampling gen frac v = V.take n' <$> uniformShuffle v gen\n      where\n        n' = max 200 $ truncate $ frac * fromIntegral (V.length v)\n\nsilhouette :: [[U.Vector Double]]   -- ^ Groups of objects\n           -> Double\nsilhouette input\n    | length input <= 1 = 0\n    | otherwise = mean $ U.fromList $ flip concatMap clusters $ \\(i, cl) ->\n        let cls = map snd $ filter ((/= i) . fst) clusters\n        in flip map cl $ \\x ->\n            let a = getD x cl\n                b = minimum $ map (getD x) cls\n            in (b - a) / max a b\n  where\n    getD i cl = mean $ U.fromList $ map (\\j -> distMat ! (i, j)) $ filter (/= i) cl\n    clusters = zip [0 :: Int ..] $ go 0 input\n      where\n        go i (x:xs) = let n = length x in take n [i..] : go (i + n) xs\n        go _ _ = []\n    distMat = computeDists euclidean $ V.fromList $ concat input\n{-# INLINE silhouette #-}\n\nconfusionTable :: (Eq a, Hashable a) => [[a]] -> [[a]] -> [[Int]]\nconfusionTable inputA inputB = flip map inputA' $ \\a -> flip map inputB' $ \\b ->\n    S.size $ S.intersection a b\n  where\n    inputA' = map S.fromList inputA\n    inputB' = map S.fromList inputB\n{-# INLINE confusionTable #-}\n\nbatchCorrect :: [Maybe (B.ByteString, Maybe B.ByteString)]  -- ^ label and group\n             -> V.Vector (U.Vector Double)    -- ^ Data\n             -> IO (V.Vector (U.Vector Double))\nbatchCorrect batchInfo input = do\n    vec <- V.thaw input\n    forM_ batchGroups $ \\(idx, label) -> when (length (nubSort label) > 1) $ do\n        res <- batchAveraging label (map (input V.!) idx)\n        forM_ (zip idx res) $ \\(i, r) -> VM.unsafeWrite vec i r\n    V.unsafeFreeze vec\n  where\n    batchGroups = map (unzip . map (\\(i, (x, _)) -> (i, x))) $\n        groupBy ((==) `on` (snd . snd)) $ sortBy (comparing (snd . snd)) $\n        mapMaybe (\\(i, b) -> maybe Nothing (\\x -> Just (i,x)) b) $ zip [0..] batchInfo\n{-# INLINE batchCorrect #-}\n\nbatchAveraging :: [B.ByteString]    -- ^ Batch labels\n               -> [U.Vector Double]    -- ^ Data\n               -> IO [U.Vector Double]\nbatchAveraging labels input = withTempDir Nothing $ \\dir -> do\n    let labelFl = dir <> \"/label.txt\"\n        matFl = dir <> \"/mat.txt\"\n        tmp = dir <> \"/tmp.txt\"\n    B.writeFile labelFl $ B.unlines labels\n    B.writeFile matFl $ B.unlines $ map (B.intercalate \"\\t\" . map toShortest . U.toList) input\n    shelly $ run_ \"taiji-utils\" [\"correct\", \"--label\", T.pack labelFl, T.pack matFl, T.pack tmp]\n    map (U.fromList . map readDouble . B.words) . B.lines <$> B.readFile tmp\n{-# INLINE batchAveraging #-}\n\nleiden :: Double -> Optimizer -> Graph 'U () Double -> IO [[Int]]\nleiden resolution optimizer gr = withSeed 9304 $ fmap (sortBy (flip (comparing length))) .\n    I.findCommunity gr nodeWeight edgeWeight I.leiden{I._resolution=res}\n  where\n    edgeWeight\n        | optimizer `elem` [RBConfiguration, CPM] = Nothing\n        | otherwise = Just id\n    (nodeWeight, res) \n        | optimizer `elem` [RBConfiguration, RBConfigurationWeighted] =\n            ( Just $ \\i _ -> foldl1' (+) $ map (\\j -> edgeLab gr (i, j)) $ neighbors gr i\n            , resolution / (2 * (foldl1' (+) $ map snd $ labEdges gr)))\n        | otherwise = (Nothing, resolution)\n\n-- |\nreproducibility :: [Int]   -- membership\n                -> Double\nreproducibility xs = fromIntegral sameGroup / fromIntegral (c2 $ length xs)\n  where\n    counts = M.elems $ M.fromListWith (+) $ zip xs $ repeat (1 :: Int)\n    sameGroup = foldl1' (+) $ map c2 counts\n    c2 x = (x * (x - 1)) `div` 2\n\n-- | Adjusted Rand Index: <http://en.wikipedia.org/wiki/Rand_index>\nari :: ([Int], [Int]) -> Double\nari (a, b) | length a /= length b = error \"unequal length\"\n           | a == b = 1\n           | otherwise = ari' $ counts a b\n  where\n    ari' (Counts cxy cx cy) =  (sum1 - sum2*sum3/choicen2) \n                            / (1/2 * (sum2+sum3) - (sum2*sum3) / choicen2)\n      where choicen2 = choice (sum . M.elems $ cx) 2\n            sum1 = sum [ choice nij 2 | nij <- M.elems cxy ]\n            sum2 = sum [ choice ni 2 | ni <- M.elems cx ]\n            sum3 = sum [ choice nj 2 | nj <- M.elems cy ]\n    -- | Creates count table 'Counts'\n    counts xs = foldl' f mempty . zipWith ((,)) xs\n        where f cs@(Counts cxy cx cy) p@(x,y) = \n                cs { joint       = M.insertWith (+) p 1 cxy\n                , marginalFst = M.insertWith (+) x 1 cx\n                , marginalSnd = M.insertWith (+) y 1 cy }\n    -- | The binomial coefficient: C^n_k = PROD^k_i=1 (n-k-i)\\/i\n    choice :: Double -> Double -> Double\n    choice n k = foldl' (*) 1 [n-k+1 .. n] / foldl' (*) 1 [1 .. k]\n\n-- | Count table\ndata Counts = Counts \n    { joint :: !(M.HashMap (Int, Int) Double) -- ^ Counts of both components\n    , marginalFst :: !(M.HashMap Int Double) -- ^ Counts of the first component\n    , marginalSnd :: !(M.HashMap Int Double) -- ^ Counts of the second component\n    } \n\ninstance Monoid Counts where\n    mempty = Counts M.empty M.empty M.empty\n    c `mappend` k = \n        Counts { joint = unionPlus (joint c) (joint k)\n               , marginalFst = unionPlus (marginalFst c) (marginalFst k)\n               , marginalSnd = unionPlus (marginalSnd c) (marginalSnd k)\n               }\n      where\n        unionPlus m = M.foldlWithKey' (\\z k' v -> M.insertWith (+) k' v z) m\n\ninstance Semigroup Counts where\n    c <> k = \n        Counts { joint = unionPlus (joint c) (joint k)\n               , marginalFst = unionPlus (marginalFst c) (marginalFst k)\n               , marginalSnd = unionPlus (marginalSnd c) (marginalSnd k)\n               }\n      where\n        unionPlus m = M.foldlWithKey' (\\z k' v -> M.insertWith (+) k' v z) m\n", "meta": {"hexsha": "81b9042223ee7ab0791ec946ff4ae6dfc2a8592f", "size": 12584, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Taiji/Utils/Clustering.hs", "max_stars_repo_name": "Taiji-pipeline/Taiji-utils", "max_stars_repo_head_hexsha": "f5e009cf7a9a683f7e43bf97fb33c758ba13d97b", "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/Taiji/Utils/Clustering.hs", "max_issues_repo_name": "Taiji-pipeline/Taiji-utils", "max_issues_repo_head_hexsha": "f5e009cf7a9a683f7e43bf97fb33c758ba13d97b", "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/Taiji/Utils/Clustering.hs", "max_forks_repo_name": "Taiji-pipeline/Taiji-utils", "max_forks_repo_head_hexsha": "f5e009cf7a9a683f7e43bf97fb33c758ba13d97b", "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": 39.2024922118, "max_line_length": 103, "alphanum_fraction": 0.5808169104, "num_tokens": 3566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334527, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.24017888633605672}}
{"text": "module Statistics.BBVI.Scheduler\n  ( stepTogether\n  , stepSeparate\n  , unsafeContent\n  )\nwhere\n\nimport           Control.Monad.ST               ( ST )\nimport           Data.Propagator\nimport           Data.Maybe                     ( fromMaybe )\nimport qualified Data.Vector                   as V\nimport           Statistics.BBVI.Class\nimport           Statistics.BBVI.Propagator     ( Time\n                                                , time\n                                                , DistCell(..)\n                                                , DistCellss\n                                                , mergeGeneric\n                                                , mergeGenericss\n                                                )\n\n-- | helper (partial) function to pull content from cell\nunsafeContent :: Cell s a -> ST s a\nunsafeContent =\n  (fromMaybe (error \"called unsafe content but no content in cell\") <$>)\n    . content\n\n-- | update all propagators in one step until first argument reaches\n-- quiesence; synonymous with traditional synchronous algorithms\nstepTogether :: (a -> b -> ST s (a, b)) -> Cell s a -> Cell s b -> ST s ()\nstepTogether f x y = watch x $ \\x' -> with y $ \\y' -> do\n  (upX, upY) <- f x' y'\n  -- careful: order below can create a bug. safer would be to use\n  -- unsafe content instead of with y\n  write y upY\n  write x upX\n\n-- | partially optimize each cell with the other held fixed, and\n-- repeat until quiesence. Each local optimization will proceed some\n-- number of steps, or until the local optimization converges, before\n-- triggering the global cell to fire.\nstepSeparate\n  :: (DistUtil a1, DistUtil a2)\n  => Time -- ^ number of local steps\n  -> Double\n  -> (  DistCell a2\n     -> DistCellss a1\n     -> ST s (DistCell a2, DistCellss a1)\n     ) -- ^ gradient propagator\n  -> Cell s (DistCell a2)\n  -> Cell s (V.Vector (V.Vector (DistCell a1))) --\n  -> ST s ()\nstepSeparate nLocal localDelta f x0 ys0 = do\n  watch x0 $ \\x -> do\n    yTemp <- unsafeContent ys0\n    ys    <- cellWith $ mergeGenericss\n      ((+ nLocal) . time . (V.! 0) . (V.! 0) $ yTemp)\n      localDelta\n    write ys yTemp\n    watch ys $ \\ys' -> do\n      (_upX, upYs) <- f x ys'\n      -- upYs <- f2 x ys'\n      write ys upYs\n    ysNew <- unsafeContent ys\n    write ys0 ysNew\n  watch ys0 $ \\ys -> do\n    xTemp <- unsafeContent x0\n    x     <- cellWith $ mergeGeneric (nLocal + time xTemp) localDelta\n    write x xTemp\n    watch x $ \\x' -> do\n      (upX, _upYs) <- f x' ys\n      -- upX <- f1 x' ys\n      write x upX\n    xNew <- unsafeContent x\n    write x0 xNew\n", "meta": {"hexsha": "67c14f55566f4a2a9503bdfcd44273cdc29ef223", "size": 2577, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/BBVI/Scheduler.hs", "max_stars_repo_name": "massma/propagator-bbvi", "max_stars_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "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/Statistics/BBVI/Scheduler.hs", "max_issues_repo_name": "massma/propagator-bbvi", "max_issues_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "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/Statistics/BBVI/Scheduler.hs", "max_forks_repo_name": "massma/propagator-bbvi", "max_forks_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "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.36, "max_line_length": 74, "alphanum_fraction": 0.545983702, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.23927465983345292}}
{"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": "{- |\nDescription :  Default values and constants\nCopyright   :  (c) Dominik Schrempf 2017\nLicense     :  GPLv3\n\nMaintainer  :  dominik.schrempf@gmail.com\nStability   :  unstable\nPortability :  non-portable (not tested)\n\nDefault values and constants.\n\n* Changelog\n\n-}\n\nmodule Defaults where\n\nimport           DNAModel              ( DNAModelSpec(..))\nimport           Numeric.LinearAlgebra\nimport qualified System.Random         as Rand\n\n-- | Output file name.\noutFileName :: String\noutFileName = \"Test\"\n\n-- | Virtual population size.\npopSize :: Int\npopSize = 9\n\n-- | A kappa value of 6.25 corresponds to a transition to transversion ratio of\n-- 3.0\ndnaModelSpec :: DNAModelSpec\ndnaModelSpec = HKY 6.25 (vector [0.3, 0.2, 0.2, 0.3])\n\n-- | Heterozygosity value.\nheterozygosity :: Double\nheterozygosity = 0.0025\n\n-- | Tree height.\ntreeHeight :: Double\ntreeHeight = 0.005\n\n-- | Tree type. At the moment, ILS (incomplete lineage sorting) and Yule trees\n-- are supported.\ntreeType :: String\ntreeType = \"ILS\"\n\n-- | Number of sites to simulate.\nnSites :: Int\nnSites = 1000000\n\n-- | By default, the seed is random.\nseed :: IO Rand.StdGen\nseed = Rand.getStdGen\n", "meta": {"hexsha": "a77778380860c070ce8ca057813a503069a20e12", "size": 1151, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Defaults.hs", "max_stars_repo_name": "dschrempf/bmm-simulate", "max_stars_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-14T15:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T15:53:08.000Z", "max_issues_repo_path": "src/Defaults.hs", "max_issues_repo_name": "pomo-dev/bmm-simulate", "max_issues_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "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/Defaults.hs", "max_forks_repo_name": "pomo-dev/bmm-simulate", "max_forks_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "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": 20.9272727273, "max_line_length": 79, "alphanum_fraction": 0.6907037359, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.23805433908392962}}
{"text": "-- |\n-- Module      : Occlusion.Types\n-- Description :\n-- Copyright   : (c) Jonatan H Sundqvist, 2015\n-- License     : MIT\n-- Maintainer  : Jonatan H Sundqvist\n-- Stability   : experimental|stable\n-- Portability : POSIX (not sure)\n--\n\n-- Created September 20 2015\n\n-- TODO | -\n--        -\n\n-- SPEC | -\n--        -\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- GHC Pragmas\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n--------------------------------------------------------------------------------------------------------------------------------------------\nmodule Occlusion.Types where\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n--------------------------------------------------------------------------------------------------------------------------------------------\nimport Data.Complex\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\nimport Graphics.UI.Gtk\nimport qualified Graphics.Rendering.Cairo as Cairo\n\nimport           Southpaw.Picasso.Palette (Colour)\nimport qualified Southpaw.Picasso.Palette as Palette\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- Types\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n-- |\ndata AppState = AppState { _gui :: GUI, _animation :: AnimationData, _input :: InputData, _scene :: Scene, _assets :: Assets }\n\n\n-- |\ndata GUI = GUI { _window :: Window,  _canvas :: DrawingArea }\n\n\n-- |\ndata InputData = InputData { _mouse :: Complex Double, _click :: Maybe (Complex Double), _keyboard :: S.Set String }\n\n\n-- |\ndata AnimationData = AnimationData { _fps :: Double, _frame :: Int }\n\n\n-- |\ndata Assets = Assets { _images :: M.Map String Cairo.Surface } --  _strings }\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n-- |\ntype Polygon n = [Complex n]\ntype Edge n    = [Complex n]\ntype Linear n  = (n, n) -- TODO: Use custom type (eg. Linear { slope :: n, intercept :: n })\ndata Line n    = Line (Complex n) (Complex n)\n-- type Scene n   = [Polygon n]\n\n\n-- |\ndata Scene = Scene { _player :: Character, _npcs :: [Character], _obstacles :: [Polygon Double] }\n\n\n-- |\n-- TODO: Factor out stats, behaviour, visuals, 'physics', etc.\n-- TODO: Should it be Behaviour Character AppState AppState (would allow player to modify world, maybe some restricted subset of it)\ndata Character = Character { _position :: Complex Double, _velocity :: Complex Double, _health :: Int, _name :: String, _colour :: Colour Double, _behaviour :: Behaviour Character AppState Character }\n\n\n-- |\n-- TODO: This type should be much more flexible\n-- TOOD: Should this be a newtype or type synonym instead (?)\ntype Behaviour self s s' = self -> s -> s'\n-- newtype Behaviour self s s' = Behaviour { _respond :: self -> s -> s' }\n-- data Behaviour self s s' = Behaviour { _respond :: self -> s -> s' }\n", "meta": {"hexsha": "eca2a16a19985b72769a10b0fd0a4ff9bb9f725c", "size": 3478, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Occlusion/Types.hs", "max_stars_repo_name": "SwiftsNamesake/Occlusion", "max_stars_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "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": "src/Occlusion/Types.hs", "max_issues_repo_name": "SwiftsNamesake/Occlusion", "max_issues_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "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": "src/Occlusion/Types.hs", "max_forks_repo_name": "SwiftsNamesake/Occlusion", "max_forks_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "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.78, "max_line_length": 200, "alphanum_fraction": 0.419493962, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.23765613952648723}}
{"text": "-- |\n-- Module      : main\n-- Description : Graphics module leveraging the Gloss package\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-- June 2 2015\n--\n\n-- TODO | - \n--        - \n\n-- SPEC | -\n--        -\n\n\n\nmodule GlossGraphics where\n\n\n\n---------------------------------------------------------------------------------------------------\n-- We'll need these\n---------------------------------------------------------------------------------------------------\n-- import Graphics.Gloss.Data.Picture (line)\nimport qualified Graphics.Gloss as Gloss --(circleSolid, rectangleSolid)\nimport Graphics.Gloss.Interface.IO.Game hiding (Vector)\n-- import Graphics.Gloss.Geometry.Angle (degToRad, radToDeg, normaliseAngle)\n-- import Graphics.Gloss.Data.Vector\n\nimport Data.Complex\n\nimport Copernicus\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Types\n---------------------------------------------------------------------------------------------------\ndata World = World { bodies :: [Body Float],\n                     grid   :: Bool\n                   }\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Interaction\n---------------------------------------------------------------------------------------------------\nsimulate :: IO ()\nsimulate = playIO\n\tdisplay \t-- Window mode\n\twhite \t\t-- Background colour\n\t60\t\t\t-- FPS (simulation steps per second, technically)\n\tworld \t\t-- Initial world\n\trender\t\t-- Converts world to Picture\n\trespond \t-- User interaction\n\tadvance \t-- Advances the world to the next simulation step\n\twhere\n\t\tdisplay = InWindow \"Simulator\" (width, height) (25, 25)\n\t\tworld   = World { bodies = map (\\ (p', v', g') -> Body p' v' g') [(0.0:+0.0, v, g), (10.0:+0.0, (-20.0):+15.0, g), (35.0:+(-28.0), v, g), (20.5:+19.2, v, g)],\n\t                      grid   = True\n\t              }\n\t\t-- TODO: Refactor this ugly mess\n\t\trender w \t \t\t  = return . pictures $ zipWith drawBall colours (bodies w) ++ [drawGround (bodies w)] ++ if grid w then [renderGrid 45 45 width height] else [] \n\t\tdrawBall col (Body (x:+y) _ _) = color col . translate x y $ circleSolid 15 \t\t\t\t\t\t\t\t\t\t\t\t-- TODO: Reorder arguments (?)\n\t\tdrawGround _ \t\t  = translate 0 (30/2-fromIntegral height/2) . color green $ Gloss.rectangleSolid (fromIntegral width) 30\n\t\trespond e w           = return $ case e of\n\t\t\tEventKey (Char 'g') Down _ _ -> w { grid = not $ grid w }\n\t\t\t_                            -> w\n\n\t\tadvance t w \t\t  = return $ w { bodies=map (animate t) $ bodies w }\n\t\tv \t\t\t\t\t  = 40.0:+20.0 --40.0 :+ 20.0\n\t\tg \t\t\t\t\t  = 0.0:+(-98.2) --0.0 :+ (-9.82)\n\t\t(width, height) \t  = (740, 540)\n\t\tcolours = cycle [red, green, orange, makeColor 0.2 0.1 0.3 1.0]\n\t\t--parabola t v a p = let (px:+py) = p; (vx:+vy) = v; (ax:+ay) = a in (px + vx*t + 0.5*ax*t**2):+(py + vy*t + 0.5*ay*t**2)\n\n\n\n--\n--renderForces\n\n\n\n--\n-- Subgrids, colours, thickness, markings, hover for coordinates, snap-to-grid\nrenderGrid :: Float -> Float -> Int -> Int -> Picture\nrenderGrid dx dy w' h' = pictures $ rows ++ cols\n\twhere\n\t\tcols = map (\\cl -> line [(cl*dx-w/2, -h/2), (cl*dx-w/2, h/2)]) [1..cls]\n\t\trows = map (\\rw -> line [(-w/2, rw*dy-h/2), (w/2, rw*dy-h/2)]) [1..rws]\n\t\trws  = h / dy -- Number of rows\n\t\tcls  = w / dx -- Number of columns\n\t\tw \t = fromIntegral w'\n\t\th \t = fromIntegral h'\n\n\n\n-- Transforms a vector from one coordinate space to another\n-- by applying the given scaling and translation\n-- Useful for converting between simulation and screen coordinates\n-- TODO: Make pure (eg. use for pure coordinates so it doesn't depend on Gloss) (?)\ntransform :: Vector Float -> Vector Float -> Picture -> Picture\ntransform (sx:+sy) (dx:+dy) = scale sx sy . translate dx dy", "meta": {"hexsha": "0f85018df7b8d8dfd12835ea9133197b1c1d3164", "size": 3877, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "GlossGraphics.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": "GlossGraphics.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": "GlossGraphics.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": 35.8981481481, "max_line_length": 160, "alphanum_fraction": 0.5101882899, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2369721616383417}}
{"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 = \u03bb x@ and generalized @A x = \u03bb 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 \"<primme.h>\"\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 OverloadedStrings #-}\n\nmodule Haskem.Lib\n    ( doGaussianParsing,\n      doFreqParsing,\n      doGenericParsing,\n      xyzParser,\n      gaussianFreqParser,\n      gaussianParser,\n      elemMass,\n      elemSym2Num,\n      calculateCoM,\n      calcDisplacementVector,\n      writeMoleculeToXYZ,\n      projectDonN,\n      calcProjectionVec,\n      calcLength3D,\n      setUpBonds,\n      setUpBonds',\n      setUpBonds'',\n      setUpBonds''',\n      checkBondCompleteness\n    ) where\n\nimport              Haskem.Parsers\nimport              Haskem.Types\nimport              Control.Applicative\nimport qualified    Formatting                  as F\nimport              Data.Attoparsec.Text.Lazy   hiding (take)\nimport qualified    Data.Text.Lazy              as T\nimport qualified    Data.Text.IO                as TIO\nimport              Data.Char\nimport              Lens.Micro.Platform\nimport              Debug.Trace\nimport              Data.List                   hiding (takeWhile)\nimport              Data.List.Extra            \n-- import              Prelude                     hiding (takeWhile)\n-- import              Data.Tuple.HT               hiding (double, triple)\nimport qualified    Data.Map.Strict             as Map\nimport qualified    Data.Vector.Storable        as VS\nimport qualified    Numeric.LinearAlgebra.Data  as LA\nimport qualified    Data.IntMap                 as IM\nimport qualified    Data.IntSet                 as IS\n\nxyzFormat :: F.Format r (String -> Double -> Double -> Double -> r)\nxyzFormat = F.string F.% \"\\t\" F.% F.fixed 4 F.% \"\\t\" F.% F.fixed 4 F.% \"\\t\" F.% F.fixed 4\n\n\ndoGaussianParsing :: FilePath -> IO GaussianInfo\ndoGaussianParsing filePath = do\n    fileContent <- TIO.readFile filePath\n    let gaussParse = parseOnly gaussianParser fileContent\n\n    case gaussParse of\n        Left    err     -> error err\n        Right   gInfo   -> return gInfo\n\n\n-- Parses a Gaussian freq calculation output to a GaussianInfo instance and a \n-- list of Normalmode instances. Returns the output as a tuple in IO.\ndoFreqParsing :: FilePath -> IO (GaussianInfo, [NormalMode])\ndoFreqParsing filePath = do\n    fileContent <- TIO.readFile filePath\n\n    let gaussParse = parseOnly gaussianParser       fileContent\n    let gaussFreq  = parseOnly gaussianFreqParser   fileContent\n\n    gFreq <- case gaussFreq of\n        Left    err     -> error err\n        Right   gFreq   -> return gFreq\n\n    gInfo <- case gaussParse of\n        Left    err     -> error err\n        Right   gInfo   -> return gInfo\n\n    return (gInfo, gFreq)\n\n\n-- Parses a file using a specified parser and returns the result in IO\ndoGenericParsing :: FilePath -> Parser a -> IO a\ndoGenericParsing filePath parser = do\n    fileContent <- TIO.readFile filePath\n    let gParse = parseOnly parser fileContent\n\n    case gParse of\n        Left    err     -> error err\n        Right   gInfo   -> return gInfo\n\n\ngetListOfCoords :: Molecule -> [CartesianCoord]\ngetListOfCoords molA' = molA' ^.. atoms . each . coordinate\n\n\n-- Calculates the center of mass of a given molecule of type Molecule (from Haskem.Types)molA\ncalculateCoM :: Molecule -> CartesianCoord\ncalculateCoM molecule' = CartesianCoord xCoM yCoM zCoM\n    where \n        atomsList   = getListOfCoords molecule' \n        massList    = map elemMass $ molecule' ^.. atoms . each . atomNumber\n        fullMass    = sum massList\n        xCoM        = (/ fullMass) $ sum $ zipWith (*) massList $ map (^. xCoord) atomsList\n        yCoM        = (/ fullMass) $ sum $ zipWith (*) massList $ map (^. yCoord) atomsList\n        zCoM        = (/ fullMass) $ sum $ zipWith (*) massList $ map (^. zCoord) atomsList\n\n\n-- Calculate a displacement vector from two molecular geometries. \n-- Outputs a maybe molecule (in case the geometries do not match \n-- (checked via number of atoms and the list of element numbers))\ncalcDisplacementVector :: Molecule -> Molecule -> [CartesianCoord]\ncalcDisplacementVector molA molB = \n    do\n        let nrOfAtomsA  = molA ^. nrOfAtoms\n            nrOfAtomsB  = molA ^. nrOfAtoms\n            elemA   = molA ^.. atoms . each . atomNumber \n            elemB   = molB ^.. atoms . each . atomNumber \n        if (nrOfAtomsA == nrOfAtomsB) && (elemA == elemB)\n            then do \n                let atomsA  = getListOfCoords molA\n                    atomsB  = getListOfCoords molB\n                    xD      = zipWith (-) (map (^. xCoord) atomsA) $ map (^. xCoord) atomsB\n                    yD      = zipWith (-) (map (^. yCoord) atomsA) $ map (^. yCoord) atomsB\n                    zD      = zipWith (-) (map (^. zCoord) atomsA) $ map (^. zCoord) atomsB\n                zipWith3 CartesianCoord xD yD zD\n            else \n                []\n\n\n-- Writes a \"Molecule\" back to disk as a .xyz file                 \nwriteMoleculeToXYZ :: Molecule -> FilePath -> IO ()\nwriteMoleculeToXYZ molA fp = writeFile fp (show nrOfAtomsA \n                                ++ \"\\nThanks for using Haskem!\\n\" \n                                ++ T.unpack (T.unlines lineList))\n    where\n        coordinates = getListOfCoords molA\n        nrOfAtomsA  = molA ^. nrOfAtoms\n        elems       = map elemNum2Sym $ molA ^.. atoms . each . atomNumber\n        lineList    = zipWith4 (F.format xyzFormat)\n                        elems \n                        (map (^. xCoord) coordinates) \n                        (map (^. yCoord) coordinates) \n                        (map (^. zCoord) coordinates)\n                                \n\nprojectDonN :: [CartesianCoord] -> NormalMode -> Double\nprojectDonN displCoordsA modesA = projectCoordNM\n    where\n        displCoordsNM   = modesA ^.. displacement . each .coordinate  :: [CartesianCoord]\n        projectCoordNM  = sum [sum $ zipWith (*) \n                            (map ( ^. cc) displCoordsA) \n                            (map ( ^. cc) displCoordsNM) | cc <- [xCoord, yCoord, zCoord]] \n\n\ncalcProjectionVec :: [NormalMode] -> [CartesianCoord] -> [Double]\ncalcProjectionVec nModes displCoords = projectionVec\n        where\n            projectionVec = map (projectDonN displCoords) nModes\n\n\n{-\nBuild redundant internal coordinates from the molecular cartesian structure\n-}\n\ncalcLength3D :: CartesianCoord -> CartesianCoord -> Double\ncalcLength3D coord1 coord2 = length3D\n        where\n            length3D = sqrt . sum $ (** 2) <$> dVector \n            dVector = [(coord1 ^. axis) - (coord2 ^. axis) \n                            | axis <- [xCoord, yCoord, zCoord]]\n               \n\nsetUpBonds :: Molecule -> [(String, String, Double)]\nsetUpBonds molA = bondsList\n        where\n            atomListN   = molA ^.. atoms . each . atomNumber\n            atomListS   = map elemNum2Sym   atomListN\n            vdWList     = map covRadius     atomListN\n            enumCoords  =  zip4 [1..] atomListS vdWList $ getListOfCoords molA\n            bondsList   = [(e1 ++ show i1, e2 ++ show i2, calcLength3D c1 c2) \n                            | (i1, e1, r1, c1) <- enumCoords,\n                              (i2, e2, r2, c2) <- enumCoords,\n                              let l12 = calcLength3D c1 c2,\n                              i1 < i2 && l12 < 1.3 * (r1 + r2)\n                            ]  \n\n\nsetUpBonds' :: Molecule -> [LinearBond]\nsetUpBonds' molA = bondsList\n        where\n            atomListN'   = molA ^.. atoms . each . atomNumber\n            atomListS   = map elemNum2Sym   atomListN'\n            vdWList     = map covRadius     atomListN'\n            enumCoords  =  zip4 [1..] atomListS vdWList $ getListOfCoords molA\n            bondsList   = [LinearBond (AtomSpec e1 i1) (AtomSpec e2 i2) l12\n                            | (i1, e1, r1, c1) <- enumCoords,\n                              (i2, e2, r2, c2) <- enumCoords,\n                              i1 < i2,\n                              let l12 = calcLength3D c1 c2,\n                              l12 <= 1.3 * (r1+r2)] \n\n\nsetUpBonds'' :: Molecule -> LA.Matrix Double\nsetUpBonds'' molA = LA.reshape nrOfAtoms' bondsMatrix\n        where\n            nrOfAtoms'  = molA ^. nrOfAtoms\n            atomListN'  = molA ^.. atoms . each . atomNumber\n            atomListS   = map elemNum2Sym   atomListN'\n            vdWList     = map covRadius     atomListN'\n            enumCoords  = zip4 [1..] atomListS vdWList $ getListOfCoords molA\n            bondsMatrix = VS.fromList [bl | (i1, e1, r1, c1) <- enumCoords,\n                                            (i2, e2, r2, c2) <- enumCoords,\n                                            let l12 = calcLength3D c1 c2,\n                                            let bl  = if l12 < 1.3 * (r1+r2) then 1 else 0]\n\n\nsetUpBonds''' :: Molecule -> [IS.IntSet]\nsetUpBonds''' molA = bondsMatrix\n        where\n            nrOfAtoms'  = molA ^. nrOfAtoms\n            atomListN'  = molA ^.. atoms . each . atomNumber\n            atomListS   = map elemNum2Sym   atomListN'\n            vdWList     = map covRadius     atomListN'\n            enumCoords  = zip4 [1..] atomListS vdWList $ getListOfCoords molA\n            bondsMatrix = IS.fromList <$> chunksOf nrOfAtoms' [bl | \n                                                (i1, e1, r1, c1) <- enumCoords,\n                                                (i2, e2, r2, c2) <- enumCoords,\n                                                let l12 = calcLength3D c1 c2,\n                                                let bl  = if l12 < 1.3 * (r1+r2) then 1 else 0]\n-- TODO!\n\n\nremoveDuplicates :: (Ord a) => [a] -> [a]\nremoveDuplicates = map head . group . sort\n\n\ncheckBondCompleteness :: Molecule -> [LinearBond] -> [Atom]\ncheckBondCompleteness mol' listOfBonds' = missing    \n        where\n            nrOfAtoms'      = mol' ^. nrOfAtoms\n            atomNums'       = removeDuplicates $ map (^. bAtomA . geomNum) listOfBonds'  \n                                ++ map (^. bAtomB . geomNum) listOfBonds'\n            missingIndxs    = findIndices (`notElem` atomNums')  [1..nrOfAtoms']\n            missing         = case missingIndxs of  \n                               []   -> []\n                               _    -> concat [mol' ^.. atoms . ix ii | ii <- missingIndxs]\n\n\ndefineFragments     :: [IS.IntSet] -> [IS.IntSet]\ndefineFragments []      = []\ndefineFragments [x]     = [x]\n\ndefineFragments (a:as)  = \n    if (all null overlaps)\n        then (a:as)\n        else defineFragments reducedSet\n    where\n        setsWithOverlap ::  IS.IntSet -> [IS.IntSet] -> [IS.IntSet]\n        setsWithOverlap bond bondsList = [ii | ii <- bondsList,\n                                                not . IS.null $ IS.intersection bond ii,\n                                                bond /= ii]\n\n        overlaps = \n            [setsWithOverlap ((a:as) !! ii) (deleteNth ii (a:as))\n                | ii <- [0..length(a:as) - 1]\n            ] \n            :: [[IS.IntSet]]\n\n        reducedSet =\n            nub\n            [ IS.unions (((a:as) !! i) : (overlaps !! i))\n                | i <- [0 .. length (a:as) - 1]\n            ]\n        \n            \ndeleteNth :: Int -> [a] -> [a]\ndeleteNth n l = (take n l) ++ (drop (n + 1) l)\n\n-- defineFragments'    :: VS.Vector (IM.IntMap Int) -> VS.Vector (IM.IntMap Int)\n-- defineFragments'", "meta": {"hexsha": "6778f89edf8f221e541f7bb4fabc37bdae1758b9", "size": 11120, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Haskem/Lib.hs", "max_stars_repo_name": "FabianGD/Haskem", "max_stars_repo_head_hexsha": "510d2195e8e1e245f82f4b3bfd15584ab676168b", "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/Haskem/Lib.hs", "max_issues_repo_name": "FabianGD/Haskem", "max_issues_repo_head_hexsha": "510d2195e8e1e245f82f4b3bfd15584ab676168b", "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/Haskem/Lib.hs", "max_forks_repo_name": "FabianGD/Haskem", "max_forks_repo_head_hexsha": "510d2195e8e1e245f82f4b3bfd15584ab676168b", "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": 40.0, "max_line_length": 95, "alphanum_fraction": 0.5350719424, "num_tokens": 2842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.23675478551271303}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\nmodule Data.Outputable.Instances where\n\nimport           Control.Applicative            (ZipList)\nimport           Data.Char                      (isAlphaNum)\nimport           Data.Complex                   (Complex)\nimport           Data.Functor.Identity          (Identity)\nimport           Data.Int                       (Int16, Int32, Int64, Int8)\nimport           Data.List.NonEmpty             (NonEmpty)\nimport qualified Data.Map                       as Map\nimport           Data.Monoid                    (All, Any, Dual, First, Last,\n                                                 Product, Sum)\nimport           Data.Outputable.Class\nimport qualified Data.Semigroup                 as S (First, Last, Max, Min,\n                                                      Option, WrappedMonoid)\nimport           Data.Text                      (Text, unpack)\nimport qualified Data.Text.Lazy                 as TL (Text, unpack)\nimport           Data.Version                   (Version)\nimport           Data.Void                      (Void)\nimport           Data.Word                      (Word16, Word32, Word64, Word8)\nimport           GHC.Generics\nimport           Numeric.Natural                (Natural)\nimport           System.Exit                    (ExitCode)\nimport           Text.PrettyPrint.HughesPJClass\n\nviaPretty :: Pretty a => Int -> a -> Doc\nviaPretty _ = pPrint\n\nviaPrettyNum :: (Ord a, Num a, Pretty a) => Int -> a -> Doc\nviaPrettyNum n x\n  | n /= 0 && x < 0 = parens $ pPrint x\n  | otherwise = pPrint x\n\nviaShow _ x = text $ show x\nviaShowNum n x\n  | n /= 0 && x < 0 = parens $ viaShow n x\n  | otherwise = viaShow n x\n\ninstance Outputable Double where pprPrec = viaPrettyNum\ninstance Outputable Float where pprPrec = viaPrettyNum\ninstance Outputable Int where pprPrec = viaPrettyNum\ninstance Outputable Int8 where pprPrec = viaShowNum\ninstance Outputable Int16 where pprPrec = viaShowNum\ninstance Outputable Int32 where pprPrec = viaShowNum\ninstance Outputable Int64 where pprPrec = viaShowNum\ninstance Outputable Integer where pprPrec = viaPrettyNum\ninstance Outputable Natural where pprPrec = viaShow\ninstance Outputable Word where pprPrec = viaShow\ninstance Outputable Word8 where pprPrec = viaShow\ninstance Outputable Word16 where pprPrec = viaShow\ninstance Outputable Word32 where pprPrec = viaShow\ninstance Outputable Word64 where pprPrec = viaShow\ninstance Outputable TL.Text where pprPrec n x = doubleQuotes $ text $ TL.unpack x\ninstance Outputable Text where pprPrec n x = doubleQuotes $ text $ unpack x\ninstance Outputable a => Outputable [a] where pprPrec _ = pprList\n\ninstance Outputable Char where\n  pprPrec _ x = quotes $ char x\n  pprList = pPrint\n\ninstance Outputable Bool\ninstance Outputable Ordering\ninstance Outputable ()\ninstance Outputable DecidedStrictness\ninstance Outputable SourceStrictness\ninstance Outputable SourceUnpackedness\ninstance Outputable Associativity\ninstance Outputable Fixity\ninstance Outputable Any\ninstance Outputable All\ninstance Outputable ExitCode\ninstance Outputable Version\ninstance Outputable Void\ninstance Outputable a => Outputable (Maybe a)\ninstance Outputable p => Outputable (Par1 p)\ninstance Outputable a => Outputable (NonEmpty a)\ninstance Outputable a => Outputable (Product a)\ninstance Outputable a => Outputable (Sum a)\ninstance Outputable a => Outputable (Dual a)\ninstance Outputable a => Outputable (Last a)\ninstance Outputable a => Outputable (First a)\ninstance Outputable a => Outputable (Identity a)\ninstance Outputable a => Outputable (ZipList a)\ninstance Outputable a => Outputable (S.Option a)\ninstance Outputable m => Outputable (S.WrappedMonoid m)\ninstance Outputable a => Outputable (S.Last a)\ninstance Outputable a => Outputable (S.First a)\ninstance Outputable a => Outputable (S.Max a)\ninstance Outputable a => Outputable (S.Min a)\ninstance Outputable a => Outputable (Complex a)\ninstance (Outputable a, Outputable b) => Outputable (Either a b)\ninstance (Outputable a, Outputable b) => Outputable (a, b) where\n  pprPrec _ (a, b) = parens $ fsep $ punctuate comma [ppr a, ppr b]\ninstance (Outputable a, Outputable b, Outputable c) => Outputable (a, b, c) where\n  pprPrec _ (a, b, c) = parens $ fsep $ punctuate comma [ppr a, ppr b, ppr c]\ninstance (Outputable a, Outputable b, Outputable c, Outputable d) => Outputable (a, b, c, d) where\n  pprPrec _ (a, b, c, d) = parens $ fsep $ punctuate comma [ppr a, ppr b, ppr c, ppr d]\ninstance (Outputable a, Outputable b, Outputable c, Outputable d, Outputable e) => Outputable (a, b, c, d, e) where\n  pprPrec _ (a, b, c, d, e) = parens $ fsep $ punctuate comma [ppr a, ppr b, ppr c, ppr d, ppr e]\n\ninstance (Outputable k, Outputable v) => Outputable (Map.Map k v) where\n  pprPrec _ m = \"fromList\" <+> ppr (Map.toList m)\n", "meta": {"hexsha": "f549e871d053b1260d33e9758bd64dec0d6e5186", "size": 4790, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Outputable/Instances.hs", "max_stars_repo_name": "takoeight0821/outputable", "max_stars_repo_head_hexsha": "b881db5ef754601fcc1cd6a110c49309154f6b3b", "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/Data/Outputable/Instances.hs", "max_issues_repo_name": "takoeight0821/outputable", "max_issues_repo_head_hexsha": "b881db5ef754601fcc1cd6a110c49309154f6b3b", "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/Data/Outputable/Instances.hs", "max_forks_repo_name": "takoeight0821/outputable", "max_forks_repo_head_hexsha": "b881db5ef754601fcc1cd6a110c49309154f6b3b", "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": 46.5048543689, "max_line_length": 115, "alphanum_fraction": 0.6734864301, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.236082533665452}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# OPTIONS_GHC -Wall #-}\n\n-- |\n-- Module      :  Numeric.NLOPT\n-- Copyright   :  (c) Matthew Peddie 2017\n-- License     :  BSD3\n-- Maintainer  :  Matthew Peddie <mpeddie@gmail.com>\n-- Stability   :  provisional\n-- Portability :  GHC\n--\n-- This module provides a high-level, @hmatrix@-compatible interface to\n-- the <http://ab-initio.mit.edu/wiki/index.php/NLopt NLOPT> library by\n-- Steven G. Johnson.\n--\n-- = Documentation\n--\n-- Most non-numerical details are documented, but for specific\n-- information on what the optimization methods do, how constraints are\n-- handled, etc., you should consult:\n--\n--   * The <http://ab-initio.mit.edu/wiki/index.php/NLopt_Introduction NLOPT introduction>\n--\n--   * The <http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference NLOPT reference manual>\n--\n--   * The <http://ab-initio.mit.edu/wiki/index.php/NLopt_Algorithms NLOPT algorithm manual>\n--\n-- = Example program\n--\n-- The following interactive session example uses the Nelder-Mead simplex\n-- algorithm, a derivative-free local optimizer, to minimize a trivial\n-- function with a minimum of 22.0 at @(0, 0)@.\n--\n-- >>> import Numeric.LinearAlgebra ( dot, fromList )\n-- >>> let objf x = x `dot` x + 22                         -- define objective\n-- >>> let stop = ObjectiveRelativeTolerance 1e-6 :| []    -- define stopping criterion\n-- >>> let algorithm = NELDERMEAD objf [] Nothing          -- specify algorithm\n-- >>> let problem = LocalProblem 2 stop algorithm         -- specify problem\n-- >>> let x0 = fromList [5, 10]                           -- specify initial guess\n-- >>> minimizeLocal problem x0\n-- Right (Solution {solutionCost = 22.0, solutionParams = [0.0,0.0], solutionResult = FTOL_REACHED})\nmodule Numeric.NLOPT\n  ( -- * Specifying the objective function\n    Objective,\n    ObjectiveD,\n    Preconditioner,\n\n    -- * Specifying the constraints\n\n    -- ** Bound constraints\n    Bounds (..),\n\n    -- ** Nonlinear constraints\n\n    --\n    -- $nonlinearconstraints\n\n    -- *** Constraint functions\n    ScalarConstraint,\n    ScalarConstraintD,\n    VectorConstraint,\n    VectorConstraintD,\n\n    -- *** Constraint types\n    Constraint (..),\n    EqualityConstraint (..),\n    InequalityConstraint (..),\n\n    -- *** Collections of constraints\n    EqualityConstraints,\n    EqualityConstraintsD,\n    InequalityConstraints,\n    InequalityConstraintsD,\n\n    -- * Stopping conditions\n\n    --\n    -- $nonempty\n    StoppingCondition (..),\n    NonEmpty (..),\n\n    -- * Additional configuration\n    RandomSeed (..),\n    Population (..),\n    VectorStorage (..),\n    InitialStep (..),\n\n    -- * Minimization problems\n\n    -- ** Local minimization\n    LocalAlgorithm (..),\n    LocalProblem (..),\n    minimizeLocal,\n\n    -- ** Global minimization\n    GlobalAlgorithm (..),\n    GlobalProblem (..),\n    minimizeGlobal,\n\n    -- ** Minimization by augmented Lagrangian\n    AugLagAlgorithm (..),\n    AugLagProblem (..),\n    minimizeAugLag,\n\n    -- ** Results\n    Solution (..),\n    N.Result (..),\n  )\nwhere\n\nimport Control.Exception (Exception)\nimport qualified Control.Exception as Ex\nimport Data.Foldable (traverse_)\nimport Data.List.NonEmpty (NonEmpty (..))\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Storable as V\nimport Numeric.LinearAlgebra as HM\nimport qualified Numeric.Optimization.NLOPT.Bindings as N\nimport System.IO.Unsafe (unsafePerformIO)\n\n{- Function wrapping for the immutable HMatrix interface -}\nwrapScalarFunction :: (Vector Double -> Double) -> N.ScalarFunction ()\nwrapScalarFunction f params _ _ = return $ f params\n\nwrapScalarFunctionD ::\n  (Vector Double -> (Double, Vector Double)) ->\n  N.ScalarFunction ()\nwrapScalarFunctionD f params grad _ = do\n  case grad of\n    Nothing -> return ()\n    Just g -> V.copy g usergrad\n  return result\n  where\n    (result, usergrad) = f params\n\nwrapVectorFunction ::\n  (Vector Double -> Word -> Vector Double) ->\n  Word ->\n  N.VectorFunction ()\nwrapVectorFunction f n params vout _ _ = V.copy vout $ f params n\n\nwrapVectorFunctionD ::\n  (Vector Double -> Word -> (Vector Double, Matrix Double)) ->\n  Word ->\n  N.VectorFunction ()\nwrapVectorFunctionD f n params vout jac _ = do\n  V.copy vout result\n  case jac of\n    Nothing -> return ()\n    Just j -> V.copy j (HM.flatten userjac)\n  where\n    (result, userjac) = f params n\n\nwrapPreconditionerFunction ::\n  (Vector Double -> Vector Double -> Vector Double) ->\n  N.PreconditionerFunction ()\nwrapPreconditionerFunction f params v vpre _ = V.copy vpre (f params v)\n\n{- Objective functions -}\n\n-- | An objective function that calculates the objective value at the\n-- given parameter vector.\ntype Objective =\n  -- | Parameter vector\n  Vector Double ->\n  -- | Objective function value\n  Double\n\n-- | An objective function that calculates both the objective value\n-- and the gradient of the objective with respect to the input\n-- parameter vector, at the given parameter vector.\ntype ObjectiveD =\n  -- | Parameter vector\n  Vector Double ->\n  -- | (Objective function value, gradient)\n  (Double, Vector Double)\n\n-- | A preconditioner function, which computes @vpre = H(x) v@, where\n-- @H@ is the Hessian matrix: the positive semi-definite second\n-- derivative at the given parameter vector @x@, or an approximation\n-- thereof.\ntype Preconditioner =\n  -- | Parameter vector @x@\n  Vector Double ->\n  -- | Vector @v@ to precondition at @x@\n  Vector Double ->\n  -- | Preconditioned vector @vpre@\n  Vector Double\n\ndata ObjectiveFunction f\n  = MinimumObjective f\n  | PreconditionedMinimumObjective Preconditioner f\n\napplyObjective :: N.Opt -> ObjectiveFunction Objective -> IO N.Result\napplyObjective opt (MinimumObjective f) =\n  N.set_min_objective opt (wrapScalarFunction f) ()\napplyObjective opt (PreconditionedMinimumObjective p f) =\n  N.set_precond_min_objective\n    opt\n    (wrapScalarFunction f)\n    (wrapPreconditionerFunction p)\n    ()\n\napplyObjectiveD :: N.Opt -> ObjectiveFunction ObjectiveD -> IO N.Result\napplyObjectiveD opt (MinimumObjective f) =\n  N.set_min_objective opt (wrapScalarFunctionD f) ()\napplyObjectiveD opt (PreconditionedMinimumObjective p f) =\n  N.set_precond_min_objective\n    opt\n    (wrapScalarFunctionD f)\n    (wrapPreconditionerFunction p)\n    ()\n\n{- Constraint functions -}\n\n-- | A constraint function which returns @c(x)@ given the parameter\n-- vector @x@.  The constraint will enforce that @c(x) == 0@ (equality\n-- constraint) or @c(x) <= 0@ (inequality constraint).\ntype ScalarConstraint =\n  -- | Parameter vector @x@\n  Vector Double ->\n  -- | Constraint violation (deviation from 0)\n  Double\n\n-- | A constraint function which returns @c(x)@ given the parameter\n-- vector @x@ along with the gradient of @c(x)@ with respect to @x@ at\n-- that point.  The constraint will enforce that @c(x) == 0@ (equality\n-- constraint) or @c(x) <= 0@ (inequality constraint).\ntype ScalarConstraintD =\n  -- | Parameter vector\n  Vector Double ->\n  -- | (Constraint violation, constraint gradient)\n  (Double, Vector Double)\n\n-- | A constraint function which returns a vector @c(x)@ given the\n-- parameter vector @x@.  The constraint will enforce that @c(x) == 0@\n-- (equality constraint) or @c(x) <= 0@ (inequality constraint).\ntype VectorConstraint =\n  -- | Parameter vector\n  Vector Double ->\n  -- | Constraint vector size\n  Word ->\n  -- | Constraint violation vector\n  Vector Double\n\n-- | A constraint function which returns @c(x)@ given the parameter\n-- vector @x@ along with the Jacobian (first derivative) matrix of\n-- @c(x)@ with respect to @x@ at that point.  The constraint will\n-- enforce that @c(x) == 0@ (equality constraint) or @c(x) <= 0@\n-- (inequality constraint).\ntype VectorConstraintD =\n  -- | Parameter vector\n  Vector Double ->\n  -- | Constraint vector size\n  Word ->\n  -- | (Constraint violation vector,\n  -- constraint Jacobian)\n  (Vector Double, Matrix Double)\n\n-- $nonlinearconstraints\n--\n-- Note that most NLOPT algorithms do not support nonlinear\n-- constraints natively; if you need to enforce nonlinear constraints,\n-- you may want to use the 'AugLagAlgorithm' family of solvers, which\n-- can add nonlinear constraints to some algorithm that does not\n-- support them by a principled modification of the objective\n-- function.\n--\n-- == Example program\n--\n-- The following interactive session example enforces a scalar\n-- constraint on the problem given in the beginning of the module: the\n-- parameters must always sum to 1.  The minimizer finds a constrained\n-- minimum of 22.5 at @(0.5, 0.5)@.\n--\n-- >>> import Numeric.LinearAlgebra ( dot, fromList, toList )\n-- >>> let objf x = x `dot` x + 22\n-- >>> let stop = ObjectiveRelativeTolerance 1e-9 :| []\n-- >>>          -- define constraint function:\n-- >>> let constraintf x = sum (toList x) - 1.0\n-- >>>          -- define constraint object to pass to the algorithm:\n-- >>> let constraint = EqualityConstraint (Scalar constraintf) 1e-6\n-- >>> let algorithm = COBYLA objf [] [] [constraint] Nothing\n-- >>> let problem = LocalProblem 2 stop algorithm\n-- >>> let x0 = fromList [5, 10]\n-- >>> minimizeLocal problem x0\n-- Right (Solution {solutionCost = 22.500000000013028, solutionParams = [0.5000025521533521,0.49999744784664796], solutionResult = FTOL_REACHED})\n\ndata Constraint s v\n  = -- | A scalar constraint.\n    Scalar s\n  | -- | A vector constraint.\n    Vector Word v\n  | -- | A scalar constraint with an attached preconditioning function.\n    Preconditioned Preconditioner s\n\n-- | An equality constraint, comprised of both the constraint function\n-- (or functions, if a preconditioner is used) along with the desired\n-- tolerance.\ndata EqualityConstraint s v = EqualityConstraint\n  { eqConstraintFunctions :: Constraint s v,\n    eqConstraintTolerance :: Double\n  }\n\n-- | An inequality constraint, comprised of both the constraint\n-- function (or functions, if a preconditioner is used) along with the\n-- desired tolerance.\ndata InequalityConstraint s v = InequalityConstraint\n  { ineqConstraintFunctions :: Constraint s v,\n    ineqConstraintTolerance :: Double\n  }\n\n-- | A collection of equality constraints that do not supply\n-- constraint derivatives.\ntype EqualityConstraints =\n  [EqualityConstraint ScalarConstraint VectorConstraint]\n\n-- | A collection of inequality constraints that do not supply\n-- constraint derivatives.\ntype InequalityConstraints =\n  [InequalityConstraint ScalarConstraint VectorConstraint]\n\n-- | A collection of equality constraints that supply constraint\n-- derivatives.\ntype EqualityConstraintsD = [EqualityConstraint ScalarConstraintD VectorConstraintD]\n\n-- | A collection of inequality constraints that supply constraint\n-- derivatives.\ntype InequalityConstraintsD = [InequalityConstraint ScalarConstraintD VectorConstraintD]\n\nclass ApplyConstraint constraint where\n  applyConstraint :: N.Opt -> constraint -> IO N.Result\n\ninstance ApplyConstraint (EqualityConstraint ScalarConstraint VectorConstraint) where\n  applyConstraint opt (EqualityConstraint ty tol) = case ty of\n    Scalar s ->\n      N.add_equality_constraint opt (wrapScalarFunction s) () tol\n    Vector n v ->\n      N.add_equality_mconstraint opt n (wrapVectorFunction v n) () tol\n    Preconditioned p s ->\n      N.add_precond_equality_constraint\n        opt\n        (wrapScalarFunction s)\n        (wrapPreconditionerFunction p)\n        ()\n        tol\n\ninstance ApplyConstraint (InequalityConstraint ScalarConstraint VectorConstraint) where\n  applyConstraint opt (InequalityConstraint ty tol) = case ty of\n    Scalar s ->\n      N.add_inequality_constraint opt (wrapScalarFunction s) () tol\n    Vector n v ->\n      N.add_inequality_mconstraint opt n (wrapVectorFunction v n) () tol\n    Preconditioned p s ->\n      N.add_precond_inequality_constraint\n        opt\n        (wrapScalarFunction s)\n        (wrapPreconditionerFunction p)\n        ()\n        tol\n\ninstance ApplyConstraint (EqualityConstraint ScalarConstraintD VectorConstraintD) where\n  applyConstraint opt (EqualityConstraint ty tol) = case ty of\n    Scalar s ->\n      N.add_equality_constraint opt (wrapScalarFunctionD s) () tol\n    Vector n v ->\n      N.add_equality_mconstraint opt n (wrapVectorFunctionD v n) () tol\n    Preconditioned p s ->\n      N.add_precond_equality_constraint\n        opt\n        (wrapScalarFunctionD s)\n        (wrapPreconditionerFunction p)\n        ()\n        tol\n\ninstance ApplyConstraint (InequalityConstraint ScalarConstraintD VectorConstraintD) where\n  applyConstraint opt (InequalityConstraint ty tol) = case ty of\n    Scalar s ->\n      N.add_inequality_constraint opt (wrapScalarFunctionD s) () tol\n    Vector n v ->\n      N.add_inequality_mconstraint opt n (wrapVectorFunctionD v n) () tol\n    Preconditioned p s ->\n      N.add_precond_inequality_constraint\n        opt\n        (wrapScalarFunctionD s)\n        (wrapPreconditionerFunction p)\n        ()\n        tol\n\n{- Bounds -}\n\n-- | Bound constraints are specified by vectors of the same dimension\n-- as the parameter space.\n--\n-- == Example program\n--\n-- The following interactive session example enforces lower bounds on\n-- the example from the beginning of the module.  This prevents the\n-- optimizer from locating the true minimum at @(0, 0)@; a slightly\n-- higher constrained minimum at @(1, 1)@ is found.  Note that the\n-- optimizer returns 'N.XTOL_REACHED' rather than 'N.FTOL_REACHED',\n-- because the bound constraint is active at the final minimum.\n--\n-- >>> import Numeric.LinearAlgebra ( dot, fromList )\n-- >>> let objf x = x `dot` x + 22                           -- define objective\n-- >>> let stop = ObjectiveRelativeTolerance 1e-6 :| []      -- define stopping criterion\n-- >>> let lowerbound = LowerBounds $ fromList [1, 1]        -- specify bounds\n-- >>> let algorithm = NELDERMEAD objf [lowerbound] Nothing  -- specify algorithm\n-- >>> let problem = LocalProblem 2 stop algorithm           -- specify problem\n-- >>> let x0 = fromList [5, 10]                             -- specify initial guess\n-- >>> minimizeLocal problem x0\n-- Right (Solution {solutionCost = 24.0, solutionParams = [1.0,1.0], solutionResult = XTOL_REACHED})\ndata Bounds\n  = -- | Lower bound vector @v@ means we want @x >= v@.\n    LowerBounds (Vector Double)\n  | -- | Upper bound vector @u@ means we want @x <= u@.\n    UpperBounds (Vector Double)\n  deriving (Eq, Show, Read)\n\napplyBounds :: N.Opt -> Bounds -> IO N.Result\napplyBounds opt (LowerBounds lbvec) = N.set_lower_bounds opt lbvec\napplyBounds opt (UpperBounds ubvec) = N.set_upper_bounds opt ubvec\n\n{- Stopping conditions -}\n\n-- | A 'StoppingCondition' tells NLOPT when to stop working on a\n-- minimization problem.  When multiple 'StoppingCondition's are\n-- provided, the problem will stop when any one condition is met.\ndata StoppingCondition\n  = -- | Stop minimizing when an objective value @J@ less than or equal\n    -- to the provided value is found.\n    MinimumValue Double\n  | -- | Stop minimizing when an optimization step changes the objective\n    -- value @J@ by less than the provided tolerance multiplied by @|J|@.\n    ObjectiveRelativeTolerance Double\n  | -- | Stop minimizing when an optimization step changes the objective\n    -- value by less than the provided tolerance.\n    ObjectiveAbsoluteTolerance Double\n  | -- | Stop when an optimization step changes /every element/ of the\n    -- parameter vector @x@ by less than @x@ scaled by the provided\n    -- tolerance.\n    ParameterRelativeTolerance Double\n  | -- | Stop when an optimization step changes /every element/ of the\n    -- parameter vector @x@ by less than the corresponding element in\n    -- the provided vector of tolerances values.\n    ParameterAbsoluteTolerance (Vector Double)\n  | -- | Stop when the number of evaluations of the objective function\n    -- exceeds the provided count.\n    MaximumEvaluations Word\n  | -- | Stop when the optimization time exceeds the provided time (in\n    -- seconds).  This is not a precise limit.\n    MaximumTime Double\n  deriving (Eq, Show, Read)\n\n-- $nonempty\n--\n-- The 'NonEmpty' data type from 'Data.List.NonEmpty' is re-exported\n-- here, because it is used to ensure that you always specify at least\n-- one stopping condition.\n\napplyStoppingCondition :: N.Opt -> StoppingCondition -> IO N.Result\napplyStoppingCondition opt (MinimumValue x) = N.set_stopval opt x\napplyStoppingCondition opt (ObjectiveRelativeTolerance x) = N.set_ftol_rel opt x\napplyStoppingCondition opt (ObjectiveAbsoluteTolerance x) = N.set_ftol_abs opt x\napplyStoppingCondition opt (ParameterRelativeTolerance x) = N.set_xtol_rel opt x\napplyStoppingCondition opt (ParameterAbsoluteTolerance v) = N.set_xtol_abs opt v\napplyStoppingCondition opt (MaximumEvaluations n) = N.set_maxeval opt n\napplyStoppingCondition opt (MaximumTime deltat) = N.set_maxtime opt deltat\n\n{- Random seed control -}\n\n-- | This specifies how to initialize the random number generator for\n-- stochastic algorithms.\ndata RandomSeed\n  = -- | Seed the RNG with the provided value.\n    SeedValue Word\n  | -- | Seed the RNG using the system clock.\n    SeedFromTime\n  | -- | Don't perform any explicit initialization of the RNG.\n    Don'tSeed\n  deriving (Eq, Show, Read)\n\napplyRandomSeed :: RandomSeed -> IO ()\napplyRandomSeed Don'tSeed = return ()\napplyRandomSeed (SeedValue n) = N.srand n\napplyRandomSeed SeedFromTime = N.srand_time\n\n{- Random stuff -}\n\n-- | This specifies the population size for algorithms that use a pool\n-- of solutions.\nnewtype Population = Population Word deriving (Eq, Show, Read)\n\napplyPopulation :: N.Opt -> Population -> IO N.Result\napplyPopulation opt (Population n) = N.set_population opt n\n\n-- | This specifies the memory size to be used by algorithms like\n-- 'LBFGS' which store approximate Hessian or Jacobian matrices.\nnewtype VectorStorage = VectorStorage Word deriving (Eq, Show, Read)\n\napplyVectorStorage :: N.Opt -> VectorStorage -> IO N.Result\napplyVectorStorage opt (VectorStorage n) = N.set_vector_storage opt n\n\n-- | This vector with the same dimension as the parameter vector @x@\n-- specifies the initial step for the optimizer to take.  (This\n-- applies to local gradient-free algorithms, which cannot use\n-- gradients to estimate how big a step to take.)\nnewtype InitialStep = InitialStep (Vector Double) deriving (Eq, Show, Read)\n\napplyInitialStep :: N.Opt -> InitialStep -> IO N.Result\napplyInitialStep opt (InitialStep v) = N.set_initial_step opt v\n\n{- Algorithms -}\n\ndata GlobalProblem = GlobalProblem\n  { -- | Lower bounds for @x@\n    lowerBounds :: Vector Double,\n    -- | Upper bounds for @x@\n    upperBounds :: Vector Double,\n    -- | At least one stopping\n    -- condition\n    gstop :: NonEmpty StoppingCondition,\n    -- | Algorithm specification\n    galgorithm :: GlobalAlgorithm\n  }\n\n-- | These are the global minimization algorithms provided by NLOPT.  Please see\n-- <http://ab-initio.mit.edu/wiki/index.php/NLopt_Algorithms the NLOPT algorithm manual>\n-- for more details on how the methods work and how they relate to one another.\n--\n-- Optional parameters are wrapped in a 'Maybe'; for example, if you\n-- see 'Maybe' 'Population', you can simply specify 'Nothing' to use\n-- the default behavior.\n--\n-- N.B.: There may be at most n equality constraints for problems with n dimensions due to restrictions\n-- in NLopt. This may be circumvented by combination of equality constraints according to: \n-- h1(x)==0 && h2(x)==0 <=> h1(x)^2+h2(x)^2==0.\ndata GlobalAlgorithm\n  = -- | DIviding RECTangles\n    DIRECT Objective\n  | -- | DIviding RECTangles, locally-biased variant\n    DIRECT_L Objective\n  | -- | DIviding RECTangles, \"slightly randomized\"\n    DIRECT_L_RAND Objective RandomSeed\n  | -- | DIviding RECTangles, unscaled version\n    DIRECT_NOSCAL Objective\n  | -- | DIviding RECTangles, locally-biased and unscaled\n    DIRECT_L_NOSCAL Objective\n  | -- | DIviding RECTangles, locally-biased, unscaled and \"slightly\n    -- randomized\"\n    DIRECT_L_RAND_NOSCAL Objective RandomSeed\n  | -- | DIviding RECTangles, original FORTRAN implementation\n    ORIG_DIRECT Objective InequalityConstraints\n  | -- | DIviding RECTangles, locally-biased, original FORTRAN\n    -- implementation\n    ORIG_DIRECT_L Objective InequalityConstraints\n  | -- | Stochastic Global Optimization.\n    -- __This algorithm is only available if you have linked with @libnlopt_cxx@.__\n    STOGO ObjectiveD\n  | -- | Stochastic Global Optimization, randomized variant.\n    -- __This algorithm is only available if you have linked with @libnlopt_cxx@.__\n    STOGO_RAND ObjectiveD RandomSeed\n  | -- | Controlled Random Search with Local Mutation\n    CRS2_LM Objective RandomSeed (Maybe Population)\n  | -- | Improved Stochastic Ranking Evolution Strategy, the population defaults to 20\u00d7(n+1) in n dimensions\n    ISRES Objective InequalityConstraints EqualityConstraints RandomSeed (Maybe Population)\n  | -- | Evolutionary Algorithm\n    ESCH Objective\n  | -- | Original Multi-Level Single-Linkage\n    MLSL Objective LocalProblem (Maybe Population)\n  | -- | Multi-Level Single-Linkage with Sobol Low-Discrepancy\n    -- Sequence for starting points\n    MLSL_LDS Objective LocalProblem (Maybe Population)\n\nalgorithmEnumOfGlobal :: GlobalAlgorithm -> N.Algorithm\nalgorithmEnumOfGlobal (DIRECT _) = N.GN_DIRECT\nalgorithmEnumOfGlobal (DIRECT_L _) = N.GN_DIRECT_L\nalgorithmEnumOfGlobal (DIRECT_L_RAND _ _) = N.GN_DIRECT_L_RAND\nalgorithmEnumOfGlobal (DIRECT_NOSCAL _) = N.GN_DIRECT_NOSCAL\nalgorithmEnumOfGlobal (DIRECT_L_NOSCAL _) = N.GN_DIRECT_L_NOSCAL\nalgorithmEnumOfGlobal (DIRECT_L_RAND_NOSCAL _ _) = N.GN_DIRECT_L_RAND_NOSCAL\nalgorithmEnumOfGlobal (ORIG_DIRECT _ _) = N.GN_ORIG_DIRECT\nalgorithmEnumOfGlobal (ORIG_DIRECT_L _ _) = N.GN_ORIG_DIRECT_L\nalgorithmEnumOfGlobal (STOGO _) = N.GD_STOGO\nalgorithmEnumOfGlobal (STOGO_RAND _ _) = N.GD_STOGO_RAND\nalgorithmEnumOfGlobal (CRS2_LM _ _ _) = N.GN_CRS2_LM\nalgorithmEnumOfGlobal (ISRES _ _ _ _ _) = N.GN_ISRES\nalgorithmEnumOfGlobal (ESCH _) = N.GN_ESCH\nalgorithmEnumOfGlobal (MLSL _ _ _) = N.G_MLSL\nalgorithmEnumOfGlobal (MLSL_LDS _ _ _) = N.G_MLSL_LDS\n\napplyGlobalObjective :: N.Opt -> GlobalAlgorithm -> IO ()\napplyGlobalObjective opt alg = go alg\n  where\n    obj = tryTo . applyObjective opt . MinimumObjective\n    objD = tryTo . applyObjectiveD opt . MinimumObjective\n\n    go (DIRECT o) = obj o\n    go (DIRECT_L o) = obj o\n    go (DIRECT_NOSCAL o) = obj o\n    go (DIRECT_L_NOSCAL o) = obj o\n    go (ESCH o) = obj o\n    go (STOGO o) = objD o\n    go (DIRECT_L_RAND o _) = obj o\n    go (DIRECT_L_RAND_NOSCAL o _) = obj o\n    go (ORIG_DIRECT o _) = obj o\n    go (ORIG_DIRECT_L o _) = obj o\n    go (STOGO_RAND o _) = objD o\n    go (CRS2_LM o _ _) = obj o\n    go (ISRES o _ _ _ _) = obj o\n    go (MLSL o _ _) = obj o\n    go (MLSL_LDS o _ _) = obj o\n\napplyGlobalAlgorithm :: N.Opt -> GlobalAlgorithm -> IO ()\napplyGlobalAlgorithm opt alg = do\n  applyGlobalObjective opt alg\n  go alg\n  where\n    seed = applyRandomSeed\n    pop = maybe (return ()) (tryTo . applyPopulation opt)\n    ic = traverse_ (tryTo . applyConstraint opt)\n    ec = traverse_ (tryTo . applyConstraint opt)\n\n    local lp = setupLocalProblem lp >>= N.set_local_optimizer opt\n\n    go (DIRECT_L_RAND _ s) = seed s\n    go (DIRECT_L_RAND_NOSCAL _ s) = seed s\n    go (ORIG_DIRECT _ ineq) = ic ineq\n    go (ORIG_DIRECT_L _ ineq) = ic ineq\n    go (STOGO_RAND _ s) = seed s\n    go (CRS2_LM _ s p) = seed s *> pop p\n    go (ISRES _ ineq eq s p) = ic ineq *> ec eq *> seed s *> pop p\n    go (MLSL _ lp p) = local lp *> pop p\n    go (MLSL_LDS _ lp p) = local lp *> pop p\n    go _ = return ()\n\ntryTo :: IO N.Result -> IO ()\ntryTo act = do\n  result <- act\n  if (N.isSuccess result)\n    then return ()\n    else Ex.throw $ NloptException result\n\ndata NloptException = NloptException N.Result deriving (Show, Typeable)\n\ninstance Exception NloptException\n\n-- | Solve the specified global optimization problem.\n--\n-- = Example program\n--\n-- The following interactive session example uses the 'ISRES'\n-- algorithm, a stochastic, derivative-free global optimizer, to\n-- minimize a trivial function with a minimum of 22.0 at @(0, 0)@.\n-- The search is conducted within a box from -10 to 10 in each\n-- dimension.\n--\n-- >>> import Numeric.LinearAlgebra ( dot, fromList )\n-- >>> let objf x = x `dot` x + 22                         -- define objective\n-- >>> let stop = ObjectiveRelativeTolerance 1e-12 :| []   -- define stopping criterion\n-- >>> let algorithm = ISRES objf [] [] (SeedValue 22)     -- specify algorithm\n-- >>> let lowerbounds = fromList [-10, -10]               -- specify bounds\n-- >>> let upperbounds = fromList [10, 10]                 -- specify bounds\n-- >>> let problem = GlobalProblem lowerbounds upperbounds stop algorithm\n-- >>> let x0 = fromList [5, 8]                            -- specify initial guess\n-- >>> minimizeGlobal problem x0\n-- Right (Solution {solutionCost = 22.000000000002807, solutionParams = [-1.660591102367038e-6,2.2407062393213684e-7], solutionResult = FTOL_REACHED})\nminimizeGlobal ::\n  -- | Problem specification\n  GlobalProblem ->\n  -- | Initial parameter guess\n  Vector Double ->\n  -- | Optimization results\n  Either N.Result Solution\nminimizeGlobal prob x0 =\n  unsafePerformIO $ (Right <$> minimizeGlobal' prob x0) `Ex.catch` handler\n  where\n    handler :: NloptException -> IO (Either N.Result a)\n    handler (NloptException retcode) = return $ Left retcode\n\napplyGlobalProblem :: N.Opt -> GlobalProblem -> IO ()\napplyGlobalProblem opt (GlobalProblem lb ub stop alg) = do\n  tryTo $ applyBounds opt (LowerBounds lb)\n  tryTo $ applyBounds opt (UpperBounds ub)\n  traverse_ (tryTo . applyStoppingCondition opt) stop\n  applyGlobalAlgorithm opt alg\n\nnewOpt :: N.Algorithm -> Word -> IO N.Opt\nnewOpt alg sz = do\n  opt' <- N.create alg sz\n  case opt' of\n    Nothing -> Ex.throw $ NloptException N.FAILURE\n    Just opt -> return opt\n\nsetupGlobalProblem :: GlobalProblem -> IO N.Opt\nsetupGlobalProblem gp@(GlobalProblem _ _ _ alg) = do\n  opt <- newOpt (algorithmEnumOfGlobal alg) (problemSize gp)\n  applyGlobalProblem opt gp\n  return opt\n\nsolveProblem :: N.Opt -> Vector Double -> IO Solution\nsolveProblem opt x0 = do\n  (N.Output outret outcost outx) <- N.optimize opt x0\n  if (N.isSuccess outret)\n    then return $ Solution outcost outx outret\n    else Ex.throw $ NloptException outret\n\nminimizeGlobal' :: GlobalProblem -> Vector Double -> IO Solution\nminimizeGlobal' gp x0 = do\n  opt <- setupGlobalProblem gp\n  solveProblem opt x0\n\ndata LocalProblem = LocalProblem\n  { -- | The dimension of the\n    -- parameter vector.\n    lsize :: Word,\n    -- | At least one stopping\n    -- condition\n    lstop :: NonEmpty StoppingCondition,\n    -- | Algorithm specification\n    lalgorithm :: LocalAlgorithm\n  }\n\n-- | These are the local minimization algorithms provided by NLOPT.  Please see\n-- <http://ab-initio.mit.edu/wiki/index.php/NLopt_Algorithms the NLOPT algorithm manual>\n-- for more details on how the methods work and how they relate to one\n-- another.  Note that some local methods require you provide\n-- derivatives (gradients or Jacobians) for your objective function\n-- and constraint functions.\n--\n-- Optional parameters are wrapped in a 'Maybe'; for example, if you\n-- see 'Maybe' 'VectorStorage', you can simply specify 'Nothing' to\n-- use the default behavior.\ndata LocalAlgorithm\n  = -- | Limited-memory BFGS\n    LBFGS_NOCEDAL ObjectiveD (Maybe VectorStorage)\n  | -- | Limited-memory BFGS\n    LBFGS ObjectiveD (Maybe VectorStorage)\n  | -- | Shifted limited-memory variable-metric, rank-2\n    VAR2 ObjectiveD (Maybe VectorStorage)\n  | -- | Shifted limited-memory variable-metric, rank-1\n    VAR1 ObjectiveD (Maybe VectorStorage)\n  | -- | Truncated Newton's method\n    TNEWTON ObjectiveD (Maybe VectorStorage)\n  | -- | Truncated Newton's method with automatic restarting\n    TNEWTON_RESTART ObjectiveD (Maybe VectorStorage)\n  | -- | Preconditioned truncated Newton's method\n    TNEWTON_PRECOND ObjectiveD (Maybe VectorStorage)\n  | -- | Preconditioned truncated Newton's method with automatic\n    -- restarting\n    TNEWTON_PRECOND_RESTART ObjectiveD (Maybe VectorStorage)\n  | -- | Method of moving averages\n    MMA ObjectiveD InequalityConstraintsD\n  | -- | Sequential Least-Squares Quadratic Programming\n    SLSQP ObjectiveD [Bounds] InequalityConstraintsD EqualityConstraintsD\n  | -- | Conservative Convex Separable Approximation\n    CCSAQ ObjectiveD Preconditioner\n  | -- | PRincipal AXIS gradient-free local optimization\n    PRAXIS Objective [Bounds] (Maybe InitialStep)\n  | -- | Constrained Optimization BY Linear Approximations\n    COBYLA\n      Objective\n      [Bounds]\n      InequalityConstraints\n      EqualityConstraints\n      (Maybe InitialStep)\n  | -- | Powell's NEWUOA algorithm\n    NEWUOA Objective (Maybe InitialStep)\n  | -- | Powell's NEWUOA algorithm with bounds by SGJ\n    NEWUOA_BOUND Objective [Bounds] (Maybe InitialStep)\n  | -- | Nelder-Mead Simplex gradient-free method\n    NELDERMEAD Objective [Bounds] (Maybe InitialStep)\n  | -- | NLOPT implementation of Rowan's Subplex algorithm\n    SBPLX Objective [Bounds] (Maybe InitialStep)\n  | -- | Bounded Optimization BY Quadratic Approximations\n    BOBYQA Objective [Bounds] (Maybe InitialStep)\n\nalgorithmEnumOfLocal :: LocalAlgorithm -> N.Algorithm\nalgorithmEnumOfLocal (LBFGS_NOCEDAL _ _) = N.LD_LBFGS_NOCEDAL\nalgorithmEnumOfLocal (LBFGS _ _) = N.LD_LBFGS\nalgorithmEnumOfLocal (VAR2 _ _) = N.LD_VAR2\nalgorithmEnumOfLocal (VAR1 _ _) = N.LD_VAR1\nalgorithmEnumOfLocal (TNEWTON _ _) = N.LD_TNEWTON\nalgorithmEnumOfLocal (TNEWTON_RESTART _ _) = N.LD_TNEWTON_RESTART\nalgorithmEnumOfLocal (TNEWTON_PRECOND _ _) = N.LD_TNEWTON_PRECOND\nalgorithmEnumOfLocal (TNEWTON_PRECOND_RESTART _ _) = N.LD_TNEWTON_PRECOND_RESTART\nalgorithmEnumOfLocal (MMA _ _) = N.LD_MMA\nalgorithmEnumOfLocal (SLSQP _ _ _ _) = N.LD_SLSQP\nalgorithmEnumOfLocal (CCSAQ _ _) = N.LD_CCSAQ\nalgorithmEnumOfLocal (PRAXIS _ _ _) = N.LN_PRAXIS\nalgorithmEnumOfLocal (COBYLA _ _ _ _ _) = N.LN_COBYLA\nalgorithmEnumOfLocal (NEWUOA _ _) = N.LN_NEWUOA\nalgorithmEnumOfLocal (NEWUOA_BOUND _ _ _) = N.LN_NEWUOA\nalgorithmEnumOfLocal (NELDERMEAD _ _ _) = N.LN_NELDERMEAD\nalgorithmEnumOfLocal (SBPLX _ _ _) = N.LN_SBPLX\nalgorithmEnumOfLocal (BOBYQA _ _ _) = N.LN_BOBYQA\n\napplyLocalObjective :: N.Opt -> LocalAlgorithm -> IO ()\napplyLocalObjective opt alg = go alg\n  where\n    obj = tryTo . applyObjective opt . MinimumObjective\n    objD = tryTo . applyObjectiveD opt . MinimumObjective\n    precond p = tryTo . applyObjectiveD opt . PreconditionedMinimumObjective p\n\n    go (LBFGS_NOCEDAL o _) = objD o\n    go (LBFGS o _) = objD o\n    go (VAR2 o _) = objD o\n    go (VAR1 o _) = objD o\n    go (TNEWTON o _) = objD o\n    go (TNEWTON_RESTART o _) = objD o\n    go (TNEWTON_PRECOND o _) = objD o\n    go (TNEWTON_PRECOND_RESTART o _) = objD o\n    go (MMA o _) = objD o\n    go (SLSQP o _ _ _) = objD o\n    go (CCSAQ o prec) = precond prec o\n    go (PRAXIS o _ _) = obj o\n    go (COBYLA o _ _ _ _) = obj o\n    go (NEWUOA o _) = obj o\n    go (NEWUOA_BOUND o _ _) = obj o\n    go (NELDERMEAD o _ _) = obj o\n    go (SBPLX o _ _) = obj o\n    go (BOBYQA o _ _) = obj o\n\napplyLocalAlgorithm :: N.Opt -> LocalAlgorithm -> IO ()\napplyLocalAlgorithm opt alg = do\n  applyLocalObjective opt alg\n  go alg\n  where\n    ic = traverse_ (tryTo . applyConstraint opt)\n    icd = traverse_ (tryTo . applyConstraint opt)\n    ec = traverse_ (tryTo . applyConstraint opt)\n    ecd = traverse_ (tryTo . applyConstraint opt)\n    store = maybe (return ()) (tryTo . applyVectorStorage opt)\n    bound = traverse_ (tryTo . applyBounds opt)\n    step0 = maybe (return ()) (tryTo . applyInitialStep opt)\n\n    go (LBFGS_NOCEDAL _ vs) = store vs\n    go (LBFGS _ vs) = store vs\n    go (VAR2 _ vs) = store vs\n    go (VAR1 _ vs) = store vs\n    go (TNEWTON _ vs) = store vs\n    go (TNEWTON_RESTART _ vs) = store vs\n    go (TNEWTON_PRECOND _ vs) = store vs\n    go (TNEWTON_PRECOND_RESTART _ vs) = store vs\n    go (MMA _ ineqd) = icd ineqd\n    go (SLSQP _ b ineqd eqd) =\n      bound b *> icd ineqd *> ecd eqd\n    go (CCSAQ _ _) = return ()\n    go (PRAXIS _ b s) = bound b *> step0 s\n    go (COBYLA _ b ineq eq s) =\n      bound b *> ic ineq *> ec eq *> step0 s\n    go (NEWUOA _ s) = step0 s\n    go (NEWUOA_BOUND _ b s) = bound b *> step0 s\n    go (NELDERMEAD _ b s) = bound b *> step0 s\n    go (SBPLX _ b s) = bound b *> step0 s\n    go (BOBYQA _ b s) = bound b *> step0 s\n\napplyLocalProblem :: N.Opt -> LocalProblem -> IO ()\napplyLocalProblem opt (LocalProblem _ stop alg) = do\n  traverse_ (tryTo . applyStoppingCondition opt) stop\n  applyLocalAlgorithm opt alg\n\nsetupLocalProblem :: LocalProblem -> IO N.Opt\nsetupLocalProblem lp@(LocalProblem sz _ alg) = do\n  opt <- newOpt (algorithmEnumOfLocal alg) sz\n  applyLocalProblem opt lp\n  return opt\n\nminimizeLocal' :: LocalProblem -> Vector Double -> IO Solution\nminimizeLocal' lp x0 = do\n  opt <- setupLocalProblem lp\n  solveProblem opt x0\n\n-- |\n-- == Example program\n--\n-- The following interactive session example enforces the same scalar\n-- constraint as the nonlinear constraint example, but this time it\n-- uses the SLSQP solver to find the minimum.\n--\n-- >>> import Numeric.LinearAlgebra ( dot, fromList, toList, scale )\n-- >>> let objf x = (x `dot` x + 22, 2 `scale` x)\n-- >>> let stop = ObjectiveRelativeTolerance 1e-9 :| []\n-- >>> let constraintf x = (sum (toList x) - 1.0, fromList [1, 1])\n-- >>> let constraint = EqualityConstraint (Scalar constraintf) 1e-6\n-- >>> let algorithm = SLSQP objf [] [] [constraint]\n-- >>> let problem = LocalProblem 2 stop algorithm\n-- >>> let x0 = fromList [5, 10]\n-- >>> minimizeLocal problem x0\n-- Right (Solution {solutionCost = 22.5, solutionParams = [0.4999999999999998,0.5000000000000002], solutionResult = FTOL_REACHED})\nminimizeLocal :: LocalProblem -> Vector Double -> Either N.Result Solution\nminimizeLocal prob x0 =\n  unsafePerformIO $ (Right <$> minimizeLocal' prob x0) `Ex.catch` handler\n  where\n    handler :: NloptException -> IO (Either N.Result a)\n    handler (NloptException retcode) = return $ Left retcode\n\nclass ProblemSize c where\n  problemSize :: c -> Word\n\ninstance ProblemSize LocalProblem where\n  problemSize = lsize\n\ninstance ProblemSize GlobalProblem where\n  problemSize = fromIntegral . HM.size . lowerBounds\n\ninstance ProblemSize AugLagProblem where\n  problemSize (AugLagProblem _ _ alg) = case alg of\n    AUGLAG_LOCAL lp _ _ -> problemSize lp\n    AUGLAG_EQ_LOCAL lp -> problemSize lp\n    AUGLAG_GLOBAL gp _ _ -> problemSize gp\n    AUGLAG_EQ_GLOBAL gp -> problemSize gp\n\n-- | __IMPORTANT NOTE__\n--\n-- For augmented lagrangian problems, you, the user, are responsible\n-- for providing the appropriate type of constraint.  If the\n-- subsidiary problem requires an `ObjectiveD`, then you should\n-- provide constraint functions with derivatives.  If the subsidiary\n-- problem requires an `Objective`, you should provide constraint\n-- functions without derivatives.  If you don't do this, you may get a\n-- runtime error.\ndata AugLagProblem = AugLagProblem\n  { -- | Possibly empty set of\n    -- equality constraints\n    alEquality :: EqualityConstraints,\n    -- | Possibly empty set of\n    -- equality constraints with\n    -- derivatives\n    alEqualityD :: EqualityConstraintsD,\n    -- | Algorithm specification.\n    alalgorithm :: AugLagAlgorithm\n  }\n\n-- | The Augmented Lagrangian solvers allow you to enforce nonlinear\n-- constraints while using local or global algorithms that don't\n-- natively support them.  The subsidiary problem is used to do the\n-- minimization, but the @AUGLAG@ methods modify the objective to\n-- enforce the constraints.  Please see\n-- <http://ab-initio.mit.edu/wiki/index.php/NLopt_Algorithms the NLOPT algorithm manual>\n-- for more details on how the methods work and how they relate to one another.\n--\n-- See the documentation for 'AugLagProblem' for an important note\n-- about the constraint functions.\ndata AugLagAlgorithm\n  = -- | AUGmented LAGrangian with a local subsidiary method\n    AUGLAG_LOCAL LocalProblem InequalityConstraints InequalityConstraintsD\n  | -- | AUGmented LAGrangian with a local subsidiary method and with\n    -- penalty functions only for equality constraints\n    AUGLAG_EQ_LOCAL LocalProblem\n  | -- | AUGmented LAGrangian with a global subsidiary method\n    AUGLAG_GLOBAL GlobalProblem InequalityConstraints InequalityConstraintsD\n  | -- | AUGmented LAGrangian with a global subsidiary method and with\n    -- penalty functions only for equality constraints.\n    AUGLAG_EQ_GLOBAL GlobalProblem\n\nalgorithmEnumOfAugLag :: AugLagAlgorithm -> N.Algorithm\nalgorithmEnumOfAugLag (AUGLAG_LOCAL _ _ _) = N.AUGLAG\nalgorithmEnumOfAugLag (AUGLAG_EQ_LOCAL _) = N.AUGLAG_EQ\nalgorithmEnumOfAugLag (AUGLAG_GLOBAL _ _ _) = N.AUGLAG\nalgorithmEnumOfAugLag (AUGLAG_EQ_GLOBAL _) = N.AUGLAG_EQ\n\n-- | This structure is returned in the event of a successful\n-- optimization.\ndata Solution = Solution\n  { -- | The objective function value\n    -- at the minimum\n    solutionCost :: Double,\n    -- | The parameter vector which\n    -- minimizes the objective\n    solutionParams :: Vector Double,\n    -- | Why the optimizer stopped\n    solutionResult :: N.Result\n  }\n  deriving (Eq, Show, Read)\n\napplyAugLagAlgorithm :: N.Opt -> AugLagAlgorithm -> IO ()\napplyAugLagAlgorithm opt alg = go alg\n  where\n    ic = traverse_ (tryTo . applyConstraint opt)\n    icd = traverse_ (tryTo . applyConstraint opt)\n    -- AUGLAG won't work at all if you don't pass it the same\n    -- objective as the subproblem -- here we pull out the subproblem\n    -- objectives from the algorithm spec and set the same objective\n    -- function so the user can't mess it up.\n    local lp = tryTo $ do\n      localopt <- setupLocalProblem lp\n      applyLocalObjective opt (lalgorithm lp)\n      N.set_local_optimizer opt localopt\n    global gp = do\n      tryTo $ setupGlobalProblem gp >>= N.set_local_optimizer opt\n      applyGlobalObjective opt (galgorithm gp)\n\n    go (AUGLAG_LOCAL lp ineq ineqd) = local lp *> ic ineq *> icd ineqd\n    go (AUGLAG_EQ_LOCAL lp) = local lp\n    go (AUGLAG_GLOBAL gp ineq ineqd) = global gp *> ic ineq *> icd ineqd\n    go (AUGLAG_EQ_GLOBAL gp) = global gp\n\napplyAugLagProblem :: N.Opt -> AugLagProblem -> IO ()\napplyAugLagProblem opt (AugLagProblem eq eqd alg) = do\n  traverse_ (tryTo . applyConstraint opt) eq\n  traverse_ (tryTo . applyConstraint opt) eqd\n  applyAugLagAlgorithm opt alg\n\nminimizeAugLag' :: AugLagProblem -> Vector Double -> IO Solution\nminimizeAugLag' ap@(AugLagProblem _ _ alg) x0 = do\n  opt <- newOpt (algorithmEnumOfAugLag alg) (problemSize ap)\n  applyAugLagProblem opt ap\n  solveProblem opt x0\n\n-- |\n-- == Example program\n--\n-- The following interactive session example enforces the same scalar\n-- constraint as the nonlinear constraint example, but this time it\n-- uses the augmented Lagrangian method to enforce the constraint and\n-- the 'SBPLX' algorithm, which does not support nonlinear constraints\n-- itself, to perform the minimization.  As before, the parameters\n-- must always sum to 1, and the minimizer finds the same constrained\n-- minimum of 22.5 at @(0.5, 0.5)@.\n-- >>> import Numeric.LinearAlgebra ( dot, fromList, toList )\n-- >>> let objf x = x `dot` x + 22\n-- >>> let stop = ObjectiveRelativeTolerance 1e-9 :| []\n-- >>> let algorithm = SBPLX objf [] Nothing\n-- >>> let subproblem = LocalProblem 2 stop algorithm\n-- >>> let x0 = fromList [5, 10]\n-- >>> minimizeLocal subproblem x0\n-- Right (Solution {solutionCost = 22.0, solutionParams = [0.0,0.0], solutionResult = FTOL_REACHED})\n-- >>>          -- define constraint function:\n-- >>> let constraintf x = sum (toList x) - 1.0\n-- >>>          -- define constraint object to pass to the algorithm:\n-- >>> let constraint = EqualityConstraint (Scalar constraintf) 1e-6\n-- >>> let problem = AugLagProblem [constraint] [] (AUGLAG_EQ_LOCAL subproblem)\n-- >>> minimizeAugLag problem x0\n-- Right (Solution {solutionCost = 22.500000015505844, solutionParams = [0.5000880506776678,0.4999119493223323], solutionResult = FTOL_REACHED})\nminimizeAugLag :: AugLagProblem -> Vector Double -> Either N.Result Solution\nminimizeAugLag prob x0 =\n  unsafePerformIO $ (Right <$> minimizeAugLag' prob x0) `Ex.catch` handler\n  where\n    handler :: NloptException -> IO (Either N.Result a)\n    handler (NloptException retcode) = return $ Left retcode\n", "meta": {"hexsha": "f5fc5d83d71fc4a2415664e4f011a5a361ee7ac7", "size": 40029, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/NLOPT.hs", "max_stars_repo_name": "tkx68/hmatrix-nlopt", "max_stars_repo_head_hexsha": "55777a4d2c7dd33290f1ec82282f990580d20e34", "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/Numeric/NLOPT.hs", "max_issues_repo_name": "tkx68/hmatrix-nlopt", "max_issues_repo_head_hexsha": "55777a4d2c7dd33290f1ec82282f990580d20e34", "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/NLOPT.hs", "max_forks_repo_name": "tkx68/hmatrix-nlopt", "max_forks_repo_head_hexsha": "55777a4d2c7dd33290f1ec82282f990580d20e34", "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": 38.415547025, "max_line_length": 150, "alphanum_fraction": 0.7116590472, "num_tokens": 10545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23597951964532393}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n\nimport Debug.Trace\n-- import Control.Monad.State.Lazy\n\nimport System.Environment (getArgs)\nimport System.IO (readFile)\nimport Data.Map.Strict (Map, (!), insert, elems, fromList, toList, findWithDefault, size, empty, member, findMin, findMax, singleton, filter)\nimport qualified Data.Map.Strict as M\nimport Data.Set (Set)\nimport qualified Data.Set as S\n--import qualified Data.Array as A\nimport Data.List (find, intercalate, intersperse, permutations, inits, tails, isPrefixOf)\nimport Data.List.Split (splitOn)\n-- import Data.Complex (Complex((:+)), realPart, imagPart) -- define my own complex\n\nimport UI.NCurses\nimport Data.Char (chr, ord)\n-- import Data.Complex (Complex((:+)))\nimport Data.Maybe (fromJust)\ntype Instructions = Map Integer Integer\n\ndata ComputerState = Ready | Running | Blocked | Done\n  deriving (Show, Eq)\n\ndata Computer = Computer {\n  state :: ComputerState,\n  memory :: Map Integer Integer,\n  iptr :: Integer, -- instruction pointer\n  base :: Integer, -- base offset\n  input :: [Integer],\n  output :: [Integer]}\n\ncomputer0 = Computer { state = Ready, memory = empty, iptr = 0, base = 0, input = [], output = [] }\n\nrun :: Computer -> Computer -- (Integer, Integer) -> Instructions -> [Integer] -> [Integer]\nrun c\n  | state c == Ready = run $ c {state = Running}\n  | state c == Done = c\n  | state c == Blocked = if input c == [] then c else run $ c {state = Running}\n  | otherwise = -- running\n    --traceShow (iptr c, base c, memory c) $ \n    case instr `mod` 100 of\n      1 -> -- add\n        run $ c {iptr = i+4, memory = insert (addr 3) (arg 1 + arg 2) instructions}\n      2 -> -- multiply\n        run $ c {iptr = i+4, memory = insert (addr 3) (arg 1 * arg 2) instructions}\n      3 -> -- read input\n        if (null $ input c)\n        then c {state = Blocked}\n        else run $ c {iptr = i+2, memory = insert (addr 1) (head $ input c) instructions, input = tail $ input c}\n      4 -> -- output\n        --traceShow (arg 1) $ \n        run $ c {iptr = i+2, output = output c ++ [arg 1]}\n      5 -> -- jump-if-true\n        run $ c {iptr = if arg 1 == 0 then i+3 else arg 2}\n      6 -> -- jump-if-false\n        run $ c {iptr = if arg 1 == 0 then arg 2 else i+3}\n      7 -> -- less than\n        run $ c {iptr = i+4, memory = insert (addr 3) (if arg 1 < arg 2 then 1 else 0) instructions}\n      8 -> -- equals\n        run $ c {iptr = i+4, memory = insert (addr 3) (if arg 1 == arg 2 then 1 else 0) instructions}\n      9 -> -- set relative base\n        run $ c {iptr = i+2, base = base c + arg 1}\n      99 -> -- halt\n        run $ c {state = Done}\n      _ -> error \"unknown opcode\"\n  where instructions = memory c\n        i = iptr c\n        instr = instructions!i\n        ii x = findWithDefault 0 x instructions\n        arg :: Integer -> Integer\n        arg n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ ii $ i+n\n          1 -> ii $ i+n\n          2 -> ii ((ii $ i+n) + base c)\n          _ -> error \"bad argument mode\"\n        addr n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ i+n\n          1 -> error \"address in mode 1\"\n          2 -> --trace \"address in mode 2\" $\n            ii (i+n) + base c\n          _ -> error $ \"address in unknown mode\"\n\ninstance (Show a) => Show (Complex a) where\n  show (C x y) = \"C \" ++ show x ++ \" \" ++ show y\n  \ninstance (Eq a) => Eq (Complex a) where\n  (C a ai) == (C b bi) = a == b && ai == bi\n  \ninstance (Eq a, Ord a) => Ord (Complex a) where\n  compare (C a ai) (C b bi) | a < b || a == b && ai < bi = LT\n                            | a > b || a == b && ai > bi = GT\n                            | otherwise = EQ\n\n-- Note that we are using a plane where imaginary (y-axis) numbers\n-- increase downward. I think this means that right and left are\n-- reversed.\n\ndata Complex a = C a a\n\n-- instance Num (Complex Int) where\n--   abs c = error \"Can't take abs of Complex Int\"\n\ninstance Num a => Num (Complex a) where\n  (C x y) + (C u v) = C (x+u) (y+v)\n  (C x y) * (C u v) = C (x*u-y*v) (x*v+y*u)\n  fromInteger n = C (fromInteger n) 0\n  abs (C x y) = C (abs x) y -- sqrt $ x*x + y*y\n  signum (C x y) = C (signum x) 0\n  negate (C x y) = C (negate x) (negate y)\n\n  \ntype Point = Complex Int\ntype Direction = Complex Int\ntype Scaffold = Set Point\ndata Move = R | L | F Int | Err\n  deriving (Show, Eq)\n\nshow' :: [Move] -> String\nshow' ms = intercalate \",\" $ map showMove ms\n  where showMove R = \"R\"\n        showMove L = \"L\"\n        showMove (F n) = show n\n        showMove Err = error \"showing err\"\n        \ncharToDirection '>' = C 1 0\ncharToDirection '<' = C (-1) 0\ncharToDirection '^' = C 0 (-1)\ncharToDirection 'v' = C 0 1\ncharToDirection c = error $ \"bad direction\" ++ [c]\n\nfromJust' :: String -> Maybe a -> a\nfromJust' s Nothing = error s\nfromJust' s (Just x) = x\n\npath :: Scaffold -> (Point, Direction) -> [Move]\npath scaffold (pt, dir)\n  | S.size scaffold < 2 = []\n  -- | otherwise = (traceShowId $ rotation ++ [F steps]) ++ path scaffold' (pt', dir')\n  | otherwise = rotation ++ [F steps] ++ path scaffold' (pt', dir')\n  where left :: Complex Int\n        left = C 0 (-1)\n        dir' = fromJust' \"dir'\" $ find (\\d -> (pt + d) `S.member` scaffold) [left^i | i <- [1 .. 4]]\n        directions = [(left, [L]), (left^2, [L,L]), (left^3, [R]), (left^4, [Err])]\n        rotation = snd $ fromJust' (\"rotation: \"++ show (dir', directions))  $\n          find (\\(d, m) -> dir * d == dir') directions\n        (pt', steps, scaffold') = walk (pt, 0, scaffold)\n        walk (p, n, s) | not $ (p+dir') `S.member` s = (p, n, s)\n                       | (p+dir'*left) `S.member` s = walk (p+dir', n+1, s) -- intersection, don't delete\n                       | otherwise = walk (p+dir', n+1, S.delete p s)\n\ntestIntersection scaffold pt = all (`S.member` scaffold) [ pt + d | d <- [l, l*l, l*l*l, l*l*l*l]]\n  where l = C 0 1\n\n\ndata Function = A | B | C' deriving (Show)\n\nsubstitute :: [Move] -> [Function]\n-- substitute (L: F n: ms) = A: (substitute $ F (n-8): ms)\n-- substitute (F n: ms) = B n: substitute ms\n-- substitute (R: F n: ms) = C': (substitute $ F (n-8): ms)\n-- substitute [] = []\n-- substitute ms = error $ \"substitute: can't do \" ++ show ms\nsubstitute (L: F 12: L: F 12: R: F 12: ms) = A: substitute ms\nsubstitute (L: F 8: L: F 8: R: F 12: L: F 8: L: F 8: ms) = B: substitute ms\nsubstitute (L: F 10: R: F 8: R: F 12: ms) = C': substitute ms\nsubstitute [] = []\nsubstitute ms = error $ \"substitute: can't do \" ++ show ms\n\nmain = do\n  -- [instructionFile] <- getArgs\n  instructionStrings <- readFile \"17.input.txt\" -- instructionFile\n  let instructions = fromList . zip [0 ..] $ map read $ splitOn \",\" instructionStrings\n\n  putStrLn \"Part 1\"\n  let c = run $ computer0{memory = instructions}\n  let view = output c\n  let viewStr = map (chr . fromIntegral) view\n  putStrLn $ viewStr\n  let listView = [(C i j, c) | (j, line) <- zip [0 ..] (lines viewStr)\n                              , (i, c) <- zip [0 ..] line\n                              , c `elem` \"#<>^vV\"]\n\n  let scaffold = S.fromList $ map fst listView\n\n  let intersections = S.filter (testIntersection scaffold) scaffold\n  print $ S.foldl' (\\s (C x y) -> s+x*y) 0 intersections\n\n  putStrLn \"Part 2\"\n  let (r, d) = fromJust' \"find robot\" $ find (\\(pt, v) -> v `elem` \"<>^vV\") listView\n  let p = path scaffold (r, charToDirection d)\n  -- print p\n  -- let cs = substitute p\n  -- print cs\n  -- print $ length cs\n  let ls = map (fromIntegral . ord) $ unlines\n        [ \"A,A,B,C,C,A,B,C,A,B\"\n        , \"L,12,L,12,R,12\"\n        , \"L,8,L,8,R,12,L,8,L,8\"\n        , \"L,10,R,8,R,12\"\n        , \"n\"\n        ]\n  print ls\n  -- let c = run $ computer0 { memory = insert 0 2 instructions\n  --                         , input = ls }\n\n  -- print $ output c\n\n  print \"Part 2 - alt\"\n  print p\n  print $ length p\n  let substrings xs = concatMap inits $ tails xs\n  let functions = Prelude.filter (\\l -> length l > 1 && (length $ show' l) < 21) $ substrings p\n  print $ length $ functions\n  -- let functions3 = [(a,b,c) | a <- functions, b <- functions, show' a < show' b, c <- functions, show' b < show' c]\n  let f xs ys = show' xs < show' ys\n  let functions3 = [[a,b,c] | a <- inits $ take 10 p, length a > 0, c <- functions, b <- Prelude.filter (f c) functions]\n  print $ length $ functions3\n\n  -- print $ Prelude.filter (\\[a,b,c] -> (length $ show' a) == 14 && (length $ show' b) == 13 && (length $ show' c) == 20) functions3\n  let test3 [] fs = True\n      test3 pth fs = any id [test3 (drop (length f) pth) fs | f <- fs, isPrefixOf f pth]\n  let goodFunctions = Prelude.filter (test3 p) $ functions3\n  let goodFunction = head $ goodFunctions\n  print $ goodFunction\n  let programs [] fs = [[]]\n      programs pth fs = [ (l: ls) | (l, f) <- zip ['A' .. 'C'] fs\n                                  , f `isPrefixOf` pth\n                                  , ls <- programs (drop (length f) pth) fs\n                                  ]\n  let program = intersperse ',' $ head $ programs p goodFunction\n  let functions = map show' goodFunction\n  print program\n  print functions\n  let ls = unlines ((program: functions) ++ [\"n\"])\n  print ls\n  print $ map (fromIntegral . ord) ls\n  let c = run $ computer0 { memory = insert 0 2 instructions\n                          , input = map (fromIntegral . ord) ls }\n\n  print $ last $ output c\n  print $ map (chr . fromIntegral) $ init $ output c\n  \n\n-- After first run:\n-- [A,B 4,\n--  A,B 4,\n--  C',B 4,\n\n--  A,B 4,\n--  A,B 4,\n--  C',B 4,\n\n--  A,B 0,\n--  A,B 0,\n--  C',B 4,\n--  A,B 0,\n--  A,B 0,\n\n--  A,B 2,\n--  C',B 0,\n--  C',B 4,\n\n--  A,B 2,\n--  C',B 0,\n--  C',B 4,\n\n--  A,B 4,\n--  A,B 4,\n--  C',B 4,\n\n--  A,B 0,\n--  A,B 0,\n--  C',B 4,\n--  A,B 0,\n--  A,B 0,\n\n--  A,B 2,\n--  C',B 0,\n--  C',B 4,\n\n--  A,B 4,\n--  A,B 4,\n--  C',B 4,\n\n--  A,B 0,\n--  A,B 0,\n--  C',B 4,\n--  A,B 0,\n--  A,B 0]\n", "meta": {"hexsha": "f0e6f58bed6c2cc89733e74d728107e42dc7576b", "size": 9781, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "17.hs", "max_stars_repo_name": "dpatru/aoc2019", "max_stars_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-30T21:19:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T21:19:29.000Z", "max_issues_repo_path": "17.hs", "max_issues_repo_name": "dpatru/aoc2019", "max_issues_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "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": "17.hs", "max_forks_repo_name": "dpatru/aoc2019", "max_forks_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "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": 33.4965753425, "max_line_length": 141, "alphanum_fraction": 0.5466721194, "num_tokens": 3241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2354575046999239}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule CPVO.IO.Reader.Ecalj.Common where\nimport CPVO.Numeric\nimport CPVO.IO\n\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\nimport Data.List.Split\nimport Data.List\nimport Data.Maybe\nimport Numeric.LinearAlgebra\nimport Data.Char (ord)\nimport Control.Monad.IO.Class (MonadIO)\n\nreadCtrlAtoms :: String -> String -> IO [T.Text]\nreadCtrlAtoms tailer foldernya = do\n    fCtrl <- T.readFile $ foldernya ++ \"/ctrl.\" ++ tailer\n    return $ catMaybes\n      $ map ( T.stripPrefix \"ATOM=\" .  head)\n      $ filter (/=[])\n      $ map ( T.words . T.takeWhile (/='#') )\n      $ head\n      $ splitWhen (T.isPrefixOf \"SPEC\")\n      $ last $ splitWhen (T.isPrefixOf \"SITE\")\n      $ T.lines fCtrl\n\n    -- uniqAtoms : [(count,noFirstAtom,atomicSymbol)]\ntype CntN1Atsym = (Int,Int,T.Text)\nreadUniqAtoms :: [T.Text] -> [CntN1Atsym]\nreadUniqAtoms allAtoms =\n          map (\\a -> (length a, snd $ head a, fst $ head a)) $\n          groupBy (\\a b -> fst a == fst b) $\n          zip  allAtoms ([1..] :: [Int])\n\n-- daftarCetak :: [((notCtk,((count,noFrstAtom,atomSymbol),label  ,[    AOs ])),spin)]\n-- daftarCetak :: [(( 1    ,((  2  ,    13    ,  \"Ni\"    ),\"Ni#2p\",[\"3\",\"4\",\"5\"])),1)]\ngenDaftarCetak :: [CntN1Atsym] -> String -> String -> [String]\n               -> IO [((Integer,(CntN1Atsym,String,[String])),Integer)]\ngenDaftarCetak listAtoms _ _ aos = do\n  return $ [ (i,j) | i <- daftarCetak' listAtoms , j <- [1,2] ]\n  where\n    daftarCetak' lAtoms = zip [1..]\n                      $ map (\\(a,label,b) -> (head $ filter (\\(_,_,aa) -> aa == (T.pack a)) lAtoms , label, b) )\n                      $ map ( (\\(a:label:as) -> (a,label,as)) . splitOn \":\") aos\n\n-- ctrlAtomicAOs :: [(atomNumber,(atomSym,(label ,[intAOs])))]\n-- ctrlAtomicAOs :: [(    1     ,(  \"O\"  ,(\"O#2p\",[ 2,3,4])))]\n-- ctrlAtomicAOs :: 14 atoms\ngenCtrlAtomicAOs :: [(String, String, [Int])]\n                 -> [T.Text]\n                 -> [(Int, (String, (String, [Int])))]\ngenCtrlAtomicAOs aoSet ctrlAtoms =  map (\\x -> (head $ takeAOs x aoSet))\n          $ concat\n          $ groupBy (\\(_,a:_) (_,b:_) -> (ord a) == (ord b))\n          $ zip ([1..]::[Int]) $ map T.unpack ctrlAtoms\n\n-- totalDOS :: Matrix Double [ energy, DOSspinUp, DOSspinDown ]\nreadTotalDOSText :: String -> String -> IO (Matrix Double)\nreadTotalDOSText tailer foldernya = loadMatrix $ foldernya ++ \"/dos.tot.\" ++ tailer\n\n-----------------------------------------------------------\ngetLastLLMF :: MonadIO io =>\n  String -> io [T.Text]\ngetLastLLMF foldernya = inshell2text $ concat [\"ls -laht \", foldernya,\"/llmf{,_gwscend.*} | head -1|awk '{print $NF}'\" ]\n-----------------------------------------------------------\n\n--readHeaderData (texFile:jd:jdHead:colAlign:xr:ymax':wTot::invS:tailer:foldernya:aos) = do\nreadHeaderData :: [String]\n               -> IO ( Either String ( Double, Double, Double, Double, [T.Text]\n                      , [CntN1Atsym]\n                      , [(Int, (String, (String,[Int])))]\n                      , String, [String], String, String, String, String))\nreadHeaderData (texFile:jd:jdHead:colAlign:xr:ymax':_:_:invS:tailer:foldernya:aos) = do\n  -------------------------------reading data------------------------\n    let invStat = if (invS == \"flipSpin\") then (-1) else 1\n    let ymax = read ymax' :: Double\n    let [xmin,xmax] = map (read :: String -> Double) $ splitOn \":\" xr\n    ctrlAtoms <- readCtrlAtoms tailer foldernya\n    let jdHeads = splitOn \"|\" jdHead\n    let uniqAtoms = readUniqAtoms ctrlAtoms\n    putStrLn $ show ctrlAtoms\n    putStrLn $ show uniqAtoms\n    -- daftarCetak : [(nourut,,jumlah,nourut,symbol)]\n    daftarCetak <- genDaftarCetak uniqAtoms tailer foldernya aos\n    putStrLn $ show aos\n    putStrLn $ show $ last daftarCetak\n      -------------------------------generating DOS data------------------------\n    totalDOS <- readTotalDOSText tailer foldernya\n      -------------------------------integrating DOS data------------------------\n    let intgTot = map (\\i -> integrateToZero $ totalDOS \u00bf [0,i]) [1,2] -- run it on spin [1,2]\n    putStrLn $ show intgTot\n    let aoSet = map ( (\\(n:l:as) -> (n,l,map ( ((+) (-1)) . read :: String -> Int) as) ) . splitOn \":\") aos\n    {-\n      -------------------------------generating PDOS data------------------------\n              -- map ditambah -1 karena input mengikuti gnuplot\n              -- input : d kolom 6-10\n              -- gnuplot : d kolom 6-10\n              -- hmatrix : d kolom 5-9\n\n              -- ((namaAtom,jdAtom,[intAOs]),[(nourutAtom,namaAtom)])\n              -- ((String , String,[ Int  ]),[(Int       , String )])\n              -- ((\"O\"    ,\"O#2p\" ,[2,3,4 ]),[(1         ,\"O\"     )])\n      -}\n    let ctrlAtomicAOs = genCtrlAtomicAOs aoSet ctrlAtoms\n    let jdTable = \"Table: \" ++ jd\n    putStrLn $ show $ head ctrlAtomicAOs\n--    pdosAtomicPilihan <- readPDOS invStat tailer foldernya $ take 2 ctrlAtomicAOs\n--    let integratedAtomicPDOS = integrateAtomicPDOS pdosAtomicPilihan\n--    putStrLn $ show $ integratedAtomicPDOS\n    putStrLn \"===done:readHeaderData@CPVO/IO/Reader/Common =====================\"\n    return $ Right\n      (invStat, ymax, xmin, xmax, ctrlAtoms, uniqAtoms, ctrlAtomicAOs,jdTable, jdHeads, foldernya, tailer, colAlign, texFile)\n\nreadHeaderData _ = return $ Left\n  \"===Error:readHeaderData@CPVO/IO/Reader/Common wrong args ========\"\n", "meta": {"hexsha": "3d08956cde38ec956143b68646fc65b85197e055", "size": 5405, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CPVO/IO/Reader/Ecalj/Common.hs", "max_stars_repo_name": "hasanalrasyid/cpvoh", "max_stars_repo_head_hexsha": "d4e40c681a512b9ffb3f79ec46a4f4e5831e4165", "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/CPVO/IO/Reader/Ecalj/Common.hs", "max_issues_repo_name": "hasanalrasyid/cpvoh", "max_issues_repo_head_hexsha": "d4e40c681a512b9ffb3f79ec46a4f4e5831e4165", "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/CPVO/IO/Reader/Ecalj/Common.hs", "max_forks_repo_name": "hasanalrasyid/cpvoh", "max_forks_repo_head_hexsha": "d4e40c681a512b9ffb3f79ec46a4f4e5831e4165", "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": 45.4201680672, "max_line_length": 125, "alphanum_fraction": 0.5535615171, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23459465935797474}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies        #-}\n\nimport           Data.Bits\nimport           Data.Convertible\nimport           Data.List                            (maximumBy)\nimport           Data.Maybe                           (fromJust)\nimport           Data.Ord\nimport qualified Data.Vector.Storable                 as V\nimport           Data.Word\nimport           Foreign.ForeignPtr\n\nimport           Numeric.LinearAlgebra\nimport qualified Numeric.LinearAlgebra.Devel          as U\nimport qualified Numeric.LinearAlgebra.Static         as SA\n\nimport           Graphics.Gloss\nimport           Graphics.Gloss.Interface.IO.Game\nimport qualified Graphics.Gloss.Interface.IO.Interact as GI\n\nimport           Grenade\nimport           Grenade.Demos.MNIST                  hiding (runNet')\nimport           Grenade.Layers.Internal.Shrink\n\ndata MouseState = MouseDown | MouseUp\n\n-- | all of the information needed to create the canvas to draw on\ndata World      = Canvas (S ('D2 224 224)) MouseState MNIST\n\n-- | turns the matrix in the world structure into a picture. To do this, we use some pointer \n--   magic to turn our matrix (which is represented internally as an array in memory) into \n--   a bitmap, where each pixel is represented by four word8s for the R, G, B, A channels\n--   (which we construct as a Word32) \nrenderCanvas :: World -> IO Picture\nrenderCanvas (Canvas (S2D !arr) _ _)\n    = return $ bitmapOfForeignPtr 224 224 (BitmapFormat BottomToTop PxABGR) bitmapPtr False\n  where\n    -- | given a RealNum p, creates an RGBA word32 of the form (p, p, p, 255) - so it is essentially\n    --   creating a greyscale pixel with no transparency.\n    convColor :: RealNum -> Word32\n    convColor p = let p'  =  convert p :: Word32\n                      !w  =  unsafeShiftL p' 24\n                         .|. unsafeShiftL p' 16\n                         .|. unsafeShiftL p' 8\n                         .|. 255\n                  in w\n\n    vec         = flatten $ SA.extract arr\n    pixels      = V.map convColor vec\n    (ptr, _, _) = U.unsafeToForeignPtr pixels\n    -- | this last step is to turn the array of word32s into an array of word8s by\n    --   interpreting each element as 4 word8s\n    bitmapPtr   = castForeignPtr ptr\n\n-- | updates the world with some event\nhandleInput :: GI.Event -> World -> IO World\n-- if the mouse button is pressed down, update the mouse state \nhandleInput (GI.EventKey (GI.MouseButton GI.LeftButton) (GI.Down) _ _) (Canvas arr _ net) \n  = return $ Canvas arr MouseDown net\n\n-- if the mouse button is unpressed, update the mouse state and run a neural network inference\n-- on the current canvas image by shrinking the image to the correct input size. Prints \n-- the result to the console.\nhandleInput (GI.EventKey (GI.MouseButton GI.LeftButton) (GI.Up) _ _) (Canvas (S2D arr') _ net) = \n  let extractedMatrix = SA.extract arr'\n      shrunkenMatrix  = shrink_2d 224 224 28 28 extractedMatrix\n      staticMatrix    = fromJust . fromStorableMatrix $ shrunkenMatrix\n  in do \n    putStrLn $ runNet' net staticMatrix\n    return $ Canvas (S2D arr') MouseUp net\n\n-- If the 'c' key is pressed and then let go of, wipe the canvas\nhandleInput (GI.EventKey (GI.Char 'c') (GI.Up) _ _) (Canvas (S2D !arr) mb net) \n  = return $ Canvas cleanCanvas mb net\n  where\n    cleanCanvas = fromJust . fromStorableMatrix $ cleanMatrix\n    cleanMatrix = U.mapMatrixWithIndex (const (const 255)) (SA.extract arr)\n\n-- if moving the mouse while the left mouse button is held down, draw to the \n-- canvas (note that we add 112, since the origin of a canvas is at the middle)\nhandleInput (GI.EventMotion (y, x)) (Canvas arr MouseDown net) \n  = return $ Canvas (draw arr (xAsInt + 112) (yAsInt + 112)) MouseDown net\n  where\n    xAsInt = convert x\n    yAsInt = convert y\n\nhandleInput _ c = return c\n\n-- | draws a circle with squared radius 50 at the given coordinates\ndraw :: S ('D2 224 224) -> Int -> Int -> S ('D2 224 224)\ndraw (S2D arr) x y = fromJust . fromStorableMatrix $ m\n  where\n    m    = U.mapMatrixWithIndex f arr'\n    arr' = SA.extract arr :: Matrix RealNum\n\n    f :: (Int, Int) -> RealNum -> RealNum\n    f (x', y') p = if (x - x') ^ (2 :: Int) + (y - y') ^ (2 :: Int) <= 50 then 0 else p\n\n-- | runs a neural network inference and pretty prints the most probable label\n--   with its probability\nrunNet' :: MNIST -> S ('D2 28 28) -> String\nrunNet' net m \n  = let S1D ps = runNet net m\n        (p, i) = (getProb . V.toList) (SA.extract ps)\n    in  \"This number is \" ++ show i ++ \" with probability \" ++ show (p * 100) ++ \"%\"\n  where\n    getProb :: [RealNum] -> (RealNum, Int)\n    getProb xs = maximumBy (comparing fst) (zip xs [0..])\n\nmain :: IO ()\nmain = do\n    mnistPath <- getPathForNetwork MNIST\n    net <- (loadSerializedNetwork mnistPath :: IO MNIST)\n    putStrLn \"Successfully loaded model\"\n\n    let initialCanvas = Canvas initialMat MouseUp net\n\n    playIO window backgroundColor 30 initialCanvas renderCanvas handleInput emptyStep\n  where\n    window            = InWindow \"Draw here!\" (224, 224) (100, 100)\n    backgroundColor   = makeColor 255 255 255 0\n    initialMat        = fromJust . fromStorable . V.fromList $ replicate (224 * 224) 255\n    emptyStep _ world = return world\n", "meta": {"hexsha": "8adc4d14257eeb1f4cb7d5fece6f5c1ea430e951", "size": 5374, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/mnist-load.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "examples/main/mnist-load.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-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": "examples/main/mnist-load.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.984375, "max_line_length": 100, "alphanum_fraction": 0.6434685523, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.23450455474148932}}
{"text": "{-# LANGUAGE TemplateHaskell, RecordWildCards, ScopedTypeVariables #-}\nmodule TestEvolution where\n\nimport qualified Data.ByteString.Lazy          as B\nimport           Data.MonoTraversable           ( MonoFoldable(olength) )\nimport           Data.Ord                       ( Down(Down) )\nimport qualified Data.Set                      as S\nimport           Data.Typeable                  ( Typeable )\nimport           Data.Word                      ( Word8 )\nimport           Instances                      ( )\nimport           Internal.Evolution\nimport           Statistics.ConfidenceInt       ( binomialCI )\nimport           Statistics.Types               ( ConfInt(ConfInt)\n                                                , Estimate(Estimate)\n                                                , cl95\n                                                )\nimport           Test.QuickCheck                ( Arbitrary(arbitrary)\n                                                , CoArbitrary\n                                                , Gen\n                                                , NonNegative(getNonNegative)\n                                                , NonPositive(getNonPositive)\n                                                , Positive(getPositive)\n                                                , Property\n                                                , choose\n                                                , cover\n                                                , elements\n                                                , listOf1\n                                                , quickCheckAll\n                                                , suchThat\n                                                , vectorOf\n                                                )\nimport           Util\n\n\nnewtype ReproduceArgs a = ReproduceArgs (EvolutionParams, [a] -> [Float], [Agent a]) deriving (Show)\n\ninstance (Show a, Typeable a, Eq a, Arbitrary a, CoArbitrary a) => Arbitrary (ReproduceArgs a) where\n    arbitrary = do\n        params@EvolutionParams {..} <- arbitrary\n        agents                      <- genPop evolvePopSize =<< arbitrary\n        -- generate a fitness fn that strictly increases fitness\n        -- fitness starts at 0 so this also guarantees fitness will be > 0\n        -- necessary because fitnesses are passed as weights to `frequency`\n        f                           <- (arbitrary :: Gen (a -> Positive Float))\n        return $ ReproduceArgs (params, map (getPositive . f), agents)\n\n\nnewtype MutateArgs = MutateArgs (Double, [Word8], B.ByteString) deriving (Show, Eq)\n\ninstance Arbitrary MutateArgs where\n    arbitrary = do\n        p     <- choose (0, 1)\n        genes <- listOf1 arbitrary\n            `suchThat` combineWith (&&) [unique, (> 1) . length]\n        genome <- B.pack <$> vectorOf 1000 (elements genes)\n        return $ MutateArgs (p, genes, genome)\n\n\nmatchup :: [Agent a] -> [[Agent a]]\n--matchup = matchWithBest 2 10 (Down . agentFitness) . S.fromDistinctAscList\nmatchup = matchups 2 . S.fromDistinctAscList\n\n\ngenPop :: (Arbitrary a) => Int -> Agent a -> Gen [Agent a]\ngenPop n Agent {..} =\n    genPopulation n agentGenes agentEncoder agentDecoder arbitrary\n\n\nprop_mergeAgentsUnique :: [Agent a] -> Bool\nprop_mergeAgentsUnique = unique . mergeAgents\n\n\nprop_mergeAgentsKeepAll :: [Agent a] -> Bool\nprop_mergeAgentsKeepAll xs = all (`elem` mergeAgents xs) xs\n\n\nprop_mergeAgentsNoNew :: [Agent a] -> Bool\nprop_mergeAgentsNoNew xs = all (`elem` xs) (mergeAgents xs)\n\n\nprop_populationLength :: Arbitrary a => NonNegative Int -> Agent a -> Gen Bool\nprop_populationLength n agent = do\n    pop <- genPop (getNonNegative n) agent\n    return $ length pop == getNonNegative n\n\n\nprop_populationIds :: Arbitrary a => NonNegative Int -> Agent a -> Gen Bool\nprop_populationIds n agent = do\n    pop <- genPop (getNonNegative n) agent\n    return . and $ zipWith (==) (map agentId pop) [0 ..]\n\n\nprop_populationUniform\n    :: (Eq a, Arbitrary a) => NonNegative Int -> Agent a -> a -> Gen Bool\nprop_populationUniform n agent c = do\n    pop <- genPop (getNonNegative n) agent\n    return $ uniform pop True\n  where\n    uniform []       acc = acc\n    uniform (x : xs) acc = uniform xs (acc && all (agentCommon x) xs)\n    agentCommon x y = fEq enc && fEq dec\n      where\n        fEq f = f x == f y\n        enc z = agentEncoder z c\n        dec z = agentDecoder z $ enc z\n\n\nprop_mutate :: MutateArgs -> Gen Property\nprop_mutate (MutateArgs (p, genes, genome)) = do\n    mutated <- mutate p genes genome\n    let Estimate p' (ConfInt lower upper _) = binomialCI\n            cl95\n            (olength genome)\n            (olength $ filter id (B.zipWith (/=) genome mutated))\n    -- proportion of mutations == p with 95% confidence\n    return $ cover 95 ((p > p' - lower) && (p < p' + upper)) \"near p\" True\n\n\nprop_reproduceLength :: ReproduceArgs a -> Gen Bool\nprop_reproduceLength (ReproduceArgs (params, f, pop)) = do\n    pop' <- reproduce params f matchup pop\n    return $ length pop == length pop'\n\n\nprop_reproduceIds :: ReproduceArgs a -> Gen Bool\nprop_reproduceIds (ReproduceArgs (params, f, pop)) =\n    fIncreasing True agentId <$> reproduce params f matchup pop\n  where\n    fIncreasing acc _ []           = acc\n    fIncreasing acc _ [_         ] = acc\n    fIncreasing acc g (x : y : xs) = fIncreasing (acc && g x < g y) g (y : xs)\n\n\nprop_evolveId :: ReproduceArgs a -> NonPositive Int -> Gen Bool\nprop_evolveId (ReproduceArgs (params, f, pop)) n =\n    (pop ==)\n        <$> evolve params { evolveGenerations = getNonPositive n } f matchup pop\n\n\nprop_evolvePreserve :: ReproduceArgs a -> Gen Bool\nprop_evolvePreserve (ReproduceArgs (params, f, pop)) = do\n    pop' <- evolve params f matchup pop\n    let args' = ReproduceArgs (params, f, pop')\n    len <- prop_reproduceLength args'\n    ids <- prop_reproduceIds args'\n    return $ len && ids\n\n\nreturn []\nrunTests :: IO Bool\nrunTests = $quickCheckAll\n", "meta": {"hexsha": "1cf199c5fbec3abfd95612c6e7d8b55032141205", "size": 5928, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/TestEvolution.hs", "max_stars_repo_name": "desophos/gamer-evolution", "max_stars_repo_head_hexsha": "1fa43143524865c6cf7db574f4a078dbd3866a50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-24T05:27:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T05:27:18.000Z", "max_issues_repo_path": "test/TestEvolution.hs", "max_issues_repo_name": "desophos/gamer-evolution", "max_issues_repo_head_hexsha": "1fa43143524865c6cf7db574f4a078dbd3866a50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-02-24T05:13:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T09:19:15.000Z", "max_forks_repo_path": "test/TestEvolution.hs", "max_forks_repo_name": "desophos/gamer-evolution", "max_forks_repo_head_hexsha": "1fa43143524865c6cf7db574f4a078dbd3866a50", "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": 39.0, "max_line_length": 100, "alphanum_fraction": 0.5499325236, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23308627966055237}}
{"text": "{-# LANGUAGE ExtendedDefaultRules #-}\n{-# LANGUAGE OverloadedStrings    #-}\n{-# LANGUAGE FlexibleContexts     #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE BangPatterns         #-}\n\nmodule TestChapter4DP (\n       testChapter4\n      )where\n\nimport           Control.Concurrent \nimport           Control.Monad\nimport           Control.Monad.IO.Class\nimport           Control.Monad.Trans.State\n\nimport           Data.Configurator\nimport           Data.Configurator.Types\nimport           Data.List.Split (chunksOf)\nimport           Data.Foldable (toList)\n\nimport           Data.Random\nimport           Data.Random.Distribution\nimport           Data.Random.Distribution.Poisson\n\nimport           Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport           Data.Text (Text)\nimport qualified Data.Vector.Unboxed as VU\n\nimport           Graphics.Matplotlib hiding (def)\n\nimport           Numeric.LinearAlgebra (Vector, Matrix)\nimport qualified Numeric.LinearAlgebra as LA\nimport           System.Console.AsciiProgress(Options(..), Stats(..),\n                                              displayConsoleRegions, complete,\n                                              getProgressStats, def, newProgressBar, tickN)\nimport           Text.Printf\n-- project\nimport           Utils\nimport           Chapter4DP\n\ntestChapter4 :: FilePath -> IO ()\ntestChapter4 configPath = do\n  print \"Chapter 4 Experiment Starting \"\n  (config, _) <- autoReload autoConfig [Required configPath]\n  (bCarRental :: Bool) <- require config \"enable.bCarRental\"\n  when bCarRental (doCarRentalTest config)\n  (bGambler :: Bool) <- require config \"enable.bGamblerProblem\"\n  when bGambler (doGamblerTest config)\n\n----------------------------------------------------------------------------------------------------\n-- Car Rental Test\ndoCarRentalTest :: Config -> IO () \ndoCarRentalTest config = do\n  (experimentName::String) <- require config \"carRental.experiment\"\n  (theTheta::Double) <- require config \"carRental.theta\"\n  (discountGamma::Double) <- require config \"carRental.discount\"\n  (maxCars::[Int]) <- require config \"carRental.maxCars\"\n  (rentalCredit::[Double]) <- require config \"carRental.rentalCredit\"\n  (transCost::[Double]) <- require config \"carRental.transferCost\"\n  (maxTransferCars::[Int]) <- require config \"carRental.maxTransferCars\"\n  (freeParkingLimit::[Int]) <- require config \"carRental.freeParkingLimit\"\n  (additionalParkingCost::[Double]) <- require config \"carRental.additionalParkingCost\"\n  (additionalTransferSaving::[Double]) <- require config \"carRental.additionalTransferSaving\"\n  (rentalCars::[Double]) <- require config \"carRental.rentalCars\"\n  (returnCars::[Double]) <- require config \"carRental.returnCars\"\n\n  let carRental = mkCarRental (length maxCars) theTheta discountGamma maxCars rentalCredit transCost\n                              maxTransferCars freeParkingLimit additionalParkingCost\n                              additionalTransferSaving rentalCars returnCars    \n  -- do experiments\n  carRental' <- goLoop carRental\n  when (_locationNum carRental == 2) (drawTwoLocationCarRental carRental' experimentName)\n  threadDelay 100000\n  where\n  goLoop carRental = displayConsoleRegions $ do\n    putStrLn \"Will do car rental experiment \" >> putStrLn (show carRental)\n    pg <- newProgressBar def { pgWidth = 80\n                             , pgTotal = 100\n                             , pgOnCompletion = Just \"Done :percent after :elapsed seconds\"\n                             }\n    carRental' <- loop pg carRental\n    putStrLn \"car rental experiment finish. Final Results: \"\n    putStrLn $ showCarRentalResult carRental'\n    pure carRental'\n    where\n    loop pg carRental = do\n      let (!(bFinish, percent), !carRental') = runState carRentalStep carRental\n      case bFinish of\n         False -> do\n           stat <- getProgressStats pg\n           let ticked = fromInteger $ stCompleted stat\n               willTick = percent - ticked\n           if (willTick > 0) then(tickN pg willTick)\n              else print (\"Finish One Improvement \" ++ show percent) \n           loop pg carRental'\n         True -> complete pg >> pure carRental'\n\ndrawTwoLocationCarRental :: CarRental -> String -> IO ()\ndrawTwoLocationCarRental carRental experimentName = do\n  putStrLn \"Draw Two Location Car Rental Result Graph\"\n  -- dataX is the second location, whereas dataY is the first location\n  let dataX = toList $ fmap (\\ (f:s:[]) -> s) (_states carRental) \n      dataY = toList $ fmap (\\ (f:s:[]) -> f) (_states carRental)\n      (dataZ::[Int]) = toList (Seq.zipWith (\\ i saPair -> calcZ . foldl (zipWith (+)) [0, 0] $ Seq.index saPair i)\n                                           (_actions carRental) (_possibleActions carRental))\n      dataValue = toList $ _stateValues carRental\n      maxZ = maximum dataZ\n      figure = readData ([dataX], [dataY], [dataZ])\n                 % mp # \"ax = plot.gca(projection='3d')\"\n                 % mp # \"ax.scatter(np.array(data[\" # 0 # \"]), np.array(data[\" # 1 # \"]), np.array(data[\" # 2 # \"]))\"\n                 % xlabel \"#Cars at second location\"\n                 % ylabel \"#Cars at first location\"\n                 % zlabel \"#Cars to move (action)\"\n                 % xticks [0, 1..(_maxCars carRental !! 1)]\n                 % yticks [0, 1..(_maxCars carRental !! 0)]\n                 % zticks [negate maxZ, (negate $ maxZ - 1)..maxZ]\n                 % title experimentName\n      valueFigure = readData ([dataX], [dataY], [dataValue])\n                      % mp # \"ax = plot.gca(projection='3d')\"\n                      % mp # \"ax.scatter(np.array(data[\" # 0 # \"]), np.array(data[\" # 1 # \"]), np.array(data[\" # 2 # \"]))\"\n                      % xlabel \"#Cars at second location\"\n                      % ylabel \"#Cars at first location\"\n                      % zlabel \"State Values\"\n                      % xticks [0, 1..(_maxCars carRental !! 1)]\n                      % yticks [0, 1..(_maxCars carRental !! 0)]\n                      % title (experimentName ++ \" - State Values\")\n  -- avoid Matplotlib's bug  \n  code figure >> code valueFigure >> onscreen figure >> onscreen valueFigure\n  threadDelay 100000\n  -- also output table format\n  let moveResult = showAsTable [0..(_maxCars carRental)!!0]\n                               [0..(_maxCars carRental)!!1] (map fromIntegral dataZ) False\n      stateResult = showAsTable [0..(_maxCars carRental)!!0]\n                                [0..(_maxCars carRental)!!1] dataValue True\n  putStrLn moveResult\n  putStrLn stateResult\n  where\n  calcZ :: [Int] -> Int\n  calcZ (firstLocation:secondLocation:[]) = \n            (firstLocation > 0) ? (negate firstLocation, secondLocation)\n  calcZ _ = error \"Not correct action move\"\n\n-- output in github markdown format\nshowAsTable :: [Int] -> [Int] -> [Double] -> Bool -> String\nshowAsTable col row vals bFloat =\n  let colLen = length col\n      header = \"|First/second| \" ++ (concat $ map ((++ \"|\") . show) col) ++ \"\\n\"\n      alignHeader = (concat . take (colLen + 1) $ repeat \"|:-----:\") ++ \"|\\n\"\n      showRows = concat $ map (go colLen vals) row\n  in  header ++ alignHeader ++ showRows\n  where\n  go len vals rowIdx =\n    let first = show rowIdx ++ \"|\"\n        rows = take len $ drop (len * rowIdx) vals\n        format = bFloat ? (\"%7.2f\", \"%7.0f\")\n    in  first ++ (concat $ map (\\ x -> (printf format x :: String) ++ \"|\") rows) ++ \"|\\n\"\n\n----------------------------------------------------------------------------------------------------\n-- Gambler Problem Test\n\ndoGamblerTest :: Config -> IO () \ndoGamblerTest config = do\n  (prob::Double) <- require config \"gambler.headProb\"\n  (gamblerGoal::Int) <- require config \"gambler.goal\"\n  (theTheta::Double) <- require config \"gambler.theta\"\n  let gambler = mkGambler prob theTheta gamblerGoal\n      (_, !gambler') = runState gamblerStep gambler\n  drawGamblerGraph gambler'\n  threadDelay 100000\n  pure ()\n\ndrawGamblerGraph :: Gambler -> IO ()\ndrawGamblerGraph gambler = do\n  putStrLn \"Draw Gambler Problem Result Graph\"\n  -- dataX is the second location, whereas dataY is the first location\n  let policyFigure = plot [0..(goal gambler)] (stateVals gambler)\n                       % xlabel (\"Capital (head probability = \" ++ (show $ headProb gambler) ++ \")\")\n                       % ylabel \"Value Estimates\"\n                       % xticks [0, 10..(goal gambler)]\n                       % title (\"Figure 4.3 - State Values\")\n      valueFigure = scatter [0..(goal gambler - 1)] (stateActs gambler)\n                      % xlabel (\"Capital (head probability = \" ++ (show $ headProb gambler) ++ \")\")\n                      % ylabel \"Final Policy (Stack)\"\n                      % xticks [0, 10..(goal gambler)]\n                      % title (\"Figure 4.3 - Optimal Actions\")\n  -- avoid Matplotlib's bug  \n  code policyFigure >> code valueFigure >> onscreen policyFigure >> onscreen valueFigure\n  threadDelay 100000\n", "meta": {"hexsha": "08d2e30ec000accb5b2fcb30a895ba432715f870", "size": 8895, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/TestChapter4DP.hs", "max_stars_repo_name": "Xingtao/ReinforceLearningIntro", "max_stars_repo_head_hexsha": "ea48c10baec4c70c4e9ad3442a082d35983731ac", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2017-12-26T04:08:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T03:29:18.000Z", "max_issues_repo_path": "test/TestChapter4DP.hs", "max_issues_repo_name": "Xingtao/ReinforceLearningIntro", "max_issues_repo_head_hexsha": "ea48c10baec4c70c4e9ad3442a082d35983731ac", "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": "test/TestChapter4DP.hs", "max_forks_repo_name": "Xingtao/ReinforceLearningIntro", "max_forks_repo_head_hexsha": "ea48c10baec4c70c4e9ad3442a082d35983731ac", "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": 46.8157894737, "max_line_length": 122, "alphanum_fraction": 0.5947161327, "num_tokens": 2195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23257594661276051}}
{"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": "{-|\n  Mapping of basic Matlab types to Haskell types.\n-}\nmodule Foreign.Matlab.Types (\n    -- * Representations of Matlab types\n    -- |Most types are simple aliases of Haskell types, given simply to identify them and provide a consistent naming scheme.\n\n    MIO,\n\n    MXClass(..),\n    MChar,\n    MLogical,\n    MScalar,\n\n    MNumeric,\n    -- * Numeric types\n    MDouble,\n    MSingle,\n    MInt8,\n    MInt16,\n    MInt32,\n    MInt64,\n    MUint8,\n    MUint16,\n    MUint32,\n    MUint64,\n    MComplex,\n\n    -- * Array indexing\n    MSize, MSubs,\n    MIndex(..),\n    mStart, mOffset,\n    mSizeRange, mRangeSize,\n    normMSize, realMSize,\n\n    -- * Opaque types\n    MXArray,\n    MAny, MAnyArray,\n    MCell(MCell), mCell,\n    MStruct, mStruct,\n    MFun\n  ) where\n\n\nimport Data.Complex\nimport Data.Ix\nimport Foreign.Matlab.Internal\n\n-- |The class of types which are simple Matlab scalars and can be array elements\nclass MScalar a\n-- |The class of types which Matlab consisters \\\"numeric\\\"\nclass (MScalar a, Num a) => MNumeric a\n\ninstance MScalar MChar\ninstance MScalar MLogical\ninstance MScalar MDouble\ninstance MScalar MSingle\ninstance MScalar MInt8\ninstance MScalar MInt16\ninstance MScalar MInt32\ninstance MScalar MInt64\ninstance MScalar MUint8\ninstance MScalar MUint16\ninstance MScalar MUint32\ninstance MScalar MUint64\ninstance MNumeric a => MScalar (MComplex a)\n\ninstance MNumeric MDouble\ninstance MNumeric MSingle\ninstance MNumeric MInt8\ninstance MNumeric MInt16\ninstance MNumeric MInt32\ninstance MNumeric MInt64\ninstance MNumeric MUint8\ninstance MNumeric MUint16\ninstance MNumeric MUint32\ninstance MNumeric MUint64\n\n-- |Complex numeric types.  Unfortunately, 'Complex' only applies to 'RealFloat' types, whereas Matlab allows any numeric type, so some types are (currently) unaccessable.\ntype MComplex = Complex\n\n-- |The type of array sizes, which are the column-major lengths of each dimensions\ntype MSize = [Int]\n-- |The type of array index subscripts, which are the column-major, 0-based indices in each dimension with normal Matlab semantics (flatten along last dimension)\ntype MSubs = [Int]\n-- |Ways to index an array.  Using Matlab semantics, a singleton MSubs [n] is equivalent to a raw 0-based offset (MOffset n).\nnewtype MIndex = MSubs MSubs\n    -- MOffset Int -- ^0-based offset from the beginning of the array (equivalent to singleton MSubs)\n\n-- |First index in array\nmStart :: MIndex\nmStart = MSubs []\n\n-- |Raw, 0-based array offset index\nmOffset :: Int -> MIndex\nmOffset i = MSubs [i]\n\ninstance Show MIndex where\n  showsPrec _ (MSubs []) = id\n  showsPrec _ (MSubs l) = showChar '(' . foldr1 (\\s r -> s . showChar ',' . r) (map shows l) . showChar ')'\ninstance Eq MIndex where\n  MSubs a == MSubs b = eq a b where\n    eq [] [] = True\n    eq (x:a) (y:b) = (x == y) && eq a b\n    eq [] b = eq [0] b\n    eq a [] = eq a [0]\ninstance Ord MIndex where\n  compare (MSubs a) (MSubs b) = cmp a b where\n    cmp [] [] = EQ\n    cmp (x:a) (y:b) = case cmp a b of { EQ -> compare x y ; r -> r }\n    cmp [] b = cmp [0] b\n    cmp a [] = cmp a [0]\ninstance Ix MIndex where\n  range (MSubs a, MSubs b) = map MSubs $ rng a b where\n    rng [] [] = [[]]\n    rng (x:a) (y:b) = concatMap (\\l -> map (:l) [x..y]) $ rng a b\n    rng [] b = rng [0] b\n    rng _ _ = error \"MIndex.range: length mismatch\"\n  index (MSubs a, MSubs b) (MSubs l) = idx a b l where\n    idx _ _ [] = 0\n    idx (x:a) (y:b) (i:l) = i-x+((y-x+1)*idx a b l)\n    idx [] [] (0:l) = idx [] [] l\n    idx [] b l = idx [0] b l\n    idx _ _ _ = error \"MIndex.index: length mismatch\"\n  inRange (MSubs a, MSubs b) (MSubs l) = inr a b l where\n    inr _ _ [] = True\n    inr a@(x:_) b@(_:_) [i] = i >= x && i-x < rangeSize (MSubs a, MSubs b)\n    inr (x:a) (y:b) (i:l) = i >= x && i <= y && inr a b l\n    inr [] [] (0:l) = inr [] [] l\n    inr [] b l = inr [0] b l\n    inr _ _ _ = error \"MIndex.inRange: length mismatch\"\n  rangeSize (MSubs a, MSubs b) = rsz a b where\n    rsz [] b = product $ map succ b\n    rsz (x:a) (y:b) = (y-x+1)*rsz a b\n    rsz _ _ = error \"MIndex.rangeSize: length mismatch\"\n\n-- |Convert an array size to an index range, which will be of the form ((0,0,0...),(i-1,j-1,k-1,...))\nmSizeRange :: MSize -> (MIndex,MIndex)\nmSizeRange l = (MSubs [], MSubs $ map pred $ normMSize l)\n\n-- |Convert an index range to an array size\nmRangeSize :: (MIndex,MIndex) -> MSize\nmRangeSize (MSubs [], MSubs l) = map succ l\nmRangeSize _ = error \"mRangeSize: invalid lower bound\"\n\n-- |Get the size form that Matlab likes (@length (realMSize s) >= 2@)\nrealMSize :: MSize -> MSize\nrealMSize [] = [1,1]\nrealMSize [n] = [n,1]\nrealMSize s = s\n\n-- |Get a more useful size form (no trailing singletons)\nnormMSize :: MSize -> MSize\nnormMSize [] = []\nnormMSize (1:l) = case normMSize l of { [] -> [] ; l -> (1:l) }\nnormMSize (x:l) = x : normMSize l\n", "meta": {"hexsha": "c13cf6040e32254c1f2339e4f39849d9388bdea9", "size": 4774, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Foreign/Matlab/Types.hs", "max_stars_repo_name": "CornellCAC/haskell-matlab", "max_stars_repo_head_hexsha": "21cdb98a2bcf23c90eb31026063f4c3a2cf5da15", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-02-10T07:58:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T12:13:16.000Z", "max_issues_repo_path": "Foreign/Matlab/Types.hs", "max_issues_repo_name": "CornellCAC/haskell-matlab", "max_issues_repo_head_hexsha": "21cdb98a2bcf23c90eb31026063f4c3a2cf5da15", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2015-01-20T02:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-28T19:48:32.000Z", "max_forks_repo_path": "Foreign/Matlab/Types.hs", "max_forks_repo_name": "CornellCAC/haskell-matlab", "max_forks_repo_head_hexsha": "21cdb98a2bcf23c90eb31026063f4c3a2cf5da15", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-02-10T07:58:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-26T22:30:15.000Z", "avg_line_length": 30.4076433121, "max_line_length": 171, "alphanum_fraction": 0.6476749057, "num_tokens": 1578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2323091998129193}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE NamedFieldPuns #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nimport qualified Data.Map as Map\nimport Data.Map(Map)\nimport qualified Data.Set as Set\nimport Control.Arrow(first, second, (&&&))\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\nimport Data.Ord\nimport qualified Text.Printf as Printf\nimport qualified Data.Array as Array\nimport Data.Array(Array, (!), range, Ix)\nimport qualified Data.Matrix\nimport qualified System.Random\nimport Control.Monad\nimport Control.Monad.Identity\nimport System.IO(stdout, hSetBuffering, BufferMode(..))\nimport Control.Parallel.Strategies\nimport GHC.Generics\nimport qualified Data.Eigen.Matrix\nimport Foreign.C.Types\nimport qualified Numeric.LinearAlgebra.HMatrix\nimport qualified Numeric.LinearAlgebra.Data\nimport Control.Arrow\nimport GHC.Stack\n\nimport Matrix\n\ndata RawMaterial =\n  BuriedIronRaw\n  | BuriedCopperRaw\n  | BuriedStoneRaw\n--  | PetroleumGasRaw\n--  | LightOilRaw\n--  | HeavyOilRaw\n  | CrudeOilRaw\n  | BuriedCoalRaw\n  | PollutionRaw\n  deriving (Eq, Ord, Enum, Bounded, Show, Ix, Generic)\n\ninstance NFData RawMaterial\n\ntype RawMaterialPressure = Map Product Rat\n\ndata Product =\n  IronPlate\n  | CopperPlate\n  | SteelPlate\n  | IronOre\n  | CopperOre\n  | CopperCable\n  | GearWheel\n  | Plastic\n  | Pipe\n  | ElectronicCircuit\n  | AdvancedCircuit\n  | EngineUnit\n  | ProcessingUnit\n  | ElectricMiningDrill\n  | PiercingRoundMagazine\n  | FirearmRoundMagazine\n  | Grenade\n  | GunTurret\n  | SciencePack1\n  | SciencePack2\n  | SciencePack3\n  | SciencePackMilitary\n  | SciencePackProduction\n  | SciencePackHighTech\n  | SpeedModule\n  | SpeedModule2\n  | SpeedModule3\n  | ProductivityModule\n  | ProductivityModule2\n  | ProductivityModule3\n  | EfficiencyModule\n  | EfficiencyModule2\n  | EfficiencyModule3\n  | Sulfur\n  | SulfuricAcid\n  | CoalLiquefaction\n  | ResearchCoalLiquefaction\n  | ResearchLaserTurretDamage5\n  | ResearchRocketSilo\n  | ResearchNuclearPower\n  | ResearchEndgame\n  | Inserter\n  | TransportBelt\n  | AssemblingMachine1\n  | AssemblingMachine2\n  | AssemblingMachine3\n  | SteelFurnace\n  | ElectricFurnace\n  | ElectricEngineUnit\n  | Lubricant\n  | StoneBrick\n  | Stone\n  | LaserTurret\n  | Battery\n  | ChemicalPlant\n  | OilRefinery\n  | LabBuilding\n  | BoilerBuilding\n  | SteamEngineBuilding\n  | SolarFacilityBuilding\n  | NuclearFacilityBuilding\n  | Roboport\n  | Substation\n  | Accumulator\n  | SolarPanel\n  | StoneFurnace\n  | SteamTurbine\n  | NuclearReactor\n  | HeatExchanger\n  | HeatPipe\n  | Concrete\n  | Beacon\n  | RocketPart\n  | RocketSiloBuilding\n  | ControlModule\n  | LightweightStructure\n  | RocketFuel\n  | SciencePackSpace\n  | Satellite\n  | Radar\n\n  | ElectricalEnergy -- in J\n  | ChemicalEnergy -- in J\n  | SolidFuel\n  | Steam\n  | Coal\n  | BuriedIron\n  | BuriedCopper\n  | PetroleumGas\n  | LightOil\n  | HeavyOil\n  | CrudeOil\n  | BuriedCoal\n  | BuriedStone\n  | Pollution\n  deriving (Eq, Ord, Show, Enum, Bounded, Ix, Generic)\n\ninstance NFData Product where\n\nnewtype Time = Time { unTime :: Rat } deriving (Eq, Ord, Show, NFData)\n\ninstance Linear Time where\n  zero = Time 0\n  add (Time x) (Time y) = Time (add x y)\n  minus (Time x) = Time (minus x)\n\ninstance VectorSpace Time where\n  type Scalar Time = Rat\n  scale x (Time t) = Time (x * t)\n\ndata VenueKind =\n  AssemblyVenueKind\n  | SmelterVenueKind\n  | ChemicalVenueKind\n  | MinerVenueKind\n  | LabVenueKind\n  | BoilerVenueKind\n  | SteamEngineVenueKind\n  | GreenPowerVenueKind\n  | RefineryVenueKind\n  | RocketSiloVenueKind\n  | NoVenueVenueKind\n  deriving (Show, Ord, Eq) \nvenuesByKind :: VenueKind -> [Venue]\nvenuesByKind AssemblyVenueKind = [Assembly2, Assembly3]\nvenuesByKind SmelterVenueKind = [SmelterBurner, SmelterElectric]\nvenuesByKind ChemicalVenueKind = [Chemical]\nvenuesByKind MinerVenueKind = [Miner]\nvenuesByKind LabVenueKind = [Lab]\nvenuesByKind BoilerVenueKind = [Boiler]\nvenuesByKind SteamEngineVenueKind = [SteamEngine]\nvenuesByKind GreenPowerVenueKind = [SolarFacility, NuclearFacility]\nvenuesByKind RefineryVenueKind = [Refinery]\nvenuesByKind NoVenueVenueKind = [NoVenue]\nvenuesByKind RocketSiloVenueKind = [RocketSilo]\n\ndata Venue =\n  Assembly2\n  | Assembly3\n  | SmelterBurner\n  | SmelterElectric\n  | Chemical\n  | Miner\n  | Lab\n  | Boiler\n  | SteamEngine\n  | SolarFacility\n  | NuclearFacility\n  | Refinery\n  | RocketSilo\n  | NoVenue\n  deriving (Show, Eq, Ord, Generic)\n\ndata ModuleConfig = ModuleConfig\n  {\n    configSpeedBonus :: Rat,\n    configProductivityBonus :: Rat,\n    configEnergyBonus :: Rat,\n    configPollutionBonus :: Rat\n  } deriving (Eq, Ord, Show, Generic)\n\ninstance Linear ModuleConfig where\n  zero = mempty\n  add = mappend\n  minus = scale (-1)\n\ninstance VectorSpace ModuleConfig where\n  type Scalar ModuleConfig = Rat\n  scale x (ModuleConfig a b c d) =\n    ModuleConfig\n     (x * a) (x * b) (x * c) (x * d)\n\n-- venue, modules and modules in beacons\ntype PreConfig = (Venue, [Product], Maybe Product)\n\ndata Config = Config\n  {\n    configVenue :: Venue,\n    configModules :: ModuleConfig,\n    configModuleMaterials :: Map Product Rat,\n    configConstantExtraPower :: Rat\n  } deriving Generic\n\n\ninstance NFData ModuleConfig\ninstance NFData Config\n\nspeedMultiplier c = (1 + configSpeedBonus x) where x = configModules c\nproductivityMultiplier c = 1 + configProductivityBonus x where x = configModules c\nenergyMultiplier c = max 0.2 (1 + configEnergyBonus x) where x = configModules c\npollutionMultiplier c = (1 + configPollutionBonus x) where x = configModules c\n\ninstance Monoid ModuleConfig where\n  mempty = ModuleConfig 0 0 0 0\n  a `mappend` b =\n    ModuleConfig\n      {\n        configSpeedBonus = (configSpeedBonus a + configSpeedBonus b),\n        configProductivityBonus = (configProductivityBonus a + configProductivityBonus b),\n        configEnergyBonus = (configEnergyBonus a + configEnergyBonus b),\n        configPollutionBonus = (configPollutionBonus a + configPollutionBonus b)\n      }\n\ndata Usability =\n  Unusable | Usable\n\nmoduleToConfig SpeedModule = ModuleConfig 0.2 0 0.5 0\nmoduleToConfig SpeedModule2 = ModuleConfig 0.3 0 0.6 0\nmoduleToConfig SpeedModule3 = ModuleConfig 0.5 0 0.7 0\nmoduleToConfig EfficiencyModule = ModuleConfig 0 0 (negate 0.3) 0\nmoduleToConfig EfficiencyModule2 = ModuleConfig 0 0 (negate 0.4) 0\nmoduleToConfig EfficiencyModule3 = ModuleConfig 0 0 (negate 0.5) 0\nmoduleToConfig ProductivityModule = ModuleConfig (negate 0.15) 0.04 0.4 0\nmoduleToConfig ProductivityModule2 = ModuleConfig (negate 0.15) 0.06 0.6 0\nmoduleToConfig ProductivityModule3 = ModuleConfig (negate 0.15) 0.10 0.8 0\nmoduleToConfig p = error $ \"not a module: \" ++ show p\n\nallModules :: Usability -> [[[Product]]]\nallModules usability =\n  [[ ([]) ]] ++\n  (map (\\ms -> map (\\m -> [m]) ms) $\n  (map return\n  [ SpeedModule\n  , EfficiencyModule\n--  , EfficiencyModule2\n--  , EfficiencyModule3\n  , SpeedModule2\n  , SpeedModule3\n  ]\n  ++ [case usability of\n   Unusable ->\n     [ ProductivityModule\n     , ProductivityModule2\n     , ProductivityModule3\n     ]\n   Usable -> []]))\n\nchoose' :: Int -> [[a]] -> [[a]]\nchoose' k l\n  | k < 0 = []\n  | k == 0 = [[]]\n  | otherwise = case l of\n    [] -> []\n    (xc : xs) -> choose' k xs ++ (do\n      i <- [1..k]\n      (x :: a) <- xc\n      rest <- choose' (k - i) xs\n      return $ replicate i x ++ rest)\n\nchoose k l\n  | k < 0 = []\n  | k == 0 = [[]]\n  | otherwise = case l of\n     [] -> []\n     (x : xs) -> map (x:) (choose (k-1) l) ++ choose k xs\n\nmoduleSlots :: Venue -> Int\nmoduleSlots venue = case venue of\n        Assembly2 -> 2\n        Assembly3 -> 4\n        SmelterElectric -> 2\n        SmelterBurner -> 0\n        Chemical -> 3\n        Miner -> 3\n        Lab -> 2\n        Boiler -> 0\n        SteamEngine -> 0\n        SolarFacility -> 0\n        NuclearFacility -> 0\n        Refinery -> 3\n        NoVenue -> 0\n        RocketSilo -> 4\n\n\ninitial_module_config gc Miner = mempty { configProductivityBonus = gc_miner_productivity_bonus gc }\ninitial_module_config _ _ = mempty\n\n-- we have [beaconizationFactor] factories per beacon\n-- and [beaconizationFactor] beacons per factory\nbeaconizationFactor :: RecipeName -> Integer\nbeaconizationFactor (ProductRecipe ElectronicCircuit) = 2\nbeaconizationFactor (ProductRecipe CopperCable) = 7\nbeaconizationFactor (ProductRecipe SciencePackProduction) = 1\nbeaconizationFactor (ProductRecipe SciencePackMilitary) = 2\nbeaconizationFactor (ProductRecipe IronOre) = 6\nbeaconizationFactor _ = 4\n\nlinksPerBeacon :: RecipeName -> Integer\nlinksPerBeacon = beaconizationFactor\nlinksPerFactory :: RecipeName -> Integer\nlinksPerFactory = beaconizationFactor\n\nbeaconsPerFactory x = fromInteger (linksPerFactory x) / fromInteger (linksPerBeacon x)\n\nmkConfig gc recipe (venue, modules, beacon) =\n  Config\n    venue\n    (mconcat $\n      (initial_module_config gc venue)\n      : map moduleToConfig modules\n      ++ (case beacon of\n        Just m ->\n          [ scale (fromIntegral (linksPerFactory recipe)) (moduleToConfig m) ]\n        Nothing ->\n          []\n        )\n      )\n    (Map.fromListWith add\n    (map (\\x -> (x, 1)) modules ++ (\n      case beacon of\n       Nothing -> []\n       Just m ->\n         let ratio = beaconsPerFactory recipe in\n         [(m, 2 * ratio), (Beacon, 1 * ratio)]\n     )\n    ))\n    (case beacon of\n      Nothing -> 0\n      Just _ -> 480e3 * (beaconsPerFactory recipe)\n    )\n\n-- in Watt\ndata Power =\n  ElectricalPower { unPower :: Rat }\n  | ChemicalPower Rat\n\nbaseBoilerPower = 3.6e6\n\nbasePower :: Venue -> Power\nbasePower Assembly2 = ElectricalPower 150e3\nbasePower Assembly3 = ElectricalPower 210e3\nbasePower Miner = ElectricalPower 90e3\nbasePower SmelterElectric = ElectricalPower 180e3\nbasePower SmelterBurner = ChemicalPower 180e3\nbasePower Chemical = ElectricalPower 210e3\nbasePower Lab = ElectricalPower 60e3\nbasePower Boiler = ChemicalPower baseBoilerPower\nbasePower SteamEngine = ElectricalPower 0\nbasePower SolarFacility = ElectricalPower 0\nbasePower NuclearFacility = ElectricalPower 0\nbasePower Refinery = ElectricalPower 420e3\nbasePower NoVenue = ElectricalPower 0\nbasePower RocketSilo = ElectricalPower 4e6\n\nbasePollution Assembly2 = 2.4\nbasePollution Assembly3 = 1.8\nbasePollution Miner = 9\nbasePollution SmelterElectric = 0.9\nbasePollution SmelterBurner = 3.6\nbasePollution Chemical = 1.8\nbasePollution Lab = 0\nbasePollution Boiler = 27.6923\nbasePollution Refinery = 3.6\nbasePollution SolarFacility = 0\nbasePollution NuclearFacility = 0\nbasePollution SteamEngine = 0\nbasePollution NoVenue = 0\nbasePollution RocketSilo = 0\n\nbaseSpeed _ SolarFacility = (42e3 * 176)\nbaseSpeed _ NuclearFacility = 160e6\nbaseSpeed _ Assembly2 = 0.75\nbaseSpeed _ Assembly3 = 1.25\nbaseSpeed _ Miner = 1 -- factored in into the recipe\nbaseSpeed _ SmelterElectric = 2\nbaseSpeed _ SmelterBurner = 2\nbaseSpeed _ Chemical = 1.25\nbaseSpeed config Lab = gc_lab_speed_multiplier config\nbaseSpeed _ Boiler = 1 -- this is factored into the recipe\nbaseSpeed _ SteamEngine = 1 -- this is factored into the recipe\nbaseSpeed _ Refinery = 1\nbaseSpeed _ NoVenue = 1 -- this is meaningless\nbaseSpeed _ RocketSilo = 1\n\nscaleTime s (Time t) = Time (s * t)\n\ncoalToEnergy coal = coal * 8e6 / 2\n\ndata Recipe = Recipe\n  {\n    recipeName :: RecipeName,\n    recipeProducts :: [(Product, Rat)],\n    recipeMaterials :: [(Product, Rat)],\n    recipeVenueKind :: VenueKind,\n    recipeTime :: Time\n  } deriving (Eq, Ord, Show)\n\ndata RecipeName =\n  ProductRecipe Product\n  | LiquefactionRecipe\n  | AdvancedOilProcessing\n  | BoilerRecipe\n  | UseAsFuelRecipe Product\n  deriving (Eq, Ord, Generic)\n\ninstance Show RecipeName where\n  show (ProductRecipe product) = show product\n  show (LiquefactionRecipe) = \"Liquefaction\"\n  show (AdvancedOilProcessing) = \"AdvancedOilProcessing\"\n  show BoilerRecipe = \"BoilerRecipe\"\n  show (UseAsFuelRecipe product) = \"UseAsFuel\" ++ show product\n\nenergy_per_steam = 30000\n\ndata ResearchCost = ResearchCost {\n  researchCostTime :: Time, -- time to process 1 stack of bottles\n  researchCostBottles :: [Product],\n  researchCostAmount :: Rat\n}\n\nmarathon_research_cost_adjustment = 4.0\n\nlab_speed_researches :: [(ResearchCost, Rat)]\nlab_speed_researches =\n  let r = SciencePack1 in\n  let g = SciencePack2 in\n  let b = SciencePack3 in\n  let p = SciencePackProduction in\n  let y = SciencePackHighTech in\n  let bot l amount =  ResearchCost (Time 30) l (amount * marathon_research_cost_adjustment) in\n  (bot [r, g] 100, 0.20)\n  : (bot [r, g] 200, 0.30)\n  : (bot [r, g, b] 250, 0.40)\n  : (bot [r, g, b] 500, 0.50)\n  : (bot [r, g, b, p] 500, 0.50)\n  : (bot [r, g, b, p, y] 500, 0.60)\n  : error \"further lab researches unknown\"\n\nmining_productivity_researches :: [(ResearchCost, Rat)]\nmining_productivity_researches =\n  let r = SciencePack1 in\n  let g = SciencePack2 in\n  let b = SciencePack3 in\n  let p = SciencePackProduction in\n  let y = SciencePackHighTech in\n  zipWith\n    (\\colors amounts -> (ResearchCost (Time 60) colors (amounts * 4), 0.02))\n    (replicate 3 [r, g] ++ replicate 4 [r, g, b] ++ replicate 4 [r, g, b, p] ++ replicate 4 [r, g, b, p, y])\n    (map fromInteger [100, 200..]) ++ error \"further mining productivity unknown\"\n\ncomputeResearchCapital :: Int -> [(ResearchCost, Rat)] -> Map Product Rat\ncomputeResearchCapital n =\n  mconcat' . map (\\r -> scale (researchCostAmount r) (Map.fromListWith (+) $ map (\\p -> (p, 1)) (researchCostBottles r))) . map fst . take n\n\ndata SmeltingMode =\n  BurnerSmelting\n  | ElectricSmelting\n\ndata Liquefaction_mode =\n  Liquefaction_disabled\n  | Liquefaction_to_gas\n  | Liquefaction_to_burn\n   deriving (Show, Generic)\n\nclass Enumerate a where\n  allOfThem :: [a]\n\ninstance Enumerate Liquefaction_mode where\n  allOfThem =\n   [ Liquefaction_disabled\n   , Liquefaction_to_gas\n   , Liquefaction_to_burn\n   ]\n\n-- the details of GameConfig sufficient to determine what recipes are available\ndata GameConfigQualitative = GameConfigQualitative {\n  qgc_liquefaction :: Liquefaction_mode\n  }\n\nto_qualitative (GameConfig { gc_liquefaction = liquefaction }) = GameConfigQualitative { qgc_liquefaction = liquefaction }\n\ndata GameConfig = GameConfig {\n  gc_lab_researches_done :: Int,\n  gc_mining_researches_done :: Int,\n  gc_liquefaction :: Liquefaction_mode,\n  gc_recipe_configs :: RecipeName -> PreConfig\n  }\n  deriving Generic\n\ndata Change =\n  ProductChange RecipeName PreConfig\n  | Other String String\n  deriving Generic\n\ninstance NFData Change\ninstance NFData GameConfig\ninstance NFData Liquefaction_mode\ninstance NFData RecipeName\n\ngc_alternatives :: GameConfig -> [(Change, GameConfig)]\ngc_alternatives gc =\n  [(Other \"Liquefaction Mode\" (show mode), gc { gc_liquefaction = mode }) | mode <- allOfThem] ++\n  [(Other \"Lab speed\" \"+1\", gc { gc_lab_researches_done = gc_lab_researches_done gc + 1 }) ] ++\n  [(Other \"Mining productivity\" \"+1\", gc { gc_mining_researches_done = gc_mining_researches_done gc + 1 }) ] ++\n  [(ProductChange recipeName config, gc { gc_recipe_configs = f' })\n  | (recipe, _) <- recipes\n  , recipeName <- [ recipeName recipe ]\n  , venue <- venuesByKind (recipeVenueKind recipe)\n  , let availableModules = allModules (usability recipeName)\n  , modules <- choose' (moduleSlots venue) availableModules\n  , modules <- [ concat modules ]\n  , beacon <- if length modules == moduleSlots venue && moduleSlots venue > 0 then [ Nothing, Just SpeedModule2, Just SpeedModule3 ] else [ Nothing ]\n  , let config = (venue, modules, beacon)\n  , let f' = (let f = gc_recipe_configs gc in (\\r -> if r == recipeName then config else f r))\n  ]\n\ngc_lab_speed_multiplier :: GameConfig -> Rat\ngc_lab_speed_multiplier t = 1 +\n  (mconcat' $ map snd $ take (gc_lab_researches_done t) lab_speed_researches)\n\ngc_miner_productivity_bonus :: GameConfig -> Rat\ngc_miner_productivity_bonus t =\n  (mconcat' $ map snd $ take (gc_mining_researches_done t) mining_productivity_researches)\n\ngc_configs :: GameConfig -> (Recipe -> Config)\ngc_configs gc =\n \\recipe ->\n let pre = gc_recipe_configs gc (recipeName recipe) in\n mkConfig gc (recipeName recipe) pre\n\n-- recipes and whether or not they should be enabled\nrecipes :: [(Recipe, (GameConfigQualitative -> Bool))]\nrecipes =\n  let assembly = AssemblyVenueKind in\n  let smelter = SmelterVenueKind in\n  let\n   miner what ingredients speed =\n     [ (Recipe (ProductRecipe what) [(what, 1)] ingredients MinerVenueKind (Time $ recip speed), const True) ]\n  in\n  concat [\n    r GearWheel 1 [(IronPlate, 4)] assembly (Time 0.5),\n    r IronPlate 1 [(IronOre, 1)] smelter (Time 3.5),\n    r CopperPlate 1 [(CopperOre, 1)] smelter (Time 3.5),\n    r SteelPlate 1 [(IronPlate, 10)] smelter (Time 35),\n    miner IronOre [(BuriedIron, 1)] 0.525,\n    miner CopperOre [(BuriedCopper, 1)] 0.525,\n    miner Coal [(BuriedCoal, 1)] 0.525,\n    r Beacon 1[(AdvancedCircuit, 20), (CopperCable, 10), (ElectronicCircuit, 20), (SteelPlate, 10)] assembly (Time 15),\n    r Plastic 2[(PetroleumGas, 20), (Coal, 1)] ChemicalVenueKind (Time 1),\n    r ElectronicCircuit 1 [(CopperCable, 10), (IronPlate, 2)] assembly (Time 0.5),\n    r AdvancedCircuit 1 [(Plastic, 4), (CopperCable, 8), (ElectronicCircuit, 2)] assembly (Time 6),\n    r CopperCable 2 [(CopperPlate, 1)] assembly (Time 0.5),\n    r Pipe 1 [(IronPlate, 2)] assembly (Time 0.5),\n    r EngineUnit 1 [(GearWheel, 1), (Pipe, 2), (SteelPlate, 1)] assembly (Time 10),\n    r ElectricMiningDrill 1 [(GearWheel, 10), (IronPlate, 20), (ElectronicCircuit, 5)] assembly (Time 2),\n    r SciencePack3 1 [(AdvancedCircuit, 1), (ElectricMiningDrill, 1), (EngineUnit, 1)] assembly (Time 12),\n    r SciencePack1 1 [(CopperPlate, 1), (GearWheel, 1)] assembly (Time 5),\n    r SciencePack2 1 [(Inserter, 1), (TransportBelt, 1)] assembly (Time 6),\n    r SciencePackProduction 2 [(ElectricEngineUnit, 1), (ElectricFurnace, 1)] assembly (Time 14),\n    r PiercingRoundMagazine 1 [(FirearmRoundMagazine, 1), (SteelPlate, 1), (CopperPlate, 5)] assembly (Time 3),\n    r FirearmRoundMagazine 1 [(IronPlate, 4)] assembly (Time 1),\n    r Grenade 1 [(IronPlate, 5), (Coal, 10)] assembly (Time 8),\n    r GunTurret 1[(GearWheel, 10), (CopperPlate, 10), (IronPlate, 20)] assembly (Time 8),\n    r SciencePackMilitary 2 [(PiercingRoundMagazine, 1), (Grenade, 1), (GunTurret, 1)] assembly (Time 10),\n    r SpeedModule 1 [(AdvancedCircuit, 5), (ElectronicCircuit, 5)] assembly (Time 15),\n    r EfficiencyModule 1 [(AdvancedCircuit, 5), (ElectronicCircuit, 5)] assembly (Time 15),\n    r ProductivityModule 1 [(AdvancedCircuit, 5), (ElectronicCircuit, 5)] assembly (Time 15),\n    r EfficiencyModule2 1 [(AdvancedCircuit, 5), (EfficiencyModule, 4), (ProcessingUnit, 5)] assembly (Time 30),\n    r SpeedModule2 1 [(AdvancedCircuit, 5), (SpeedModule, 4), (ProcessingUnit, 5)] assembly (Time 30),\n    r ProductivityModule2 1 [(AdvancedCircuit, 5), (ProductivityModule, 4), (ProcessingUnit, 5)] assembly (Time 30),\n    r ProductivityModule3 1 [(AdvancedCircuit, 5), (ProductivityModule2, 5), (ProcessingUnit, 5)] assembly (Time 60),\n    r SpeedModule3 1 [(AdvancedCircuit, 5), (SpeedModule2, 5), (ProcessingUnit, 5)] assembly (Time 60),\n    r EfficiencyModule3 1 [(AdvancedCircuit, 5), (EfficiencyModule2, 5), (ProcessingUnit, 5)] assembly (Time 60),\n    r ProcessingUnit 1 [(AdvancedCircuit, 2), (ElectronicCircuit, 20), (SulfuricAcid, 10)] assembly (Time 10),\n    r SulfuricAcid 50 [(IronPlate, 1), (Sulfur, 5)] ChemicalVenueKind (Time 1),\n    r Sulfur 2 [(PetroleumGas, 30)] ChemicalVenueKind (Time 1),\n    r ResearchCoalLiquefaction (1/800) [(SciencePack1, 1), (SciencePack2, 1), (SciencePack3, 1), (SciencePackProduction, 1)] LabVenueKind (Time 30),\n    r ResearchNuclearPower (1/4000) [(SciencePack1, 1), (SciencePack2, 1), (SciencePack3, 1)] LabVenueKind (Time 30),\n    r ResearchLaserTurretDamage5 (1/800)\n      [(SciencePack1, 1), (SciencePack2, 1), (SciencePack3, 1), (SciencePackProduction, 1), (SciencePackHighTech, 1)] LabVenueKind (Time 60),\n    r ResearchRocketSilo (1/4000)\n      [ (SciencePack1, 1)\n      , (SciencePack2, 1)\n      , (SciencePack3, 1)\n      , (SciencePackProduction, 1)\n      , (SciencePackHighTech, 1)\n      , (SciencePackMilitary, 1)] LabVenueKind (Time 60),\n    r ResearchEndgame (1/10000)\n      [ (SciencePack1, 1)\n      , (SciencePack2, 1)\n      , (SciencePack3, 1)\n      , (SciencePackProduction, 1)\n      , (SciencePackHighTech, 1)\n      , (SciencePackMilitary, 1)\n      , (SciencePackSpace, 1)\n      ] LabVenueKind (Time 60),\n    r Inserter 1 [(ElectronicCircuit, 1), (IronPlate, 1), (GearWheel, 1)] assembly (Time 0.5),\n    r TransportBelt 2 [(GearWheel, 1), (IronPlate, 1)] assembly (Time 0.5),\n    r AssemblingMachine1 1 [(GearWheel, 5), (IronPlate, 9), (ElectronicCircuit, 3)] assembly (Time 0.5),\n    r AssemblingMachine2 1 [(AssemblingMachine1, 1), (ElectronicCircuit, 5), (GearWheel, 10), (IronPlate, 20)] assembly (Time 0.5),\n    r AssemblingMachine3 1 [(AssemblingMachine2, 2), (SpeedModule, 4)] assembly (Time 0.5),\n    r SteelFurnace 1 [(SteelPlate, 6), (StoneBrick, 10)] assembly (Time 3),\n    r ElectricFurnace 1 [(AdvancedCircuit, 5), (SteelPlate, 10), (StoneBrick, 10)] assembly (Time 5),\n    r ElectricEngineUnit 1 [(ElectronicCircuit, 2), (EngineUnit, 1), (Lubricant, 15)] assembly (Time 10),\n    r StoneBrick 1 [(Stone, 2)] smelter (Time 3.5),\n    miner Stone [(BuriedStone, 1)] 0.65,\n    r Lubricant 10 [(HeavyOil, 10)] ChemicalVenueKind (Time 1),\n    r LaserTurret 1 [(Battery, 12), (ElectronicCircuit, 20), (SteelPlate, 20)] assembly (Time 20),\n    r Battery 1[(CopperPlate, 1), (IronPlate, 1), (SulfuricAcid, 40)] ChemicalVenueKind (Time 5),\n    r SciencePackHighTech 2 [(Battery, 1), (CopperCable, 30), (ProcessingUnit, 3), (SpeedModule, 1)] assembly (Time 14),\n    r ChemicalPlant 1 [(ElectronicCircuit, 5), (GearWheel, 5), (Pipe, 5), (SteelPlate, 5)] assembly (Time 5),\n    r OilRefinery 1 [(ElectronicCircuit, 10), (GearWheel, 10), (Pipe, 10), (SteelPlate, 15), (StoneBrick, 10)] assembly (Time 8),\n    r LabBuilding 1 [(ElectronicCircuit, 10), (GearWheel, 10), (TransportBelt, 4)] assembly (Time 2),\n    r BoilerBuilding 1 [(Pipe, 4), (StoneFurnace, 1)] assembly (Time 0.5),\n    r StoneFurnace 1 [(Stone, 5)] assembly (Time 0.5),\n    r SteamEngineBuilding 1 [(GearWheel, 10), (IronPlate, 50), (Pipe, 5)] assembly (Time 0.5),\n    \n    [ (Recipe BoilerRecipe [(Steam, (baseBoilerPower * 0.5) / energy_per_steam)] [] BoilerVenueKind (Time 1), const True) ],\n--    r ElectricalEnergy 1 [(Steam, 1/energy_per_steam)] SteamEngineVenueKind (Time (1/900e3)),\n    r ElectricalEnergy 1 [] GreenPowerVenueKind (Time 1),\n    r SolarFacilityBuilding 1 [(SolarPanel, 176), (Accumulator, 166), (Substation, 10), (Roboport, 1)] NoVenueVenueKind (Time 1),\n    r Roboport 1 [(AdvancedCircuit, 45), (GearWheel, 45), (SteelPlate, 45)] assembly (Time 5),\n    r Substation 1 [(AdvancedCircuit, 5), (CopperPlate, 5), (SteelPlate, 10)] assembly (Time 0.5),\n    r Accumulator 1 [(Battery, 5), (IronPlate, 2)] assembly (Time 10),\n    r SolarPanel 1 [(CopperPlate, 5), (ElectronicCircuit, 15), (SteelPlate, 5)] assembly (Time 10),\n    \n    r PetroleumGas 2 [(LightOil, 3)] ChemicalVenueKind (Time 5),\n    \n    r SolidFuel 1 [(LightOil, 10)] ChemicalVenueKind (Time 3),\n    r LightOil 3 [(HeavyOil, 4)] ChemicalVenueKind (Time 5),\n    [ (Recipe AdvancedOilProcessing [(HeavyOil, 10), (LightOil, 45), (PetroleumGas, 55)] [(CrudeOil, 100)] RefineryVenueKind (Time 5), const True) ],\n    r Concrete 10 [(StoneBrick, 5), (IronOre, 1)] assembly (Time 10),\n    r NuclearFacilityBuilding 1 [(NuclearReactor, 1), (HeatExchanger, 16), (SteamTurbine, 25), (HeatPipe, 60)] NoVenueVenueKind (Time 1),\n    r SteamTurbine 1 [(GearWheel, 50), (CopperPlate, 50), (Pipe, 20)] assembly (Time 3),\n    r NuclearReactor 1 [(Concrete, 500), (SteelPlate, 500), (AdvancedCircuit, 500), (CopperPlate, 500)] assembly (Time 8),\n    r HeatExchanger 1 [(SteelPlate, 10), (CopperPlate, 100), (Pipe, 10)] assembly (Time 3),\n    r HeatPipe 1 [(SteelPlate, 10), (CopperPlate, 20)] assembly (Time 1),\n\n    r RocketSiloBuilding 1 [(Concrete, 1000), (ElectricEngineUnit, 200), (Pipe, 100), (ProcessingUnit, 200), (SteelPlate, 1000)] assembly (Time 30),\n    r RocketPart 1 [(ControlModule, 10), (LightweightStructure, 10), (RocketFuel, 10)] RocketSiloVenueKind (Time 3),\n    r ControlModule 1 [(ProcessingUnit, 1), (SpeedModule, 1)] assembly (Time 30),\n    r LightweightStructure 1 [(CopperPlate, 10), (Plastic, 10), (SteelPlate, 10)] assembly (Time 30),\n    r RocketFuel 1 [(SolidFuel, 10)] ChemicalVenueKind (Time 30),\n    r SciencePackSpace 1000 [(RocketPart, 100), (Satellite, 1)] NoVenueVenueKind (Time 1),\n    r Satellite 1 [(Accumulator, 100), (LightweightStructure, 100), (ProcessingUnit, 100), (Radar, 5), (RocketFuel, 50), (SolarPanel, 100)] assembly (Time 5),\n    r Radar 1 [(ElectronicCircuit, 5), (GearWheel, 5), (IronPlate, 10)] assembly (Time 0.5),\n    (\n    let\n     burn_coal =\n      Recipe (UseAsFuelRecipe Coal) [(ChemicalEnergy, 8e6)] [(Coal, 1)] NoVenueVenueKind (Time 1) -- time is meaningless here\n     liquefaction =\n      Recipe LiquefactionRecipe [(HeavyOil, 35), (LightOil, 15), (PetroleumGas, 20)] [(Coal, 10), (HeavyOil, 25), (Steam, 50)] RefineryVenueKind (Time 5)\n     burn_bricks =\n      Recipe (UseAsFuelRecipe SolidFuel) [(Steam, (25e6 * 0.5) / energy_per_steam)] [(SolidFuel, 1)] BoilerVenueKind (Time 1) -- incorrect time, but nothing cares\n    in\n    [ (burn_coal, (\\gc -> case qgc_liquefaction gc of { Liquefaction_to_burn -> False; _ -> True }))\n    , (burn_bricks, (\\gc -> case qgc_liquefaction gc of { Liquefaction_to_burn -> True; _ -> False }))\n    , (liquefaction, (\\gc -> case qgc_liquefaction gc of { Liquefaction_disabled -> False; _ -> True }))\n    ])\n  ] where\n  r product quantity ingredients venues time = [ (Recipe (ProductRecipe product) [(product, quantity)] ingredients venues time, const True) ]\n\nmconcat' x = foldr add zero x\n\nfunctionToMatrix :: (Num v, Ix' b, Ix' a) => (a -> [(b, v)]) -> Matrix a b v\nfunctionToMatrix f =\n  Matrix (Array.array fullRange [ ((a, b), maybe 0 id (Map.lookup b bs)) | a <- range fullRange, let bs = Map.fromListWith (+) (f a), b <- range fullRange])\n\nrecipesByName = Map.fromListWith (error \"multiple recipes with the same name\") (map (\\(recipe, _enabled) -> (recipeName recipe, recipe)) (recipes))\n\nenabledRecipesByName gc =\n  Map.fromListWith (error \"multiple recipes with the same name\") (concatMap (\\(recipe, enabled) -> if not (enabled gc) then [] else [(recipeName recipe, recipe)]) (recipes))\n\nrecipesToMatrix :: GameConfig -> Map RecipeName (Map Product Rat)\nrecipesToMatrix gc = \n  fmap (\\(Recipe recipeName production consumption _venueKind (Time baseTime)) ->\n         (\n         let preConfig = gc_recipe_configs gc recipeName in\n         let config = mkConfig gc recipeName preConfig in\n         let venue = configVenue config in\n           let\n             time = (baseTime / (speedMultiplier config * baseSpeed gc venue))\n             extra_energy = time * configConstantExtraPower config\n             energy_and_pollution =\n               let multiplier = time * energyMultiplier config in\n               let pollution = basePollution venue in\n               case basePower venue of\n                 ElectricalPower basePower ->\n                   [(ElectricalEnergy, (basePower * multiplier) + extra_energy), (Pollution, pollution * multiplier)]\n                 ChemicalPower basePower ->\n                   [(ChemicalEnergy, basePower * multiplier + extra_energy), (Pollution, pollution * multiplier)]\n           in\n             Map.fromListWith add (fmap (second negate) (consumption ++ energy_and_pollution) ++ map (second ((* productivityMultiplier config))) production)\n         )) (enabledRecipesByName (to_qualitative gc))\n\nmatrix_add (Matrix x) (Matrix y) = Matrix (Array.array fullRange [(i, x ! i + y ! i) | i <- range fullRange])\nmatrix_negate (Matrix x) = Matrix (Array.array fullRange [(i, - x ! i) | i <- range fullRange])\n\nmatrix_subtract a b = matrix_add a (matrix_negate b)\n\nmatrix_identity :: (Ix' a, Num v) => Matrix a a v\nmatrix_identity = Matrix (Array.array fullRange [((a,b), if a == b then 1 else 0) | (a,b) <- range fullRange])\n\nto_data_matrix :: forall a v . (Ix' a) => Matrix a a v -> Data.Matrix.Matrix v\nto_data_matrix (Matrix m) =\n  Data.Matrix.matrix\n  (Array.rangeSize (fullRange :: (a, a)))\n  (Array.rangeSize (fullRange :: (a, a)))\n  (\\(i, j) ->\n     m ! (toEnum (i - 1), toEnum (j - 1)))\n\nof_data_matrix :: forall a v . Ix' a => Data.Matrix.Matrix v -> Matrix a a v\nof_data_matrix m =\n  let (all_as :: [a]) = range fullRange in\n  Matrix (Array.array fullRange\n          [ ((i, j), v)\n          | (i, r) <- zip all_as (Data.Matrix.toLists m)\n          , (j, v) <- zip all_as r])\n\nmatrix_inverse_precise :: (Ix' a, Num v, Fractional v, Eq v) => Matrix a a v -> Matrix a a v\nmatrix_inverse_precise x = trace \"inverting\" $ of_data_matrix . (\\(Right res) -> res) . Data.Matrix.inverse . to_data_matrix $ x\n\n\nto_hmatrix :: forall a . (Ix' a) => Matrix a a Rat -> Numeric.LinearAlgebra.HMatrix.Matrix Double\nto_hmatrix (Matrix m) =\n  Numeric.LinearAlgebra.Data.fromLists\n   $ [\n     [ fromRational . toRational $ (m ! (i, j))\n       | j <- range fullRange\n     ]\n     | i <- range fullRange\n     ]\n\nof_hmatrix :: forall a . Ix' a => Numeric.LinearAlgebra.HMatrix.Matrix Double -> Matrix a a Rat\nof_hmatrix m =\n  let (all_as :: [a]) = range fullRange in\n  Matrix (Array.array fullRange\n          [ ((i, j), fromRational . toRational $ v)\n          | (i, r) <- zip all_as (Numeric.LinearAlgebra.Data.toLists m)\n          , (j, v) <- zip all_as r])\n\nmatrix_inverse_hmatrix :: (Ix' a) => Matrix a a Rat -> Matrix a a Rat\nmatrix_inverse_hmatrix x = of_hmatrix . Numeric.LinearAlgebra.HMatrix.inv . to_hmatrix $ x\n\nto_eigen_matrix :: forall a . (Ix' a) => Matrix a a Rat -> Data.Eigen.Matrix.Matrix Double CDouble\nto_eigen_matrix (Matrix m) =\n  Data.Eigen.Matrix.fromList\n   [\n     [ fromRational . toRational $ (m ! (toEnum (i - 1), toEnum (j - 1)))\n       | j <- range fullRange\n     ]\n     | i <- range fullRange\n     ]\n\nof_eigen_matrix :: forall a . Ix' a => Data.Eigen.Matrix.Matrix Double CDouble -> Matrix a a Rat\nof_eigen_matrix m =\n  let (all_as :: [a]) = range fullRange in\n  Matrix (Array.array fullRange\n          [ ((i, j), fromRational . toRational $ v)\n          | (i, r) <- zip all_as (Data.Eigen.Matrix.toList m)\n          , (j, v) <- zip all_as r])\n\nmatrix_inverse_eigen :: (Ix' a) => Matrix a a Rat -> Matrix a a Rat\nmatrix_inverse_eigen x = of_eigen_matrix . Data.Eigen.Matrix.inverse . to_eigen_matrix $ x\n\nmatrix_inverse_verified inverse x =\n  let y = inverse x in\n    if (matrix_mult x y == Matrix (f_array (\\(x, y) -> if x == y then 1 else 0))) then y else error $ \"matrix inverse broken: \" ++ \"\\n\" ++ show x ++\"\\n\" ++ show y\n\n-- x = m * x + x_0\n-- solve_equation :: (Ix' a, Num v, Fractional v, Eq v) => Matrix a a v -> Vector a v -> Vector a v\n-- solve_equation a x0 = matrix_inverse (matrix_subtract a matrix_identity) `matrix_mult` matrix_negate x0\n\nsparse_transpose :: (Ord a, Ord b) => Map a (Map b v) -> Map b (Map a v)\nsparse_transpose m =\n  fmap\n  Map.fromList\n  $ Map.fromListWith (++) (concatMap (\\(a, m') -> map (\\(b, v) -> (b, [(a, v)])) (Map.toList m')) (Map.toList m))\n\n\nmatrix_to_sparse :: (Ix' a, Ix' b, Ord b, Linear v, Eq v) => Matrix a b v -> [(a, (Map b v))]\nmatrix_to_sparse (Matrix m) =\n  [ (a, Map.fromList\n    [\n      (b, x)\n      | b <- range fullRange\n      , let x = m ! (a,b)\n      , x /= zero\n    ])\n    | a <- range fullRange\n  ]\n\n\ntype RawProduct = Product\n\nsolvedRecipes\n  :: GameConfig\n     -> Map Product (Map RawProduct Rat, Map RecipeName Rat)\nsolvedRecipes gc =\n  find_kernel_with_trace (/) (*) (recipesToMatrix gc)\n\ncurrentSolvedRecipes = solvedRecipes current_game_config\ncurrentRecipeMatrix = recipesToMatrix current_game_config\n\nvector_lookup :: Ix' a => Vector a v -> a -> v\nvector_lookup (Matrix x) a = x ! (a, ())\n\ncompute'_new :: GameConfig -> Product -> RawMaterialPressure\ncompute'_new gc =\n  let recipes = fmap fst $ solvedRecipes gc in\n   \\product -> case Map.lookup product recipes of\n     Nothing -> Map.empty\n     Just m -> m\n\ncompute_recipe gc =\n  let compute = compute'_new gc in\n    \\recipe ->\n      mconcat'\n        [ scale quantity (compute product)\n        | (product, quantity) <- recipeProducts recipe\n        ]\n\ncompute' gc = compute'_new gc\n\ndata SparseMatrix a b v = SparseMatrix [(a, Map b v)]\n\ndata MatrixError =\n  Not_enough_equations\n  | Contradicting_equations\n  deriving Show\n\ncomputeTotalCost :: Product -> RawMaterialPressure\ncomputeTotalCost = compute' current_game_config\n\nusability' Beacon = Usable\nusability' GearWheel = Unusable\nusability' IronPlate = Unusable\nusability' IronOre = Unusable\nusability' CopperOre = Unusable\nusability' CopperCable = Unusable\nusability' ElectronicCircuit = Unusable\nusability' AdvancedCircuit = Unusable\nusability' Plastic = Unusable\nusability' Sulfur = Unusable\nusability' SulfuricAcid = Unusable\nusability' EngineUnit = Unusable\nusability' CopperPlate = Unusable\nusability' SteelPlate = Unusable\nusability' ElectricMiningDrill = Usable\nusability' Pipe = Usable\nusability' Inserter = Usable\nusability' ElectricFurnace = Usable\nusability' SciencePack1 = Unusable\nusability' SciencePack2 = Unusable\nusability' SciencePack3 = Unusable\nusability' AssemblingMachine1 = Usable\nusability' AssemblingMachine2 = Usable\nusability' AssemblingMachine3 = Usable\nusability' TransportBelt = Usable\nusability' StoneBrick = Unusable\nusability' Lubricant = Unusable\nusability' SciencePackProduction = Unusable\nusability' SciencePackHighTech = Unusable\nusability' CoalLiquefaction = Unusable\nusability' ElectricEngineUnit = Unusable\nusability' Stone = Unusable\nusability' Coal = Unusable\nusability' ProcessingUnit = Unusable\nusability' SpeedModule = Usable\nusability' SpeedModule2 = Usable\nusability' SpeedModule3 = Usable\nusability' EfficiencyModule = Usable\nusability' EfficiencyModule2 = Usable\nusability' EfficiencyModule3 = Usable\nusability' ProductivityModule = Usable\nusability' ProductivityModule2 = Usable\nusability' ProductivityModule3 = Usable\nusability' SolidFuel = Unusable\nusability' ElectricalEnergy = Usable\nusability' PetroleumGas = Unusable\nusability' ResearchCoalLiquefaction = Unusable\nusability' ResearchEndgame = Unusable\nusability' ResearchRocketSilo = Unusable\nusability' ResearchNuclearPower = Unusable\nusability' ResearchLaserTurretDamage5 = Unusable\nusability' LightOil = Unusable\nusability' HeavyOil = Unusable\nusability' CrudeOil = Unusable\nusability' Steam = Unusable\nusability' LaserTurret = Usable\nusability' Battery = Unusable\nusability' PiercingRoundMagazine = Usable\nusability' FirearmRoundMagazine = Usable\nusability' Grenade = Usable\nusability' GunTurret = Usable\nusability' SciencePackMilitary = Unusable\nusability' SteelFurnace = Usable\nusability' StoneFurnace = Usable\nusability' LabBuilding = Usable\nusability' SteamEngineBuilding = Usable\nusability' BoilerBuilding = Usable\nusability' OilRefinery = Usable\nusability' ChemicalPlant = Usable\nusability' SolarFacilityBuilding = Usable\nusability' SolarPanel = Usable\nusability' Accumulator = Usable\nusability' Substation = Usable\nusability' Roboport = Usable\nusability' SteamTurbine = Usable\nusability' NuclearReactor = Usable\nusability' HeatExchanger = Usable\nusability' HeatPipe = Usable\nusability' Concrete = Usable\nusability' RocketPart = Unusable\nusability' RocketSiloBuilding = Unusable\nusability' ControlModule = Unusable\nusability' LightweightStructure = Unusable\nusability' RocketFuel = Unusable\nusability' SciencePackSpace = Unusable\nusability' NuclearFacilityBuilding = Usable\nusability' Satellite = Usable\nusability' Radar = Usable\nusability' ChemicalEnergy = Unusable\nusability' BuriedIron = Unusable\nusability' BuriedCopper = Unusable\nusability' BuriedCoal = Unusable\nusability' BuriedStone = Unusable\nusability' Pollution = Unusable\n\nusability recipeName =\n  case recipeName of\n    ProductRecipe product -> usability' product\n    LiquefactionRecipe -> Unusable\n    AdvancedOilProcessing -> Unusable\n    UseAsFuelRecipe _product -> Unusable\n    BoilerRecipe -> Usable\n\nevaluateTotalCost  :: RawMaterialPressure -> Rat\nevaluateTotalCost f = sum [ (estimate k * v) | (k, v) <- Map.toList f, v /= zero] where\n--  estimate LightOil = 0.1\n  estimate CrudeOil = 0.1\n  estimate HeavyOil = 0.1\n  estimate BuriedCoal = 1\n  estimate BuriedIron = 1.5\n  estimate BuriedCopper = 1\n  estimate BuriedStone = 0.3\n  estimate Pollution = 0.001\n  estimate product = error $ \"don't know how much this is worth: \" ++ show product\n--  estimate PetroleumGas = 0.1\n\nsubtract' a b = add a (minus b)\n\ninstance NFData Venue\n\ndata Assessment = Assessment {\n  totalRawMaterials :: RawMaterialPressure,\n  totalCapitalSeconds :: RawMaterialPressure,\n  totalCapital :: RawMaterialPressure\n} deriving (Generic, Show)\n\ninstance NFData Assessment\n\ninstance Linear Assessment where\n  zero = Assessment {\n    totalRawMaterials = zero,\n    totalCapitalSeconds = zero,\n    totalCapital = zero\n    }\n  a `add` b =\n    Assessment\n      {\n        totalRawMaterials = add (totalRawMaterials a) (totalRawMaterials b),\n        totalCapitalSeconds = add (totalCapitalSeconds a) (totalCapitalSeconds b),\n        totalCapital = add (totalCapital a) (totalCapital b)\n      }\n  minus a = \n    Assessment\n      {\n        totalRawMaterials = minus (totalRawMaterials a),\n        totalCapitalSeconds = minus (totalCapitalSeconds a),\n        totalCapital = minus (totalCapital a)\n      }\n\ninstance VectorSpace Assessment where\n  type Scalar Assessment = Rat\n  scale x a =\n    Assessment\n      {\n        totalRawMaterials = scale x (totalRawMaterials a),\n        totalCapitalSeconds = scale x (totalCapitalSeconds a),\n        totalCapital = scale x (totalCapital a)\n      }\n\ncapitalUsePerExecution :: GameConfig -> Recipe -> RawMaterialPressure\ncapitalUsePerExecution gc recipe =\n    let config = gc_configs gc recipe in\n    let Time time = recipeTime recipe in\n    let execution_time = time / (speedMultiplier config * baseSpeed gc (configVenue config)) in\n    let facility_cost = capitalCost config in\n    scale execution_time facility_cost\n\ntype CapitalUse = RawMaterialPressure\n\ncomputeTotalCost_multi :: Map Product Rat -> RawMaterialPressure\ncomputeTotalCost_multi = mconcat' . map (\\(product, amount) -> scale amount (computeTotalCost product)) . Map.toList\n\nassess_gc' :: GameConfig -> Map Product Rat -> (Map RecipeName CapitalUse, Assessment)\nassess_gc' gc =\n  let solved = solvedRecipes gc in\n  let rbn = enabledRecipesByName (to_qualitative gc) in\n  \\demand -> runIdentity $ do\n    (rawMaterials, executions) <- return $ dot_product_with scale demand solved\n    capitalSeconds <- return $ Map.mapWithKey (\\recipeName executions ->\n        let Just recipe = Map.lookup recipeName rbn in\n        scale executions (capitalUsePerExecution gc recipe)\n      ) executions\n    labResearchCapital <- return $ computeResearchCapital (gc_lab_researches_done gc) lab_speed_researches\n    miningResearchCapital <- return $ computeResearchCapital (gc_mining_researches_done gc) mining_productivity_researches\n    return $ (capitalSeconds, Assessment\n      {\n        totalRawMaterials = rawMaterials,\n        totalCapitalSeconds = mconcat' (Map.elems capitalSeconds),\n        totalCapital = computeTotalCost_multi (mconcat' [labResearchCapital, miningResearchCapital])\n      })\n\nassess_gc configs =\n  let a = assess_gc' configs in\n  \\demand -> snd (a demand)\n\nnewtype Rat = Rat Double deriving (Eq, Ord, Generic, NFData, Linear, Num, Fractional, Real)\n\ninstance VectorSpace Rat where\n  type Scalar Rat = Rat\n  scale (Rat x) (Rat y) = Rat (x * y)\n\ndot_product_with :: (Ord k, Linear a, Linear b, Linear c) => (a -> b -> c) -> Map k a -> Map k b -> c\ndot_product_with f m1 m2 = foldr add zero $ Map.elems $\n  Map.mergeWithKey\n    (\\_k a b -> Just (f a b))\n    (\\_ -> Map.empty)\n    (\\_ -> Map.empty)\n    m1\n    m2\n\ninstance Show Rat where\n  show (Rat x) = Printf.printf \"%.4f\" (fromRational $ toRational x :: Double)\n\nshowModule SpeedModule = \"s1\"\nshowModule SpeedModule2 = \"s2\"\nshowModule SpeedModule3 = \"s3\"\nshowModule EfficiencyModule = \"e1\"\nshowModule EfficiencyModule2 = \"e2\"\nshowModule EfficiencyModule3 = \"e3\"\nshowModule ProductivityModule = \"p1\"\nshowModule ProductivityModule2 = \"p2\"\nshowModule ProductivityModule3 = \"p3\"\nshowModule x = error $ \"not a module: \" ++ show x\n\ndivv a b = if b == 0 then 1e10 else a / b\n\nvenueBuilding :: Venue -> [Product]\nvenueBuilding venue = case venue of\n  Assembly2 -> [AssemblingMachine2]\n  Assembly3 -> [AssemblingMachine3]\n  Miner -> [ElectricMiningDrill]\n  SmelterElectric -> [ElectricFurnace]\n  SmelterBurner -> [SteelFurnace]\n  Chemical -> [ChemicalPlant]\n  Lab -> [LabBuilding]\n  Boiler -> [BoilerBuilding]\n  SteamEngine -> [SteamEngineBuilding]\n  SolarFacility -> [SolarFacilityBuilding]\n  NuclearFacility -> [NuclearFacilityBuilding]\n  NoVenue -> []\n  Refinery -> [OilRefinery]\n  RocketSilo -> [RocketSiloBuilding]\n\ncapitalCost :: Config -> RawMaterialPressure\ncapitalCost config =\n  computeTotalCost_multi (\n    configModuleMaterials config\n    `add`\n    Map.fromListWith (+) (map (\\p -> (p, 1)) (venueBuilding (configVenue config))))\n\npartition_market :: (a -> (Rat, Rat)) -> [a] -> ([a], [a], [a], [a], [a])\npartition_market evaluate l\n  =\n  ( p (\\(gain, cost) -> gain >= 0 && cost <= 0) (\\(_gain, cost) -> cost) -- free capital\n  , p (\\(gain, cost) -> gain >= 0 && cost <= 0) (\\(gain, _cost) -> (-gain)) -- free resources\n  , p (\\(gain, cost) -> gain >= 0 && cost <= 0) (\\(gain, cost) -> (gain * cost)) -- free both\n  , p (\\(gain, cost) -> gain > 0 && cost >= 0) (\\(gain, cost) -> cost / gain) -- buy\n  , p (\\(gain, cost) -> gain < 0 && cost < 0) (\\(gain, cost) -> gain / cost) -- sell\n  ) where\n  p predicate order = sortBy (comparing (order . evaluate)) $ filter (predicate . evaluate) l\n\nallRecipeNames qgc = [recipeName recipe | (recipe, check) <- recipes, check qgc]\n\nvenueKind_of_venue venue = case venue of\n  Assembly2 -> AssemblyVenueKind\n  Assembly3 -> AssemblyVenueKind\n  SmelterBurner -> SmelterVenueKind\n  SmelterElectric -> SmelterVenueKind\n  Chemical -> ChemicalVenueKind\n  Miner -> MinerVenueKind\n  Lab -> LabVenueKind\n  Boiler -> BoilerVenueKind\n  SteamEngine -> SteamEngineVenueKind\n  Refinery -> RefineryVenueKind\n  NoVenue -> NoVenueVenueKind\n  SolarFacility -> GreenPowerVenueKind\n  NuclearFacility -> GreenPowerVenueKind\n  RocketSilo -> RocketSiloVenueKind\n  \n  \nisVenueDefault venue =\n  venue == currentDefaultVenue (venueKind_of_venue venue)\n\npossibleSavings :: RawMaterialPressure -> GameConfig -> [(Change, GameConfig, Assessment)]\npossibleSavings demand gc =\n  let assessment_base = assess_gc gc demand in\n  let\n   assess_diff gc' =\n    let assessment_tip = assess_gc gc' demand in\n    add assessment_tip (minus assessment_base)\n  in\n   (`using` parListChunk 10 rdeepseq) $ map (\\(change, config) -> (change, config, assess_diff config)) (gc_alternatives gc)\n\nshowChange :: Change -> (String, String)\nshowChange (ProductChange product (venue, modules, beacon)) =\n    let\n     showVenue SmelterElectric = \"+\"\n     showVenue SmelterBurner = \"-\"\n     showVenue Assembly2 = \"-\"\n     showVenue Assembly3 = \"+\"\n     showVenue venue | isVenueDefault venue = \"\" | otherwise = \"??\"\n\n     showBeacon Nothing = \"\"\n     showBeacon (Just b) = \"!\" ++ showModule b\n    in\n    (show product, showVenue venue ++ (concatMap showModule modules) ++ showBeacon beacon)\nshowChange (Other a b) = (a, b)  \n\ndata TableEntry = TableEntry {\n  te_name :: (String, String),\n  te_efficiency :: Time,\n  te_saving :: RawMaterialPressure,\n  te_cost :: RawMaterialPressure,\n  te_saving_and_cost :: (Rat, Rat)\n  }\n\nevaluate (Time totalTime)\n  name (Assessment {\n              totalRawMaterials,\n              totalCapitalSeconds,\n              totalCapital}) =\n  let te_saving = minus totalRawMaterials in\n  let te_cost = scale (recip totalTime) totalCapitalSeconds `add` totalCapital in\n  let efficiency = Time (totalTime * (evaluateTotalCost te_cost / evaluateTotalCost te_saving)) in\n  let\n   te_saving_and_cost =\n    (evaluateTotalCost te_saving, evaluateTotalCost te_cost + installationCost )\n  in\n  (TableEntry { te_name = name, te_efficiency = efficiency, te_saving, te_cost, te_saving_and_cost })\n  \npossibleSavings' demand time =\n  [ evaluate time (showChange change) assessment\n  | (change, _gc, assessment) <- possibleSavings demand current_game_config\n  ]\n\ninstallationCost = 40000\n\ndesiredMaterials =\n  [ (ResearchEndgame,  1)\n  , (PiercingRoundMagazine, 20000)\n  , (ProductivityModule3, 200)\n  ]\n\nlookup0 m k = case Map.lookup k m of\n  Nothing -> zero\n  Just x -> x\n\ncurrentRecipeVenue recipe =\n  let config = (gc_configs current_game_config recipe) in\n  configVenue config\n\ncurrentEffectiveExecutionTime recipeName =\n  let recipe = (enabledRecipesByName (to_qualitative current_game_config) !!! recipeName) in\n  unTime (recipeTime recipe)\n     / (speedMultiplier (gc_configs current_game_config recipe) * baseSpeed current_game_config (currentRecipeVenue recipe))\n\nshowHours (Time t) =\n  show (t / 3600) ++ \"h\"\n\nformat_material_pressure = show . evaluateTotalCost\n\nrCols =\n  [ (\"Efficiency\", (showHours . te_efficiency))\n  , (\"Name\", (fst . te_name))\n  , (\"Mod\", (snd . te_name))\n  , (\"Gain\", (format_material_pressure . te_saving))\n  , (\"Cost\", (format_material_pressure . te_cost))\n  ]\n\npad n l = replicate (n - length l) ' ' ++ l\n\nprintTable :: [[String]] -> [String]\nprintTable =\n  map concat . transpose . map (\\col -> let maxl = maximum (map length col) in map (pad (maxl + 1)) col) . transpose\n\nprintTableG :: [a] -> [(String, (a -> String))] -> IO ()\nprintTableG l cols =\n  let title = map fst cols in\n  let showA row = map (($row) . snd) cols in\n  mapM_ putStrLn $ printTable (title : map showA l)\n\nprintRs l = printTableG l rCols\n\ninterestingProducts = []\n\nshow_percent n =\n  Printf.printf \"%.2f%%\" (fromRational (toRational n) * (100 :: Double))\n\nprintDetailedCost cost =\n    let overall = evaluateTotalCost cost in\n    let\n     r =\n      map (\\(k, v) ->\n      let here = evaluateTotalCost (Map.singleton k v) in\n      [show k, show v, show here, show_percent $ here / overall])\n      (Map.toList cost) ++ [[\"Total\", \"_\", show overall, \"100.00%\"]]\n    in\n    mapM_ putStrLn $ printTable r\n\nprint_config_details totalTime demand gc =\n  let solved = solvedRecipes gc in\n  let matrix = recipesToMatrix gc in\n  let\n   (total_cost_per_second, executions_per_second) =\n    foldr add zero (\n      map\n        (\\(product, amount) ->\n            scale (recip $ unTime totalTime) (scale amount $ solved !!! product)\n            ) desiredMaterials)\n  in\n  let\n    negative_executions_per_second =\n      filter\n       ((<0) . snd)\n        (Map.toList executions_per_second)\n  in\n  let\n   effective_execution_time recipeName =\n    let recipe = (enabledRecipesByName (to_qualitative gc)  !!! recipeName) in\n    unTime (recipeTime recipe)\n       / (speedMultiplier (gc_configs gc recipe) * baseSpeed gc (configVenue (gc_configs gc recipe)))\n  in\n  do\n    mapM_ print negative_executions_per_second\n    print \"total factories:\"\n    let factories k = flip fmap (Map.lookup k executions_per_second) (* effective_execution_time k)\n    let (capital_use_per_recipe, Assessment _raw total_capital_use total_capital_oneoff) = assess_gc' gc demand\n    let scale_capital_use = scale (recip $ unTime totalTime)\n    printTableG (sortBy (comparing factories) (allRecipeNames currentQGC)) $\n      [ (\"Name\", show)\n      , (\"Factories\", maybe \"<none>\" show . factories)\n      , (\"Price\",\n          \\k ->\n            case k of\n              ProductRecipe product ->\n                show $ evaluateTotalCost $ computeTotalCost product\n              _ -> \"<complex>\")\n      , (\"Capital\", (\\k -> show $ evaluateTotalCost $ scale_capital_use (lookup0 capital_use_per_recipe k)))\n      ] ++ flip map interestingProducts (\\product -> (show product, (\\k -> show $ lookup0 (matrix !!! k) product * (lookup0 executions_per_second k))))\n    putStrLn \"Total cost:\"\n    printDetailedCost (scale (unTime totalTime) total_cost_per_second)\n    putStrLn \"Total production capital:\"\n    print (evaluateTotalCost $ scale_capital_use total_capital_use)\n    putStrLn \"Total research capital:\"\n    print (evaluateTotalCost $ total_capital_oneoff)\n\nreport =\n  let totalTime = Time (5 * 3600) in\n  let\n   demand =\n    Map.fromList desiredMaterials\n  in\n  let savings = possibleSavings' demand totalTime in\n   do\n    let (free_capital, free_resources, free_both, buys, sells) = partition_market te_saving_and_cost savings\n    print_config_details totalTime demand current_game_config\n    putStrLn $ \"Number of alternative configurations considered:\" ++ show (length (gc_alternatives current_game_config))\n    putStrLn \"Free capital:\"\n    printRs (take 10 free_capital)\n    putStrLn \"Free resources:\"\n    printRs (take 10 free_resources)\n    putStrLn \"Free both:\"\n    printRs (take 10 free_both)\n    putStrLn \"Buys:\"\n    printRs (take 20 buys)\n    putStrLn \"Sells:\"\n    printRs (take 20 sells)\n    \n\nmatrix_of_lists lists =\n  Matrix (Array.array fullRange\n          [ ((i, j), toRational v)\n          | (i, r) <- zip (range fullRange) lists\n          , (j, v) <- zip (range fullRange) r])\n\n_identity_matrix :: (Ix' a) => Matrix a a Rat\n_identity_matrix = Matrix (f_array (\\(a,b) -> if a == b then 1 else 0))\n\ncurrentDefaultVenue :: VenueKind -> Venue\ncurrentDefaultVenue AssemblyVenueKind = Assembly2\ncurrentDefaultVenue SmelterVenueKind = SmelterElectric\ncurrentDefaultVenue GreenPowerVenueKind = NuclearFacility\ncurrentDefaultVenue venueKind = case venuesByKind venueKind of\n  [ venue ] -> venue\n  _ -> error \"ambiguous venue\"\n\ntrivial recipe =\n  (currentDefaultVenue (recipeVenueKind recipe), [], Nothing)\n\n\n(!!!) :: (Ord k, HasCallStack) => Map k v -> k -> v\n(!!!) m x = m Map.! x\n\nparseSpec :: String -> (Maybe Char, [Product], Maybe Product)\nparseSpec ('+' : rest) = (\\(m,b) -> (Just '+', m, b)) (parseSpec' rest)\nparseSpec ('-' : rest) = (\\(m,b) -> (Just '-', m, b)) (parseSpec' rest)\nparseSpec rest = (\\(m,b) -> (Nothing, m, b)) (parseSpec' rest)\nparseSpec' ('!' : rest) = ([], parseBeaconSpec rest)\nparseSpec' (c1 : c2 : rest) = (parseModule c1 c2 : ms, b) where\n  (ms, b) = parseSpec' rest\nparseSpec' [] = ([], Nothing)\nparseSpec' s = error $ \"syntax error when parsing modules configuration \" ++ show s\nparseBeaconSpec [c1, c2] = Just (parseModule c1 c2)\nparseBeaconSpec [] = Nothing\nparseBeaconSpec s = error $ \"syntax error when parsing beacon configuration \" ++ show s\nparseModule 'p' '3' = ProductivityModule3\nparseModule 'p' '2' = ProductivityModule2\nparseModule 'p' '1' = ProductivityModule\nparseModule 's' '3' = SpeedModule3\nparseModule 's' '2' = SpeedModule2\nparseModule 's' '1' = SpeedModule\nparseModule 'e' '3' = EfficiencyModule3\nparseModule 'e' '2' = EfficiencyModule2\nparseModule 'e' '1' = EfficiencyModule\nparseModule c1 c2 = error $ \"unrecognized module: \" ++ [c1, c2]\n\nvenueByChar :: VenueKind -> Maybe Char -> Venue\nvenueByChar SmelterVenueKind (Just '+') = SmelterElectric\nvenueByChar SmelterVenueKind (Just '-') = SmelterBurner\nvenueByChar SmelterVenueKind Nothing = error \"ambiguous smelter\"\nvenueByChar AssemblyVenueKind (Just '-') = Assembly2\nvenueByChar AssemblyVenueKind (Just '+') = Assembly3\nvenueByChar AssemblyVenueKind Nothing = error \"ambiguous assembly\"\nvenueByChar GreenPowerVenueKind (Just '-') = SolarFacility\nvenueByChar GreenPowerVenueKind (Just '+') = NuclearFacility\nvenueByChar GreenPowerVenueKind Nothing = error \"ambiguous green power\"\nvenueByChar kind Nothing = currentDefaultVenue kind\nvenueByChar kind (Just c) = error $ \"venueByChar weird invocation\" ++ show (kind, c)\n\ncurrentSpecs =\n let\n  products =\n   init[\n    --(ProcessingUnit,\"+s2p3p3p3\"),\n    --(GearWheel,\"+p2p2p2s1\"),\n    --(Plastic,\"p2p2e1\"),\n    (SulfuricAcid,\"p2p2p2\"),\n    --(AdvancedCircuit,\"+e1e1p1p1\"),\n    --(ResearchNuclearPower,\"p2p2\"),\n    --(ResearchRocketSilo,\"p2p2\"),\n    --(EngineUnit,\"-e1e1\"),\n    (SciencePack1,\"-e1e1\"),\n    (SciencePack2,\"-e1e1\"),\n    (LightOil,\"e1e1e1\"),\n    --(CopperCable,\"+e1e1e1p1\"),\n    --(PetroleumGas,\"e1e1e1\"),\n    (IronOre,\"e1e1e1\"),\n    (CopperOre,\"e1e1e1\"),\n    (Coal,\"e1e1e1\"),\n    (PiercingRoundMagazine,\"-e1e1\"),\n    --(SciencePackHighTech,\"+p3p3p3p3\"),\n    --(ElectronicCircuit,\"+p3p3p3s2\"),\n    --(SciencePack3,\"+p3p3p3s2\")\n\n    (ProcessingUnit,\"+p3p3p3p3!s3\"),\n    (SciencePack3,\"+p3p3p3p3!s3\"),\n    (SciencePackHighTech,\"+p3p3p3p3!s3\"),\n    --(CopperCable,\"+p2p2p2p2!s2\"),\n    (ElectronicCircuit,\"+p3p3p3p3!s2\"),\n    (ResearchEndgame,\"p3p3!s2\"),\n    (GearWheel,\"+p3p3p3p3!s3\"),\n\n    (AdvancedCircuit,\"+p3p3p3p3!s3\"),\n    (SciencePackMilitary,\"+p3p3p3p3!s2\"),\n    (Plastic,\"p3p3p3!s3\"),\n\n    (CopperPlate,\"+p2p2!s2\"),\n    (IronPlate,\"+p2p2!s2\"),\n    (SteelPlate,\"+p2p2!s2\"),\n    (CopperCable, \"+p3p3p3p3!s3\"),\n    (PetroleumGas, \"p2p2p2!s2\"),\n\n    (RocketPart, \"p3p3p3p3\"),\n    (ControlModule, \"+p3p3p3p3!s3\"),\n    (RocketFuel, \"p3p3p3p3!s3\"),\n    (LightweightStructure, \"+p3p3p3p3!s3\"),\n\n    -- make sure:\n    (SciencePackProduction,\"+p3p3p3p3!s2\"),\n\n    (EngineUnit,\"+p3p3p3p3!s2\"),\n   undefined]\n in\n map (\\(p,s) -> (ProductRecipe p, s)) products ++ [\n   (AdvancedOilProcessing, \"p3p3p3!s3\")\n ]\n\ncurrentModules :: RecipeName -> PreConfig\ncurrentModules = runIdentity $ do\n  specs <- return $ Map.fromListWith (error \"spec for the same product given twice\") (map (second parseSpec) currentSpecs)\n  let byName = Map.fromList (map (\\(r, _) -> (recipeName r, r)) recipes)\n  return $ \\recipeName ->\n    let recipe = byName !!! recipeName in\n    case Map.lookup recipeName specs of\n      Nothing ->\n        trivial recipe\n      Just (venue_char, modules, beacon) ->\n        let venue = venueByChar (recipeVenueKind recipe) venue_char in\n        (venue, modules, beacon)\n\ncurrent_game_config :: GameConfig\ncurrent_game_config =\n GameConfig {\n  gc_lab_researches_done = 4,\n  gc_mining_researches_done = 6,\n  gc_liquefaction = Liquefaction_disabled,\n  gc_recipe_configs = currentModules\n  }\n\ncurrentQGC = to_qualitative current_game_config\n\n\n--main = print $ computeTotalCost SciencePack3\nmain = report\n--main =\n--  print $ solvedRecipes currentConfig !!! SulfuricAcid\n-- main = mapM_ print $ possibleSavings'''\n{-\nmain = do\n flip mapM_ (range fullRange :: [Product]) $ \\product -> do\n  let configs =\n        (\\p -> if p == GearWheel\n          then Config {configSpeedBonus = 0, configProductivityBonus = 0, configEnergyBonus = 0}\n          else currentConfig p)\n  let x = compute' configs GearWheel\n  let y = compute' configs GearWheel\n  print $ x\n  print $ y\n  print $ x == y\n-}\n", "meta": {"hexsha": "9fc969954a0d74d2e86e8f63efa63eea13d0515d", "size": 54507, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "factorio-module-selector.hs", "max_stars_repo_name": "Rotsor/factorio-module-selector", "max_stars_repo_head_hexsha": "22a595ba36bbf9ca337bba0dfbe3c387308f43b3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "factorio-module-selector.hs", "max_issues_repo_name": "Rotsor/factorio-module-selector", "max_issues_repo_head_hexsha": "22a595ba36bbf9ca337bba0dfbe3c387308f43b3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "factorio-module-selector.hs", "max_forks_repo_name": "Rotsor/factorio-module-selector", "max_forks_repo_head_hexsha": "22a595ba36bbf9ca337bba0dfbe3c387308f43b3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0973509934, "max_line_length": 173, "alphanum_fraction": 0.6971765094, "num_tokens": 16140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764746, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.23199214067346915}}
{"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<m) then (n:(fromTo (n+1) m)) else (n:[])\n\nbigSum :: (Int -> ((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<m) then ((s 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<hi)\n\nrunP :: (a -> ((((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<m) then ((s n lastx)>>=(\\(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<ratio;\n (sigmaNext::Double) = if accept then (sigma*((min 1.400 (1+(5.000/i)))**3)) else (sigma*(max 0.714 (1-(5.000/i))));\n } in return (if accept then ((((xstar,((sigmaNext,(((i+1),(iaccept+1))))))),pstar)) else ((((xi,((sigmaNext,(((i+1),iaccept)))))),pi)))))\n\nrwmIni :: (a -> ((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<ratio;\n (sigmaNext::Double) = sigma;\n } in return (if accept then ((((xstar,sigmaNext)),((pstar,gradientStar)))) else ((((xi,sigmaNext)),((pi,gradienti)))))))\n\nmalaIni :: (BayNum b) => (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 ((x<hi)&&(x>lo)) 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<p))\n\nbernoulli01 :: (Double -> (Prob Int))\nbernoulli01 = \\((p::Double)) -> unit>>=(\\((u::Double)) -> if (u<p) then (return 1) else (return 0))\n\nbernoulliLogPdf :: (Double -> ((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<p))))>>=(\\((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<y) xs);\n } in (unround under)/(unround total)\n\ngammaLogPdf :: (Double -> ((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 FlexibleInstances #-}\n\nimport Debug.Trace\n-- import Control.Monad.State.Lazy\n\nimport System.Environment (getArgs)\nimport System.IO (readFile)\nimport Data.Map.Strict (Map, (!))\nimport qualified Data.Map.Strict as M\nimport Data.Set (Set)\nimport qualified Data.Set as S\n--import qualified Data.Array as A\nimport Data.List (find, intercalate, intersperse, permutations, inits, tails, isPrefixOf, isInfixOf, delete)\nimport Data.List.Split (splitOn)\n-- import Data.Complex (Complex((:+)), realPart, imagPart) -- define my own complex\n\nimport Text.Regex.PCRE\n\nimport UI.NCurses\nimport Data.Char (chr, ord)\n-- import Data.Complex (Complex((:+)))\nimport Data.Maybe (fromJust, isNothing, isJust)\ntype Instructions = Map Integer Integer\n\ndata ComputerState = Ready | Running | Blocked | Done\n  deriving (Show, Eq)\n\ndata Computer = Computer {\n  state :: ComputerState,\n  memory :: Map Integer Integer,\n  iptr :: Integer, -- instruction pointer\n  base :: Integer, -- base offset\n  input :: [Integer],\n  output :: [Integer]}\n\ntoAscii ii = map (chr . fromIntegral) ii\nfromAscii s = map (fromIntegral . ord) s\n\ninstance Show Computer where\n  show c = \"Computer < \\\"\"++toAscii (input c)++\"\\\" > \\\"\"++toAscii (output c)++\"\\\"\\n\"\n\ncomputer0 = Computer { state = Ready, memory = M.empty, iptr = 0, base = 0, input = [], output = [] }\n\nrun :: Computer -> Computer -- (Integer, Integer) -> Instructions -> [Integer] -> [Integer]\nrun c\n  | state c == Ready = -- traceShowId $\n    run $ c {state = Running}\n  | state c == Done = -- traceShowId $\n    c\n  | state c == Blocked = -- traceShowId $\n    if input c == [] then c\n    else run $ c {state = Running}\n  | otherwise = -- running\n    --traceShow (iptr c, base c, memory c) $ \n    case instr `mod` 100 of\n      1 -> -- add\n        run $ c {iptr = i+4, memory = M.insert (addr 3) (arg 1 + arg 2) instructions}\n      2 -> -- multiply\n        run $ c {iptr = i+4, memory = M.insert (addr 3) (arg 1 * arg 2) instructions}\n      3 -> -- read input\n        if (null $ input c)\n        then c {state = Blocked}\n        else run $ c {iptr = i+2, memory = M.insert (addr 1) (head $ input c) instructions, input = tail $ input c}\n      4 -> -- output\n        --traceShow (arg 1) $ \n        run $ c {iptr = i+2, output = output c ++ [arg 1]}\n      5 -> -- jump-if-true\n        run $ c {iptr = if arg 1 == 0 then i+3 else arg 2}\n      6 -> -- jump-if-false\n        run $ c {iptr = if arg 1 == 0 then arg 2 else i+3}\n      7 -> -- less than\n        run $ c {iptr = i+4, memory = M.insert (addr 3) (if arg 1 < arg 2 then 1 else 0) instructions}\n      8 -> -- equals\n        run $ c {iptr = i+4, memory = M.insert (addr 3) (if arg 1 == arg 2 then 1 else 0) instructions}\n      9 -> -- set relative base\n        run $ c {iptr = i+2, base = base c + arg 1}\n      99 -> -- halt\n        run $ c {state = Done}\n      _ -> error \"unknown opcode\"\n  where instructions = memory c\n        i = iptr c\n        instr = instructions!i\n        ii x = M.findWithDefault 0 x instructions\n        arg :: Integer -> Integer\n        arg n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ ii $ i+n\n          1 -> ii $ i+n\n          2 -> ii ((ii $ i+n) + base c)\n          _ -> error \"bad argument mode\"\n        addr n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ i+n\n          1 -> error \"address in mode 1\"\n          2 -> --trace \"address in mode 2\" $\n            ii (i+n) + base c\n          _ -> error $ \"address in unknown mode\"\n\ntype Direction = String\n\n-- data Direction = N | S | E | W\n-- instance Show Direction where\n--   show N = \"north\"\n--   show S = \"south\"\n--   show E = \"east\"\n--   show W = \"west\"\n-- instance Read Direction where\n--   readsPrec _ ('n':'o':'r':'t':'h':theRest) = [(N, theRest)]\n--   readsPrec _ ('s':'o':'u':'t':'h':theRest) = [(S, theRest)]\n--   readsPrec _ ('e':'a':'s':'t':theRest) = [(E, theRest)]\n--   readsPrec _ ('w':'e':'s':'t':theRest) = [(W, theRest)]\n  \ntype Graph = Map String (Map Direction (Maybe String))\n\nback \"north\" = \"south\"\nback \"south\" = \"north\"\nback \"east\" = \"west\"\nback \"west\" = \"east\"\nback d = error $ \"unknown door type \" ++ d\n\nstripRoomName = reverse . drop 3 . reverse . drop 3 -- strip first 3 and last 3 characters \ninteractc :: Graph -> [(Direction, String)] -> Computer -> IO()\ninteractc g explorePath c = do\n  let out = toAscii $ output c\n      linesOut = lines out\n      room = map stripRoomName $ filter (isPrefixOf \"==\") $ linesOut\n      droidWeight\n        | \"Droids on this ship are heavier\" `isInfixOf` out = \"too light\"\n        | \"Droids on this ship are lighter\" `isInfixOf` out = \"too heavy\"\n        | otherwise = \"not applicable\"\n      -- if booted out, then last room listed is current room\n      -- room = map (head . tail) $ (out =~ \"== (.+?) ==\" :: [[String]]) -- init $ tail $ head linesOut\n      prompt = not $ null $ filter (== \"Command?\") linesOut\n      stuff = map (drop 2) $ filter (isPrefixOf \"- \") linesOut\n      doors = filter (`elem` [\"north\",\"south\",\"east\",\"west\"]) stuff\n      items = filter (not . (`elem` [\"infinite loop\", \"molten lava\", \"escape pod\", \"photons\", \"giant electromagnet\"])) $ filter (not . (`elem` doors)) stuff\n      newFrontier = not $ (null room || head room `M.member` g)\n      (previousDoor, previousRoom) = head explorePath -- laziness ensures that explorePath is not null\n      g' | newFrontier = M.insert (head room) (M.fromList [(door, Nothing)| door <- doors]) g\n         | null room = g\n         | null explorePath = trace \"setting g': no explorePath\" g\n         | otherwise = M.adjust (\\m -> M.insert (back $ previousDoor) (Just previousRoom) m) (head room) $\n                       M.adjust (\\m -> M.insert previousDoor (Just $ head room) m) previousRoom g\n      (move, explorePath')\n        | null room = (\"to checkpoint\", explorePath)\n        | head room == \"Security Checkpoint\" = (back previousDoor, tail explorePath)\n        | newFrontier = (head doors, (head doors, head room): explorePath)\n        | null unexplored && null explorePath = (\"inv\", []) -- error \"explored all\"\n        | null unexplored || head unexplored == previousRoom = (back previousDoor, tail explorePath)\n        | otherwise = (head unexplored, (head unexplored, head room) : explorePath)\n        where unexplored :: [Direction]\n              unexplored = M.keys $ M.filter isNothing $ g!(head room)\n  putStrLn out\n  putStrLn $ \"room: \" ++ show room ++ \"\\nprompt: \" ++ show prompt ++ \"\\ndoors: \" ++ show doors ++ \"\\nitems: \" ++ show items ++ \"\\nmove: \" ++ show move ++ \"\\nexplorePath': \" ++ show explorePath\n  if not prompt then return ()\n  else if move == \"to checkpoint\" then do\n    putStrLn \"Move to checkpoint\"\n    let pathToCheckpoint = traceShowId $ toCheckpoint g'\n        c' = run $ c{output=[], input=concatMap ((\\s -> s ++ [10]) . fromAscii) pathToCheckpoint}\n    putStrLn $ toAscii $ output c'\n    let c'' = run $ c'{output=[], input=fromAscii \"inv\\n\"}\n        items = map (drop 2) $ filter (\"- \" `isPrefixOf`) $ lines $ toAscii $ output c''\n        c''' = run $ c''{output=[], input=concatMap fromAscii $ [\"drop \"++i++\"\\n\" | i <- items]++[\"inv\\n\"]}\n        testComputer = c'''{output=[]}\n        testWeight items' | \"heavier\" `isInfixOf` out = True -- the items are ok, can add more\n                          | \"lighter\" `isInfixOf` out = False -- too many items already\n                          | otherwise = error $ \"found it!\\n\" ++ out ++ show items'\n          where out = toAscii $ output $ run $\n                      testComputer{input=concatMap fromAscii $ [\"take \"++i++\"\\n\"|i<-traceShowId $ S.toList items']++[\"east\\n\"]}\n    putStrLn $ toAscii $ output c'''\n    putStrLn \"testing ...\"\n    print $ searchPowerSet 0 testWeight S.empty [(S.empty, items)]\n\n\n    -- let c'' = passCheckpoint (head $ M.keys $ M.filter isNothing $ g!\"Security Checkpoint\") $\n    --           c'{output = []}\n\n\n    -- print $ g'\n    -- s <- getLine\n    -- interactc g' explorePath' $ run $ c{output=[], input=fromAscii s ++ [10]}\n      \n  else do\n      if not (null items) then do\n        putStrLn \"Picking up items\"\n        let move' = \"take \" ++ head items\n            c' = run $ c{output=[], input=fromAscii move' ++ [10]}\n        putStrLn move'\n        putStrLn $ toAscii $ output c'\n        putStrLn move\n        putStrLn $  \"(explorePath = \"++show explorePath++\")\"\n        interactc g' explorePath' $ run $ c'{output=[], input=fromAscii move ++ [10]}\n      else do\n        putStrLn move\n        putStrLn $  \"(explorePath = \"++show explorePath++\")\"\n        interactc g' explorePath' $ run $ c{output=[], input=fromAscii move ++ [10]}\n\ntoCheckpoint g = search g \"Security Checkpoint\" $ [[\"Hull Breach\"]]\n  -- search the graph g depth-first, with the longest, current path at\n  -- the head of the list of paths.\n  where search g goal paths\n          | null paths = error \"null paths\"\n          | room == goal -- done, return path after removing rooms and reversing the order.\n          = filter (`elem` [\"north\", \"south\", \"east\", \"west\"]) $ trace \"path\" $ traceShowId $ reverse path\n          | null frontier -- if there is no frontier, ie, nothing\n                          -- further to explore in the current path,\n                          -- discard it and search the rest of the\n                          -- paths.\n          = search g goal $ tail paths\n          | otherwise -- If there is a frontier, create new paths to\n                      -- explore, add them to the front of the list,\n                      -- and keep searching.\n          = search g goal $ [room:door:path | (door, room) <- frontier] ++ tail paths\n          where path = head paths\n                room = head path\n                frontier :: [(Direction, String)]\n                -- the frontier is the doors leading to rooms from the\n                -- current room, that also don't go back to rooms\n                -- we've already explored in this path.\n                frontier = M.toList $ M.filter (not . (`elem` path)) $ M.map fromJust $ M.filter isJust $ g!room\n\n\nsearchPowerSet:: Int -> (Set String -> Bool) -> Set (Set String) -> [(Set String, [String])] -> Set String\nsearchPowerSet i test tooBig ((yes,unknown): candidates)\n  \n  | (S.null $ S.filter (`S.isSubsetOf` yes) tooBig) && test yes\n  = trace (show i++ \": keep going: \"++show (S.toList yes)) $\n    searchPowerSet (i+1) test tooBig $\n    [(yes', unknown')\n    | (u:unknown')<- init $ tails unknown\n    , let yes' = S.insert u yes\n    , S.null $ S.filter (`S.isSubsetOf` yes') tooBig\n    ] ++candidates\n  | otherwise\n  = trace (show i++\": skip this: \"++show (S.toList yes)++\"\\nsets rejected: \"++show (S.size tooBig + 1)) $\n    searchPowerSet (i+1) test (S.insert yes tooBig) candidates\n\n-- -- We're looking for a set of the right weight. Put the items in some\n-- -- standard order and represent the set as a boolean list bs, whose\n-- -- head is the last one included, i.e,\n-- --      set = [i | (i, b) <- zip items $ reverse bs, b].\n-- nextSet:: Int -> [Bool] -> ([Bool],[Bool]) -- (next smaller, next greater)\n-- nextSet n bs\n--   | n == length bs\n--   = let bs' = True: False: drop 1 $ dropWhile (== False) $ dropWhile (== True) bs\n--     in (bs', bs')\n--   | otherwise\n--   = ( True: False: drop 1 $ dropWhile (== False) $ drop 1 bs,\n--       if length bs < n then True: bs else\n--         True: False: drop 1 $ dropWhile (== False) $ dropWhile (== True) bs)\n-- (error \"True: bs, \n-- hiloPowersetTester n = tester [Truen\n--   where tester \n\n\n-- (\"Arcade\",fromList [(\"north\",Just \"Navigation\"),(\"west\",Just \"Kitchen\")]),\n-- (\"Corridor\",fromList [(\"north\",Just \"Holodeck\"),(\"west\",Just \"Gift Wrapping Center\")]),\n-- (\"Crew Quarters\",fromList [(\"north\",Just \"Engineering\")]),\n-- (\"Engineering\",fromList [(\"east\",Just \"Hull Breach\"),(\"south\",Just \"Crew Quarters\"),(\"west\",Just \"Hallway\")]),\n-- (\"Gift Wrapping Center\",fromList [(\"east\",Just \"Corridor\"),(\"north\",Just \"Observatory\"),(\"south\",Just \"Hull Breach\")]),\n-- (\"Hallway\",fromList [(\"east\",Just \"Engineering\"),(\"north\",Just \"Science Lab\"),(\"south\",Just \"Sick Bay\")]),\n-- (\"Holodeck\",fromList [(\"south\",Just \"Corridor\")]),\n-- (\"Hot Chocolate Fountain\",fromList [(\"east\",Just \"Storage\")]),\n-- (\"Hull Breach\",fromList [(\"east\",Just \"Kitchen\"),(\"north\",Just \"Gift Wrapping Center\"),(\"west\",Just \"Engineering\")]),\n-- (\"Kitchen\",fromList [(\"east\",Just \"Arcade\"),(\"west\",Just \"Hull Breach\")]),\n-- (\"Navigation\",fromList [(\"south\",Just \"Arcade\"),(\"west\",Just \"Storage\")]),\n-- (\"Observatory\",fromList [(\"north\",Just \"Passages\"),(\"south\",Just \"Gift Wrapping Center\")]),\n-- (\"Passages\",fromList [(\"south\",Just \"Observatory\")]),\n-- (\"Science Lab\",fromList [(\"east\",Just \"Security Checkpoint\"),(\"south\",Just \"Hallway\")]),\n-- (\"Security Checkpoint\",fromList [(\"east\",Nothing),(\"west\",Just \"Science Lab\")]),\n-- (\"Sick Bay\",fromList [(\"east\",Just \"Warp Drive Maintenance\"),(\"north\",Just \"Hallway\")]),\n-- (\"Stables\",fromList [(\"south\",Just \"Warp Drive Maintenance\")]),\n-- (\"Storage\",fromList [(\"east\",Just \"Navigation\"),(\"west\",Just \"Hot Chocolate Fountain\")]),\n-- (\"Warp Drive Maintenance\",fromList [(\"north\",Just \"Stables\"),(\"west\",Just \"Sick Bay\")])]\n\n\nmain = do\n  print $ toAscii $ fromAscii \"This is a test\"\n  -- [instructionFile] <- getArgs\n  instructionStrings <- readFile \"25.input.txt\" -- instructionFile\n  let instructions = M.fromList . zip [0 ..] $ map read $ splitOn \",\" instructionStrings\n\n  putStrLn \"Part 1\"\n  interactc M.empty [] $ run $ computer0{memory = instructions}\n  -- let c = run $ computer0{memory = instructions}\n  -- let view = output c\n  -- let viewStr = map (chr . fromIntegral) view\n  -- putStrLn $ viewStr\n\n", "meta": {"hexsha": "ed6c361e1434e48a1c71c1cce30b2e9acef5d3ad", "size": 13573, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "25.hs", "max_stars_repo_name": "dpatru/aoc2019", "max_stars_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-30T21:19:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T21:19:29.000Z", "max_issues_repo_path": "25.hs", "max_issues_repo_name": "dpatru/aoc2019", "max_issues_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "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": "25.hs", "max_forks_repo_name": "dpatru/aoc2019", "max_forks_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "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": 47.1284722222, "max_line_length": 192, "alphanum_fraction": 0.5885950048, "num_tokens": 3853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.2307762042413224}}
{"text": "-- To run:\n--\n--   stack build :hardware-examples\n--\n--   stack build :hardware-trace >& ~/Haskell/concat/hardware/out/o1\n--\n-- You might also want to use stack's --file-watch flag for automatic recompilation.\n\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE ConstraintKinds     #-}\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE DeriveFoldable      #-}\n{-# LANGUAGE DeriveFunctor       #-}\n{-# LANGUAGE DeriveGeneric       #-}\n{-# LANGUAGE DeriveTraversable   #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE FlexibleInstances   #-}\n{-# LANGUAGE KindSignatures      #-}\n{-# LANGUAGE PatternSynonyms     #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications    #-}\n{-# LANGUAGE TypeFamilies        #-}\n{-# LANGUAGE TypeOperators       #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\n{-# OPTIONS_GHC -Wall #-}\n\n{-# OPTIONS_GHC -Wno-missing-signatures #-}\n{-# OPTIONS_GHC -Wno-unused-imports #-}\n\n{-# OPTIONS_GHC -dsuppress-idinfo #-}\n{-# OPTIONS_GHC -dsuppress-uniques #-}\n{-# OPTIONS_GHC -dsuppress-module-prefixes #-}\n\n-- {-# OPTIONS_GHC -ddump-simpl #-}\n\n-- {-# OPTIONS_GHC -ddump-rule-rewrites #-}\n-- {-# OPTIONS_GHC -fsimpl-tick-factor=250 #-}  -- default 100\n\n-- {-# OPTIONS -fplugin-opt=ConCat.Plugin:trace #-}\n\n{-# OPTIONS_GHC -fno-do-lambda-eta-expansion #-}\n\nmodule Main where\n\nimport Control.Applicative (liftA2,liftA3)\nimport Data.Complex\nimport Data.List           (mapAccumL)\nimport GHC.Float (int2Double)   -- TEMP\nimport GHC.Generics hiding (S)\n-- import ShapedTypes.FFT\n\nimport ConCat.Pair\nimport ConCat.FFT\nimport ConCat.Misc ((:*),R,sqr,magSqr,Unop,Binop,inNew,inNew2,(:+))\nimport ConCat.Circuit (GenBuses(..),(:>),Ty(..),Buses(..))\nimport qualified ConCat.RunCircuit as RC\nimport ConCat.Syntactic (Syn,render)\nimport ConCat.AltCat (Ok2,ccc,(:**:)(..),toCcc')\nimport qualified ConCat.AltCat as A\n\nimport ConCat.Rebox () -- necessary for reboxing rules to fire\n\nimport ConCat.Hardware.Verilog\nimport ConCat.Rep\nimport ConCat.Nat\nimport ConCat.Shaped\n\nmain :: IO ()\nmain = sequence_\n  [ putChar '\\n' -- return ()\n    -- Unary\n  , runVerilog' \"neg\" $ \\ (x :: Int) -> - x  -- Yields bit inversion, not 2's complement!\n  , runVerilog' \"odd\" $ \\ (x :: Int) -> x `mod` 2\n\n    -- Binary\n  , runVerilog' \"adder\" $ \\ (x :: Int, y :: Int) -> x + y\n\n    -- Conditional\n  , runVerilog' \"cond\" $ \\ (p :: Bool, x :: Int, y :: Int) -> if p then x else y\n\n    -- FFT, via functor composition\n  -- , runVerilog' \"fft_fc_pair\" $ \\ ( pr :: (UPair (Complex Double)) ) -> fft pr\n  , runVerilog' \"fft_fc_pair\" $ \\ ( (x0::(Complex Double)) :# x1 ) -> fft (x0 :# x1)\n  -- , runVerilog' \"fft_fc_quad\" $ \\ ( fc :: ( (Pair :.: Pair) (Complex Float) )) -> fft fc\n  -- TODO: Understand why only the second alternative, below, works.\n  --       (The other two cause a compilation time-out error.)\n  -- , runVerilog' \"fft_fc_octet\" $ \\ ( fc :: ( ((Pair :.: Pair) :.: (Pair :.: Pair)) (Complex Float) )) -> fft fc\n  , runVerilog' \"fft_fc_rb3\" $ fft @(RBin N3) @Float\n  -- , runVerilog' \"fft_fc_rb3\" $ fft @((Pair :.: Pair) :.: (Pair :.: Pair)) @Float\n  -- , runCirc \"fft-rb3\" $ ccc $ fft @(RBin N3) @Double\n  ]\n\n{--------------------------------------------------------------------\n    Testing utilities\n--------------------------------------------------------------------}\n\nrunVerilog' :: (GenBuses a, GenBuses b) => String -> (a -> b) -> IO ()\nrunVerilog' _ _ = error \"runVerilog' called directly\"\n{-# NOINLINE runVerilog' #-}\n{-# RULES \"runVerilog'\"\n  forall n f. runVerilog' n f = runVerilog n $ toCcc' f #-}\n\n", "meta": {"hexsha": "dc8a3ed97bfb0ea5d4414af6270e63d1f4a40e16", "size": 3521, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "hardware/test/Examples.hs", "max_stars_repo_name": "kenranunderscore/concat", "max_stars_repo_head_hexsha": "632c3f37a969725053dc55ebec26f5b7aacf8c07", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-11T10:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:54:10.000Z", "max_issues_repo_path": "hardware/test/Examples.hs", "max_issues_repo_name": "con-kitty/concat", "max_issues_repo_head_hexsha": "6321dab53677de419f1b57302fe343c5a1341768", "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": "hardware/test/Examples.hs", "max_forks_repo_name": "con-kitty/concat", "max_forks_repo_head_hexsha": "6321dab53677de419f1b57302fe343c5a1341768", "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": 33.8557692308, "max_line_length": 114, "alphanum_fraction": 0.6035217268, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.23023564916092623}}
{"text": "{-# LANGUAGE GADTs, RecordWildCards, ScopedTypeVariables #-}\nmodule Data.Eigen.SparseMatrix.Mutable (\n    -- * Mutable SparseMatrix\n    IOSparseMatrix(..),\n    IOSparseMatrixXf,\n    IOSparseMatrixXd,\n    IOSparseMatrixXcf,\n    IOSparseMatrixXcd,\n    new,\n    reserve,\n    -- * Matrix properties\n    rows,\n    cols,\n    innerSize,\n    outerSize,\n    nonZeros,\n    -- * Matrix compression\n    compressed,\n    compress,\n    uncompress,\n    -- * Accessing matrix data\n    read,\n    write,\n    setZero,\n    setIdentity,\n    -- * Changing matrix shape\n    resize,\n    conservativeResize\n) where\n\nimport Prelude hiding (read)\nimport Data.Complex\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.Storable\nimport qualified Foreign.Concurrent as FC\nimport qualified Data.Eigen.Internal as I\n\n-- | Mutable version of sparse matrix. See `Data.Eigen.SparseMatrix.SparseMatrix` for details about matrix layout.\ndata IOSparseMatrix a b where\n    IOSparseMatrix :: I.Elem a b => !(ForeignPtr (I.CSparseMatrix a b)) -> IOSparseMatrix a b\n\n-- | Alias for single precision mutable matrix\ntype IOSparseMatrixXf = IOSparseMatrix Float CFloat\n-- | Alias for double precision mutable matrix\ntype IOSparseMatrixXd = IOSparseMatrix Double CDouble\n-- | Alias for single previsiom mutable matrix of complex numbers\ntype IOSparseMatrixXcf = IOSparseMatrix (Complex Float) (I.CComplex CFloat)\n-- | Alias for double prevision mutable matrix of complex numbers\ntype IOSparseMatrixXcd = IOSparseMatrix (Complex Double) (I.CComplex CDouble)\n\n\n-- | Creates new matrix with the given size @rows x cols@\nnew :: I.Elem a b => Int -> Int -> IO (IOSparseMatrix a b)\nnew rows cols = alloca $ \\pm -> do\n    I.call $ I.sparse_new (I.cast rows) (I.cast cols) pm\n    m <- peek pm\n    fm <- FC.newForeignPtr m $ I.call $ I.sparse_free m\n    return $! IOSparseMatrix fm\n\n-- | Returns the number of rows of the matrix\nrows :: I.Elem a b => IOSparseMatrix a b -> IO Int\nrows = _prop I.sparse_rows (return . I.cast)\n\n-- | Returns the number of columns of the matrix\ncols :: I.Elem a b => IOSparseMatrix a b  -> IO Int\ncols = _prop I.sparse_cols (return . I.cast)\n\n-- | Returns the number of rows (resp. columns) of the matrix if the storage order column major (resp. row major)\ninnerSize :: I.Elem a b => IOSparseMatrix a b  -> IO Int\ninnerSize = _prop I.sparse_innerSize (return . I.cast)\n\n-- | Returns the number of columns (resp. rows) of the matrix if the storage order column major (resp. row major)\nouterSize :: I.Elem a b => IOSparseMatrix a b  -> IO Int\nouterSize = _prop I.sparse_outerSize (return . I.cast)\n\n-- | Returns whether this matrix is in compressed form.\ncompressed :: I.Elem a b => IOSparseMatrix a b -> IO Bool\ncompressed = _prop I.sparse_isCompressed (return . (==1))\n\n-- | Turns the matrix into the compressed format.\ncompress :: I.Elem a b => IOSparseMatrix a b -> IO ()\ncompress = _inplace I.sparse_compressInplace\n\n-- | Turns the matrix into the uncompressed mode.\nuncompress :: I.Elem a b => IOSparseMatrix a b -> IO ()\nuncompress = _inplace I.sparse_uncompressInplace\n\n-- | Reads the value of the matrix at position @i@, @j@.\n-- This function returns @Scalar(0)@ if the element is an explicit zero.\nread :: I.Elem a b => IOSparseMatrix a b -> Int -> Int -> IO a\nread (IOSparseMatrix fm) row col = withForeignPtr fm $ \\m -> alloca $ \\px -> do\n    I.call $ I.sparse_coeff m (I.cast row) (I.cast col) px\n    I.cast <$> peek px\n\n{- | Writes the value of the matrix at position @i@, @j@.\n    This function turns the matrix into a non compressed form if that was not the case.\n\n    This is a @O(log(nnz_j))@ operation (binary search) plus the cost of element insertion if the element does not already exist.\n        \n    Cost of element insertion is sorted insertion in O(1) if the elements of each inner vector are inserted in increasing inner index order, and in @O(nnz_j)@ for a random insertion.\n-}\nwrite :: I.Elem a b => IOSparseMatrix a b -> Int -> Int -> a -> IO ()\nwrite (IOSparseMatrix fm) row col x = withForeignPtr fm $ \\m -> alloca $ \\px -> do\n    I.call $ I.sparse_coeffRef m (I.cast row) (I.cast col) px\n    peek px >>= (`poke` I.cast x)\n\n-- | Sets the matrix to the identity matrix\nsetIdentity :: I.Elem a b => IOSparseMatrix a b -> IO ()\nsetIdentity = _inplace I.sparse_setIdentity\n\n-- | Removes all non zeros but keep allocated memory\nsetZero :: I.Elem a b => IOSparseMatrix a b -> IO ()\nsetZero = _inplace I.sparse_setZero\n\n-- | The number of non zero coefficients\nnonZeros :: I.Elem a b => IOSparseMatrix a b -> IO Int\nnonZeros = _prop I.sparse_nonZeros (return . I.cast)\n\n-- | Preallocates space for non zeros. The matrix must be in compressed mode.\nreserve :: I.Elem a b => IOSparseMatrix a b -> Int -> IO ()\nreserve m s = _inplace (\\p -> I.sparse_reserve p (I.cast s)) m\n\n-- | Resizes the matrix to a rows x cols matrix and initializes it to zero.\nresize :: I.Elem a b => IOSparseMatrix a b -> Int -> Int -> IO ()\nresize m rows cols = _inplace (\\p -> I.sparse_resize p (I.cast rows) (I.cast cols)) m\n\n-- | Resizes the matrix to a rows x cols matrix leaving old values untouched.\nconservativeResize :: I.Elem a b => IOSparseMatrix a b -> Int -> Int -> IO ()\nconservativeResize m rows cols = _inplace (\\p -> I.sparse_conservativeResize p (I.cast rows) (I.cast cols)) m\n\n_inplace :: I.Elem a b => (Ptr (I.CSparseMatrix a b) -> IO CString) -> IOSparseMatrix a b -> IO ()\n_inplace f (IOSparseMatrix fm) = withForeignPtr fm $ \\m -> I.call $ f m\n\n_prop :: Storable c => (I.CSparseMatrixPtr a b -> Ptr c -> IO CString) -> (c -> IO d) -> IOSparseMatrix a b -> IO d\n_prop f g (IOSparseMatrix fp) =\n    withForeignPtr fp $ \\p ->\n        alloca $ \\pq -> do\n            I.call (f p pq)\n            peek pq >>= g\n\n", "meta": {"hexsha": "2ed71910c78a563019d531e093d2d8f53288d1b7", "size": 5782, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Eigen/SparseMatrix/Mutable.hs", "max_stars_repo_name": "osidorkin/haskell-eigen", "max_stars_repo_head_hexsha": "2537faa99d3714d6a4c7621433f854e46f07f296", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2015-04-06T06:36:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T08:19:06.000Z", "max_issues_repo_path": "Data/Eigen/SparseMatrix/Mutable.hs", "max_issues_repo_name": "osidorkin/haskell-eigen", "max_issues_repo_head_hexsha": "2537faa99d3714d6a4c7621433f854e46f07f296", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2015-04-06T06:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-21T18:13:08.000Z", "max_forks_repo_path": "Data/Eigen/SparseMatrix/Mutable.hs", "max_forks_repo_name": "osidorkin/haskell-eigen", "max_forks_repo_head_hexsha": "2537faa99d3714d6a4c7621433f854e46f07f296", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-03-29T07:08:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-09T03:08:23.000Z", "avg_line_length": 39.875862069, "max_line_length": 182, "alphanum_fraction": 0.6928398478, "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.22899326553173605}}
{"text": "{-# LANGUAGE BangPatterns          #-}\n{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DefaultSignatures     #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE InstanceSigs          #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PolyKinds             #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-|\nModule      : Grenade.Core.Network\nDescription : Core definition of a Neural Network\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n\nThis module defines the core data types and functions\nfor non-recurrent neural networks.\n-}\n\nmodule Grenade.Core.Network (\n    Network (..)\n  , CreatableNetwork (..)\n  , Gradients (..)\n  , Tapes (..)\n  , GNum (..)\n  , FoldableGradient (..)\n\n  , l2Norm\n  , clipByGlobalNorm\n  , clipByValue\n  , runNetwork\n  , runGradient\n  , applyUpdate\n  , randomNetwork\n  , randomNetworkInitWith\n  ) where\n\nimport           Control.DeepSeq\nimport           Control.Monad.IO.Class\nimport           Control.Monad.Primitive          (PrimBase, PrimState)\nimport           Control.Parallel.Strategies\nimport           Data.Default\nimport           Data.Serialize\nimport           Data.Singletons\nimport           Data.Singletons.Prelude\nimport qualified Data.Vector.Storable             as V\nimport           GHC.TypeLits                     (KnownNat)\nimport           Numeric.LinearAlgebra.Static\nimport           System.Random.MWC\n\n#if MIN_VERSION_base(4,9,0)\nimport           Data.Kind                        (Type)\n#endif\n\nimport           Grenade.Core.Layer\nimport           Grenade.Core.NetworkInitSettings\nimport           Grenade.Core.NetworkSettings\nimport           Grenade.Core.Optimizer\nimport           Grenade.Core.Shape\nimport           Grenade.Layers.Internal.CUDA     (setCudaTriggerSize)\nimport           Grenade.Types\n\n-- | Type of a network.\n--\n--   The @[*]@ type specifies the types of the layers.\n--\n--   The @[Shape]@ type specifies the shapes of data passed between the layers.\n--\n--   Can be considered to be a heterogeneous list of layers which are able to\n--   transform the data shapes of the network.\ndata Network :: [Type] -> [Shape] -> Type where\n    NNil  :: SingI i\n          => Network '[] '[i]\n\n    (:~>) :: (SingI i, SingI h, Layer x i h)\n          => !x\n          -> !(Network xs (h ': hs))\n          -> Network (x ': xs) (i ': h ': hs)\ninfixr 5 :~>\n\ninstance Show (Network '[] '[i]) where\n  show NNil = \"NNil\"\ninstance (Show x, Show (Network xs rs)) => Show (Network (x ': xs) (i ': rs)) where\n  show (x :~> xs) = show x ++ \" ~> \" ++ show xs\n\ninstance NFData (Network '[] '[ i]) where\n  rnf NNil = ()\ninstance (NFData x, NFData (Network xs rs)) => NFData (Network (x ': xs) (i ': rs)) where\n  rnf ((!x) :~> (!xs)) = rnf x `seq` rnf xs\n\n\n-- | Gradient of a network.\n--\n--   Parameterised on the layers of the network.\ndata Gradients :: [Type] -> Type where\n   GNil  :: Gradients '[]\n\n   (:/>) :: UpdateLayer x\n         => !(Gradient x)\n         -> !(Gradients xs)\n         -> Gradients (x ': xs)\n\ninstance NFData (Gradients '[]) where\n  rnf GNil = ()\ninstance (NFData (Gradient x), NFData (Gradients xs)) => NFData (Gradients (x ': xs)) where\n  rnf (g :/> gs) = rnf g `seq` rnf gs\n\n\ninstance Serialize (Gradients '[]) where\n  put GNil = put ()\n  get = return GNil\ninstance (UpdateLayer x, Serialize (Gradient x), Serialize (Gradients xs)) => Serialize (Gradients (x ': xs)) where\n  put (g :/> gs) = put g >> put gs\n  get = (:/>) <$> get <*> get\n\n\n-- | Wegnert Tape of a network.\n--\n--   Parameterised on the layers and shapes of the network.\ndata Tapes :: [Type] -> [Shape] -> Type where\n   TNil  :: SingI i\n         => Tapes '[] '[i]\n\n   (:\\>) :: (SingI i, SingI h, Layer x i h)\n         => !(Tape x i h)\n         -> !(Tapes xs (h ': hs))\n         -> Tapes (x ': xs) (i ': h ': hs)\n\ninstance NFData (Tapes '[] '[i]) where\n  rnf TNil       = ()\n\ninstance (NFData (Tape x i h), NFData (Tapes xs (h ': hs))) => NFData (Tapes (x ': xs) (i ': h ': hs)) where\n  rnf (t :\\> ts) = rnf t `seq` rnf ts\n\n-- | Running a network forwards with some input data.\n--\n--   This gives the output, and the Wengert tape required for back\n--   propagation.\nrunNetwork :: forall layers shapes.\n              Network layers shapes\n           -> S (Head shapes)\n           -> (Tapes layers shapes, S (Last shapes))\nrunNetwork = go\n    where\n  go  :: forall js ss. (Last js ~ Last shapes)\n      => Network ss js\n      -> S (Head js)\n      -> (Tapes ss js, S (Last js))\n  go (layer :~> n) !x =\n    let (tape, forward) =\n\n          runForwards layer x\n        (tapes, answer) = go n forward\n    in  (tape :\\> tapes, answer)\n\n  go NNil !x\n      = (TNil, x)\n\n\n-- | Running a loss gradient back through the network.\n--\n--   This requires a Wengert tape, generated with the appropriate input\n--   for the loss.\n--\n--   Gives the gradients for the layer, and the gradient across the\n--   input (which may not be required).\nrunGradient :: forall layers shapes.\n               Network layers shapes\n            -> Tapes layers shapes\n            -> S (Last shapes)\n            -> (Gradients layers, S (Head shapes))\nrunGradient net tapes o =\n  go net tapes\n    where\n  go  :: forall js ss. (Last js ~ Last shapes)\n      => Network ss js\n      -> Tapes ss js\n      -> (Gradients ss, S (Head js))\n  go (layer :~> n) (tape :\\> nt) =\n    let (gradients, feed)  = go n nt\n        (layer', backGrad) = runBackwards layer tape feed\n    in  (layer' :/> gradients, backGrad)\n\n  go NNil TNil\n      = (GNil, o)\n\n\n-- | Apply one step of stochastic gradient descent across the network.\napplyUpdate :: Optimizer opt -> Network layers shapes -> Gradients layers -> Network layers shapes\napplyUpdate rate (layer :~> rest) (gradient :/> grest) =\n  let layer' = runUpdate rate layer gradient\n      rest' = applyUpdate rate rest grest `using` rpar\n   in layer' :~> rest'\napplyUpdate _ NNil GNil = NNil\n\n-- | Apply network settings across the network.\napplySettingsUpdate :: NetworkSettings -> Network layers shapes -> Network layers shapes\napplySettingsUpdate settings (layer :~> rest) =\n  let layer' = runSettingsUpdate settings layer\n      layers' = applySettingsUpdate settings rest `using` rpar\n   in layer' :~> layers'\napplySettingsUpdate _ NNil = NNil\n\n\n-- | A network can easily be created by hand with (:~>), but an easy way to\n--   initialise a random network is with the @randomNetworkWith@ function.\nclass CreatableNetwork (xs :: [Type]) (ss :: [Shape])\n  -- | Create a network with randomly initialised weights.\n  --\n  --   Calls to this function will not compile if the type of the neural\n  --   network is not sound.\n  where\n  randomNetworkWith :: PrimBase m => NetworkInitSettings -> Gen (PrimState m) -> m (Network xs ss)\n\n-- | Create a random network using uniform distribution.\nrandomNetwork :: (MonadIO m, CreatableNetwork xs ss) => m (Network xs ss)\nrandomNetwork = randomNetworkInitWith def\n\n-- | Create a random network using the specified weight initialization method.\nrandomNetworkInitWith :: (MonadIO m, CreatableNetwork xs ss) => NetworkInitSettings -> m (Network xs ss)\nrandomNetworkInitWith m = liftIO $ withSystemRandom . asGenST $ \\gen -> randomNetworkWith m gen\n\n\ninstance SingI i => CreatableNetwork '[] '[i] where\n  randomNetworkWith initCfg  _ = setCudaTriggerSize (gpuTriggerSize initCfg) >> return NNil\n\ninstance (SingI i, SingI o, Layer x i o, RandomLayer x, CreatableNetwork xs (o ': rs)) => CreatableNetwork (x ': xs) (i ': o ': rs) where\n  randomNetworkWith m gen = (:~>) <$> createRandomWith m gen <*> randomNetworkWith m gen\n\n-- | Add very simple serialisation to the network\ninstance SingI i => Serialize (Network '[] '[i]) where\n  put NNil = pure ()\n  get = return NNil\n\ninstance (SingI i, SingI o, Layer x i o, Serialize x, Serialize (Network xs (o ': rs))) => Serialize (Network (x ': xs) (i ': o ': rs)) where\n  put (x :~> r) = put x >> put r\n  get = (:~>) <$> get <*> get\n\n-- | Ultimate composition.\n--\n--   This allows a complete network to be treated as a layer in a larger network.\ninstance UpdateLayer (Network sublayers subshapes) where\n  type Gradient (Network sublayers subshapes) = Gradients sublayers\n  runUpdate = applyUpdate\n  runSettingsUpdate = applySettingsUpdate\n\ninstance FoldableGradient (Gradients '[]) where\n  mapGradient _ GNil = GNil\n  squaredSums GNil = []\n\ninstance (NFData (Gradient x), NFData (Gradients xs), FoldableGradient (Gradient x), FoldableGradient (Gradients xs)) => FoldableGradient (Gradients (x ': xs)) where\n  mapGradient f (x :/> xs) =\n    let x' = mapGradient f x `using` rparWith rdeepseq\n        xs' = mapGradient f xs `using` rparWith rdeepseq\n     in x' :/> xs'\n  squaredSums (x :/> xs) = (squaredSums x `using` rparWith rdeepseq) ++ (squaredSums xs `using` rparWith rdeepseq)\n\n-- | Get the L2 Norm of a Foldable Gradient.\nl2Norm :: (FoldableGradient x) => x -> RealNum\nl2Norm grad = sqrt . sum $ squaredSums grad\n\n-- | Clip the gradients by the global norm.\nclipByGlobalNorm :: (FoldableGradient (Gradients xs)) => RealNum -> Gradients xs -> Gradients xs\nclipByGlobalNorm c grads =\n  let divisor = sqrt . sum $ squaredSums grads\n   in if divisor > c\n        then mapGradient (* (c / divisor)) grads\n        else grads\n\n-- | Clip the gradients by the value v. Preforms @min v (max(-v) x)@ on all gradients.\nclipByValue :: (FoldableGradient (Gradients xs)) => RealNum -> Gradients xs -> Gradients xs\nclipByValue v grads = mapGradient (min v . (max (-v))) grads\n\n\ninstance CreatableNetwork sublayers subshapes => RandomLayer (Network sublayers subshapes) where\n  createRandomWith = randomNetworkWith\n\n\n-- | Ultimate composition.\n--\n--   This allows a complete network to be treated as a layer in a larger network.\ninstance (i ~ (Head subshapes), o ~ (Last subshapes)) => Layer (Network sublayers subshapes) i o where\n  type Tape (Network sublayers subshapes) i o = Tapes sublayers subshapes\n  runForwards  = runNetwork\n  runBackwards = runGradient\n\n\n--------------------------------------------------\n\n-- | Grenade Num class.\n--\n-- This allows for instance scalar multiplication of the weights, which is useful for slowly adapting networks, e.g. NN'\n-- <- \\tau * NN' + (1-\\tau) * NN. Or one could sum up some gradients in parallel and apply them at once: @applyUpdate lp\n-- net $ foldl1 (|+) ...@aq.\nclass GNum a where\n  (|*) :: Rational -> a -> a\n  (|+) :: a -> a -> a\n  sumG :: [a] -> a\n  default sumG :: [a] -> a\n  sumG = foldl1 (|+)\n\ninfixl 7 |*\ninfixr 5 |+\n\ninstance (SingI i) => GNum (Network '[] '[ i]) where\n  _ |* NNil = NNil\n  _ |+ NNil = NNil\n  sumG _ = NNil\n\ninstance (SingI i, SingI o, Layer x i o, NFData x, NFData (Network xs (o ': rs)), GNum x, GNum (Network xs (o ': rs))) => GNum (Network (x ': xs) (i ': o ': rs)) where\n  s |* (x :~> xs) =\n    let x' = (s |* x)\n        xs' = (s |* xs) `using` rparWith rdeepseq\n     in x' :~> xs'\n  (x :~> xs) |+ (y :~> ys) =\n    let x' = (x |+ y)\n        xs' = (xs |+ ys) `using` rparWith rdeepseq\n     in x' :~> xs'\n  sumG xs = sumG (map (\\(l :~> _) -> l) xs) :~> (sumG (map (\\(_ :~> ls) -> ls) xs) `using` rparWith rdeepseq)\n\ninstance GNum (Gradients '[]) where\n  _ |* GNil = GNil\n  _ |+ GNil = GNil\n  sumG _ = GNil\n\ninstance (GNum a) => GNum [a] where\n  r |* xs = fmap (r |*) xs\n  xs |+ ys = zipWith (|+) xs ys\n  sumG = map sumG\n\ninstance (UpdateLayer x, GNum (Gradient x), GNum (Gradients xs), NFData (Gradient x), NFData (Gradients xs)) => GNum (Gradients (x ': xs)) where\n  s |* (x :/> xs) =\n    let x' = (s |* x)\n        xs' = (s |* xs) `using` rparWith rdeepseq\n     in x' :/> xs'\n  (x :/> xs) |+ (y :/> ys) =\n    let x' = (x |+ y)\n        xs' = (xs |+ ys) `using` rparWith rdeepseq\n     in x' :/> xs'\n  sumG xs = sumG (map (\\(x :/> _) -> x) xs) :/> (sumG (map (\\(_ :/> xs') -> xs') xs) `using` rparWith rdeepseq)\n\n\ninstance GNum () where\n  _ |* () = ()\n  _ |+ () = ()\n  sumG _ = ()\n\ninstance (GNum a, GNum b) => GNum (a, b) where\n  s |* (a, b) = (s |* a, s |* b)\n  (a1, b1) |+ (a2, b2) = (a1 |+ a2, b1 |+ b2)\n  sumG xs = (sumG (map fst xs), sumG (map snd xs))\n\ninstance (KnownNat m) => GNum (R m) where\n  s |* vec = dvmap (fromRational s *) vec\n  (|+) = (+)\n  sumG xs = sum xs\n\n\ninstance (KnownNat m, KnownNat n) => GNum (L m n) where\n  s |* mat = dmmap (fromRational s *) mat\n  (|+) = (+)\n  sumG xs = sum xs\n", "meta": {"hexsha": "fabb8bd2dc1002fa21018483d608cbf507506e6c", "size": 12452, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Core/Network.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Core/Network.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-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/Grenade/Core/Network.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 33.7452574526, "max_line_length": 167, "alphanum_fraction": 0.6108255702, "num_tokens": 3654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22891758064735176}}
{"text": "{-# LANGUAGE ExistentialQuantification #-}\n\nmodule Lib\n    ( libMain\n    ) where\n\nimport Control.Monad\nimport Control.Monad.Except\nimport Data.Array\nimport Data.Complex\nimport Data.Ratio\nimport Data.Void\nimport Numeric\nimport System.Environment\nimport Text.Megaparsec\nimport Text.Megaparsec.Char\nimport qualified Text.Megaparsec.Char.Lexer as L\n\n-- Types \n-------------------------------------------------------------\n\ndata LispVal = Atom String\n             | List [LispVal]\n             | DottedList [LispVal] LispVal\n             | Vector (Array Int LispVal)\n             | Number Integer\n             | String String\n             | Bool Bool\n             | Character Char\n             | Float Double\n             | Ratio Rational\n             | Complex (Complex Double)\n\ndata LispError = NumArgs Integer [LispVal]\n               | TypeMismatch String LispVal\n               | Parser String -- we'll just pass the ouput from errorBundlePretty here\n               | BadSpecialForm String LispVal\n               | NotFunction String String\n               | UnboundVar String String\n               | Default String\n\ntype ThrowsError = Either LispError\n\n-- Parser\n-------------------------------------------------------------\n\n-- Numeric conversion helpers\noct2dig x = fst $ head (readOct x)\nhex2dig x = fst $ head (readHex x)\nbin2dig  = bin2dig' 0\nbin2dig' digint \"\" = digint\nbin2dig' digint (x:xs) = let old = 2 * digint + (if x == '0' then 0 else 1) in\n                         bin2dig' old xs\n\ntoDouble :: LispVal -> Double\ntoDouble (Float f)  = realToFrac f\ntoDouble (Number n) = fromIntegral n\n\ntype Parser = Parsec Void String\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = space1\n\nescapedChars :: Parser Char\nescapedChars = do\n    char '\\\\'\n    x <- oneOf \"\\\\\\\"nrt\"\n    return $ case x of\n        '\\\\' -> x\n        '\"'  -> x\n        'n'  -> '\\n'\n        'r'  -> '\\r'\n        't'  -> '\\t'\n        x    -> x\n\nparseString :: Parser LispVal\nparseString = do\n    char '\"'\n    x <- many $ escapedChars <|> noneOf \"\\\"\\\\\"\n    char '\"'\n    return $ String x\n\n-- parses characters specified like #\\a #\\A #\\space #\\newline\nparseCharacter :: Parser LispVal\nparseCharacter = do\n    try $ string \"#\\\\\"\n    value <- try (string \"newline\" <|> string \"space\")\n            <|> do { x <- L.charLiteral; notFollowedBy alphaNumChar; return [x] }\n    return $ Character $ case value of\n        \"space\"     -> ' '\n        \"newline\"   -> '\\n'\n        _           -> head value\n\nparseAtom :: Parser LispVal\nparseAtom = do\n    first <- letterChar <|> symbol\n    rest <- many (letterChar <|> digitChar <|> symbol)\n    let atom = first:rest\n    return $ Atom atom\n\nparseBool :: Parser LispVal\nparseBool = do\n    char '#'\n    (Bool True <$ char 't') <|> (Bool False <$ char 'f')\n\nparseDecimal1 :: Parser LispVal\nparseDecimal1 = Number . read <$> some digitChar\n\nparseDecimal2 :: Parser LispVal\nparseDecimal2 = do\n    try $ string \"#x\"\n    Number . read <$> some digitChar\n\nparseHex :: Parser LispVal\nparseHex = do\n    try $ string \"#x\"\n    Number . hex2dig <$> some hexDigitChar\n\nparseOct :: Parser LispVal\nparseOct = do\n    try $ string \"#o\"\n    Number . oct2dig <$> some octDigitChar\n\nparseBin :: Parser LispVal\nparseBin = do\n    try $ string \"#b\"\n    Number . bin2dig <$> some binDigitChar\n\nparseNumber :: Parser LispVal\nparseNumber = parseDecimal1 <|> parseDecimal2 <|> parseHex <|> parseOct <|> parseBin\n\nparseFloat :: Parser LispVal\nparseFloat = Float <$> L.float\n\nparseRatio :: Parser LispVal\nparseRatio = do\n    x <- some digitChar\n    char '/'\n    y <- some digitChar\n    return $ Ratio (read x % read y)\n\nparseComplex :: Parser LispVal\nparseComplex = do\n    x <- try parseFloat <|> try parseDecimal1\n    char '+'\n    y <- try parseFloat <|> try parseDecimal1\n    char 'i'\n    return $ Complex (toDouble x :+ toDouble y)\n\nparseList :: Parser LispVal\nparseList = List <$> sepBy parseExpr spaces\n\nparseDottedList :: Parser LispVal\nparseDottedList = do\n    head <- endBy parseExpr spaces\n    tail <- char '.' >> spaces >> parseExpr\n    return $ DottedList head tail\n\nparseQuoted :: Parser LispVal\nparseQuoted = do\n    char '\\''\n    x <- parseExpr\n    return $ List [Atom \"quote\", x]\n\nparseQuasiQuoted :: Parser LispVal\nparseQuasiQuoted = do\n    char '`'\n    x <- parseExpr\n    return $ List [Atom \"quasiquote\", x]\n\nparseUnQuote :: Parser LispVal\nparseUnQuote = do\n    char ','\n    x <- parseExpr\n    return $ List [Atom \"unquote\", x]\n\nparseUnQuoteSplicing :: Parser LispVal\nparseUnQuoteSplicing = do\n    char ','\n    char '@'\n    x <- parseExpr\n    return $ List [Atom \"unquote-splicing\", x]\n\nparseVector :: Parser LispVal\nparseVector = do\n    arrayValues <- sepBy parseExpr spaces\n    return $ Vector (listArray (0, length arrayValues - 1) arrayValues)\n\nparseExpr :: Parser LispVal\nparseExpr = parseAtom\n         <|> parseString\n         <|> try parseComplex\n         <|> try parseFloat\n         <|> try parseRatio\n         <|> try parseNumber\n         <|> try parseBool\n         <|> try parseCharacter\n         <|> parseQuoted\n         <|> parseQuasiQuoted\n         <|> parseUnQuote\n         <|> parseUnQuoteSplicing\n         <|> try (do\n             string \"#(\"\n             x <- parseVector\n             char ')'\n             return x)\n         <|> do\n                char '('\n                x <- try parseList <|> parseDottedList\n                char ')'\n                return x\n\nreadExpr :: String -> ThrowsError LispVal\nreadExpr input = case parse parseExpr \"lisp\" input of\n    Left err -> throwError $ Parser $ errorBundlePretty err\n    Right val -> return val\n\n-- Eval\n-------------------------------------------------------------\n\nunwordsList :: [LispVal] -> String\nunwordsList = unwords . map showVal\n\nshowVal :: LispVal -> String\nshowVal (String contents) = \"\\\"\" ++ contents ++ \"\\\"\"\nshowVal (Atom name) = name\nshowVal (Number contents) = show contents\nshowVal (Bool True) = \"#t\"\nshowVal (Bool False) = \"#f\"\nshowVal (List contents) = \"(\" ++ unwordsList contents ++ \")\"\nshowVal (DottedList head tail) = \"(\" ++ unwordsList head ++ \" . \" ++ showVal tail ++ \")\"\nshowVal (Float contents) = show contents\nshowVal (Character char) = show char\nshowVal (Ratio contents) = show contents\nshowVal (Complex contents) = show contents\n--TODO: Implement the rest so this isn't required\n-- showVal _ = error \"showVal not implemented for type\"\n\ninstance Show LispVal where show = showVal\n\nshowError :: LispError -> String\nshowError (UnboundVar message varname)  = message ++ \": \" ++ varname\nshowError (BadSpecialForm message form) = message ++ \": \" ++ show form\nshowError (NotFunction message func)    = message ++ \": \" ++ show func\nshowError (NumArgs expected found)      = \"Expected \" ++ show expected ++ \" args; found values \" ++ unwordsList found\nshowError (TypeMismatch expected found) = \"Invalid type: expected \" ++ expected ++ \", found \" ++ show found\nshowError (Parser parseErr)             = \"Parse error at \" ++ show parseErr\nshowError (Default message)             = \"Error: \" ++ message\n\ninstance Show LispError where show = showError\n\ntrapError action = catchError action (return . show)\n\n-- Non exhaustiveness here is intentional, it's a programmer error to apply extractValue to a Left val\nextractValue :: ThrowsError a -> a\nextractValue (Right val) = val\n\nunaryOp :: (LispVal -> LispVal) -> [LispVal] -> ThrowsError LispVal\nunaryOp f [] = throwError $ NumArgs 1 []\nunaryOp f [v] = return $ f v\nunaryOp _ args = throwError $ NumArgs 1 args\n\n--TODODB: Should implement numberp for Complex\nsymbolp, numberp, stringp, boolp, listp :: LispVal -> LispVal\nsymbolp (Atom _)   = Bool True\nsymbolp _          = Bool False\nnumberp (Number _) = Bool True\nnumberp _          = Bool False\nstringp (String _) = Bool True\nstringp _          = Bool False\nboolp   (Bool _)   = Bool True\nboolp   _          = Bool False\nlistp   (List _)   = Bool True\nlistp   (DottedList _ _) = Bool False\nlistp   _          = Bool False\n\nunpackNum :: LispVal -> ThrowsError Integer\nunpackNum (Number n) = return n\nunpackNum (String n) = let parsed = reads n in\n                           if null parsed\n                             then throwError $ TypeMismatch \"number\" $ String n\n                             else return $ fst $ head parsed\nunpackNum (List [n]) = unpackNum n\nunpackNum notNum     = throwError $ TypeMismatch \"number\" notNum\n\nunpackStr :: LispVal -> ThrowsError String\nunpackStr (String s) = return s\nunpackStr (Number s) = return $ show s\nunpackStr (Bool s)   = return $ show s\nunpackStr notString  = throwError $ TypeMismatch \"string\" notString\n\nunpackBool :: LispVal -> ThrowsError Bool\nunpackBool (Bool b) = return b\nunpackBool notBool  = throwError $ TypeMismatch \"boolean\" notBool\n\nnumericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal\nnumericBinop op []              = throwError $ NumArgs 2 []\nnumericBinop op singleVal@[_]   = throwError $ NumArgs 2 singleVal\nnumericBinop op params          = mapM unpackNum params >>= return . Number . foldl1 op\n\nboolBinop :: (LispVal -> ThrowsError a) -> (a -> a -> Bool) -> [LispVal] -> ThrowsError LispVal\nboolBinop unpacker op args = if length args /= 2\n                             then throwError $ NumArgs 2 args\n                             else do left <- unpacker $ head args\n                                     right <- unpacker $ args !! 1\n                                     return $ Bool $ left `op` right\n\nnumBoolBinop  = boolBinop unpackNum\nstrBoolBinop  = boolBinop unpackStr\nboolBoolBinop = boolBinop unpackBool\n\nprimitives :: [(String, [LispVal] -> ThrowsError LispVal)]\nprimitives = [  (\"+\", numericBinop (+)),\n                (\"-\", numericBinop (-)),\n                (\"*\", numericBinop (*)),\n                (\"/\", numericBinop div),\n                (\"mod\", numericBinop mod),\n                (\"quotient\", numericBinop quot),\n                (\"remainder\", numericBinop rem),\n                (\"symbol?\", unaryOp symbolp),\n                (\"string?\", unaryOp stringp),\n                (\"number?\", unaryOp numberp),\n                (\"bool?\", unaryOp boolp),\n                (\"list?\", unaryOp listp),\n                (\"=\", numBoolBinop (==)),\n                (\"<\", numBoolBinop (<)),\n                (\">\", numBoolBinop (>)),\n                (\"/=\", numBoolBinop (/=)),\n                (\">=\", numBoolBinop (>=)),\n                (\"<=\", numBoolBinop (<=)),\n                (\"&&\", boolBoolBinop (&&)),\n                (\"||\", boolBoolBinop (||)),\n                (\"string=?\", strBoolBinop (==)),\n                (\"string<?\", strBoolBinop (<)),\n                (\"string>?\", strBoolBinop (>)),\n                (\"string<=?\", strBoolBinop (<=)),\n                (\"string>=?\", strBoolBinop (>=)),\n                (\"car\", car),\n                (\"cdr\", cdr),\n                (\"cons\", cons),\n                (\"eq?\", eqv),\n                (\"eqv?\", eqv),\n                (\"equal?\", equal)]\n\n-- lookup primitive, if not present, error\napply :: String -> [LispVal] -> ThrowsError LispVal\napply func args = maybe (throwError $ NotFunction \"Unrecognized primitive function args\" func)\n                  ($ args)\n                  (lookup func primitives)\n\neval :: LispVal -> ThrowsError LispVal\neval val@(String _) = return val\neval val@(Number _) = return val\neval val@(Bool _)   = return val\neval val@(Float _)  = return val\neval val@(Complex _) = return val\neval (List [Atom \"quote\", val]) = return val\neval (List [Atom \"if\", pred, conseq, alt]) = do\n    result <- eval pred\n    case result of\n        Bool False -> eval alt\n        Bool True -> eval conseq\n        _ -> throwError $ TypeMismatch \"bool\" pred\neval (List (Atom func : args)) = mapM eval args >>= apply func\neval badForm = throwError $ BadSpecialForm \"Unrecognized special form\" badForm\n\n-- List primitives\n\n{- \n(car '(a b c)) = a\n(car '(a)) = a\n(car '(a b . c)) = a\n(car 'a) = error \u2013 not a list\n(car 'a 'b) = error \u2013 car only takes one argument\n-}\ncar :: [LispVal] -> ThrowsError LispVal\ncar [List (x : xs)]         = return x\ncar [DottedList (x : xs) _] = return x\ncar [badArg]                = throwError $ TypeMismatch \"pair\" badArg\ncar badArgList              = throwError $ NumArgs 1 badArgList\n\n{-\n(cdr '(a b c)) = (b c)\n(cdr '(a b)) = (b)\n(cdr '(a)) = NIL\n(cdr '(a . b)) = b\n(cdr '(a b . c)) = (b . c)\n(cdr 'a) = error \u2013 not a list\n(cdr 'a 'b) = error \u2013 too many arguments\n-}\ncdr :: [LispVal] -> ThrowsError LispVal\ncdr [List (x : xs)]         = return $ List xs\ncdr [DottedList [_] x]      = return x\ncdr [DottedList (_ : xs) x] = return $ DottedList xs x\ncdr [badArg]                = throwError $ TypeMismatch \"pair\" badArg\ncdr badArgList              = throwError $ NumArgs 1 badArgList\n\ncons :: [LispVal] -> ThrowsError LispVal\ncons [x1, List []]              = return $ List [x1]\ncons [x, List xs]               = return $ List $ x : xs\ncons [x, DottedList xs xlast]   = return $ DottedList (x:xs) xlast\ncons [x1, x2]                   = return $ DottedList [x1] x2\ncons badArgList                 = throwError $ NumArgs 2 badArgList\n\n-- There are 3 levels of equivalence predicates in scheme. eq? eqv? and equal?\n-- eq? and eqv? as basically the same: Two items are the same if they print the same\n-- We can write one function for both, and register just the one function for both symbols\neqv :: [LispVal] -> ThrowsError LispVal\neqv [Bool arg1, Bool arg2]             = return $ Bool $ arg1 == arg2\neqv [Number arg1, Number arg2]         = return $ Bool $ arg1 == arg2\neqv [String arg1, String arg2]         = return $ Bool $ arg1 == arg2\neqv [Atom arg1, Atom arg2]             = return $ Bool $ arg1 == arg2\neqv [DottedList xs x, DottedList ys y] = eqv [List $ xs ++ [x], List $ ys ++ [y]]\neqv [List arg1, List arg2]             = return $ Bool $ (length arg1 == length arg2) &&\n                                                             all eqvPair (zip arg1 arg2)\n     where eqvPair (x1, x2) = case eqv [x1, x2] of\n                                Left err -> False\n                                Right (Bool val) -> val\neqv [_, _]                                 = return $ Bool False\neqv badArgList                             = throwError $ NumArgs 2 badArgList\n\n-- Now we want an equal? function that ignores differences in the type tags.\n-- e.g. we want to keep weak typing and let that work across different type tags.\n--      (equal? 2 \"2\") = #t\n--\n-- Existential types to the rescue.\n-- We need a data type that can hold any function from a `LispVal -> something`\n-- (provided that something supports equality)\ndata Unpacker = forall a. Eq a => AnyUnpacker (LispVal -> ThrowsError a)\n\n-- \"For any type that is an instance of Eq, you can define an Unpacker that takes a function\n-- from LispVal to that type, and may throw an error.\"\n-- All we have to do is wrap our functions with the AnyUnpacker constructor,\n-- then we can create a list of Unpackers that does what we want.\n\n-- Take an Unpacker and determine if two LispVals are equal after unpack\nunpackEquals :: LispVal -> LispVal -> Unpacker -> ThrowsError Bool\nunpackEquals arg1 arg2 (AnyUnpacker unpacker) =\n             do unpacked1 <- unpacker arg1\n                unpacked2 <- unpacker arg2\n                return $ unpacked1 == unpacked2\n        `catchError` const (return False)\n\nequal :: [LispVal] -> ThrowsError LispVal\nequal [arg1, arg2] = do\n    let unpackers = [AnyUnpacker unpackNum, AnyUnpacker unpackStr, AnyUnpacker unpackBool]\n    primitiveEquals <- liftM or $ mapM (unpackEquals arg1 arg2) unpackers\n    eqvEquals <- eqv [arg1, arg2]\n    return $ Bool (primitiveEquals || let (Bool x) = eqvEquals in x)\nequal badArgList = throwError $ NumArgs 2 badArgList\n\nlibMain :: IO ()\nlibMain = do\n    args <- getArgs\n    let evaled = fmap show $ readExpr (args !! 0) >>= eval\n    putStrLn $ extractValue $ trapError evaled\n", "meta": {"hexsha": "13b1f339320c06546e78908768b559108fadf0ad", "size": 15777, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "daniel-beard/scheme48", "max_stars_repo_head_hexsha": "6d07eef2cdffd0915edcf049b8d05e57e6a5b4be", "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": "daniel-beard/scheme48", "max_issues_repo_head_hexsha": "6d07eef2cdffd0915edcf049b8d05e57e6a5b4be", "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": "daniel-beard/scheme48", "max_forks_repo_head_hexsha": "6d07eef2cdffd0915edcf049b8d05e57e6a5b4be", "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.297826087, "max_line_length": 117, "alphanum_fraction": 0.5904798124, "num_tokens": 4175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22891757446279754}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE UnicodeSyntax #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Graphics.Rendering.Plot.Render.Plot.Data\n-- Copyright   :  (c) A. V. H. McPhail 2010, 2013\n-- License     :  BSD3\n--\n-- Maintainer  :  haskell.vivian.mcphail <at> gmail <dot> com\n-- Stability   :  provisional\n-- Portability :  portable\n--\n-- Rendering 'Figure's\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Plot.Render.Plot.Data (\n                                       -- * Rendering\n                                       renderData\n                                       ) where\n\n-----------------------------------------------------------------------------\n\nimport Data.List(partition)\n--import Prelude.Unicode\n\n--import Foreign.Storable \n--import Foreign.Ptr\n\n--import Data.Packed.Vector\n--import Data.Packed.Matrix\n--import Data.Packed()\nimport Numeric.LinearAlgebra\n\nimport qualified Data.Array.IArray as A\n--import qualified Data.Array.MArray as M\nimport qualified Data.Array.Base as B\n\nimport Data.Word\n\nimport Data.Maybe \nimport qualified Graphics.Rendering.Cairo as C\nimport qualified Graphics.Rendering.Cairo.Matrix as CM\n\nimport Control.Monad.Reader\nimport Control.Monad.State\nimport Control.Monad.Maybe\n\nimport Graphics.Rendering.Plot.Types\n\nimport Graphics.Rendering.Plot.Render.Types\nimport Graphics.Rendering.Plot.Render.Plot.Format\nimport Graphics.Rendering.Plot.Render.Plot.Glyph\n--import Graphics.Rendering.Plot.Render.Plot.Annotation\nimport Graphics.Rendering.Plot.Defaults\n\nimport Prelude hiding(min,max,abs)\nimport qualified Prelude\n\n-----------------------------------------------------------------------------\n\nfindMinIdx, findMaxIdx :: Vector Double -> Double -> Int -> Int -> Int\nfindMinIdx v x n max\n    | n >= max       = error \"findMinIdx: data not in range\"\n    | v @> n >= x    = n\n    | otherwise     = findMinIdx v x (n+1) max\n\nfindMaxIdx v x n min\n    | n < 0          = error \"findMaxIdx: data not in range\"\n    | v @> n <= x     = n\n    | otherwise      = findMaxIdx v x (n-1) min\n\n-----------------------------------------------------------------------------\n\ngreySurfaceFromMatrix :: C.SurfaceData Int Word8 -> Surface -> Int -> Int -> Int -> IO ()\ngreySurfaceFromMatrix s m stride r' c' = do\n  let r = rows m\n      c = cols m\n  let fm = flatten m\n      mx = maxElement m\n      mn = minElement m\n  mapM_ (\\ri -> mapM_ (\\(rj,ci) -> do\n     let mi = ((rj `div` r')*c) + (ci `div` c')\n     let e = round . (* 255) . (/ (mx-mn)) . (\\x -> x - mn) $ (fm @> mi)\n     let si = (rj*stride) + ci\n     B.unsafeWrite s si e) $ zip (repeat ri) [0..((c*c')-1)]) [0..((r*r')-1)]\n\n----------------------------------------------------------------------------\n\nzeroToOne :: Double -> Double\nzeroToOne x\n    | x == 0.0  = 1.0\n    | otherwise = x\n\nrenderData :: Ranges -> BarSetting -> SampleData -> DataSeries -> Render ()\nrenderData _ _ _ (DS_Surf m) = do \n  (BoundingBox x y w h) <- get\n  let r = rows m\n      c = cols m\n  cairo $ do\n    C.save\n    --C.setAntialias C.AntialiasNone\n    let r'' = Prelude.min 4 ((round h) `div` r)\n        c'' = Prelude.min 4 ((round w) `div` c)\n        r' = if r'' < 1 then 1 else r''\n        c' = if c'' < 1 then 1 else c''\n    s <- liftIO $ C.createImageSurface C.FormatA8 (c*c') (r*r')\n    p <- liftIO $ C.imageSurfaceGetPixels s\n    C.surfaceFlush s\n    stride <- liftIO $ C.imageSurfaceGetStride s\n    liftIO $ greySurfaceFromMatrix p m stride r' c'\n    C.surfaceMarkDirty s\n    C.setSourceSurface s x y\n    pa <- C.getSource\n    pm <- liftIO $ C.patternGetMatrix pa\n    let pm' = CM.scale ((fromIntegral (c*c'))/w) ((fromIntegral (r*r'))/h) pm\n    liftIO $ C.patternSetMatrix pa pm'\n    --C.patternSetFilter pa C.FilterBest\n    C.rectangle x y w h --(fromIntegral c) (fromIntegral r)\n    C.paint\n    C.stroke\n    C.restore\n    return ()\n\nrenderData r bc sd ds = do\n  let aos = case ds of\n              (DS_Y         os') -> zip (repeat (AbsFunction id)) (A.elems os')\n              (DS_1toN abs' os') -> zip (repeat abs')             (A.elems os') \n              (DS_1to1 aos')     -> A.elems aos'\n              _                  -> error \"renderData: DataSeries not handled\"\n  let (los,ups) = partition (\\(_,DecSeries o _) -> isLower o) aos\n  (BoundingBox x y w h) <- get\n  let (xsc,xmin',xmax') = getRanges XAxis Lower r\n  let (xmin,xmax) = if xsc == Log then (logBase 10 $ zeroToOne xmin',logBase 10 $ zeroToOne xmax') else (xmin',xmax')\n  let xscale = w/(xmax-xmin) \n  cairo $ C.save\n  let (yscl,yminl',ymaxl') = getRanges YAxis Lower r\n  let (yminl,ymaxl) = if yscl == Log then (logBase 10 $ zeroToOne yminl',logBase 10 $ zeroToOne ymaxl') else (yminl',ymaxl')\n  let yscalel = h/(ymaxl-yminl) \n  -- transform to data coordinates\n  cairo $ do \n    C.translate x (y+h)\n    --C.scale xscale yscalel\n    C.translate (-xmin*xscale) (yminl*yscalel)\n    flipVertical\n  los' <- configureBars xsc yscl xmin xmax xscale yscalel bc los \n  mapM_ (renderSeries xsc yscl xmin xmax xscale yscalel sd) los'\n  cairo $ C.restore\n  when (not $ null ups)\n           (do\n             cairo $ C.save\n             let (yscu,yminu',ymaxu') = getRanges YAxis Upper r\n             let (yminu,ymaxu) = if yscu == Log then (logBase 10 $ zeroToOne yminu',logBase 10 $ zeroToOne ymaxu') else (yminu',ymaxu')\n             let yscaleu = h/(ymaxu-yminu) \n             -- transform to data coordinates\n             cairo $ do \n               C.translate x (y+h)\n               --C.scale xscale yscaleu\n               C.translate (-xmin*xscale) (yminu*yscaleu)\n               flipVertical\n             ups' <- configureBars xsc yscu xmin xmax xscale yscaleu bc ups \n             mapM_ (renderSeries xsc yscu xmin xmax xscale yscaleu sd) ups'\n             cairo $ C.restore)\n             -- could filter annotations as well\n  return ()\n\nlogSeries :: Scale -> Vector Double -> Vector Double\nlogSeries Log a = logBase 10 $ mapVector zeroToOne a\nlogSeries _   a = a\n\nmidpoints :: (Num (Vector t), Container Vector t) \n            => (t1, Vector t) -> (t1, Vector t)\nmidpoints(mi,v) = let v' = subVector 1 (dim v - 1) v\n                      w' = subVector 0 (dim v - 1) v\n                  in (mi,(v'+w')/2.0)\n\nlogSeriesMinMax :: Scale -> (Vector Double,Vector Double) -> (Vector Double,Vector Double)\nlogSeriesMinMax Log    (v,w) = (logSeries Log v,logSeries Log w)\nlogSeriesMinMax Linear x     = x\n\ngetBar :: (Integer,(Abscissae,DecoratedSeries)) \n        -> Maybe (Integer,(Abscissae,DecoratedSeries,BarType)) \ngetBar (ix,(as,DecSeries os ds)) = let d = decorationGetBarType ds\n   in case d of\n        Just d' -> Just (ix,(as,DecSeries os ds,d'))\n        Nothing -> Nothing\n\ngetBarWidth :: (Integer,(Abscissae,DecoratedSeries,BarType)) -> Render Double\ngetBarWidth (_,(_,_,(ColourBar _)))                  = do\n  (BarOptions w _ _) <- asks (_baroptions . _renderoptions)\n  return w\ngetBarWidth (_,(_,_,(TypeBar (BarOptions w _ _) _))) = return w\n\nreplace :: Integer -> a -> [a] -> [a]\nreplace n x xs = let (pre,post) = splitAt (fromIntegral n) xs\n                 in pre ++ x:(tail post)\n\nshiftAbscissa :: (Integer,(Abscissae,DecoratedSeries,BarType)) -> Double\n              -> (Integer,(Abscissae,DecoratedSeries))\nshiftAbscissa (j,(AbsFunction f,ds,_)) s  = (j,(AbsFunction ((+) s . f),ds))\nshiftAbscissa (j,(AbsPoints mi t,ds,_)) s = (j,(AbsPoints mi (addConstant s t),ds))\n\nreplaceBars :: [(Integer,(Abscissae,DecoratedSeries))] \n            -> [(Abscissae,DecoratedSeries)] \n            -> [(Abscissae,DecoratedSeries)] \nreplaceBars [] as = as\nreplaceBars ((j,ds):dss) as = replaceBars dss $ replace j ds as\n\nscanStacked :: Vector Double\n            -> (Integer,(Abscissae,DecoratedSeries,BarType))\n            -> Vector Double\nscanStacked v (_,(_,DecSeries (OrdPoints _ o _) _,_)) = v + (getOrdData o)\nscanStacked _ _                                       = error \"Data.hs:scanStacked: unreachable code\"\n\nconvertBarToCandle :: (Vector Double,Vector Double)\n                   -> OrdSeries\n                   -> OrdSeries\nconvertBarToCandle (v,w) os =\n    case os of\n      Plain _                 -> MinMax (v,w) Nothing\n      Error _ (Right (el,eh)) -> MinMax (v,w) (Just (el,eh))\n      _                       -> error \"convertBarToCandle: unreachable code\"\n\nmkCandlesFromBars :: (Vector Double,Vector Double)\n                  -> (Integer,(Abscissae,DecoratedSeries,BarType))\n                  -> (Integer,(Abscissae,DecoratedSeries))\nmkCandlesFromBars (v,w) (j,(a,DecSeries (OrdPoints ax o mb_l) _,bt)) = \n  (j,(a,DecSeries (OrdPoints ax ordSeries mb_l) (DecCand bt)))\n      where\n        ordSeries = convertBarToCandle (v,w) o\nmkCandlesFromBars _     _                                            = error \"Data.hs:mkCandlesFromBars: unreachable code\"\n\ngetOrdData' :: DecoratedSeries -> Series\ngetOrdData' (DecSeries (OrdPoints _ os _) _) = getOrdData os\ngetOrdData' _                                = error \"Data.hs:getOrdData': unreachable code\"\n\nconfigureBars :: Scale -> Scale\n             -> Double -> Double -> Double -> Double\n             -> BarSetting\n             -> [(Abscissae,DecoratedSeries)] \n             -> Render [(Abscissae,DecoratedSeries)] \nconfigureBars _ _ _ _ xscale _ bs aos = do\n   let bars = mapMaybe getBar $ zip [0..] aos\n   case bs of\n     BarNone   -> return aos\n     BarSpread -> do\n        widths <- mapM getBarWidth bars\n        let half_total = (sum widths) / 2\n        let shifts' = init $ scanl (+) 0 widths\n            shifts = map ((/ xscale) . flip (-) half_total) shifts'\n        let shifted = zipWith shiftAbscissa bars shifts\n        let aos' = replaceBars shifted aos\n        return aos'\n     BarStack  -> do\n        let od = (getOrdData' . (\\(_,b,_) -> b) . snd . head) bars\n        let ln = dim $ od\n        let zero = constant 0 ln\n        let pairs = pair $ scanl scanStacked zero bars  \n        let candles = zipWith mkCandlesFromBars pairs bars\n        let aos' = replaceBars candles aos\n        return aos'\n            where pair [] = []\n                  pair [_] = error \"Data.hs:configureBars:pair: unreachable code\"\n                  pair [x,y] = [(x,y)]\n                  pair (x:y:xs) = (x,y) : pair (y:xs)\n\nrenderSeries :: Scale -> Scale \n             -> Double -> Double -> Double -> Double -> SampleData \n             -> (Abscissae,DecoratedSeries) -> Render ()\nrenderSeries xsc ysc xmin xmax xscale yscale sd (abs,(DecSeries o d)) = do\n  dat  <- case o of\n     (OrdFunction _ f _)            -> do\n        (BoundingBox _ _ w _) <- get\n        let t = logSeries xsc $ linspace (round w) (xmin,xmax)\n        return $ Left $ Left ((True,t),logSeries ysc $ mapVector f t)\n     (OrdPoints _ (Plain o') _)     -> do\n        let t = case abs of\n                  AbsFunction f    -> \n                    if isHist d\n                    then (True,mapVector f $ fromList [0.0..(fromIntegral $ dim o')])\n                    else (True,mapVector f $ fromList [1.0..(fromIntegral $ dim o')])\n                  AbsPoints mi t'  -> (mi,t')\n        return $ Left $ Left ((fst t,logSeries xsc $ snd t),logSeries ysc $ o')\n     (OrdPoints _ (Error o' (Left e)) _) -> do\n        let t = case abs of\n                  AbsFunction f    -> \n                    if isHist d\n                    then (True,mapVector f $ fromList [0.0..(fromIntegral $ dim o')])\n                    else (True,mapVector f $ fromList [1.0..(fromIntegral $ dim o')])\n                  AbsPoints mi t'  -> (mi,t')\n        let t' = (fst t,logSeries xsc $ snd t)\n        return $ Left $ Right $ Left ((t',logSeries ysc $ o'),(t',logSeries ysc $ e))\n     (OrdPoints _ (Error o' (Right (l,h))) _) -> do\n        let t = case abs of\n                  AbsFunction f    -> \n                    if isHist d\n                    then (True,mapVector f $ fromList [0.0..(fromIntegral $ dim o')])\n                    else (True,mapVector f $ fromList [1.0..(fromIntegral $ dim o')])\n                  AbsPoints mi t'  -> (mi,t') \n        let t' = (fst t,logSeries xsc $ snd t)\n        return $ Left $ Right $ Right ((t',logSeries ysc $ o'),(t',logSeries ysc $ l),(t',logSeries ysc $ h))\n     (OrdPoints _ (MinMax o' Nothing) _) -> do\n        let t = case abs of\n                  AbsFunction f    -> (True,mapVector f $ fromList [1.0..(fromIntegral $ dim $ fst o')])\n                  AbsPoints mi t'  -> (mi,t')\n        let t' = (fst t,logSeries xsc $ snd t)\n        return $ Right $ Left (t',logSeriesMinMax ysc $ o')\n     (OrdPoints _ (MinMax o' (Just (l,h))) _) -> do\n        let t = case abs of\n                  AbsFunction f    -> (True,mapVector f $ fromList [1.0..(fromIntegral $ dim l)])\n                  AbsPoints mi t'  -> (mi,t')\n        let t' = (fst t,logSeries xsc $ snd t)\n        return $ Right $ Right ((t',logSeriesMinMax ysc o'),(t',(logSeries ysc l,logSeries ysc h)))\n  case d of\n    (DecLine lt)   -> do\n        formatLineSeries lt\n        case dat of\n          Left (Left (t',y')) -> do\n            renderSamples xscale yscale xmin xmax sd Nothing renderLineSample endLineSample t' y'\n          _  -> error \"Data.hs renderSeries: cannot have error bars with line type\"\n    (DecPoint pt)  -> do\n        (pz,g) <- formatPointSeries pt\n        case dat of\n          Left (Left (t',y')) -> do\n            renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz g) endPointSample t' y'\n          Left (Right (Left ((t',y'),(_,e')))) -> do\n            renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz g) endPointSample t' y'\n            renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz Bot) endPointSample t' (y'-e')\n            renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz Top) endPointSample t' (y'+e')\n          Left (Right (Right ((t',y'),(_,l),(_,h)))) -> do\n            renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz g) endPointSample t' y'\n            renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz Bot) endPointSample t' l \n            renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz Top) endPointSample t' h \n          _  -> error \"Data.hs renderSeries: cannot have MinMax data series with point type\"\n    (DecLinPt lt pt) -> do\n       formatLineSeries lt\n       (pz,g) <- formatPointSeries pt\n       case dat of\n         Left (Left (t',y')) -> do\n           renderSamples xscale yscale xmin xmax sd Nothing renderLineSample endLineSample t' y'\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz g) endPointSample t' y'\n         Left (Right (Left ((t',y'),(_,e')))) -> do\n           renderSamples xscale yscale xmin xmax sd Nothing renderLineSample endLineSample t' y'\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz g) endPointSample t' y'\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz Bot) endPointSample t' (y'-e')\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz Top) endPointSample t' (y'+e')\n--               error \"Data.hs renderSeries: cannot have single error value with line-points type\"        \n         Left (Right (Right ((t',y'),(_,l),(_,h)))) -> do\n           renderSamples xscale yscale xmin xmax sd Nothing renderLineSample endLineSample t' y'\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz g) endPointSample t' y'\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz Bot) endPointSample t' l \n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample pz Top) endPointSample t' h \n         _  -> error \"Data.hs renderSeries: cannot have MinMax data series with line-point type\"\n    (DecImpulse lt) -> do\n       formatLineSeries lt\n       case dat of\n         Left (Left (t',y')) -> do\n           renderSamples xscale yscale xmin xmax sd Nothing renderImpulseSample endImpulseSample t' y'\n         _  -> error \"Data.hs renderSeries: cannot have error bars with impulse type\"\n    (DecStep lt) -> do\n        formatLineSeries lt\n        case dat of\n          Left (Left (t',y')) -> do\n            renderSamples xscale yscale xmin xmax sd Nothing renderStepSample endStepSample t' y'\n          _  -> error \"Data.hs renderSeries: cannot have error bars with step type\"\n    (DecArea lt) -> do\n       formatLineSeries lt\n       case dat of\n         Left (Left (t',y')) -> do\n           let ln = dim $ snd t'\n               xmin_ix = findMinIdx (snd t') xmin 0 (ln-1)\n               x0 = (snd t') @> xmin_ix\n               y0 = y' @> xmin_ix\n           renderSamples xscale yscale xmin xmax sd Nothing renderAreaSample (endAreaSample x0 y0) t' y'\n         _  -> error \"Data.hs renderSeries: cannot have error bars with area type\"\n    (DecBar bt)   -> do\n       (bw,bc,c) <- formatBarSeries bt\n       (gw,_) <- formatPointSeries defaultPointType \n       case dat of\n         Left (Left (t',y')) -> do\n           renderSamples xscale yscale xmin xmax sd Nothing (renderBarSample bw bc c) endBarSample t' y' \n         Left (Right (Left ((t',y'),(_,e')))) -> do\n           renderSamples xscale yscale xmin xmax sd Nothing (renderBarSample bw bc c) endBarSample t' y' \n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSampleUpDown gw) endPointSample t' e'\n         Left (Right (Right ((t',y'),(_,l'),(_,h')))) -> do\n           renderSamples xscale yscale xmin xmax sd Nothing (renderBarSample bw bc c) endBarSample t' y' \n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample gw Bot) endPointSample t' l'\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample gw Top) endPointSample t' h'\n         _  -> error \"Data.hs renderSeries: cannot have MinMax data series with bar type\"\n    (DecHist bt)  -> do\n       (bw,bc,c) <- formatBarSeries bt\n       (gw,_) <- formatPointSeries defaultPointType \n       case dat of\n         Left (Left (t',y')) -> do\n           let ln = dim $ snd $ t'\n               xmin_ix = findMinIdx (snd t') xmin 0 (ln-1)\n               rest (m,v) = (m,subVector 1 (dim v - 1) v)\n               x0 = (snd t') @> xmin_ix\n               y0 = 0\n           renderSamples xscale yscale xmin xmax sd (Just $ C.moveTo x0 y0) (renderHistSample bw bc c) endHistSample (rest t') y'\n         Left (Right (Left ((t',y'),(_,e')))) -> do\n           let ln = dim $ snd $ t'\n               xmin_ix = findMinIdx (snd t') xmin 0 (ln-1)\n               rest (m,v) = (m,subVector 1 (dim v - 1) v)\n               x0 = (snd t') @> xmin_ix\n               y0 = 0\n           renderSamples xscale yscale xmin xmax sd (Just $ C.moveTo x0 y0) (renderHistSample bw bc c) endHistSample (rest t') y'\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSampleUpDown gw) endPointSample (midpoints t') e'\n         Left (Right (Right ((t',y'),(_,l'),(_,h')))) -> do\n           let ln = dim $ snd $ t'\n               xmin_ix = findMinIdx (snd t') xmin 0 (ln-1)\n               rest (m,v) = (m,subVector 1 (dim v - 1) v)\n               x0 = (snd t') @> xmin_ix\n               y0 = 0\n           renderSamples xscale yscale xmin xmax sd (Just $ C.moveTo x0 y0) (renderHistSample bw bc c) endHistSample (rest t') y'\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample gw Bot) endPointSample (midpoints t') l'\n           renderSamples xscale yscale xmin xmax sd Nothing (renderPointSample gw Top) endPointSample (midpoints t') h'\n         _  -> error \"Data.hs renderSeries: cannot have MinMax data series with histogram type\"\n    (DecCand bt)  \u2192 do\n       (bw,bc,c) <- formatBarSeries bt\n       case dat of \n         Left _ -> error \"Candles series requires two data series (MinMax series)\"\n         Right (Left (t',y')) -> do\n           renderMinMaxSamples xscale yscale xmin xmax sd Nothing (renderCandleSample bw bc c) endCandleSample t' y'\n         Right (Right ((t',y'),(_,e'))) -> do\n           renderMinMaxSamples xscale yscale xmin xmax sd Nothing (renderWhiskerSample bw bc c False) endWhiskerSample t' e'\n           renderMinMaxSamples xscale yscale xmin xmax sd Nothing (renderCandleSample bw bc c) endCandleSample t' y'\n    (DecWhisk bt)  \u2192 do\n      (bw,bc,c) <- formatBarSeries bt\n      case dat of \n        Left _ -> error \"Candles series requires two data series (MinMax series)\"\n        Right (Left (t',y')) -> do\n          renderMinMaxSamples xscale yscale xmin xmax sd Nothing (renderCandleSample bw bc c) endCandleSample t' y'\n        Right (Right ((t',y'),(_,e'))) -> do\n          renderMinMaxSamples xscale yscale xmin xmax sd Nothing (renderWhiskerSample bw bc c True) endWhiskerSample t' e'\n          renderMinMaxSamples xscale yscale xmin xmax sd Nothing (renderCandleSample bw bc c) endCandleSample t' y'\n  return ()\n\n-----------------------------------------------------------------------------\n\nrenderSamples :: Double -> Double \n              -> Double -> Double \n              -> SampleData\n              -> Maybe (C.Render ())\n              -> (Double -> Double -> Double -> Double -> C.Render ()) -> (Double -> Double -> C.Render ())\n              -> (Bool,Vector Double) -> Vector Double -> Render ()\nrenderSamples xscale yscale xmin xmax sd s f e (mono,t) y = do\n  (BoundingBox _ _ w _) <- get\n  let ln = dim t\n      (xmin_ix,xmax_ix,num_pts) = if mono\n                                  then (findMinIdx t xmin 0 (ln-1)\n                                       ,findMaxIdx t xmax (ln-1) 0\n                                       ,xmax_ix - xmin_ix + 1)\n                                  else (0,ln-1,ln)\n      diff'' = floor $ (fromIntegral num_pts)/w\n      diff' = if diff'' <= 1 then 1 else diff''\n      diff = if mono then if sd then diff' else 1 else 1\n  cairo $ do\n    case s of\n      Nothing -> C.moveTo ((t @> xmin_ix)*xscale) ((y @> xmin_ix)*yscale)\n      Just s' -> s'\n    _ <- runMaybeT $ do\n            mapVectorWithIndexM_ (\\j y' -> do\n               when (j >= xmin_ix && j `mod` diff == 0)\n                        (renderSample j xmax_ix t (f xscale yscale) y')\n               return ()) y\n    (e xscale yscale)\n\n-----------------------------------------------------------------------------\n\nrenderMinMaxSamples :: Double -> Double \n              -> Double -> Double \n              -> SampleData\n              -> Maybe (C.Render ())\n              -> (Double -> Double -> Double -> (Double,Double) -> C.Render ()) -> (Double -> Double -> C.Render ())\n              -> (Bool,Vector Double) -> (Vector Double,Vector Double) -> Render ()\nrenderMinMaxSamples xscale yscale xmin xmax sd s f e (mono,t) y = do\n  (BoundingBox _ _ w _) <- get\n  let ln = dim t\n      (xmin_ix,xmax_ix,num_pts) = if mono\n                                  then (findMinIdx t xmin 0 (ln-1)\n                                       ,findMaxIdx t xmax (ln-1) 0\n                                       ,xmax_ix - xmin_ix + 1)\n                                  else (0,ln-1,ln)\n      diff'' = floor $ (fromIntegral num_pts)/w\n      diff' = if diff'' <= 1 then 1 else diff''\n      diff = if mono then if sd then diff' else 1 else 1\n  cairo $ do\n    case s of\n      Nothing -> C.moveTo ((t @> xmin_ix)*xscale) (((fst $ y) @> xmin_ix)*yscale)\n      Just s' -> s'\n    _ <- runMaybeT $ mapVectorWithIndexM_ (\\j t' -> do\n        when (j >= xmin_ix && j `mod` diff == 0)\n           (renderMinMaxSample j xmax_ix t' (f xscale yscale) (e xscale yscale) y)\n        return ()) t\n    return ()\n\n-----------------------------------------------------------------------------\n\nrenderSample :: Int -> Int -> Vector Double \n             -> (Double -> Double -> C.Render ())\n             -> Double -> MaybeT C.Render ()\nrenderSample ix xmax_ix t f y\n    | ix >= xmax_ix            = do\n                                lift $ f (t @> ix) y\n                                fail \"end of bounded area\"\n    | otherwise               = do\n                                lift $ f (t @> ix) y\n\nrenderMinMaxSample :: Int -> Int -> Double \n             -> (Double -> (Double,Double) -> C.Render ()) -> C.Render () \n             -> (Vector Double,Vector Double) -> MaybeT C.Render ()\nrenderMinMaxSample ix xmax_ix t f e (yl,yu)\n    | ix >= xmax_ix            = do\n                                lift $ do\n                                       f t (yl @> ix,yu @> ix)\n                                       e\n                                fail \"end of bounded area\"\n    | otherwise               = do\n                                lift $ f t (yl @> ix,yu @> ix)\n\n-----------------------------------------------------------------------------\n\nrenderLineSample :: Double \u2192 Double -> Double -> Double -> C.Render ()\nrenderLineSample xscale yscale x y = C.lineTo (x*xscale) (y*yscale)\n\nendLineSample :: Double -> Double -> C.Render ()\nendLineSample _ _ = C.stroke\n\nrenderPointSample :: LineWidth -> Glyph -> Double -> Double -> Double -> Double -> C.Render ()\nrenderPointSample pz g xscale yscale x y = do\n  C.moveTo (x*xscale) (y*yscale)\n  renderGlyph pz g\n\nrenderPointSampleUpDown :: LineWidth -> Double -> Double -> Double -> Double -> C.Render ()\nrenderPointSampleUpDown pz xscale yscale x y = do\n  C.moveTo (x*xscale) (y*yscale)\n  renderGlyph pz (if y < 0 then Bot else Top)\n\nendPointSample :: Double -> Double -> C.Render ()\nendPointSample _ _ = return ()\n\nrenderImpulseSample :: Double -> Double -> Double -> Double -> C.Render ()\nrenderImpulseSample xscale yscale x y = do\n  let x' = x*xscale\n  C.moveTo x' 0\n  C.lineTo x (y*yscale)\n  C.stroke\n\nendImpulseSample :: Double -> Double -> C.Render ()\nendImpulseSample _ _ = return ()\n\nrenderStepSample :: Double -> Double -> Double -> Double -> C.Render ()\nrenderStepSample xscale yscale x y = do\n  (x',_) <- C.getCurrentPoint\n  let y' = y*yscale\n  C.lineTo x'         y'\n  C.lineTo (x*xscale) y'\n\nendStepSample :: Double -> Double -> C.Render ()\nendStepSample _ _ = C.stroke\n\nrenderAreaSample :: Double -> Double -> Double -> Double -> C.Render ()\nrenderAreaSample xscale yscale x y = C.lineTo (x*xscale) (y*yscale)\n\nendAreaSample :: Double -> Double -> Double -> Double -> C.Render ()\nendAreaSample x0 _ xscale _ = do\n  (x',_) <- C.getCurrentPoint\n  let x0' = x0*xscale\n  C.lineTo x'  0\n  C.lineTo x0' 0\n  -- C.lineTo x0 y0\n  C.closePath\n  C.fill\n  C.stroke\n\nrenderBarSample :: Width -> Color -> Color -> Double -> Double -> Double -> Double -> C.Render ()\nrenderBarSample bw c bc xscale yscale x y = do\n  setColour bc\n  C.rectangle ((x*xscale)-bw/2) 0 bw (y*yscale)\n  C.strokePreserve\n  setColour c\n  C.fill\n                                 \nendBarSample :: Double -> Double -> C.Render ()\nendBarSample _ _ = return ()\n\nrenderHistSample :: Width -> Color -> Color -> Double -> Double -> Double -> Double -> C.Render ()\nrenderHistSample _ c bc xscale yscale x y = do\n  (x',_) <- C.getCurrentPoint\n  let x'' = x*xscale\n  C.stroke\n  setColour bc\n  C.rectangle x' 0 (x''-x') (y*yscale)\n  C.strokePreserve\n  setColour c\n  C.fill\n  C.moveTo x'' 0\n\nendHistSample :: Double -> Double -> C.Render ()\nendHistSample _ _ = return ()\n\nrenderCandleSample :: Width -> Color -> Color -> Double -> Double -> Double -> (Double,Double) -> C.Render ()\nrenderCandleSample bw c bc xscale yscale x (yl,yu) = do\n  setColour bc\n  let (yl',yu') = (yl*yscale,yu*yscale)\n  C.rectangle ((x*xscale)-bw/2) yl' bw (yu'-yl')\n  C.strokePreserve\n  if (yl < yu)\n     then do\n       setColour c\n     else do\n       C.setSourceRGBA 1 1 1 1\n  C.fill\n\nendCandleSample :: Double -> Double -> C.Render ()\nendCandleSample _ _ = return ()\n\nrenderWhiskerSample :: Width -> Color -> Color \u2192 Bool -> Double -> Double -> Double -> (Double,Double) -> C.Render ()\nrenderWhiskerSample bw _ bc whiskers xscale yscale x (yl,yu) = do\n  setColour bc\n  let (x',yl',yu') = (x*xscale,yl*yscale,yu*yscale)\n  C.moveTo x' yl'\n  C.lineTo x' yu'\n  if whiskers\n     then do\n       C.moveTo (x'-bw/2) yu'\n       C.lineTo (x'+bw/2) yu'\n       C.moveTo (x'-bw/2) yl'\n       C.lineTo (x'+bw/2) yl'\n     else return ()\n  C.stroke\n\nendWhiskerSample :: Double -> Double -> C.Render ()\nendWhiskerSample _ _ = return ()\n\n-----------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "1a2a7ed4e299a3fc59d69148181183a758b89ee3", "size": 28178, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Graphics/Rendering/Plot/Render/Plot/Data.hs", "max_stars_repo_name": "tsurucapital/plot", "max_stars_repo_head_hexsha": "e1bfddcac26acdcc782c9ed11ed8554bdae3b1cd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-29T23:36:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T23:36:19.000Z", "max_issues_repo_path": "lib/Graphics/Rendering/Plot/Render/Plot/Data.hs", "max_issues_repo_name": "tsurucapital/plot", "max_issues_repo_head_hexsha": "e1bfddcac26acdcc782c9ed11ed8554bdae3b1cd", "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": "lib/Graphics/Rendering/Plot/Render/Plot/Data.hs", "max_forks_repo_name": "tsurucapital/plot", "max_forks_repo_head_hexsha": "e1bfddcac26acdcc782c9ed11ed8554bdae3b1cd", "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": 43.8909657321, "max_line_length": 135, "alphanum_fraction": 0.5652636809, "num_tokens": 7608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.22858879395031229}}
{"text": "module Fungine.Graphics.Texture where\nimport Fungine.Prelude\nimport Fungine.Graphics.RGBA\nimport Numeric.LinearAlgebra\ndata Texture = StaticImage (Matrix RGBA)\n", "meta": {"hexsha": "6381901c3ade78bcaa78065f495b4c8ee41f8a9f", "size": 160, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fungine/Graphics/Texture.hs", "max_stars_repo_name": "jmdurr/fungine", "max_stars_repo_head_hexsha": "21e92efc7abe61317eb8c098bc8a566583986242", "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/Fungine/Graphics/Texture.hs", "max_issues_repo_name": "jmdurr/fungine", "max_issues_repo_head_hexsha": "21e92efc7abe61317eb8c098bc8a566583986242", "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/Fungine/Graphics/Texture.hs", "max_forks_repo_name": "jmdurr/fungine", "max_forks_repo_head_hexsha": "21e92efc7abe61317eb8c098bc8a566583986242", "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": 26.6666666667, "max_line_length": 40, "alphanum_fraction": 0.85, "num_tokens": 38, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2284983035006683}}
{"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": "-- |\n-- Module      : BattleHack.Render\n-- Description :\n-- Copyright   : (c) Jonatan H Sundqvist, 2015\n-- License     : MIT\n-- Maintainer  : Jonatan H Sundqvist\n-- Stability   : experimental\n-- Portability : POSIX\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- GHC pragmas\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n--------------------------------------------------------------------------------------------------------------------------------------------\nmodule BattleHack.Render where\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n--------------------------------------------------------------------------------------------------------------------------------------------\nimport Control.Monad (forM_, liftM, when)\nimport Control.Lens\nimport Control.Applicative\nimport Data.Complex\nimport Data.Fixed (mod')\nimport qualified Data.Set as S\n\nimport qualified Graphics.Rendering.Cairo as Cairo\n\nimport BattleHack.Types\nimport BattleHack.Lenses\nimport BattleHack.Utilities.Vector\nimport BattleHack.Utilities.General\nimport BattleHack.Utilities.Math\nimport qualified BattleHack.Piano as Piano\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- Data\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- General rendering functions -------------------------------------------------------------------------------------------------------------\n-- |\npolygon :: [Complex Double] -> Cairo.Render ()\npolygon (p:oints) = vectorise Cairo.moveTo p >> forM_ (oints) (vectorise Cairo.lineTo) >> Cairo.closePath\n\n\n-- Piano -----------------------------------------------------------------------------------------------------------------------------------\n-- |\n-- TODO: Create utility functions for significant key layout points\nkey :: PianoSettings -> Int -> Cairo.Render ()\nkey piano i = do\n  polygon . map (+Piano.keyorigin piano i) $ keylayout\n  let (r, g, b, a) = colour i in Cairo.setSourceRGBA r g b a\n  Cairo.fill\n\n  keylabel piano i\n  Cairo.fill\n  where\n    keylayout = Piano.layout (piano-->keysize) (piano-->indent) (piano-->mid) (Piano.keylayout i) :: [Complex Double]\n    colour ikey\n      | (piano-->keys) !! ikey            = (0.3, 0.12, 0.22, 1.0)\n      | Just ikey == (piano-->active)     = (0.3, 0.12, 0.22, 1.0)\n      | mod ikey 12 `elem` Piano.naturals = (0.4, 1/7 * fromIntegral (ikey `mod` 7), 0.75, 1.00)\n      | otherwise                         = (0.0, 0.0,                               0.00, 1.00)\n\n\n-- |\nkeylabel :: PianoSettings -> Int -> Cairo.Render ()\nkeylabel piano i = do\n  Cairo.setFontSize (if (i `mod` 12) `elem` Piano.naturals then 48 else 22)\n  Cairo.selectFontFace \"Old English\" Cairo.FontSlantNormal Cairo.FontWeightNormal\n  Cairo.setSourceRGBA 0.20 0.12 0.08 1.00\n  centredText (Piano.keyorigin piano i + o + dotwise (*) sz (0.5:+0.90)) (Piano.notenameFromKeyIndex i)\n  where\n    (o, sz) = Piano.keybounds piano (Piano.keylayout i)\n\n\n-- |\nclaviature :: PianoSettings -> Cairo.Render ()\nclaviature settings = do\n  forM_ (zipWith const [0..] (settings-->keys)) $ \\i -> do\n    key settings i\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- |\nsinewave :: AppState -> Cairo.Render ()\nsinewave appstate = do\n  vectorise Cairo.moveTo o\n  forM_ [o + (\u03b8:+(48*sin (fromIntegral n/ fromIntegral fps')*sin (\u03b8*0.04))) | \u03b8 <- [0,5..600]] (vectorise Cairo.lineTo)\n  Cairo.setLineWidth 12\n  Cairo.setSourceRGBA 0.62 0.94 0.44 1.0\n  Cairo.stroke\n  where\n    o    = 6.32 * 50:+50\n    n    = appstate-->animation.frame\n    fps' = appstate-->animation.fps\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- |\ndebugHUD :: AppState -> Cairo.Render ()\ndebugHUD appstate = do\n  Cairo.setFontSize 14\n  Cairo.selectFontFace \"Helvetica\" Cairo.FontSlantNormal Cairo.FontWeightNormal\n  Cairo.setSourceRGBA 0.05 0.59 0.62 1.00\n\n  let keywidth = appstate-->piano.keysize.real\n  when (Piano.insideLeft (appstate-->piano) $ (mouse' & real %~ flip mod' keywidth)) $ do\n    centredText (100:+30) \"Inside left\"\n\n  when (Piano.insideRight (appstate-->piano) $ (mouse' & real %~ flip mod' keywidth)) $ do\n    centredText (100:+45) \"Inside right\"\n\n  maybe pass (\\i -> centredText (100:+60) $ Piano.notenameFromKeyIndex i) (appstate-->piano.active)\n  -- when (Piano.insideLeft (appstate-->piano) $ (mouse' & real %~ flip mod' keywidth)) $ do\n    -- centredText (appstate-->piano.origin + (100:+30)) \"Inside left\"\n\n  where\n    mouse' = appstate-->inputstate.mouse\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n-- |\ntextsize :: String -> Cairo.Render Vector\ntextsize text = do\n  extents <- Cairo.textExtents text\n  return $ Cairo.textExtentsWidth extents :+ Cairo.textExtentsHeight extents\n\n\n-- | Borrowed from Southpaw\n-- TODO: General anchor (?)\ncentredText :: Vector -> String -> Cairo.Render ()\ncentredText centre text = do\n  size <- textsize text\n  vectorise Cairo.moveTo $ centre - 0.5*size\n  Cairo.showText text\n\n\n-- Experiments  ----------------------------------------------------------------------------------------------------------------------------\n\n-- |\nradial :: AppState -> Cairo.Render ()\nradial appstate = Cairo.withRadialPattern a b c d e f $ \\ pattern -> do\n  Cairo.patternAddColorStopRGBA pattern 0 1 1 1 1\n  Cairo.patternAddColorStopRGBA pattern 1 0 0 0 1\n  Cairo.setSource pattern\n  Cairo.arc mx my 76.8 0 (2*\u03c0)\n  Cairo.fill\n\n  Cairo.arc mx my 76.8 0 (2*\u03c0)\n  Cairo.setSourceRGBA 0.0 0.0 0.0 1.0\n  Cairo.setLineWidth  12\n  Cairo.stroke\n  where\n    (mx:+my) = appstate-->inputstate.mouse\n    [a, b, c, d, e, f] = [115.2, 102.4, 25.6, 102.4, 102.4, 128.0]\n\n\n-- Menu ------------------------------------------------------------------------------------------------------------------------------------\n\n-- |\noverlay :: AppState -> Cairo.Render ()\noverlay appstate = do\n  -- TODO: Writing animation\n  -- Cairo.setOperator Cairo.OperatorDestIn\n  Cairo.setFontSize 180\n  Cairo.selectFontFace (\"Verdana\" :: String) Cairo.FontSlantNormal Cairo.FontWeightBold\n  Cairo.setSourceRGBA 1.0 1.0 1.0 0.8\n  -- centredText ((winx:+winy) * 0.5) \"CHORDIAL\"\n  -- Cairo.setLineWidth 12\n  size' <- textsize \"CUERDIAL\"\n  vectorise Cairo.moveTo $ (winsize - size') * 0.5\n  Cairo.textPath \"CUERDIAL\"\n  Cairo.clip\n  -- Cairo.stroke\n  where\n    winsize = dotwise (*) (appstate-->piano.keysize) (7:+1) + 2*(appstate-->piano.origin) -- TODO: Find canvas size directly\n\n\n-- Menu ------------------------------------------------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "15ed6fdaa06fdbf90c2f34459d3e9d61a87eafe4", "size": 7627, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/BattleHack/Render.hs", "max_stars_repo_name": "SwiftsNamesake/BattleHack-2015", "max_stars_repo_head_hexsha": "14b47f3482dc80ee1469161a0cebb5a0e1b16a05", "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": "src/BattleHack/Render.hs", "max_issues_repo_name": "SwiftsNamesake/BattleHack-2015", "max_issues_repo_head_hexsha": "14b47f3482dc80ee1469161a0cebb5a0e1b16a05", "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": "src/BattleHack/Render.hs", "max_forks_repo_name": "SwiftsNamesake/BattleHack-2015", "max_forks_repo_head_hexsha": "14b47f3482dc80ee1469161a0cebb5a0e1b16a05", "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": 38.7157360406, "max_line_length": 140, "alphanum_fraction": 0.4537826144, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22590486000420426}}
{"text": "-- | Reanimate Fuckery\nmodule CalamityBot.Commands.Reanimate\n    ( reanimateGroup,\n    ) where\n\nimport Calamity.Commands as C\nimport Calamity.Commands.Context (FullContext)\nimport Calamity\nimport CalamityBot.Utils.Reanimate\nimport qualified Data.Text as T\nimport qualified Polysemy as P\nimport Reanimate\nimport Reanimate.Render (Format(RenderWebm, RenderGif), Raster(RasterAuto))\n\nimport           Data.Complex\nimport           Graphics.SvgTree\nimport qualified Graphics.SvgTree.Types\nimport           Linear.V2\nimport           Codec.Picture\nimport qualified Data.ByteString as B\nimport Network.Mime (defaultMimeLookup)\nimport Control.Lens\nimport Network.Wreq\n\nprotectText :: T.Text -> T.Text\nprotectText = T.concatMap (fromString . protectChar)\n\nprotectChar :: Char -> String\nprotectChar '#'  = \"\\\\#\"\nprotectChar '$'  = \"\\\\$\"\nprotectChar '%'  = \"\\\\%\"\nprotectChar '^'  = \"\\\\^{}\"\nprotectChar '&'  = \"\\\\&\"\nprotectChar '{'  = \"\\\\{\"\nprotectChar '}'  = \"\\\\}\"\nprotectChar '~'  = \"\\\\~{}\"\nprotectChar '\\\\' = \"\\\\textbackslash{}\"\nprotectChar '_'  = \"\\\\_{}\"\nprotectChar x = [x]\n\n\nrenderText :: T.Text -> Animation\nrenderText text =\n  let rt = center . latex $ text\n      rtRotated = mkAnimation 5 (\\t -> rotateAroundCenter (t * 360) rt)\n  in addStatic (mkBackground \"white\") rtRotated\n\nfindSVG :: [Attachment] -> Maybe Attachment\nfindSVG = listToMaybe . filter (\\a -> \"image/svg\" `B.isPrefixOf` defaultMimeLookup (a ^. #filename))\n\nusableTree :: Tree -> Bool\nusableTree None = False\nusableTree (UseTree _ _) = False\nusableTree (DefinitionTree _) = False\nusableTree _ = True\n\nreanimateGroup :: BotC r => P.Sem (DSLState FullContext r) ()\nreanimateGroup = void\n  . help (const \"Commands related to reanimate fuckery\")\n  . C.group \"reanimate\"\n  $ do\n    help (const \"Render a message\") $\n      command @'[KleenePlusConcat T.Text] \"render\" \\ctx msg -> do\n        let anim = renderText msg\n        r <- P.embed $ renderToMemory anim RasterAuto RenderWebm 400 400 30\n        case r of\n          Right s -> do\n            void $ tell ctx (TFile \"lol.webm\" s)\n          Left e ->\n            putLBSLn $ \"Failed with reason: \" <> e\n\n    help (const \"Render a fourier thing of an svg\") $\n      command @'[] \"renders\" \\ctx -> do\n        case findSVG (ctx ^. #message . #attachments) of\n          Just svg -> do\n            r <- P.embed $ Network.Wreq.get (T.unpack $ svg ^. #url)\n            let file = r ^. responseBody\n            let Just doc = parseSvgFile \"a.svg\" (decodeUtf8 file)\n            let tree = head . fromList . filter usableTree $ doc ^. Graphics.SvgTree.Types.documentElements\n            let f = mkSVGLatex $ flipYAxis tree\n            let anim = setDuration 20 $ scene $ do\n                  _ <- newSpriteSVG $ mkBackgroundPixel (PixelRGBA8 252 252 252 0xFF)\n                  play $ fourierA f (fromToS 0 5)      -- Rotate 15 times\n                    & setDuration 30\n                    & signalA (reverseS . powerS 2 . reverseS) -- Start fast, end slow\n                    & pauseAtEnd 2\n                  play $ fourierA f (constantS 0)       -- Don't rotate at all\n                    & setDuration 10\n                    & reverseA\n                    & signalA (powerS 2)                       -- Start slow, end fast\n                    & pauseAtEnd 2\n            r <- P.embed $ renderToMemory anim RasterAuto RenderGif 480 360 15\n            case r of\n              Right s -> do\n                void $ tell ctx (TFile \"lol.gif\" s)\n              Left e ->\n                putLBSLn $ \"Failed with reason: \" <> e\n          Nothing ->\n            void $ tell @T.Text ctx \"Couldn't find an svg\"\n\n    help (const \"Render a fourier thing\") $\n      command @'[KleenePlusConcat T.Text] \"renderf\" \\ctx msg -> do\n        let f = mkFourierLatex msg\n        let anim = setDuration 20 $ scene $ do\n              _ <- newSpriteSVG $ mkBackgroundPixel (PixelRGBA8 252 252 252 0xFF)\n              play $ fourierA f (fromToS 0 5)      -- Rotate 15 times\n                & setDuration 30\n                & signalA (reverseS . powerS 2 . reverseS) -- Start fast, end slow\n                & pauseAtEnd 2\n              play $ fourierA f (constantS 0)       -- Don't rotate at all\n                & setDuration 10\n                & reverseA\n                & signalA (powerS 2)                       -- Start slow, end fast\n                & pauseAtEnd 2\n        r <- P.embed $ renderToMemory anim RasterAuto RenderGif 480 360 15\n        case r of\n          Right s -> do\n            void $ tell ctx (TFile \"lol.gif\" s)\n          Left e ->\n            putLBSLn $ \"Failed with reason: \" <> e\n\nscaleToFit :: Double -> Double -> Tree -> Tree\nscaleToFit w h t =\n  let oh = svgHeight t\n      ow = svgWidth t\n  in scale (min (w / ow) (h / oh)) t\n\n-- layer 2\nfourierA :: Fourier -> (Double -> Double) -> Animation\nfourierA f genPhi = animate $ \\t ->\n    let circles = setFourierLength (t* fourierLen f) f\n        coeffs = fourierCoefficients $ rotateFourier (genPhi t) circles\n    in mkGroup\n    [ drawCircles coeffs\n    , withStrokeColor \"green\" $\n      withStrokeLineJoin JoinRound $\n      withFillOpacity 0 $\n      withStrokeWidth (defaultStrokeWidth*2) $\n      mkLinePath $ mkFourierOutline circles\n    , let x :+ y = sum coeffs in\n      translate x y $ withFillColor \"red\" $ mkCircle (defaultStrokeWidth*3)\n    ]\n\ndrawCircles :: [Complex Double] -> SVG\ndrawCircles [] = mkGroup []\ndrawCircles ( x :+ y : xs) =\n  translate x y $ drawCircles' xs\n\ndrawCircles' :: [Complex Double] -> SVG\ndrawCircles' circles = mkGroup\n    [ worker circles\n    , withStrokeColor \"black\" $\n      withStrokeLineJoin JoinRound $\n      withFillOpacity 0 $\n      mkLinePath [ (x, y) | x :+ y <- scanl (+) 0 circles ]]\n  where\n    worker [] = None\n    worker (x :+ y : rest) =\n      let radius = sqrt(x*x+y*y) in\n      mkGroup\n      [ withStrokeColor \"dimgrey\" $\n        withFillOpacity 0 $\n        mkCircle radius\n      , translate x y $ worker rest ]\n\n-- layer 1\nnewtype Fourier = Fourier {fourierCoefficients :: [Complex Double]}\n\nmkSVGLatex :: Tree -> Fourier\nmkSVGLatex t = mkFourier $ lineToPoints 500 $\n  toLineCommands $ extractPath $ center $ scaleToFit 9.6 7.2 $ t\n\nmkFourierLatex :: T.Text -> Fourier\nmkFourierLatex t = mkFourier $ lineToPoints 500 $\n  toLineCommands $ extractPath $ center $ scaleToFit 9.6 7.2 $ latex t\n\nfourierLen :: Fourier -> Double\nfourierLen f = sum $ map magnitude $ drop 1 $ take 500 $ fourierCoefficients f\n\npointAtFourier :: Fourier -> Complex Double\npointAtFourier = sum . fourierCoefficients\n\nmkFourier :: [RPoint] -> Fourier\nmkFourier points = Fourier $ findCoefficient 0 :\n    concat [ [findCoefficient n, findCoefficient (-n)] | n <- [1..] ]\n  where\n    findCoefficient :: Int -> Complex Double\n    findCoefficient n =\n        sum [ toComplex point * exp (negate (fromIntegral n) * 2 *pi * i*t) * deltaT\n            | (idx, point) <- zip [0::Int ..] points, let t = fromIntegral idx/nPoints ]\n    i = 0 :+ 1\n    toComplex (V2 x y) = x :+ y\n    deltaT = recip nPoints\n    nPoints = fromIntegral (length points)\n\nsetFourierLength :: Double -> Fourier -> Fourier\nsetFourierLength _ (Fourier []) = Fourier []\nsetFourierLength len0 (Fourier (first:lst)) = Fourier $ first : worker len0 lst\n  where\n    worker _len [] = []\n    worker len (c:cs) =\n      if magnitude c < len\n        then c : worker (len - magnitude c) cs\n        else [c * realToFrac (len / magnitude c)]\n\nrotateFourier :: Double -> Fourier -> Fourier\nrotateFourier phi (Fourier coeffs) =\n    Fourier $ worker coeffs (0::Integer)\n  where\n    worker [] _ = []\n    worker (x:rest) 0 = x : worker rest 1\n    worker [left] n = worker [left,0] n\n    worker (left:right:rest) n =\n      let n' = fromIntegral n in\n      left * exp (negate n' * 2 * pi * i * phi') :\n      right * exp (n' * 2 * pi * i * phi') :\n      worker rest (n+1)\n    i = 0 :+ 1\n    phi' = realToFrac phi\n\nmkFourierOutline :: Fourier -> [(Double, Double)]\nmkFourierOutline fourier =\n    [ (x, y)\n    | idx <- [0 .. granularity]\n    , let x :+ y = pointAtFourier $ rotateFourier (idx/granularity) fourier\n    ]\n  where\n    granularity = 500\n", "meta": {"hexsha": "4c9f2a9603f0e71ca5a7c6493ebb2430749cf258", "size": 8067, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CalamityBot/Commands/Reanimate.hs", "max_stars_repo_name": "simmsb/calamity-bot", "max_stars_repo_head_hexsha": "8f7f3585d8a799166040f012b2ccea6b484722d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-29T02:58:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-30T00:25:22.000Z", "max_issues_repo_path": "src/CalamityBot/Commands/Reanimate.hs", "max_issues_repo_name": "simmsb/calamity-bot", "max_issues_repo_head_hexsha": "8f7f3585d8a799166040f012b2ccea6b484722d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-27T03:49:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-14T07:55:07.000Z", "max_forks_repo_path": "src/CalamityBot/Commands/Reanimate.hs", "max_forks_repo_name": "simmsb/calamity-bot", "max_forks_repo_head_hexsha": "8f7f3585d8a799166040f012b2ccea6b484722d0", "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": 35.2270742358, "max_line_length": 107, "alphanum_fraction": 0.6007189786, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22546262429762703}}
{"text": "{-# LANGUAGE DeriveFoldable    #-}\n{-# LANGUAGE DeriveFunctor     #-}\n{-# LANGUAGE DeriveGeneric     #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TemplateHaskell   #-}\n\nmodule Bench where\n\nimport           Control.Lens                    (set)\nimport           Control.Lens.Operators\nimport           Control.Lens.TH\nimport           Criterion\nimport           Criterion.Types                 (Regression (..), Report (..),\n                                                  SampleAnalysis (..))\nimport qualified Data.Binary                     as Bin\nimport qualified Data.ByteString.Lazy            as B\nimport           Data.Csv\nimport qualified Data.Map.Lazy                   as Map\nimport           Data.Maybe                      (fromJust)\nimport           Data.Monoid                     ((<>))\nimport qualified Data.Text                       as T\nimport qualified Data.Text.Encoding              as T\nimport           GHC.Generics                    (Generic)\nimport           Statistics.Resampling.Bootstrap (Estimate (..))\n\n\ndata Bench a = Bench {\n      _benchDescription :: T.Text\n    , _benchData        :: [(Double, a)]\n    }\n    deriving (Functor, Generic, Show, Foldable, Traversable)\n\nmakeLenses ''Bench\n\ndata BenchGroup a = BenchGroup {\n      _bgId          :: T.Text\n    , _bgDescription :: T.Text\n    , _bgBenches     :: [Bench a]\n    , _bgXAxisName   :: T.Text\n    }\n    deriving (Functor, Generic, Show, Foldable, Traversable)\n\nmakeLenses ''BenchGroup\n\ninstance Bin.Binary a => Bin.Binary (Bench a)\ninstance Bin.Binary a => Bin.Binary (BenchGroup a)\n\nrunBenchGroup :: BenchGroup Benchmarkable -> IO (BenchGroup Report)\nrunBenchGroup group = do\n    putStrLn $ \"Benchmarking group: \" <> T.unpack (group ^. bgDescription) <>\n               \" (\" <> T.unpack (group ^. bgId) <> \")\"\n    results <- mapM describeAndRun (group ^. bgBenches)\n    return $ set bgBenches results group\n\ndescribeAndRun :: Bench Benchmarkable -> IO (Bench Report)\ndescribeAndRun bench = do\n    putStrLn $ \"Running benchmark: \" <> T.unpack (bench ^. benchDescription)\n    mapM benchAndRetry bench\n  where\n    benchAndRetry singleBench = do\n        result <- benchmark' singleBench\n        if getRSquared result < 0.99\n            then putStrLn \"R^2 < 0.99 => RETRY!\" >> benchAndRetry singleBench\n            else return result\n\ngetOLS :: Report -> Double\ngetOLS = estPoint . fromJust . Map.lookup \"iters\" . regCoeffs . head . anRegress . reportAnalysis\n\ngetRSquared :: Report -> Double\ngetRSquared = estPoint . regRSquare . head . anRegress . reportAnalysis\n\ngetMean :: Report -> Double\ngetMean = estPoint . anMean . reportAnalysis\n\ngetHeader :: BenchGroup a -> [T.Text]\ngetHeader group = [\"framework\", group ^. bgXAxisName, \"time\"]\n\ngetMeasurements :: Bench a -> [Measurement a]\ngetMeasurements bench =\n    map (\\(x, y) -> Measurement (bench ^. benchDescription) x y)\n        (bench ^. benchData)\n\ndata Measurement a = Measurement {\n      _mLabel  :: T.Text\n    , _mXValue :: Double\n    , _mYValue :: a\n    }\n    deriving (Functor, Generic, Show)\n\nmakeLenses ''Measurement\n\ninstance ToField a => ToRecord (Measurement a)\n\ntoCsv :: ToField a => BenchGroup a -> B.ByteString\ntoCsv group =\n       B.intercalate \",\" (map (B.fromStrict . T.encodeUtf8) (getHeader group))\n    <> \"\\n\"\n    <> encode (concatMap getMeasurements (group ^. bgBenches))\n", "meta": {"hexsha": "4d5df56376b3567d57fb53a4f906c7abe1d6230a", "size": 3376, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Bench.hs", "max_stars_repo_name": "jaaket/dippa-bench", "max_stars_repo_head_hexsha": "93c088e1ff039fa33388ccdb3817a79515d63180", "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/Bench.hs", "max_issues_repo_name": "jaaket/dippa-bench", "max_issues_repo_head_hexsha": "93c088e1ff039fa33388ccdb3817a79515d63180", "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/Bench.hs", "max_forks_repo_name": "jaaket/dippa-bench", "max_forks_repo_head_hexsha": "93c088e1ff039fa33388ccdb3817a79515d63180", "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": 33.76, "max_line_length": 97, "alphanum_fraction": 0.6128554502, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2245050818593929}}
{"text": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE UnboxedTuples #-}\n\n-- |\n-- Module      : PSO.Neural\n-- Description : Particle Swarm Optimisation\n-- Copyright   : (c) Tom Westerhout, 2017\n-- License     : BSD3\n-- Maintainer  : t.westerhout@student.ru.nl\n-- Stability   : experimental\nmodule PSO.Neural\n  (\n  -- mutableMcmcLoop\n  -- , energyHH1DOpen\n  -- , energyHH1DOpenC\n  -- , energyHH1DOpenMKLC\n  -- , energyHH1DOpenZ\n  -- , energyVarHH1DOpen\n  -- , RBM(..)\n    Rbm\n  , mkRbm\n  , uniformRbm\n  , IsRbm(..)\n  , fromRbm\n  , toRbm\n  , unsafeFreezeRbm\n  , unsafeThawRbm\n  , mcmcHeisenberg1D\n  -- , MCMC(..)\n  -- , unsafeFreezeMcmc\n  -- , Mcmc\n  -- , HH1DOpen(..)\n  -- , listAll\n  , Measurement(..)\n  , HasMean(..)\n  , HasVar(..)\n  ) where\n\nimport Prelude hiding (map, mapM, zipWith, zipWithM)\nimport qualified Prelude as Prelude\n\nimport Control.Exception(assert)\nimport Control.Monad (Monad(..), (>=>), (<=<))\nimport Control.Monad.Primitive\nimport Control.Monad.ST\n\nimport Data.Bits\nimport Data.Coerce\nimport Data.Complex\nimport Data.Functor.Identity\nimport Data.NumInstances.Tuple\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Storable.Mutable as MV\nimport Data.Vector.Fusion.Stream.Monadic (Stream(..), Step(..), SPEC(..))\nimport qualified Data.Vector.Fusion.Stream.Monadic as Stream\nimport qualified Data.Vector.Fusion.Bundle.Monadic as Bundle\n\nimport Foreign.C.Types\nimport Foreign.Storable\nimport Foreign.ForeignPtr\n\nimport GHC.Generics (Generic)\n\nimport Lens.Micro\nimport Lens.Micro.TH\n\nimport System.IO.Unsafe\n\nimport PSO.Internal.Neural\nimport PSO.Random\nimport PSO.Swarm\n\n\ntype family RealOf x\n\ntype instance RealOf Float = Float\n\ntype instance RealOf Double = Double\n\ntype instance RealOf CFloat = CFloat\n\ntype instance RealOf CDouble = CDouble\n\ntype instance RealOf (Complex a) = a\n\ntype family RbmCore a\n\ntype instance RbmCore Float = RbmC\n\n-- type instance RbmCore (Complex Double) = RbmZ\n\nnewtype Rbm a = R (ForeignPtr (RbmCore a)) deriving (Generic)\n\nnewtype MRbm s a = MR (ForeignPtr (RbmCore a)) deriving (Generic)\n\n\nclass Storable a => IsRbm a where\n  newRbm :: PrimMonad m => Int -> Int -> m (MRbm (PrimState m) a)\n  cloneRbm :: PrimMonad m => Rbm a -> m (MRbm (PrimState m) a)\n  getWeights :: PrimMonad m => MRbm (PrimState m) a -> m (V.MVector (PrimState m) a, V.MVector (PrimState m) a)\n  getVisible :: PrimMonad m => MRbm (PrimState m) a -> m (V.MVector (PrimState m) a, V.MVector (PrimState m) a)\n  getHidden  :: PrimMonad m => MRbm (PrimState m) a -> m (V.MVector (PrimState m) a, V.MVector (PrimState m) a)\n  sizeWeights :: Rbm a -> Int\n  sizeVisible :: Rbm a -> Int\n  sizeHidden  :: Rbm a -> Int\n  -- debugPrintRbm :: Rbm a -> IO ()\n\nunsafeThawRbm :: PrimMonad m => Rbm a -> m (MRbm (PrimState m) a)\nunsafeThawRbm (R p) = return (MR p)\n\nunsafeFreezeRbm :: PrimMonad m => MRbm (PrimState m) a -> m (Rbm a)\nunsafeFreezeRbm (MR p) = return (R p)\n\n-- setWeights :: PrimMonad m => MRbm (PrimState m) a -> V.Vector a -> V.Vector a -> m ()\n-- setWeights mrbm wR wI = do\n--   (mwR, mwI) <- getWeights mrbm\n--   V.copy mwR wR\n--   V.copy mwI wI\n-- \n-- setVisible :: PrimMonad m => MRbm (PrimState m) a -> V.Vector a -> V.Vector a -> m ()\n-- setVisible mrbm aR aI = do\n--   (maR, maI) <- getVisible mrbm\n--   V.copy maR aR\n--   V.copy maI aI\n-- \n-- setHidden :: PrimMonad m => MRbm (PrimState m) a -> V.Vector a -> V.Vector a -> m ()\n-- setHidden mrbm bR bI = do\n--   (mbR, mbI) <- getHidden mrbm\n--   V.copy mbR bR\n--   V.copy mbI bI\n\n\nfromRbm :: (Monad m, IsRbm a) => Rbm a -> Stream.Stream m a\nfromRbm rbm = Bundle.elements $ Bundle.fromVectors (runST $ unsafeThawRbm rbm >>= go)\n  where\n    go :: IsRbm a => MRbm s a -> ST s [V.Vector a]\n    go mrbm = do\n      (wR, wI) <- getWeights mrbm\n      (aR, aI) <- getVisible mrbm\n      (bR, bI) <- getHidden mrbm\n      Prelude.mapM V.freeze [wR, wI, aR, aI, bR, bI]\n\ntoRbm :: (PrimMonad m, IsRbm a) => Int -> Int -> Stream.Stream m a -> m (Rbm a)\ntoRbm n m (Stream step t) = do\n  mrbm <- newRbm n m\n  (wR, wI) <- getWeights mrbm\n  (aR, aI) <- getVisible mrbm\n  (bR, bI) <- getHidden mrbm\n  copy SPEC wR (n * m) 0 t >>=\n    copy SPEC wI (n * m) 0 >>=\n      copy SPEC aR n 0 >>=\n        copy SPEC aI n 0 >>=\n          copy SPEC bR m 0 >>=\n            copy SPEC bI m 0\n  unsafeFreezeRbm mrbm\n  where\n    copy !_ !v !size !i s\n      | i < size = step s >>= \\r ->\n        case r of\n          Yield x s' -> MV.write v i x >> copy SPEC v size (i + 1) s'\n          Skip    s' -> copy SPEC v size i s'\n          Done       -> error \"No, we're not done yet!\"\n      | otherwise = return s\n\n-- | Creates a new Restricted Boltzmann Machine with given weights.\nmkRbm :: IsRbm a\n      => V.Vector (Complex a) -- ^ Visible bias \\(a^N\\).\n      -> V.Vector (Complex a) -- ^ Hidden bias \\(a^M\\).\n      -> V.Vector (Complex a) -- ^ Weights \\(a^{M\\times N}\\). *Column-major layout is assumed!*.\n      -> Rbm a\nmkRbm a@(V.length -> nx1) b@(V.length -> mx1) w@(V.length -> mxn)\n  | mxn == nx1 * mx1 = runST $ toRbm nx1 mx1 $ Bundle.elements $\n    Bundle.fromVectors [ realPart `V.map` w, imagPart `V.map` w\n                       , realPart `V.map` a, imagPart `V.map` a\n                       , realPart `V.map` b, imagPart `V.map` b\n                       ]\n  | otherwise = error \"mkRbm: Dimensions mismatch.\"\n\n-- | Creates an RBM with weights distributed uniformly within given intervals.\nuniformRbm ::\n     (PrimMonad m, IsRbm a, Ord a, UniformDist m (Complex a))\n  => Int -- ^ Number of visible nodes.\n  -> Int -- ^ Number of hidden nodes.\n  -> (a, a) -- ^ Range for visible bias.\n  -> (a, a) -- ^ Range for hidden bias.\n  -> (a, a) -- ^ Range for weights.\n  -> m (Rbm a)\nuniformRbm !n !m !(amin, amax) !(bmin, bmax) !(wmin, wmax)\n  | n < 0 || m < 0 = error \"uniformRbm: Negative dimensions??\"\n  | amin > amax || bmin > bmax || wmin > wmax =\n    error \"uniformRbm: Lower bound is per definition not \\\n          \\greater than the upper bound.\"\n  | otherwise = do\n    a <- uniformVector n (amin :+ amin, amax :+ amin)\n    b <- uniformVector m (bmin :+ bmin, bmin :+ bmax)\n    w <- uniformVector (n * m) (wmin :+ wmin, wmax :+ wmax)\n    return $ mkRbm a b w\n\ninstance IsRbm Float where\n  {-# INLINE newRbm #-}\n  newRbm n m = unsafeIOToPrim $ MR <$> _RbmC'construct n m\n  {-# INLINE cloneRbm #-}\n  cloneRbm (R p) = unsafeIOToPrim $ MR <$> _RbmC'clone p\n  {-# INLINE getWeights #-}\n  getWeights (MR p) = _RbmC'getWeights p\n  {-# INLINE getVisible #-}\n  getVisible (MR p) = _RbmC'getVisible p\n  {-# INLINE getHidden #-}\n  getHidden (MR p) = _RbmC'getHidden p\n  {-# INLINE sizeVisible #-}\n  sizeVisible (R fp) = unsafePerformIO $\n    withForeignPtr fp (peek >=> return . _rbmC'sizeVisible)\n  {-# INLINE sizeHidden #-}\n  sizeHidden (R fp) = unsafePerformIO $\n    withForeignPtr fp (peek >=> return . _rbmC'sizeHidden)\n  {-# INLINE sizeWeights #-}\n  sizeWeights x = sizeHidden x * sizeVisible x\n\ngetDims :: IsRbm a => Rbm a -> (Int, Int)\ngetDims x = (sizeVisible x, sizeHidden x)\n{-# INLINE getDims #-}\n\nzipWithM :: (IsRbm a, IsRbm b, IsRbm c, PrimMonad m)\n         => (a -> b -> m c) -> Rbm a -> Rbm b -> m (Rbm c)\nzipWithM f x y = assert (getDims x == getDims y) $\n  toRbm (sizeVisible x) (sizeHidden x) $ Stream.zipWithM f (fromRbm x) (fromRbm y)\n\nzipWith :: forall a b c. (IsRbm a, IsRbm b, IsRbm c)\n        => (a -> b -> c) -> Rbm a -> Rbm b -> Rbm c\nzipWith f x y = runST $ zipWithM f' x y\n  where f' :: a -> b -> ST s c\n        f' a b = return $ f a b\n\nmapM :: (IsRbm a, IsRbm b, PrimMonad m)\n     => (a -> m b) -> Rbm a -> m (Rbm b)\nmapM f x = toRbm (sizeVisible x) (sizeHidden x) $ Stream.mapM f $ fromRbm x\n\nmap :: (IsRbm a, IsRbm b)\n     => (a -> b) -> Rbm a -> Rbm b\nmap f x = runST $ mapM (return . f) x\n\ninstance Num (Rbm Float) where\n  (+) x y = zipWith (+) x y\n  (-) x y = zipWith (-) x y\n  (*) x y = zipWith (*) x y\n  abs x = map abs x\n  signum x = map signum x\n  negate x = map negate x\n  fromInteger = undefined\n\ninstance Scalable Float (Rbm Float) where\n  scale \u03bb = map (*\u03bb)\n\ninstance (PrimMonad m, DeltaWell m Float Float)\n  => DeltaWell m Float (Rbm Float) where\n    upDeltaWell \u03ba p x = zipWithM (upDeltaWell \u03ba) p x\n\n{-\ninstance RBM (Complex Double) where\n  newRbm nrVis nrHid = unsafeIOToPrim $ liftM MR (_newRbmZ nrVis nrHid)\n  cloneRbm (R p) = unsafeIOToPrim $ liftM MR (_cloneRbmZ p)\n  setWeights (MR p) w = unsafeIOToPrim $ _setWeightsZ p (coerce w)\n  setVisible (MR p) a = unsafeIOToPrim $ _setVisibleZ p (coerce a)\n  setHidden (MR p) b = unsafeIOToPrim $ _setHiddenZ p (coerce b)\n  sizeVisible (R p) = _sizeVisibleZ p\n  sizeHidden (R p) = _sizeHiddenZ p\n  debugPrintRbm (R p) = _printRbmZ p\n\ninstance AXPBY (Complex Float) (Complex Float) where\n  axpby a (R x) b (MR y) = unsafeIOToPrim $ _caxpbyRbmC (coerce a) x (coerce b) y\n\ninstance AXPBY (Complex Double) (Complex Double) where\n  axpby a (R x) b (MR y) = unsafeIOToPrim $ _zaxpbyRbmZ (coerce a) x (coerce b) y\n\ninstance SCAL (Complex Float) (Complex Float) where\n  scal a (MR x) = unsafeIOToPrim $ _cscaleRbmC (coerce a) x\n\ninstance SCAL Float (Complex Float) where\n  scal a (MR x) = unsafeIOToPrim $ _cscaleRbmC (coerce a :+ 0) x\n\ninstance SCAL (Complex Double) (Complex Double) where\n  scal a (MR x) = unsafeIOToPrim $ _zscaleRbmZ (coerce a) x\n\ninstance SCAL Double (Complex Double) where\n  scal a (MR x) = unsafeIOToPrim $ _zscaleRbmZ (coerce a :+ 0) x\n\ninstance (Num a, AXPBY a a, SCAL a a) => Num (Rbm a) where\n  (+) x y = runST $ cloneRbm x >>= \\z ->\n    axpby (1 :: a) y (1 :: a) z >> unsafeFreezeRbm z\n  (-) x y = runST $ cloneRbm x >>= \\z ->\n    axpby ((-1) :: a) y (1 :: a) z >> unsafeFreezeRbm z\n  (*) x y = undefined\n  negate x = runST $ cloneRbm x >>= \\z -> scal ((-1) :: a) z >> unsafeFreezeRbm z\n  fromInteger = undefined\n  abs = undefined\n  signum = undefined\n\ninstance (SCAL \u03bb a) => Scalable \u03bb (Rbm a) where\n  scale k x = runST $ cloneRbm x >>= \\z -> scal k z >> unsafeFreezeRbm z\n\ninstance MCMC (Complex Float) where\n  newMcmc (R rbm) spin = unsafeIOToPrim $\n    _newMcmcC rbm (coerce spin) >>= \\mcmc -> return (MM mcmc rbm)\n  logWF (M p _) = coerce $ _logWFC p\n  logQuotient1 (M p _) flip1 = coerce $ _logQuotientWF1C p flip1\n  logQuotient2 (M p _) flip1 flip2 = coerce $ _logQuotientWF2C p flip1 flip2\n  propose1 m@(M p _) = (^2) . magnitude . exp . logQuotient1 m -- _proposeC1 p flip1\n  propose2 (M p _) flip1 flip2 = _propose2C p flip1 flip2\n  update1 (MM p _) flip1 = unsafeIOToPrim $ _accept1C p flip1\n  update2 (MM p _) flip1 flip2 = unsafeIOToPrim $ _accept2C p flip1 flip2\n  debugPrintMcmc (M p _) = _printMcmcC p\n\ninstance MCMC (Complex Double) where\n  newMcmc (R rbm) spin = unsafeIOToPrim $\n    _newMcmcZ rbm (coerce spin) >>= \\mcmc -> return (MM mcmc rbm)\n  logWF (M p _) = coerce $ _logWFZ p\n  logQuotient1 (M p _) flip1 = coerce $ _logQuotientWF1Z p flip1\n  logQuotient2 (M p _) flip1 flip2 = coerce $ _logQuotientWF2Z p flip1 flip2\n  propose1 m@(M p _) = (^2) . magnitude . exp . logQuotient1 m -- _proposeZ1 p flip1\n  propose2 (M p _) flip1 flip2 = _propose2Z p flip1 flip2\n  update1 (MM p _) flip1 = unsafeIOToPrim $ _accept1Z p flip1\n  update2 (MM p _) flip1 flip2 = unsafeIOToPrim $ _accept2Z p flip1 flip2\n  debugPrintMcmc (M p _) = _printMcmcZ p\n\n\nmutableMcmcLoop ::\n     (PrimMonad m)\n  => (\u03b1 -> Int -> m \u03b2)\n  -> (\u03b1 -> \u03b2 -> m Bool)\n  -> (\u03b1 -> \u03b2 -> m ())\n  -> \u03b1\n  -> Int\n  -> Producer \u03b1 m ()\nmutableMcmcLoop propose accept update \u03c8 n = do\n  proposal <- lift $ propose \u03c8 n\n  isAcceptable <- lift $ accept \u03c8 proposal\n  yield \u03c8\n  when isAcceptable (lift (update \u03c8 proposal))\n  mutableMcmcLoop propose accept update \u03c8 (n + 1)\n\nclass MCMC a => HH1DOpen a where\n  locEnergyHH1DOpen :: Mcmc a -> a\n\ninstance HH1DOpen (Complex Float) where\n  locEnergyHH1DOpen (M p _) = coerce (_locEHH1DOpenC p)\n\ninstance HH1DOpen (Complex Double) where\n  locEnergyHH1DOpen (M p _) = coerce (_locEHH1DOpenZ p)\n\nunpack2Bools :: (Num \u03b1, Bits \u03b1) => Int -> \u03b1 -> V.Vector Bool\nunpack2Bools n x = V.fromList $ doUnpack n x []\n  where doUnpack 0 _ []   = [False]\n        doUnpack 0 _ bits = bits\n        doUnpack n x bits = doUnpack (n - 1) (x `shiftR` 1) $\n                              (testBit x 0) : bits\n\nlistAll :: forall m a.\n     ( PrimMonad m\n     , HH1DOpen a\n     , Num a\n     )\n  => Rbm a -> m (V.Vector a)\nlistAll rbm =\n  let n = sizeVisible rbm\n      toSpin True  = 1\n      toSpin False = -1\n      \u03c3s :: [V.Vector a]\n      \u03c3s = V.map toSpin <$> unpack2Bools n <$> [(0 :: Int) .. (2 ^ n - 1)]\n   in V.fromList <$> (newMcmc rbm >=> unsafeFreezeMcmc >=> return . logWF) `mapM` \u03c3s\n\nenergyHH1DOpen ::\n     forall m a \u03bb.\n     ( PrimMonad m\n     , Ord (RealOf a)\n     , Fractional a\n     , HH1DOpen a\n     , Randomisable m Bool\n     , Randomisable m (RealOf a)\n     , UniformDist m Int\n     -- , MonadIO m\n     -- , a ~ Complex \u03bb\n     -- , Fractional \u03bb\n     -- , Real \u03bb\n     -- , Show \u03bb\n     )\n  => Rbm a -> Int -> Int -> m a\nenergyHH1DOpen rbm offset steps =\n  let n = sizeVisible rbm\n      proposer :: MMcmc (PrimState m) a -> Int -> m Int\n      proposer _ i = {- return (i `mod` n) -} uniform (0, n - 1)\n      acceptor :: MMcmc (PrimState m) a -> Int -> m Bool\n      acceptor mx flip = unsafeFreezeMcmc mx >>= \\x ->\n                            ((<= propose1 x flip) <$> random)\n      updater :: MMcmc (PrimState m) a -> Int -> m ()\n      updater = update1\n      func :: MMcmc (PrimState m) a -> m a\n      func = unsafeFreezeMcmc >=> return . locEnergyHH1DOpen\n      mmcmc :: m (MMcmc (PrimState m) a)\n      mmcmc = randomSpin n >>= newMcmc rbm\n      states = mutableMcmcLoop proposer acceptor updater\n   in mmcmc >>= \\mmcmc' ->\n                  (/ fromIntegral steps)\n                    <$> P.sum\n                  --     P.fold debugAdd\n                  --            (toRational 0, toRational 0)\n                  --            (\\(x, y) -> fromRational (x / toRational steps)\n                  --                         :+ fromRational (y / toRational steps))\n                             (states mmcmc' 0 >-> P.drop offset\n                                              >-> P.mapM func\n                                              >-> P.take steps)\n\nenergyHH1DOpenC :: forall m.\n     ( PrimMonad m\n     , Randomisable m Bool\n     , Randomisable m Float\n     , UniformDist m Int\n     )\n  => Rbm (Complex Float) -> Int -> Int -> m (Complex Float)\nenergyHH1DOpenC rbm offset steps =\n  let n = sizeVisible rbm\n      mmcmc = randomSpin n >>= newMcmc rbm\n      ints :: m (V.Vector Int)\n      ints = uniformVector (offset + steps) (0, n - 1)\n      floats :: m (V.Vector Float)\n      floats = V.replicateM (offset + steps) random\n   in ints >>= \\ is ->\n        floats >>= \\ fs ->\n          mmcmc >>= \\ (MM p (RbmC m)) ->\n            unsafeIOToPrim $ (_runMcmcC p offset steps is fs) >>= \\ x ->\n              touchForeignPtr m >> return (coerce x)\n\nenergyHH1DOpenZ :: forall m.\n     ( PrimMonad m\n     , Randomisable m Bool\n     , Randomisable m Double\n     , UniformDist m Int\n     )\n  => Rbm (Complex Double) -> Int -> Int -> m (Complex Double)\nenergyHH1DOpenZ rbm offset steps =\n  let n = sizeVisible rbm\n      mmcmc = randomSpin n >>= newMcmc rbm\n      ints :: m (V.Vector Int)\n      ints = uniformVector (offset + steps) (0, n - 1)\n      floats :: m (V.Vector Double)\n      floats = V.replicateM (offset + steps) random\n   in ints >>= \\ is ->\n        floats >>= \\ fs ->\n          mmcmc >>= \\ (MM p (RbmZ m)) ->\n            unsafeIOToPrim $ (_runMcmcZ p offset steps is fs) >>= \\ x ->\n              touchForeignPtr m >> return (coerce x)\n-}\n\nmcmcHeisenberg1D ::\n     PrimMonad m => Rbm Float -> Int -> Int -> m (Measurement Float)\nmcmcHeisenberg1D (R rbm) offset steps = unsafeIOToPrim $ _RbmC'heisenberg1D rbm offset steps\n\ninstance Eq a => Eq (Measurement a) where\n  (==) (Measurement _ x) (Measurement _ y) = x == y\n\ninstance Ord a => Ord (Measurement a) where\n  -- (<=) (Measurement a x) (Measurement b y) = x <= y\n  (<=) (Measurement a x) (Measurement b y) = a <= b\n\ninstance Num a => Num (Measurement a) where\n  (+) (Measurement a b) (Measurement c d) = Measurement (a + c) (b + d)\n  (-) (Measurement a b) (Measurement c d) = Measurement (a - c) (b - d)\n  (*) (Measurement a b) (Measurement c d) = Measurement (a * c) (b * d)\n  negate (Measurement a b) = Measurement (negate a) (negate b)\n  fromInteger n = Measurement (fromInteger n) (fromInteger n)\n  abs (Measurement a b) = Measurement (abs a) (abs b)\n  signum (Measurement a b) = Measurement (signum a) (signum b)\n\ninstance Fractional a => Fractional (Measurement a) where\n  (/) (Measurement a b) (Measurement c d) = Measurement (a / c) (b / d)\n  recip (Measurement a b) = Measurement (recip a) (recip b)\n\nmakeFields ''Measurement\n\n{-\n\ndebugAdd :: forall \u03bb. (Real \u03bb, Fractional \u03bb, Show \u03bb)\n         => (\u03bb, \u03bb) -> (\u03bb, \u03bb) -> (\u03bb, \u03bb)\ndebugAdd (x, y) (a, b) = unsafePerformIO $ do\n  putStrLn $ show x ++ \"\\t\" ++ show y ++ \"\\t\" ++ show a ++ \"\\t\" ++ show b\n  return (x + a, y + b)\n\nenergyVarHH1DOpen ::\n     forall m a.\n     ( PrimMonad m\n     , Ord a\n     , RealFloat a\n     , HH1DOpen (Complex a)\n     , Randomisable m Bool\n     , Randomisable m a\n     , UniformDist m Int\n     -- , MonadIO m\n     , Show a\n     )\n  => Rbm (Complex a) -> Int -> Int -> m (Measurement a)\nenergyVarHH1DOpen rbm offset steps =\n  let n = sizeVisible rbm\n      proposer :: MMcmc (PrimState m) (Complex a) -> Int -> m Int\n      proposer _ i = return (i `mod` n) {- uniform (0, n - 1) -}\n      acceptor :: MMcmc (PrimState m) (Complex a) -> Int -> m Bool\n      acceptor mx flip = unsafeFreezeMcmc mx >>= \\x ->\n                            ((<= propose1 x flip) <$> random)\n      updater :: MMcmc (PrimState m) (Complex a) -> Int -> m ()\n      updater = update1\n      func :: MMcmc (PrimState m) (Complex a) -> m (a, a)\n      func = unsafeFreezeMcmc >=> return . locEnergyHH1DOpen\n                              >=> return . (\\ x -> (realPart x, (realPart x)^2))\n      mmcmc :: m (MMcmc (PrimState m) (Complex a))\n      mmcmc = randomSpin n >>= newMcmc rbm\n      states = mutableMcmcLoop proposer acceptor updater\n   in mmcmc >>= \\mmcmc' ->\n                  P.fold debugAdd\n                         0\n                         (\\(h, h2) -> let mean = (h  / fromIntegral steps)\n                                          var  = (h2 / fromIntegral steps) - mean^2\n                                       in MV mean var)\n                         (states mmcmc' 0 >-> P.drop offset\n                                          >-> P.mapM func\n                                          >-> P.take steps)\n-}\n", "meta": {"hexsha": "b742b06b1cc1453c6657ae960076b17a15ca1134", "size": 18860, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PSO/Neural.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/PSO/Neural.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/PSO/Neural.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.9907235622, "max_line_length": 111, "alphanum_fraction": 0.5984093319, "num_tokens": 6157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22439591663640376}}
{"text": "module Main where\n\nimport           Control.Concurrent\nimport           Control.Concurrent.Chan\nimport           Control.Monad.Writer\nimport           Data.Array\nimport           Data.Bits\nimport qualified Data.ByteString           as B\nimport           Data.Complex\nimport           Data.Function\nimport           Data.List\nimport           Data.Word\nimport           Network.Socket            hiding (sendTo)\nimport           Network.Socket.ByteString\nimport           System.IO\n\nartWorkLeft :: Rythm\nartWorkLeft = Rest 1 :+: Hit 1 1 :+: incrAmp  (incrDur artWorkLeft)\n\nartWorkRight :: Rythm\nartWorkRight = Hit 1 1 :+: Rest 1 :+: incrAmp (incrDur artWorkRight)\n\nartWorkMiddle :: Rythm\nartWorkMiddle = Hit 1 1 :+: Hit 1 1 :+: go 1 True\n  where\n    go :: Int -> Bool -> Rythm\n    go dur up =\n        Rest 1 :+: Hit 119 dur :+: go dur' up'\n      where\n        dur' =\n            if up\n                then dur + 1\n                else dur - 1\n        up' = up && dur < 119 || (not up && dur < 2)\n\ndecrAmpN 0 r = r\ndecrAmpN n r = r' :+: decrAmpN (n - 1) r'\n  where\n    r' = decrAmp r\n\nincrAmpN 0 r = r\nincrAmpN n r = r' :+: incrAmpN (n-1) r'\n  where\n    r' = incrAmp r\n\nnTimes r 1 = r\nnTimes r n = r :+: nTimes r (n-1)\n\nssht :: Rythm\nssht = Hit 12 1\n\nincrDur (Hit a d) = Hit a (cap 1 120 (d + 1))\nincrDur (r1 :+: r2) = incrDur r1 :+: incrDur r2\nincrDur ( = r\n\ndecrAmp :: Rythm -> Rythm\ndecrAmp (Hit a d) | a > 1 = Hit (a - 1) d\n                  | otherwise = Hit a d\ndecrAmp (r1 :+: r2) = decrAmp r1 :+: decrAmp r2\ndecrAmp r = r\n\nincrAmp :: Rythm -> Rythm\nincrAmp (Hit a d) | a < 120 = Hit (a + 1) d\n                  | otherwise = Hit a d\nincrAmp (r1 :+: r2) = incrAmp r1 :+: incrAmp r2\nincrAmp r = r\n\n\ndata Action\n    = Render Track\n    | Stop\n    deriving (Show)\n\nipLeft = \"2001:67c:20a1:1095:ba27:ebff:feb9:db12\"\nipMiddle = \"2001:67c:20a1:1095:ba27:ebff:fe23:60d7\"\nipRight = \"2001:67c:20a1:1095:ba27:ebff:fe71:dd32\"\n\n-- small panel: 16x20\n-- panel: 3 x 6 small: 48 x 120\n\ndata Panel = P Track (Chan Action)\n\nmain :: IO ()\nmain = do\n    l <- startPanel 'L' artWorkLeft (mandelBrot 0 newImage) ipLeft\n    m <- startPanel 'M' artWorkMiddle (mandelBrot 49 newImage) ipMiddle\n    r <- startPanel 'R' artWorkRight (mandelBrot 97 newImage) ipRight\n    hSetBuffering stdin NoBuffering\n    hSetBuffering stdout NoBuffering\n    xxxLoop l m r\n    hSetBuffering stdin LineBuffering\n    hSetBuffering stdout LineBuffering\n    stopPanel l\n    stopPanel m\n    stopPanel r\n\nxxxLoop :: Panel -> Panel -> Panel -> IO ()\nxxxLoop l m r = do\n    i <- readInput\n    processInput i l m r\n\nprocessInput :: Input -> Panel -> Panel -> Panel -> IO ()\nprocessInput Quit _ _ _ = return ()\nprocessInput Tick l m r = do\n    let l' = updatePanel l\n        m' = updatePanel m\n        r' = updatePanel r\n    renderToPanel l\n    renderToPanel m\n    renderToPanel r\n    xxxLoop l' m' r'\n\nupdatePanel :: Panel -> Panel\nupdatePanel (P t c) = P (dropCurrent t) c\n  where\n    dropCurrent (_ :>>: t') = t'\n    dropCurrent _ = Done\n\ndata Input\n    = Quit\n    | Tick\n\nreadInput :: IO Input\nreadInput = do\n    c <- getChar\n    return\n        (case c of\n             ' ' -> Tick\n             _ -> Quit)\n\nstartPanel :: Char -> Rythm -> Image -> String -> IO Panel\nstartPanel name artWork initialImage host = do\n    c <- newChan\n    ai <- head <$> getAddrInfo Nothing (Just host) (Just \"2323\")\n    s <- socket (addrFamily ai) Datagram defaultProtocol\n    void $ forkIO (panelLoop name (addrAddress ai) c s)\n    return (P (renderRythm artWork initialImage) c)\n\nstopPanel :: Panel -> IO ()\nstopPanel = sendAction Stop\n\nrenderToPanel :: Panel -> IO ()\nrenderToPanel p@(P t _) = sendAction (Render t) p\n\nsendAction :: Action -> Panel -> IO ()\nsendAction a (P _ c) = writeChan c a\n\npanelLoop :: Char -> SockAddr -> Chan Action -> Socket -> IO ()\npanelLoop name a c s = do\n    putStr [name, '?']\n    action <- readChan c\n    case action of\n        Stop -> do\n            putStr [name, '$']\n            return ()\n        Render t -> do\n            panelRenderNext t\n            panelLoop name a c s\n  where\n    panelRenderNext t =\n        case t of\n            Done -> do\n                putStr [name, 'X']\n                return ()\n            Sleep d -> do\n                putStr [name, '<']\n                threadDelay (durationToMicros d)\n                putStr [name, '>']\n            Draw i -> do\n                putStr [name, '#']\n                void $ sendTo s (convertToDisplay i) a\n            t' :>>: _ -> panelRenderNext t'\n\n\n-- * MUSIC API\n\ntype Amplitude = Int\ntype Duration = Int\n\ndurationToMicros :: Int -> Int\ndurationToMicros = (microsPerCol *)\n  where\n    microsPerCol = 1500000 `div` panelW\n\ndata Rythm = Hit Amplitude Duration | Rest Duration | Rythm :+: Rythm\n    deriving (Show)\n\ntype Micros = Int\ndata Track = Done | Sleep Micros | Draw Image | Track :>>: Track\n    deriving (Show)\n\ninstance Monoid Track where\n    mempty = Done\n    mappend Done t = t\n    mappend t Done = t\n    mappend (ll :>>: lr) r = ll :>>: mappend lr r\n    mappend l r = l :>>: r\n\nrenderRythm :: Rythm -> Image -> Track\nrenderRythm r orig = execWriter (go r orig)\n  where\n    go :: Rythm -> Image -> Writer Track Image\n    go (r1 :+: r2) i = do\n        i' <- go r1 i\n        go r2 i'\n    go (Rest d) i = do\n        tell (Sleep (cap 1 120 d))\n        return i\n    go (Hit a d) i = do\n        let i' = flipBlock d a i\n        tell (Draw i')\n        tell (Sleep (cap 1 120 d))\n        return i'\n\ncap l u t | l <= t && t <= u = t\n          | l <= t         = u\n          | otherwise     = l\n\n-- * Image API\ntype Image = Array (Int,Int) Bool\n\n\npanelW, panelH :: Int\npanelW = 48\npanelH = 120\n\ncapCoords (x, y) = (cap 1 48 x, cap 1 120 y)\n\nmandelBrot :: Int -> Image -> Image\nmandelBrot offset img = foldr mandelPixel img (indices img)\n  where\n    mandelPixel (x,y) = setPixel x y (inMandelSet (0.0 :+ 0.0) 0)\n      where\n        maxIter = 100\n        c :: Complex Double\n        c =\n            (fromIntegral (offset + x) * (4.0 / 144.0) - 2.0) :+\n            (fromIntegral y * (4.0 / 120.0) - 2.0)\n        inMandelSet z i\n          | ((magnitude z) <= 2.0) && i < maxIter =\n              inMandelSet (z * z + c) (i + 1)\n          | otherwise = rem i 2 == 1\n\nnewImage :: Image\nnewImage =\n    array\n        ((1, 1), (panelW, panelH))\n        [((x, y), False) | x <- [1 .. panelW]\n                         , y <- [1 .. panelH]]\n\nflipBlock width height img = foldr (flipCol height) img [1 .. width]\n\nflipCol height col img = foldr flipPixel img [(col, y) | y <- [1..height]]\n\nflipPixel (x,y) img = setPixel x y (not (getPixel x y img)) img\n\nsetPixel :: Int -> Int -> Bool -> Image -> Image\nsetPixel x y v img = img // [((x, y), v)]\n\ngetPixel :: Int -> Int -> Image -> Bool\ngetPixel x y img = img ! (x,y)\n\nconvertToDisplay :: Image -> B.ByteString\nconvertToDisplay img = pixels\n  where\n    pixels = B.pack $ toFlipDotFormat $ toBit <$> elems img\n    toFlipDotFormat :: [Word8] -> [Word8]\n    toFlipDotFormat x = go x []\n      where\n        go x acc =\n            case take 8 x of\n              [] -> reverse acc\n              sx -> go (drop 8 x) (toByte (reverse sx) 1 0 : acc)\n    toByte [] _ acc =  acc\n    toByte (b:rest) p acc = toByte rest (p*2) (acc .|. b * p)\n    toBit :: Bool -> Word8\n    toBit = fromIntegral . fromEnum\n\n    (_,(w,h)) = bounds img\n\ntoPixel :: Int -> Char\ntoPixel = toEnum\n", "meta": {"hexsha": "638aa66a3d024276bdb27a7722cb964caae09fed", "size": 7335, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "sheyll/rythm-flipdot", "max_stars_repo_head_hexsha": "49320d57c6b6d25e9aad6dacad5ccb6c5cf57cb9", "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/Main.hs", "max_issues_repo_name": "sheyll/rythm-flipdot", "max_issues_repo_head_hexsha": "49320d57c6b6d25e9aad6dacad5ccb6c5cf57cb9", "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/Main.hs", "max_forks_repo_name": "sheyll/rythm-flipdot", "max_forks_repo_head_hexsha": "49320d57c6b6d25e9aad6dacad5ccb6c5cf57cb9", "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": 25.9187279152, "max_line_length": 74, "alphanum_fraction": 0.5627811861, "num_tokens": 2369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22317699621927717}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n-- {-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport           Common                         ( Analysis(..)\n                                                , Path(..)\n                                                )\nimport           Control.Monad                  ( foldM\n                                                , forM\n                                                , forM_\n                                                , replicateM\n                                                , zipWithM_\n                                                )\nimport           Control.Monad.Except           ( runExceptT )\nimport           Data.Either                    ( rights )\nimport           Data.List                      ( unzip4 )\nimport qualified Data.List                     as L\nimport           Data.Maybe                     ( catMaybes\n                                                , listToMaybe\n                                                , mapMaybe\n                                                )\nimport qualified Data.Vector                   as V\nimport           GHC.Float                      ( int2Double )\nimport qualified Graphics.Matplotlib           as Plt\nimport qualified GreedyParser                  as Greedy\nimport           Inference.Conjugate            ( Hyper\n                                                , HyperRep\n                                                , Prior(sampleProbs)\n                                                , Probs\n                                                , ProbsRep\n                                                , Trace\n                                                , evalTraceLogP\n                                                , evalTracePredLogP\n                                                , getPosterior\n                                                , jeffreysPrior\n                                                , traceTrace\n                                                , uniformPrior\n                                                )\nimport           Musicology.Pitch               ( SPitch )\nimport qualified Numeric.Log                   as Log\nimport           PVGrammar                      ( Edge\n                                                , PVAnalysis\n                                                , loadAnalysis\n                                                , loadInput\n                                                , topEdges\n                                                )\nimport           PVGrammar.Parse                ( protoVoiceEvaluator\n                                                , pvCountUnrestricted\n                                                )\nimport           PVGrammar.Prob.Simple          ( PVParams(PVParams)\n                                                , observeDerivation'\n                                                , sampleDerivation'\n                                                )\nimport qualified Parser\nimport qualified Statistics.Sample             as Stats\nimport           System.FilePath                ( (<.>)\n                                                , (</>)\n                                                )\nimport qualified System.FilePattern            as FP\nimport qualified System.FilePattern.Directory  as FP\nimport qualified System.Random.MWC.Probability as MWC\nimport           System.Random.Stateful         ( StatefulGen\n                                                , initStdGen\n                                                , newIOGenM\n                                                )\nimport           Text.Pretty.Simple             ( CheckColorTty(..)\n                                                , OutputOptions(..)\n                                                , defaultOutputOptionsNoColor\n                                                , pPrintOpt\n                                                )\nimport           Text.Printf                    ( printf )\n\nprettyPrint :: (Show a) => a -> IO ()\nprettyPrint = pPrintOpt\n  NoCheckColorTty\n  (defaultOutputOptionsNoColor { outputOptionsCompact = True })\n\ndataDir :: FilePath\ndataDir = \"data/\"\n\nmain = mainLearn\n\nnBaselines :: Int\nnBaselines = 100 -- default: 100\n\nnSamples :: Int\nnSamples = 250 -- default: 250\n\nmainLearn :: IO ()\nmainLearn = do\n  -- initialize\n  genPure <- initStdGen\n  gen     <- newIOGenM genPure\n  genMWC  <- MWC.create -- uses a fixed seed\n  let prior = uniformPrior @PVParams\n  -- load data\n  articleExamples <- loadDir\n    (dataDir </> \"theory-article\")\n    [\"05b_cello_prelude_1-4\", \"09a_hinunter\", \"03_bwv784_pattern\"]\n  Just bwv939 <- loadItem (dataDir </> \"bach\" </> \"f\u00fcnf-kleine-pr\u00e4ludien\")\n                          \"BWV_0939\"\n  Just bwv940 <- loadItem (dataDir </> \"bach\" </> \"f\u00fcnf-kleine-pr\u00e4ludien\")\n                          \"BWV_0940\"\n  let dataset = bwv939 : bwv940 : articleExamples\n  -- let dataset = take 3 articleExamples\n  putStrLn \"list of pieces:\"\n  forM_ dataset $ \\(name, _ana, _trace, _surface) -> do\n    putStrLn $ \"  \" <> name\n  -- compute overall posterior\n  posteriorTotal <- learn prior dataset\n  prettyPrint posteriorTotal\n  -- cross validation\n  let splits = leaveOneOut dataset\n  crossPerps <- forM splits (comparePerNote gen genMWC prior)\n  let (logpPriors, logpPosts, counts, basemeans, baselines) =\n        L.unzip5 crossPerps\n      count           = sum counts\n      logppnPrior     = sum logpPriors / count\n      logppnTrained   = sum logpPosts / count\n      logppnBaseline  = sum basemeans / count\n      -- look at each split\n      logppns         = zipWith (/) logpPosts counts -- fmap (\\(_, logp, count, _, _) -> logp / count) crossPerps\n      baselinelogppns = zipWith (\\bs n -> (/ n) <$> bs) baselines counts\n      testpieces      = fst <$> splits\n      testnames       = (\\(name, _, _, _) -> name) <$> testpieces\n  showSplits logppns baselinelogppns counts testnames\n      -- nsplits         = int2Double $ length splits\n      -- meanlogppn      = sum logppns / nsplits\n  putStrLn $ \"prior logppn: \" <> show logppnPrior\n  putStrLn $ \"prior perppn: \" <> show (exp $ negate logppnPrior)\n  putStrLn $ \"overall trained logppn: \" <> show logppnTrained\n  putStrLn $ \"overall trained perppn: \" <> show (exp $ negate logppnTrained)\n  putStrLn $ \"baseline logppn: \" <> show logppnBaseline\n  putStrLn $ \"baseline perppn: \" <> show (exp $ negate logppnBaseline)\n  putStrLn $ \"prior-posterior \u0394logppn:\" <> show (logppnPrior - logppnTrained)\n  putStrLn $ printf \"logppn (nats) & %.3f & %.3f & %.3f\\\\\\\\\"\n                    logppnPrior\n                    logppnTrained\n                    logppnBaseline\n  let natsbits = log 2\n  putStrLn $ printf \"logppn (bits) & %.3f & %.3f & %.3f\\\\\\\\\"\n                    (logppnPrior / natsbits)\n                    (logppnTrained / natsbits)\n                    (logppnBaseline / natsbits)\n  putStrLn $ printf \"perppn & %.2f & %.2f & %.2f\\\\\\\\\"\n                    (exp $ negate logppnPrior)\n                    (exp $ negate logppnTrained)\n                    (exp $ negate logppnBaseline)\n\ntestEstimator = do\n  (long, short)   <- loadExamples\n  articleExamples <- loadDir\n    (dataDir </> \"theory-article\")\n    [\"05b_cello_prelude_1-4\", \"09a_hinunter\", \"03_bwv784_pattern\"]\n  Just bwv939 <- loadItem (dataDir </> \"bach\" </> \"f\u00fcnf-kleine-pr\u00e4ludien\")\n                          \"BWV_0939\"\n  Just bwv940 <- loadItem (dataDir </> \"bach\" </> \"f\u00fcnf-kleine-pr\u00e4ludien\")\n                          \"BWV_0940\"\n  let dataset = bwv939 : bwv940 : articleExamples\n  genMWC <- MWC.createSystemRandom\n  let prior = uniformPrior @PVParams\n  posteriorTotal <- learn prior dataset\n  estimates      <- derivationLogProb genMWC posteriorTotal long\n  -- let means = meanOfLogs <$> tail (L.inits estimates)\n  -- -- print means\n  -- Plt.onscreen $ Plt.line [1 .. length means] means\n  print $ meanOfLogs estimates\n\ncountRareIntDerivs = do\n  Just (_, _, _, surface) <- loadItem (dataDir </> \"theory-article\")\n                                      \"10c_rare_int\"\n  count <- Parser.parseSize pvCountUnrestricted surface\n  print count\n\n-- loading data\n-- ------------\n\ntype Piece\n  = (String, PVAnalysis SPitch, Trace PVParams, Path [SPitch] [Edge SPitch])\n\nloadItem :: FilePath -> FilePath -> IO (Maybe Piece)\nloadItem dir name = do\n  ana <- loadAnalysis (dir </> name <.> \"analysis.json\")\n  case ana of\n    Left  _err -> pure Nothing\n    Right a    -> if anaTop a == PathEnd topEdges\n      then do\n        surface <- loadInput (dir </> name <.> \"musicxml\")\n        case observeDerivation' (anaDerivation a) of\n          Left _err -> do\n            putStrLn $ \"could not observe trace for \" <> name <> \", skipping.\"\n            pure Nothing\n          Right trace -> pure $ Just (name, a, trace, surface)\n      else do\n        putStrLn $ \"derivation for \" <> name <> \" is incomplete, skipping.\"\n        pure Nothing\n\nloadDir :: FilePath -> [String] -> IO [Piece]\nloadDir dir exclude = do\n  files <- FP.getDirectoryFiles dir [\"*.analysis.json\"]\n  let getName file = FP.match \"*.analysis.json\" file >>= listToMaybe\n      names =\n        -- exclude duplicats\n        filter (`L.notElem` exclude) $ catMaybes $ getName <$> files\n  -- print names\n  items <- mapM (loadItem dir) names\n  pure $ catMaybes items\n\nloadExamples :: IO (Trace PVParams, Trace PVParams)\nloadExamples = do\n  Just (_, _, bwv940Trace, _) <- loadItem\n    (dataDir </> \"bach\" </> \"f\u00fcnf-kleine-pr\u00e4ludien\")\n    \"BWV_0940\"\n  Just (_, _, rareTrace, _) <- loadItem (dataDir </> \"theory-article\")\n                                        \"10c_rare_int\"\n  pure (bwv940Trace, rareTrace)\n\n-- learning\n-- --------\n\nlearn :: Hyper PVParams -> [Piece] -> IO (Hyper PVParams)\nlearn = foldM train\n where\n  train prior (name, _, trace, _) =\n    case getPosterior prior trace sampleDerivation' of\n      Nothing -> do\n        putStrLn $ \"couldn't compute posterior for \" <> name <> \", skipping.\"\n        pure prior\n      Just post -> do\n        -- putStrLn $ \"learned from \" <> name <> \".\"\n        pure post\n\n-- evaluating\n-- ----------\n\nleaveOneOut :: [a] -> [(a, [a])]\nleaveOneOut dataset = go dataset [] []\n where\n  go []       _    splits = splits\n  go (x : xs) done splits = go xs (x : done) ((x, xs <> done) : splits)\n\nderivationLogProb\n  :: MWC.GenIO -> Hyper PVParams -> Trace PVParams -> IO [Double]\nderivationLogProb gen hyper trace = do\n  probs <- replicateM nSamples $ MWC.sample (sampleProbs @PVParams hyper) gen\n  let estimates = mapMaybe\n        (\\params -> snd <$> evalTraceLogP params trace sampleDerivation')\n        probs\n  pure $! estimates\n\nderivationLogProb'\n  :: MWC.GenIO -> Hyper PVParams -> Trace PVParams -> IO Double\nderivationLogProb' gen hyper trace = do\n  estimates <- derivationLogProb gen hyper trace\n  pure $! meanOfLogs estimates\n\nmeanOfLogs :: (RealFloat b, Foldable t, Functor t) => t b -> b\nmeanOfLogs logs =\n  Log.ln $! Log.sum (Log.Exp <$> logs) / fromIntegral (length logs)\n\ncountNotes :: Path [a] b -> Int\ncountNotes (PathEnd notes       ) = length notes\ncountNotes (Path notes edges rst) = length notes + countNotes rst\n\nsampleBaselines\n  :: (StatefulGen g IO)\n  => g\n  -> MWC.GenIO\n  -> Hyper PVParams\n  -> Piece\n  -> IO [Double]\nsampleBaselines gen genMWC posterior (name, _, _, surface) = do\n  derivsTry <- replicateM nBaselines $ runExceptT $ Greedy.parseRandom'\n    gen\n    protoVoiceEvaluator\n    surface\n  let derivs = rights derivsTry\n  putStrLn $ \"  collected \" <> show (length derivs) <> \" samples for \" <> name\n  let baselines = flip fmap derivs $ \\ana -> do\n        trace <- observeDerivation' (anaDerivation ana)\n        pure $ derivationLogProb' genMWC posterior trace\n  baselines <- traverse sequence baselines -- maaaaagic\n  fmap catMaybes $ forM baselines $ \\case\n    Left  err -> putStrLn err >> pure Nothing\n    Right val -> pure $ Just val\n\nsummarize :: [Double] -> (Double, Double)\nsummarize xs = (Stats.mean sample, Stats.stdDev sample)\n  where sample = V.fromList xs\n\ncomparePerNote\n  :: (StatefulGen g IO)\n  => g\n  -> MWC.GenIO\n  -> Hyper PVParams\n  -> (Piece, [Piece])\n  -> IO (Double, Double, Double, Double, [Double])\ncomparePerNote gen genMWC prior (test@(tstName, _, tstTrace, tstSurface), train)\n  = do\n    putStrLn $ \"testing on \" <> tstName\n    posterior <- learn prior train\n    -- compute normalized logprobs\n    let nnotes = int2Double $ countNotes tstSurface\n    logpPrior <- derivationLogProb' genMWC prior tstTrace\n    logpPost  <- derivationLogProb' genMWC posterior tstTrace\n    let logppnPrior = logpPrior / nnotes\n        logppnPost  = logpPost / nnotes\n    baselines <- sampleBaselines gen genMWC posterior test\n    let (basemean, basestd) = summarize baselines\n        basemeanpn          = basemean / nnotes\n        basestdpn           = basestd / nnotes\n    putStrLn $ \"  nnotes: \" <> show nnotes\n    putStrLn $ \"  logppn prior: \" <> show logppnPrior <> \" nats\"\n    putStrLn $ \"  logppn posterior: \" <> show logppnPost <> \" nats\"\n    putStrLn\n      $  \"  logppn baseline: mean=\"\n      <> show basemeanpn\n      <> \", std=\"\n      <> show basestdpn\n    putStrLn $ \"  baselines top 5: \" <> show\n      (drop 95 $ (/ nnotes) <$> L.sort baselines)\n    putStrLn $ \"  perplexity prior: \" <> show (exp $ negate logppnPrior)\n    putStrLn $ \"  perplexity posterior: \" <> show (exp $ negate logppnPost)\n    putStrLn $ \"  \u0394logppn: \" <> show (logppnPost - logppnPrior) <> \" nats\"\n    pure (logpPrior, logpPost, nnotes, basemean, baselines)\n\n-- plotting\n-- --------\n\na % b = a Plt.% Plt.mp Plt.# b\ninfixl 5 %\n\nshowSplits\n  :: [Double] -> [[Double]] -> [Double] -> [String] -> IO (Either String String)\nshowSplits logppns blogppns counts testpieces =\n  Plt.file \"splits.svg\"\n    $ Plt.readData (logppns, blogppns, counts, testpieces)\n    % \"import numpy as np\"\n    % \"import pandas as pd\"\n    % \"import seaborn as sns\"\n    % \"(logppns, blogppns, counts, pieces) = tuple(map(np.array, data))\"\n    % \"baselines = pd.concat([pd.DataFrame({'logppn': bppns, 'piece': piece}) for bppns, piece in zip(blogppns, pieces)])\"\n    % \"testscores = pd.DataFrame({'logppn': logppns, 'piece': pieces})\"\n    % \"colors = sns.color_palette()\"\n    % \"fig, ax = plot.subplots(figsize=(10,5))\"\n    % \"sns.boxplot(ax=ax, y='piece', x='logppn', data=baselines, whis=(2,98), color=colors[0], fliersize=4)\"\n    % \"sns.scatterplot(ax=ax, y='piece', x='logppn', data=testscores, color=colors[1])\"\n    % \"ax.invert_yaxis()\"\n    % \"fig.tight_layout()\"\n    % \"fig.savefig('splits.pdf')\"\n    % \"fig.savefig('splits.png')\"\n", "meta": {"hexsha": "485fe493905d920e0a4fc7f542555313b16be5d5", "size": 14526, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/MainLearning.hs", "max_stars_repo_name": "DCMLab/protovoices-haskell", "max_stars_repo_head_hexsha": "5ad21cee95ceb7297ae4ef73e7b67d8fc3ab0006", "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": "app/MainLearning.hs", "max_issues_repo_name": "DCMLab/protovoices-haskell", "max_issues_repo_head_hexsha": "5ad21cee95ceb7297ae4ef73e7b67d8fc3ab0006", "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": "app/MainLearning.hs", "max_forks_repo_name": "DCMLab/protovoices-haskell", "max_forks_repo_head_hexsha": "5ad21cee95ceb7297ae4ef73e7b67d8fc3ab0006", "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": 41.0338983051, "max_line_length": 122, "alphanum_fraction": 0.5338703015, "num_tokens": 3538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.22236750666689167}}
{"text": "{-# OPTIONS_GHC -fno-warn-orphans #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TupleSections #-}\n\nmodule HackageBenchmark (\n    hackageBenchmarkMain\n\n-- Exposed for testing:\n  , CabalResult(..)\n  , isSignificantTimeDifference\n  , combineTrialResults\n  , isSignificantResult\n  , shouldContinueAfterFirstTrial\n  ) where\n\nimport Control.Monad (forM_, replicateM, unless, when)\nimport qualified Data.ByteString as B\nimport Data.List (nub, unzip4)\nimport Data.Maybe (isJust)\nimport Data.Monoid ((<>))\nimport Data.String (fromString)\nimport Data.Time (NominalDiffTime, diffUTCTime, getCurrentTime)\nimport qualified Data.Vector.Unboxed as V\nimport Options.Applicative\nimport Statistics.Sample (mean, stdDev)\nimport Statistics.Test.MannWhitneyU ( PositionTest(..), TestResult(..)\n                                    , mannWhitneyUCriticalValue\n                                    , mannWhitneyUtest)\nimport Statistics.Types (PValue, mkPValue)\nimport System.Directory (getTemporaryDirectory)\nimport System.Exit (ExitCode(..), exitFailure)\nimport System.FilePath ((</>))\nimport System.IO ( BufferMode(LineBuffering), hPutStrLn, hSetBuffering, stderr\n                 , stdout)\nimport System.Process ( StdStream(CreatePipe), CreateProcess(..), callProcess\n                      , createProcess, readProcess, shell, waitForProcess )\nimport Text.Printf (printf)\n\nimport Distribution.Package (PackageName, mkPackageName, unPackageName)\n\ndata Args = Args {\n    argCabal1                      :: FilePath\n  , argCabal2                      :: FilePath\n  , argCabal1Flags                 :: [String]\n  , argCabal2Flags                 :: [String]\n  , argPackages                    :: [PackageName]\n  , argMinRunTimeDifferenceToRerun :: Double\n  , argPValue                      :: PValue Double\n  , argTrials                      :: Int\n  , argPrintTrials                 :: Bool\n  , argPrintSkippedPackages        :: Bool\n  , argTimeoutSeconds              :: Int\n  }\n\ndata CabalTrial = CabalTrial NominalDiffTime CabalResult\n\ndata CabalResult\n  = Solution\n  | NoInstallPlan\n  | BackjumpLimit\n  | Unbuildable\n  | UnbuildableDep\n  | ComponentCycle\n  | ModReexpIssue\n  | PkgNotFound\n  | Timeout\n  | Unknown\n  deriving (Eq, Show)\n\nhackageBenchmarkMain :: IO ()\nhackageBenchmarkMain = do\n  hSetBuffering stdout LineBuffering\n  args@Args {..} <- execParser parserInfo\n  checkArgs args\n  printConfig args\n  pkgs <- getPackages args\n  putStrLn \"\"\n\n  let -- The maximum length of the heading and package names.\n      nameColumnWidth :: Int\n      nameColumnWidth =\n          maximum $ map length $ \"package\" : map unPackageName pkgs\n      runCabal1 = runCabal argTimeoutSeconds argCabal1 argCabal1Flags\n      runCabal2 = runCabal argTimeoutSeconds argCabal2 argCabal2Flags\n\n  -- When the output contains both trails and summaries, label each row as\n  -- \"trial\" or \"summary\".\n  when argPrintTrials $ putStr $ printf \"%-16s \" \"trial/summary\"\n  putStrLn $\n      printf \"%-*s %-14s %-14s %11s %11s %11s %11s %11s\"\n             nameColumnWidth \"package\" \"result1\" \"result2\"\n             \"mean1\" \"mean2\" \"stddev1\" \"stddev2\" \"speedup\"\n\n  forM_ pkgs $ \\pkg -> do\n    let printTrial msgType result1 result2 time1 time2 =\n            putStrLn $\n            printf \"%-16s %-*s %-14s %-14s %10.3fs %10.3fs\"\n                   msgType nameColumnWidth (unPackageName pkg)\n                   (show result1) (show result2)\n                   (diffTimeToDouble time1) (diffTimeToDouble time2)\n\n    CabalTrial t1 r1 <- runCabal1 pkg\n    CabalTrial t2 r2 <- runCabal2 pkg\n    if not $\n       shouldContinueAfterFirstTrial argMinRunTimeDifferenceToRerun t1 t2 r1 r2\n    then when argPrintSkippedPackages $\n         if argPrintTrials\n         then printTrial \"trial (skipping)\" r1 r2 t1 t2\n         else putStrLn $ printf \"%-*s (first run times were too similar)\"\n                                nameColumnWidth (unPackageName pkg)\n    else do\n      when argPrintTrials $ printTrial \"trial\" r1 r2 t1 t2\n      (ts1, ts2, rs1, rs2) <- (unzip4 . ((t1, t2, r1, r2) :) <$>)\n                            . replicateM (argTrials - 1) $ do\n        CabalTrial t1' r1' <- runCabal1 pkg\n        CabalTrial t2' r2' <- runCabal2 pkg\n        when argPrintTrials $ printTrial \"trial\" r1' r2' t1' t2'\n        return (t1', t2', r1', r2')\n\n      let result1 = combineTrialResults rs1\n          result2 = combineTrialResults rs2\n          times1 = V.fromList (map diffTimeToDouble ts1)\n          times2 = V.fromList (map diffTimeToDouble ts2)\n          mean1 = mean times1\n          mean2 = mean times2\n          stddev1 = stdDev times1\n          stddev2 = stdDev times2\n          speedup = mean1 / mean2\n\n      when argPrintTrials $ putStr $ printf \"%-16s \" \"summary\"\n      if isSignificantResult result1 result2\n          || isSignificantTimeDifference argPValue ts1 ts2\n      then putStrLn $\n           printf \"%-*s %-14s %-14s %10.3fs %10.3fs %10.3fs %10.3fs %10.3f\"\n                  nameColumnWidth (unPackageName pkg)\n                  (show result1) (show result2) mean1 mean2 stddev1 stddev2 speedup\n      else when (argPrintTrials || argPrintSkippedPackages) $\n           putStrLn $\n           printf \"%-*s (not significant)\" nameColumnWidth (unPackageName pkg)\n  where\n    checkArgs :: Args -> IO ()\n    checkArgs Args {..} = do\n      let die msg = hPutStrLn stderr msg >> exitFailure\n      unless (argTrials > 0) $ die \"--trials must be greater than 0.\"\n      unless (argMinRunTimeDifferenceToRerun >= 0) $\n          die \"--min-run-time-percentage-difference-to-rerun must be non-negative.\"\n      unless (isSampleLargeEnough argPValue argTrials) $\n          die \"p-value is too small for the number of trials.\"\n\n    printConfig :: Args -> IO ()\n    printConfig Args {..} = do\n      putStrLn \"Comparing:\"\n      putStrLn $ \"1: \" ++ argCabal1 ++ \" \" ++ unwords argCabal1Flags\n      callProcess argCabal1 [\"--version\"]\n      putStrLn $ \"2: \" ++ argCabal2 ++ \" \" ++ unwords argCabal2Flags\n      callProcess argCabal2 [\"--version\"]\n      -- TODO: Print index state.\n      putStrLn \"Base package database:\"\n      callProcess \"ghc-pkg\" [\"list\"]\n\n    getPackages :: Args -> IO [PackageName]\n    getPackages Args {..} = do\n      pkgs <-\n          if null argPackages\n          then do\n            putStrLn $ \"Obtaining the package list (using \" ++ argCabal1 ++ \") ...\"\n            list <- readProcess argCabal1 [\"list\", \"--simple-output\"] \"\"\n            return $ nub [mkPackageName $ head (words line) | line <- lines list]\n          else do\n            putStrLn \"Using given package list ...\"\n            return argPackages\n      putStrLn $ \"Done, got \" ++ show (length pkgs) ++ \" packages.\"\n      return pkgs\n\nrunCabal :: Int -> FilePath -> [String] -> PackageName -> IO CabalTrial\nrunCabal timeoutSeconds cabal flags pkg = do\n  ((exitCode, err), time) <- timeEvent $ do\n    tmpDir <- getTemporaryDirectory\n\n    let timeout = \"timeout --foreground -sINT \" ++ show timeoutSeconds\n        cabalCmd = unwords $\n            [ cabal\n\n              -- A non-existent store directory prevents cabal from reading the\n              -- store, which would cause the size of the store to affect run\n              -- time.\n            , \"--store-dir=\" ++ (tmpDir </> \"non-existent-store-dir\")\n\n            , \"v2-install\"\n\n              -- These flags prevent a Cabal project or package environment from\n              -- affecting the install plan.\n            , \"--ignore-project\"\n            , \"--package-env=non-existent-package-env\"\n\n              -- --lib allows solving for packages with libraries or\n              -- executables.\n            , \"--lib\"\n\n            , unPackageName pkg\n\n            , \"--dry-run\"\n\n              -- The test doesn't currently handle stdout, so we suppress it\n              -- with silent. nowrap simplifies parsing the errors messages.\n            , \"-vsilent+nowrap\"]\n\n             ++ flags\n        cmd = (shell (timeout ++ \" \" ++ cabalCmd)) { std_err = CreatePipe }\n\n    -- TODO: Read stdout and compare the install plans.\n    (_, _, Just errh, ph) <- createProcess cmd\n    err <- B.hGetContents errh\n    (, err) <$> waitForProcess ph\n  let exhaustiveMsg =\n          \"After searching the rest of the dependency tree exhaustively\"\n      result\n        | exitCode == ExitSuccess                                                          = Solution\n        | exitCode == ExitFailure 124                                                      = Timeout\n        | fromString exhaustiveMsg `B.isInfixOf` err                                       = NoInstallPlan\n        | fromString \"Backjump limit reached\" `B.isInfixOf` err                            = BackjumpLimit\n        | fromString \"none of the components are available to build\" `B.isInfixOf` err     = Unbuildable\n        | fromString \"Dependency on unbuildable\" `B.isInfixOf` err                         = UnbuildableDep\n        | fromString \"Dependency cycle between the following components\" `B.isInfixOf` err = ComponentCycle\n        | fromString \"Problem with module re-exports\" `B.isInfixOf` err                    = ModReexpIssue\n        | fromString \"There is no package named\" `B.isInfixOf` err                         = PkgNotFound\n        | otherwise                                                                        = Unknown\n  return (CabalTrial time result)\n\nisSampleLargeEnough :: PValue Double -> Int -> Bool\nisSampleLargeEnough pvalue trials =\n    -- mannWhitneyUCriticalValue, which can fail with too few samples, is only\n    -- used when both sample sizes are less than or equal to 20.\n    trials > 20 || isJust (mannWhitneyUCriticalValue (trials, trials) pvalue)\n\nisSignificantTimeDifference :: PValue Double -> [NominalDiffTime] -> [NominalDiffTime] -> Bool\nisSignificantTimeDifference pvalue xs ys =\n  let toVector = V.fromList . map diffTimeToDouble\n  in case mannWhitneyUtest SamplesDiffer pvalue (toVector xs) (toVector ys) of\n       Nothing             -> error \"not enough data for mannWhitneyUtest\"\n       Just Significant    -> True\n       Just NotSignificant -> False\n\n-- Should we stop after the first trial of this package to save time? This\n-- function skips the package if the results are uninteresting and the times are\n-- within --min-run-time-percentage-difference-to-rerun.\nshouldContinueAfterFirstTrial :: Double\n                              -> NominalDiffTime\n                              -> NominalDiffTime\n                              -> CabalResult\n                              -> CabalResult\n                              -> Bool\nshouldContinueAfterFirstTrial 0                            _  _  _       _       = True\nshouldContinueAfterFirstTrial _                            _  _  Timeout Timeout = False\nshouldContinueAfterFirstTrial maxRunTimeDifferenceToIgnore t1 t2 r1      r2      =\n    isSignificantResult r1 r2\n || abs (t1 - t2) / min t1 t2 >= realToFrac (maxRunTimeDifferenceToIgnore / 100)\n\nisSignificantResult :: CabalResult -> CabalResult -> Bool\nisSignificantResult r1 r2 = r1 /= r2 || not (isExpectedResult r1)\n\n-- Is this result expected in a benchmark run on all of Hackage?\nisExpectedResult :: CabalResult -> Bool\nisExpectedResult Solution       = True\nisExpectedResult NoInstallPlan  = True\nisExpectedResult BackjumpLimit  = True\nisExpectedResult Timeout        = True\nisExpectedResult Unbuildable    = True\nisExpectedResult UnbuildableDep = True\nisExpectedResult ComponentCycle = True\nisExpectedResult ModReexpIssue  = True\nisExpectedResult PkgNotFound    = False\nisExpectedResult Unknown        = False\n\n-- Combine CabalResults from multiple trials. Ignoring timeouts, all results\n-- should be the same. If they aren't the same, we returns Unknown.\ncombineTrialResults :: [CabalResult] -> CabalResult\ncombineTrialResults rs\n  | allEqual rs                          = head rs\n  | allEqual [r | r <- rs, r /= Timeout] = Timeout\n  | otherwise                            = Unknown\n  where\n    allEqual :: Eq a => [a] -> Bool\n    allEqual xs = length (nub xs) == 1\n\ntimeEvent :: IO a -> IO (a, NominalDiffTime)\ntimeEvent task = do\n  start <- getCurrentTime\n  r <- task\n  end <- getCurrentTime\n  return (r, diffUTCTime end start)\n\ndiffTimeToDouble :: NominalDiffTime -> Double\ndiffTimeToDouble = fromRational . toRational\n\nparserInfo :: ParserInfo Args\nparserInfo = info (argParser <**> helper)\n     ( fullDesc\n    <> progDesc (\"Find differences between two cabal commands when solving\"\n                   ++ \" for all packages on Hackage.\")\n    <> header \"hackage-benchmark\" )\n\nargParser :: Parser Args\nargParser = Args\n    <$> strOption\n         ( long \"cabal1\"\n        <> metavar \"PATH\"\n        <> help \"First cabal executable\")\n    <*> strOption\n         ( long \"cabal2\"\n        <> metavar \"PATH\"\n        <> help \"Second cabal executable\")\n    <*> option (words <$> str)\n         ( long \"cabal1-flags\"\n        <> value []\n        <> metavar \"FLAGS\"\n        <> help \"Extra flags for the first cabal executable\")\n    <*> option (words <$> str)\n         ( long \"cabal2-flags\"\n        <> value []\n        <> metavar \"FLAGS\"\n        <> help \"Extra flags for the second cabal executable\")\n    <*> option (map mkPackageName . words <$> str)\n         ( long \"packages\"\n        <> value []\n        <> metavar \"PACKAGES\"\n        <> help (\"Space separated list of packages to test, or all of Hackage\"\n                   ++ \" if unspecified\"))\n    <*> option auto\n         ( long \"min-run-time-percentage-difference-to-rerun\"\n        <> showDefault\n        <> value 0.0\n        <> metavar \"PERCENTAGE\"\n        <> help (\"Stop testing a package when the difference in run times in\"\n                   ++ \" the first trial are within this percentage, in order to\"\n                   ++ \" save time\"))\n    <*> option (mkPValue <$> auto)\n         ( long \"pvalue\"\n        <> showDefault\n        <> value (mkPValue 0.05)\n        <> metavar \"DOUBLE\"\n        <> help (\"p-value used to determine whether to print the results for\"\n                   ++ \" each package\"))\n    <*> option auto\n         ( long \"trials\"\n        <> showDefault\n        <> value 10\n        <> metavar \"N\"\n        <> help \"Number of trials for each package\")\n    <*> switch\n         ( long \"print-trials\"\n        <> help \"Whether to include the results from individual trials in the output\")\n    <*> switch\n         ( long \"print-skipped-packages\"\n        <> help \"Whether to include skipped packages in the output\")\n    <*> option auto\n         ( long \"timeout\"\n        <> showDefault\n        <> value 90\n        <> metavar \"SECONDS\"\n        <> help \"Maximum time to run a cabal command, in seconds\")\n", "meta": {"hexsha": "ef5d9efa5989fb81e95aee9811364bd5b1d02646", "size": 14549, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "solver-benchmarks/HackageBenchmark.hs", "max_stars_repo_name": "strake/cabal", "max_stars_repo_head_hexsha": "42e18f763b6abc3e5f530e72300428065584ebb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-26T16:21:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T16:21:39.000Z", "max_issues_repo_path": "solver-benchmarks/HackageBenchmark.hs", "max_issues_repo_name": "strake/cabal", "max_issues_repo_head_hexsha": "42e18f763b6abc3e5f530e72300428065584ebb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-08T20:21:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T07:40:32.000Z", "max_forks_repo_path": "solver-benchmarks/HackageBenchmark.hs", "max_forks_repo_name": "strake/cabal", "max_forks_repo_head_hexsha": "42e18f763b6abc3e5f530e72300428065584ebb3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-31T05:57:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T22:00:08.000Z", "avg_line_length": 40.1906077348, "max_line_length": 107, "alphanum_fraction": 0.6063646986, "num_tokens": 3596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.22232959083005524}}
{"text": "{-# language GADTs                 #-}\n{-# language StandaloneDeriving    #-}\n{-# language TypeOperators         #-}\n{-# language FlexibleInstances     #-}\n{-# language FlexibleContexts      #-}\n{-# language UndecidableInstances  #-}\n{-# language MultiParamTypeClasses #-}\n{-# language TypeFamilies          #-}\n\n{-# options_ghc -fwarn-incomplete-patterns #-}\n\nmodule Feldspar.Software.Primitive where\n\nimport Feldspar.Representation\nimport Data.Struct\n\nimport Data.Array ((!))\nimport Data.Bits (Bits)\nimport Data.Complex\nimport Data.Int\nimport Data.Word\nimport Data.List (genericTake)\nimport Data.Typeable hiding (TypeRep)\nimport Data.Constraint hiding (Sub)\nimport qualified Data.Bits as Bits\n\n-- syntactic.\nimport Language.Syntactic\nimport Language.Syntactic.Functional\nimport Language.Syntactic.Functional.Tuple\nimport qualified Language.Syntactic as Syn\n\n-- imperative-edsl.\nimport Language.Embedded.Expression\nimport qualified Language.Embedded.Imperative.CMD as Imp (IArr(..))\n\n--------------------------------------------------------------------------------\n-- * Software primitives.\n--------------------------------------------------------------------------------\n\n--------------------------------------------------------------------------------\n-- ** Software primitive types.\n\n-- | Representation of supported, primitive software types.\ndata SoftwarePrimTypeRep a\n  where\n    -- booleans\n    BoolST   :: SoftwarePrimTypeRep Bool\n    -- signed numbers.\n    Int8ST   :: SoftwarePrimTypeRep Int8\n    Int16ST  :: SoftwarePrimTypeRep Int16\n    Int32ST  :: SoftwarePrimTypeRep Int32\n    Int64ST  :: SoftwarePrimTypeRep Int64\n    -- unsigned numbers.\n    Word8ST  :: SoftwarePrimTypeRep Word8\n    Word16ST :: SoftwarePrimTypeRep Word16\n    Word32ST :: SoftwarePrimTypeRep Word32\n    Word64ST :: SoftwarePrimTypeRep Word64\n    -- floating point numbers.\n    FloatST  :: SoftwarePrimTypeRep Float\n    DoubleST :: SoftwarePrimTypeRep Double\n    -- complex numbers.\n    ComplexFloatST  :: SoftwarePrimTypeRep (Complex Float)\n    ComplexDoubleST :: SoftwarePrimTypeRep (Complex Double)\n\nderiving instance Eq       (SoftwarePrimTypeRep a)\nderiving instance Show     (SoftwarePrimTypeRep a)\nderiving instance Typeable (SoftwarePrimTypeRep a)\n\ninstance Inhabited (Complex Float)\n  where\n    reset = 0 :+ 0\n\ninstance Inhabited (Complex Double)\n  where\n    reset = 0 :+ 0\n\n--------------------------------------------------------------------------------\n\n-- | Class of supported, primitive software types.\nclass (Eq a, Show a, Typeable a, Inhabited a) => SoftwarePrimType a\n  where\n    softwareRep :: SoftwarePrimTypeRep a\n\ninstance SoftwarePrimType Bool   where softwareRep = BoolST\ninstance SoftwarePrimType Int8   where softwareRep = Int8ST\ninstance SoftwarePrimType Int16  where softwareRep = Int16ST\ninstance SoftwarePrimType Int32  where softwareRep = Int32ST\ninstance SoftwarePrimType Int64  where softwareRep = Int64ST\ninstance SoftwarePrimType Word8  where softwareRep = Word8ST\ninstance SoftwarePrimType Word16 where softwareRep = Word16ST\ninstance SoftwarePrimType Word32 where softwareRep = Word32ST\ninstance SoftwarePrimType Word64 where softwareRep = Word64ST\ninstance SoftwarePrimType Float  where softwareRep = FloatST\ninstance SoftwarePrimType Double where softwareRep = DoubleST\ninstance SoftwarePrimType (Complex Float)  where softwareRep = ComplexFloatST\ninstance SoftwarePrimType (Complex Double) where softwareRep = ComplexDoubleST\n\n-- | Compare two primitive software types for equality.\nsoftwarePrimTypeEq :: SoftwarePrimTypeRep a -> SoftwarePrimTypeRep b -> Maybe (Dict (a ~ b))\nsoftwarePrimTypeEq (BoolST)   (BoolST)   = Just Dict\nsoftwarePrimTypeEq (Int8ST)   (Int8ST)   = Just Dict\nsoftwarePrimTypeEq (Int16ST)  (Int16ST)  = Just Dict\nsoftwarePrimTypeEq (Int32ST)  (Int32ST)  = Just Dict\nsoftwarePrimTypeEq (Int64ST)  (Int64ST)  = Just Dict\nsoftwarePrimTypeEq (Word8ST)  (Word8ST)  = Just Dict\nsoftwarePrimTypeEq (Word16ST) (Word16ST) = Just Dict\nsoftwarePrimTypeEq (Word32ST) (Word32ST) = Just Dict\nsoftwarePrimTypeEq (Word64ST) (Word64ST) = Just Dict\nsoftwarePrimTypeEq (FloatST)  (FloatST)  = Just Dict\nsoftwarePrimTypeEq (DoubleST) (DoubleST) = Just Dict\nsoftwarePrimTypeEq (ComplexFloatST)  (ComplexFloatST)  = Just Dict\nsoftwarePrimTypeEq (ComplexDoubleST) (ComplexDoubleST) = Just Dict\nsoftwarePrimTypeEq _          _          = Nothing\n\n-- | Construct the primitive software type representation of 'a'.\nsoftwarePrimTypeOf :: SoftwarePrimType a => a -> SoftwarePrimTypeRep a\nsoftwarePrimTypeOf _ = softwareRep\n\n-- | Construct a primitive software type witness from its representation.\nsoftwarePrimWitType :: SoftwarePrimTypeRep a -> Dict (SoftwarePrimType a)\nsoftwarePrimWitType BoolST   = Dict\nsoftwarePrimWitType Int8ST   = Dict\nsoftwarePrimWitType Int16ST  = Dict\nsoftwarePrimWitType Int32ST  = Dict\nsoftwarePrimWitType Int64ST  = Dict\nsoftwarePrimWitType Word8ST  = Dict\nsoftwarePrimWitType Word16ST = Dict\nsoftwarePrimWitType Word32ST = Dict\nsoftwarePrimWitType Word64ST = Dict\nsoftwarePrimWitType FloatST  = Dict\nsoftwarePrimWitType DoubleST = Dict\nsoftwarePrimWitType ComplexFloatST  = Dict\nsoftwarePrimWitType ComplexDoubleST = Dict\n\n--------------------------------------------------------------------------------\n-- ** Software primitive expressions.\n\n-- | Software primitive symbols.\ndata SoftwarePrim sig\n  where\n    -- free variables and literals.\n    FreeVar :: (SoftwarePrimType a) => String -> SoftwarePrim (Full a)\n    Lit     :: (Show a, Eq a)       => a      -> SoftwarePrim (Full a)\n    -- numerical operations.\n    Neg  :: (SoftwarePrimType a, Num a) => SoftwarePrim (a :-> Full a)\n    Abs  :: (SoftwarePrimType a, Num a) => SoftwarePrim (a :-> Full a)\n    Sign :: (SoftwarePrimType a, Num a) => SoftwarePrim (a :-> Full a)\n    Add  :: (SoftwarePrimType a, Num a) => SoftwarePrim (a :-> a :-> Full a)\n    Sub  :: (SoftwarePrimType a, Num a) => SoftwarePrim (a :-> a :-> Full a)\n    Mul  :: (SoftwarePrimType a, Num a) => SoftwarePrim (a :-> a :-> Full a)\n    -- integral operations.\n    Div  :: (SoftwarePrimType a, Integral a) => SoftwarePrim (a :-> a :-> Full a)\n    Mod  :: (SoftwarePrimType a, Integral a) => SoftwarePrim (a :-> a :-> Full a)\n    Quot :: (SoftwarePrimType a, Integral a) => SoftwarePrim (a :-> a :-> Full a)\n    Rem  :: (SoftwarePrimType a, Integral a) => SoftwarePrim (a :-> a :-> Full a)\n    --\n    FDiv :: (SoftwarePrimType a, Fractional a) => SoftwarePrim (a :-> a :-> Full a)\n    -- floating point operators.\n    Pi    :: (SoftwarePrimType a, Floating a) => SoftwarePrim (Full a)\n    Exp   :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Log   :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Sqrt  :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Pow   :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> a :-> Full a)\n    Sin   :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Cos   :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Tan   :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Asin  :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Acos  :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Atan  :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Sinh  :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Cosh  :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Tanh  :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Asinh :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Acosh :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    Atanh :: (SoftwarePrimType a, Floating a) => SoftwarePrim (a :-> Full a)\n    -- complex operators.\n    Complex   :: (SoftwarePrimType a, SoftwarePrimType (Complex a), Num a) =>\n      SoftwarePrim (a :-> a :-> Full (Complex a))\n    Real      :: (SoftwarePrimType a, SoftwarePrimType (Complex a)) =>\n      SoftwarePrim (Complex a :-> Full a)\n    Imag      :: (SoftwarePrimType a, SoftwarePrimType (Complex a)) =>\n      SoftwarePrim (Complex a :-> Full a)\n    Polar     :: (SoftwarePrimType a, SoftwarePrimType (Complex a), Floating a) =>\n      SoftwarePrim (a :-> a :-> Full (Complex a))\n    Magnitude :: (SoftwarePrimType a, SoftwarePrimType (Complex a), RealFloat a) =>\n      SoftwarePrim (Complex a :-> Full a)\n    Phase     :: (SoftwarePrimType a, SoftwarePrimType (Complex a), RealFloat a) =>\n      SoftwarePrim (Complex a :-> Full a)\n    Conjugate :: (SoftwarePrimType a, SoftwarePrimType (Complex a), Num a) =>\n      SoftwarePrim (Complex a :-> Full (Complex a))\n    -- type casting.\n    I2N   :: (SoftwarePrimType a, Integral a, SoftwarePrimType b, Num b) =>\n      SoftwarePrim (a :-> Full b)\n    I2B   :: (SoftwarePrimType a, Integral a) =>\n      SoftwarePrim (a :-> Full Bool)\n    B2I   :: (SoftwarePrimType a, Integral a) =>\n      SoftwarePrim (Bool :-> Full a)\n    Round :: (SoftwarePrimType a, RealFrac a, SoftwarePrimType b, Num b) =>\n      SoftwarePrim (a :-> Full b)\n    -- logical operations.\n    Not     :: SoftwarePrim (Bool :-> Full Bool)\n    And     :: SoftwarePrim (Bool :-> Bool :-> Full Bool)\n    Or      :: SoftwarePrim (Bool :-> Bool :-> Full Bool)\n    -- bitwise logical operations.\n    BitAnd   :: (SoftwarePrimType a, Bits a) => SoftwarePrim (a :-> a :-> Full a)\n    BitOr    :: (SoftwarePrimType a, Bits a) => SoftwarePrim (a :-> a :-> Full a)\n    BitXor   :: (SoftwarePrimType a, Bits a) => SoftwarePrim (a :-> a :-> Full a)\n    BitCompl :: (SoftwarePrimType a, Bits a) => SoftwarePrim (a :-> Full a)\n    ShiftL   :: (SoftwarePrimType a, Bits a, SoftwarePrimType b, Integral b) =>\n      SoftwarePrim (a :-> b :-> Full a)\n    ShiftR   :: (SoftwarePrimType a, Bits a, SoftwarePrimType b, Integral b) =>\n      SoftwarePrim (a :-> b :-> Full a)\n    RotateL  :: (SoftwarePrimType a, Bits a, SoftwarePrimType b, Integral b) =>\n      SoftwarePrim (a :-> b :-> Full a)\n    RotateR  :: (SoftwarePrimType a, Bits a, SoftwarePrimType b, Integral b) =>\n      SoftwarePrim (a :-> b :-> Full a)\n    -- relational operations.\n    Eq  :: (SoftwarePrimType a, Eq a)  => SoftwarePrim (a :-> a :-> Full Bool)\n    Neq :: (SoftwarePrimType a, Eq a)  => SoftwarePrim (a :-> a :-> Full Bool)\n    Lt  :: (SoftwarePrimType a, Ord a) => SoftwarePrim (a :-> a :-> Full Bool)\n    Lte :: (SoftwarePrimType a, Ord a) => SoftwarePrim (a :-> a :-> Full Bool)\n    Gt  :: (SoftwarePrimType a, Ord a) => SoftwarePrim (a :-> a :-> Full Bool)\n    Gte :: (SoftwarePrimType a, Ord a) => SoftwarePrim (a :-> a :-> Full Bool)\n    -- conditional.\n    Cond :: SoftwarePrim (Bool :-> a :-> a :-> Full a)\n    -- array indexing.\n    ArrIx :: (SoftwarePrimType a) => Imp.IArr Index a ->\n      SoftwarePrim (Index :-> Full a)\n\nderiving instance Show     (SoftwarePrim a)\nderiving instance Typeable (SoftwarePrim a)\n\n--------------------------------------------------------------------------------\n\n-- | Software primitive symbols.\ntype SoftwarePrimConstructs = SoftwarePrim\n\n-- | Software primitive symbols tagged with their type representation.\ntype SoftwarePrimDomain = SoftwarePrimConstructs :&: SoftwarePrimTypeRep\n\n-- | Software primitive expressions.\nnewtype Prim a = Prim { unPrim :: ASTF SoftwarePrimDomain a }\n\n-- | Evaluate a closed, software primitive expression.\nevalPrim :: Prim a -> a\nevalPrim = go . unPrim\n  where\n    go :: AST SoftwarePrimDomain sig -> Denotation sig\n    go (Sym (s :&: _)) = evalSym s\n    go (f :$ a)        = go f $ go a\n\n-- | Sugar a software primitive symbol as a smart constructor.\nsugarSymPrim\n  :: ( Signature sig\n     , fi  ~ SmartFun dom sig\n     , sig ~ SmartSig fi\n     , dom ~ SmartSym fi\n     , dom ~ SoftwarePrimDomain\n     , SyntacticN f fi\n     , sub :<: SoftwarePrimConstructs\n     , SoftwarePrimType (DenResult sig)\n     )\n  => sub sig -> f\nsugarSymPrim = sugarSymDecor softwareRep\n\n--------------------------------------------------------------------------------\n\ninstance Syntactic (Prim a)\n  where\n    type Domain   (Prim a) = SoftwarePrimDomain\n    type Internal (Prim a) = a\n    desugar = unPrim\n    sugar   = Prim\n\ninstance FreeExp Prim\n  where\n    type FreePred Prim = SoftwarePrimType\n    constExp = sugarSymPrim . Lit\n    varExp   = sugarSymPrim . FreeVar\n\ninstance EvalExp Prim\n  where\n    evalExp = evalPrim\n\n--------------------------------------------------------------------------------\n-- front-end.\n\ninstance (SoftwarePrimType a, Num a) => Num (Prim a)\n  where\n    fromInteger = constExp . fromInteger\n    (+)         = sugarSymPrim Add\n    (-)         = sugarSymPrim Sub\n    (*)         = sugarSymPrim Mul\n    negate      = sugarSymPrim Neg\n    abs         = error \"Num (Prim a): abs.\"\n    signum      = error \"Num (Prim a): signum.\"\n\n--------------------------------------------------------------------------------\n-- syntactic instances.\n\ninstance Eval SoftwarePrim\n  where\n    evalSym (FreeVar v) = error $ \"evaluating free variable \" ++ show v\n    evalSym (Lit a)     = a\n    evalSym Cond        = \\c t f -> if c then t else f\n    evalSym Neg         = negate\n    evalSym Abs         = abs\n    evalSym Sign        = signum\n    evalSym Add         = (+)\n    evalSym Sub         = (-)\n    evalSym Mul         = (*)\n    evalSym Div         = div\n    evalSym Mod         = mod\n    evalSym Quot        = quot\n    evalSym Rem         = rem\n    evalSym FDiv        = (/)\n    evalSym Pi          = pi\n    evalSym Exp         = exp\n    evalSym Log         = log\n    evalSym Sqrt        = sqrt\n    evalSym Pow         = (**)\n    evalSym Sin         = sin\n    evalSym Cos         = cos\n    evalSym Tan         = tan\n    evalSym Asin        = asin\n    evalSym Acos        = acos\n    evalSym Atan        = atan\n    evalSym Sinh        = sinh\n    evalSym Cosh        = cosh\n    evalSym Tanh        = tanh\n    evalSym Asinh       = asinh\n    evalSym Acosh       = acosh\n    evalSym Atanh       = atanh\n    evalSym Complex     = (:+)\n    evalSym Polar       = mkPolar\n    evalSym Real        = realPart\n    evalSym Imag        = imagPart\n    evalSym Magnitude   = magnitude\n    evalSym Phase       = phase\n    evalSym Conjugate   = conjugate\n    evalSym I2N         = fromIntegral\n    evalSym I2B         = (/=0)\n    evalSym B2I         = \\a -> if a then 1 else 0\n    evalSym Round       = fromInteger . round\n    evalSym Not         = not\n    evalSym And         = (&&)\n    evalSym Or          = (||)\n    evalSym BitAnd      = (Bits..&.)\n    evalSym BitOr       = (Bits..|.)\n    evalSym BitXor      = Bits.xor\n    evalSym BitCompl    = Bits.complement\n    evalSym ShiftL      = \\b i -> Bits.shiftL  b (fromIntegral i)\n    evalSym ShiftR      = \\b i -> Bits.shiftR  b (fromIntegral i)\n    evalSym RotateL     = \\b i -> Bits.rotateL b (fromIntegral i)\n    evalSym RotateR     = \\b i -> Bits.rotateR b (fromIntegral i)\n    evalSym Eq          = (==)\n    evalSym Neq         = (/=)\n    evalSym Lt          = (<)\n    evalSym Lte         = (<=)\n    evalSym Gt          = (>)\n    evalSym Gte         = (>=)\n    evalSym (ArrIx (Imp.IArrRun arr)) = \\i -> arr ! i\n    evalSym (ArrIx _)   = error \"eval of variable.\"\n\ninstance Symbol SoftwarePrim\n  where\n    symSig (FreeVar v) = signature\n    symSig (Lit a)     = signature\n    symSig Cond        = signature\n    symSig Neg         = signature\n    symSig Abs         = signature\n    symSig Sign        = signature\n    symSig Add         = signature\n    symSig Sub         = signature\n    symSig Mul         = signature\n    symSig Div         = signature\n    symSig Mod         = signature\n    symSig Quot        = signature\n    symSig Rem         = signature\n    symSig FDiv        = signature\n    symSig Pi          = signature\n    symSig Exp         = signature\n    symSig Log         = signature\n    symSig Sqrt        = signature\n    symSig Pow         = signature\n    symSig Sin         = signature\n    symSig Cos         = signature\n    symSig Tan         = signature\n    symSig Asin        = signature\n    symSig Acos        = signature\n    symSig Atan        = signature\n    symSig Sinh        = signature\n    symSig Cosh        = signature\n    symSig Tanh        = signature\n    symSig Asinh       = signature\n    symSig Acosh       = signature\n    symSig Atanh       = signature\n    symSig Complex     = signature\n    symSig Real        = signature\n    symSig Imag        = signature\n    symSig Polar       = signature\n    symSig Magnitude   = signature\n    symSig Phase       = signature\n    symSig Conjugate   = signature\n    symSig I2N         = signature\n    symSig I2B         = signature\n    symSig B2I         = signature\n    symSig Round       = signature\n    symSig Not         = signature\n    symSig And         = signature\n    symSig Or          = signature\n    symSig BitAnd      = signature\n    symSig BitOr       = signature\n    symSig BitXor      = signature\n    symSig BitCompl    = signature\n    symSig ShiftL      = signature\n    symSig ShiftR      = signature\n    symSig RotateL     = signature\n    symSig RotateR     = signature\n    symSig Eq          = signature\n    symSig Neq         = signature\n    symSig Lt          = signature\n    symSig Lte         = signature\n    symSig Gt          = signature\n    symSig Gte         = signature\n    symSig (ArrIx a)   = signature\n\ninstance Render SoftwarePrim\n  where\n    renderSym  = show\n    renderArgs = renderArgsSmart\n\ninstance Equality SoftwarePrim\n  where\n    equal s1 s2 = show s1 == show s2\n\ninstance StringTree SoftwarePrim\ninstance EvalEnv SoftwarePrim env\n\n--------------------------------------------------------------------------------\n", "meta": {"hexsha": "f5cacc1994ac519df8bbeaeff6c0ca39a9e97574", "size": 17624, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Feldspar/Software/Primitive.hs", "max_stars_repo_name": "markus-git/co-feldspar", "max_stars_repo_head_hexsha": "580c693f0c80505ad879e4363c715464c5e04aab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-08-17T13:31:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T14:16:09.000Z", "max_issues_repo_path": "src/Feldspar/Software/Primitive.hs", "max_issues_repo_name": "markus-git/co-feldspar", "max_issues_repo_head_hexsha": "580c693f0c80505ad879e4363c715464c5e04aab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-05T23:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T17:10:33.000Z", "max_forks_repo_path": "src/Feldspar/Software/Primitive.hs", "max_forks_repo_name": "markus-git/co-feldspar", "max_forks_repo_head_hexsha": "580c693f0c80505ad879e4363c715464c5e04aab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-09-12T13:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-30T14:16:26.000Z", "avg_line_length": 39.8733031674, "max_line_length": 92, "alphanum_fraction": 0.6104743532, "num_tokens": 4648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.22220688215258028}}
{"text": "{-# LANGUAGE BangPatterns, GADTs, StandaloneDeriving, OverloadedStrings #-}\n-- |\n-- Module      : Criterion\n-- Copyright   : (c) 2009-2014 Bryan O'Sullivan\n--\n-- License     : BSD-style\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : GHC\n--\n-- 'Versus'-type bgroup support\n\nmodule Criterion.Versus\n       (\n         vscsv\n       , versusReports\n       , VersusReport(..)\n       ) where\n\nimport Criterion.Types\nimport Criterion.IO.Printf (writeCsv)\nimport Criterion.Monad (Criterion)\nimport Control.Monad\nimport Control.Monad.Trans (liftIO)\nimport Control.Monad.Reader (asks)\nimport Control.Arrow ((&&&))\nimport Data.Function (on)\nimport qualified Data.Csv as Csv\nimport Data.List (groupBy, sortBy)\nimport Statistics.Resampling.Bootstrap (Estimate(..))\nimport Data.Aeson (ToJSON(..), object, encode, (.=))\n\ndata VersusReport where\n  VersusReport :: (Show l, Ord l) => {\n    vsReportDescription :: String\n  , vsReportDataPoints :: [l]\n  , vsReportData :: [(String, [Estimate])]\n  , vsReportIndices :: [((String, l), Int)]\n  } -> VersusReport\nderiving instance Show VersusReport\n\n{- This instance is actually incomplete -}\ninstance ToJSON VersusReport where\n  toJSON VersusReport{\n      vsReportDescription = desc\n    , vsReportDataPoints  = dp\n    , vsReportData        = d\n    } = object [ \"name\"       .= toJSON desc\n               , \"dataPoints\" .= toJSON (map show dp)\n               , \"data\"       .= toJSON (map mkArr d)]\n        where\n          mkArr (alg, p) = object [ \"alg\"  .= toJSON alg\n                                  , \"data\" .= toJSON p]\n\nvscsv :: [VersusReport] -> Criterion ()\nvscsv = mapM_ f\n  where f VersusReport{\n            vsReportDescription = d\n          , vsReportData        = r\n          , vsReportDataPoints  = p} = do\n          file <- asks vsCsvFile\n          writeCsv file [d]\n          writeCsv file $ \"name\":(map show p)\n          forM_ r $ \\(a, m) -> writeCsv file $ a:(map (show . estPoint) m)\n\n\nversusReports :: [VersusReport] -> [Report] -> [VersusReport]\nversusReports vrpts rpts = map (vsReport rpts) vrpts\n\nvsReport :: [Report] -> VersusReport -> VersusReport\nvsReport rpts vr@VersusReport{vsReportIndices = indices} =\n  vr{vsReportData = map f l}\n  where\n    valg = fst . fst\n    venv = snd . fst\n    l    = groupBy' ((==) `on` valg) valg indices\n    rpts' = sortBy (compare `on` reportNumber) rpts\n    f (alg, idx) = (alg, [anMean . reportAnalysis $ rpts'!!i\n                         | (_, i)<-sortBy (compare `on` venv) idx])\n\ngroupBy' :: (a -> a -> Bool) -> (a -> b) -> [a] -> [(b, [a])]\ngroupBy' f g = map (g . head &&& id) . groupBy f\n", "meta": {"hexsha": "5633db70da6dfe2c03db2db0cac54803ba870577", "size": 2617, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Criterion/Versus.hs", "max_stars_repo_name": "k32/criterion", "max_stars_repo_head_hexsha": "131fcc4f8b4d97e5e75c06cbb125c6880b70fd84", "max_stars_repo_licenses": ["BSD-2-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": "Criterion/Versus.hs", "max_issues_repo_name": "k32/criterion", "max_issues_repo_head_hexsha": "131fcc4f8b4d97e5e75c06cbb125c6880b70fd84", "max_issues_repo_licenses": ["BSD-2-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": "Criterion/Versus.hs", "max_forks_repo_name": "k32/criterion", "max_forks_repo_head_hexsha": "131fcc4f8b4d97e5e75c06cbb125c6880b70fd84", "max_forks_repo_licenses": ["BSD-2-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.5301204819, "max_line_length": 75, "alphanum_fraction": 0.6071837982, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2220755216739912}}
{"text": "{-# language RecordWildCards #-}\n{-# options_ghc -Wno-type-defaults #-}\n\n{- |\nModule      : UI.WX.Viewer\nDescription : Interactive view based on wxWidgets\n-}\nmodule UI.WX.Viewer ( wxView\n                    ) where\n\nimport Data.Planar\nimport UI.Tile\n\nimport           Graphics.UI.WX hiding (pt)\nimport           qualified Graphics.UI.WX as WX\nimport           Graphics.UI.WXCore.Draw\nimport           Graphics.UI.WXCore.WxcClassTypes\nimport           Graphics.UI.WXCore.WxcTypes      (rgba)\nimport           Graphics.UI.WXCore.WxcClassesAL\nimport           Graphics.UI.WXCore.WxcClassesMZ\n\nimport Graphics.UI.WXCore.Events\n\nimport Control.Concurrent\nimport Data.Time (diffUTCTime, getCurrentTime)\nimport Data.IORef\nimport Text.Printf\nimport Control.Monad (forM_)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromMaybe)\nimport qualified Data.Set as Set\n\nimport UI\nimport UI.WxWidgets\n\nimport Actor.Viewer\n\nimport Data.Word\nimport Foreign (Ptr)\nimport Data.Complex\n\ndata Model = Model\n  { modelCenter   :: (Double, Double)\n  , modelPixelDim :: (Double, Double)\n  }\n\nmodelToRect :: Planar a => (Int,Int) -> Model -> Rectangle a\nmodelToRect (w,h) Model{..} = flippedRectangle (fromCoords ul) (fromCoords lr)\n  where\n    ul = (cx - px * fromIntegral w / 2, cy - py * fromIntegral h / 2)\n    lr = (cx + px * fromIntegral w / 2, cy + py * fromIntegral h / 2)\n    (cx, cy) = modelCenter\n    (px, py) = modelPixelDim\n\ninterpolateModel :: Double -> Model -> Model -> Model\ninterpolateModel t m1 m2 = m2\n    { modelCenter   = interpolate modelCenter\n    , modelPixelDim = logInterpolate modelPixelDim\n    }\n  where\n    interp p q = p + t * (q - p)\n    interp2 (p1,p2) (q1,q2) = (interp p1 q1, interp p2 q2)\n    interpolate f = interp2 (f m1) (f m2)\n    logInterp p q = p * (q/p) ** t\n    logInterp2  (p1,p2) (q1,q2) = (logInterp p1 q1, logInterp p2 q2)\n    logInterpolate f = logInterp2 (f m1) (f m2)\n\nhelloFrom :: String -> IO ()\nhelloFrom me = do\n    tid <- myThreadId\n    bound <- isCurrentThreadBound\n    capInfo <- threadCapability tid\n    putStrLn (\"Hello from \" ++ me\n              ++ \", on thread \" ++ show tid\n              ++ \" cap=\" ++ show capInfo\n              ++ \" bound=\" ++ show bound)\n\n-- | Create a window with an interactive view of a complex-dynamical system.\nwxView :: Rectangle (Double, Double)\n          -- ^ The upper-left and lower-right corners of the view.\n       -> (Word32 -> Word32 -> Complex Double -> Complex Double -> Ptr Word8 -> IO ()) -- ([(Double, Double)] -> IO [Color])\n          -- ^ The rendering action\n       -> Viewer\n          -- ^ The script-defined viewer\n       -> IO ()\nwxView _modelRect renderAction testViewer = start $ do\n\n    model <- variable [value := Model (0,0) (1/128,1/128)]\n\n    helloFrom \"wxView\"\n\n    let (width, height) = (512, 512)\n\n    -- Create the main viewer frame\n    f <- frame [ text := \"FractalStream\"\n               , clientSize := sz width height ]\n\n    _myViewer <- toUI @WX testViewer ()\n\n    -- Create a \"simple complex dynamics\" wizard\n    do\n      wiz <- frame [ text := \"Parametric complex dynamics\" ]\n\n      p <- panel wiz [ clientSize := sz 200 200 ]\n\n      initialZ <- textEntry p [ text := \"0\" ]\n      fun <- textEntry p [ text := \"z^2 + C\" ]\n      stopWhen <- textEntry p [ text := \"|z| > maxRadius\" ]\n\n      set wiz [ layout := margin 10 $ container p $ grid 10 10 $\n                [ [ widget (label \"Starting from z = \"), hfill (widget initialZ) ]\n                , [ widget (label \"Iterate f(z) = \"), hfill (widget fun) ]\n                , [ widget (label \"         until \"), hfill (widget stopWhen) ]]\n              ]\n\n    -- Create a code editor frame\n    ce <- frame [ text := \"Script editor\"\n                , clientSize := sz 300 300 ]\n    cep <- panel ce [ clientSize := sz 100 100 ]\n    stc <- styledTextCtrl cep [ clientSize := sz 100 100 ]\n    styledTextCtrlSetMarginWidth stc 0 30\n    styledTextCtrlSetMarginWidth stc 1 0\n    styledTextCtrlSetMarginWidth stc 2 0\n    -- see Style Definition at https://www.scintilla.org/ScintillaDoc.html#Styling\n    lum <- do\n      col <- get ce bgcolor\n      let rc :: Float = colorRed col / 255\n          gc = colorGreen col / 255\n          bc = colorBlue col / 255\n      pure (0.299 * rc + 0.587 * gc + 0.114 * bc)\n    if lum > 0.5\n      then do\n        styledTextCtrlStyleSetSpec stc  0 \"fore:#000000,back:#f8f8f8\"\n        styledTextCtrlStyleSetSpec stc 32 \"fore:#000000,back:#f8f8f8\"\n        styledTextCtrlStyleSetSpec stc 33 \"fore:#808080,back:#f0f060\"\n        styledTextCtrlSetCaretLineBackground stc (rgb 240 240 255)\n      else do\n        styledTextCtrlStyleSetSpec stc  0 \"fore:#dbdbdb,back:#14191e\"\n        styledTextCtrlStyleSetSpec stc 32 \"fore:#dbdbdb,back:#14191e\"\n        styledTextCtrlStyleSetSpec stc 33 \"fore:#a0a0a0,back:#101040\"\n        styledTextCtrlSetCaretLineBackground stc (rgb 0x20 0x30 0x38)\n\n    styledTextCtrlStyleSetFaceName stc 0 \"Monaco\"\n    -- Set the minimum size, or else Scintilla will default to 2000 pixels(!)\n    styledTextCtrlSetScrollWidth stc 100\n    styledTextCtrlSetCaretLineVisible stc True\n\n    styledTextCtrlSetUseTabs stc False\n    styledTextCtrlSetTabWidth stc 4\n    styledTextCtrlSetIndent stc 4\n    styledTextCtrlSetTabIndents stc True\n    styledTextCtrlSetBackSpaceUnIndents stc True\n    --styledTextCtrlSetIndentationGuides stc True\n    styledTextCtrlSetViewWhiteSpace stc 3\n\n    seFileMenu <- menuPane [ text := \"&File\" ]\n    menuItem seFileMenu [ text := \"&Open...\"\n                        , on command := putStrLn \"TODO\" ]\n    seEditMenu <- menuPane [ text := \"&Edit\" ]\n    --menuItem seEditMenu [ text := \"Copy\\tCtrl-C\" ]\n    --menuItem seEditMenu [ text := \"Cut\\tCtrl-X\" ]\n    --menuItem seEditMenu [ text := \"Paste\\tCtrl-V\" ]\n    seHelpMenu  <- menuHelp      [ text := \"&Help\" ]\n    --seAboutMenu <- menuAbout seHelpMenu [text := \"About FractalStream\"]\n    set ce [ menuBar := [ seFileMenu\n                        , seEditMenu\n                        , seHelpMenu\n                        ] ]\n\n    titleBox <- textEntry cep [ text := \"\" ]\n\n    lc <- listView cep [ \"Variable\", \"Initial value\", \"Type\", \"Label\" ] id\n\n    listViewAddItem lc [\"maxRadius\", \"10\", \"\u211d\", \"Escape radius\"]\n    listViewAddItem lc [\"maxIters\", \"100\", \"\u2115\", \"Iteration limit\"]\n    listViewAddItem lc [\"exterior\", \"blue\", \"Color\", \"Exterior color\"]\n\n    addParam <- button cep [ text := \"Add parameter...\" ]\n    delParam <- button cep [ text := \"Delete parameter\" ]\n\n    set ce [ layout := container cep $ column 1\n               [ hstretch\n                 $ margin 5\n                 $ row 5 [ widget (label \"Title:\")\n                         , fill (widget titleBox) ]\n               , fill $ widget stc\n               , hstretch\n                 $ margin 10\n                 $ row 5 [ column 5 [ widget (label \"Parameters\")\n                                    , vglue\n                                    , widget addParam\n                                    , widget delParam ]\n                         , fill (widget $ listViewLayout lc) ]\n               ]\n           , clientSize := sz 400 400 ]\n\n    -- Test dialog\n    dlog <- dialog ce [ text := \"Edit parameter\"\n                      , resizeable := True\n                      , on resize := propagateEvent\n                      , visible := False ]\n    dlog_ok <- button dlog [ text := \"Ok\" ]\n    dlog_cancel <- button dlog [ text := \"Cancel\" ]\n\n    varEditor <- entry dlog [ font := fontFixed\n                            , text := \"\"\n                            ]\n    editor <- entry dlog [ font := fontFixed\n                         , text := \"0\"\n                         ]\n    descEditor <- entry dlog [ font := fontFixed\n                             , text := \"\"\n                             ]\n    editorB <- checkBox dlog [ text := \"true\"\n                             , checkable := True\n                             , checked := True\n                             , visible := False ]\n\n    set editorB [ on command := do\n                    isChecked <- get editorB checked\n                    set editorB [ text := if isChecked then \"true\" else \"false\" ]\n                ]\n    let colorPickerCtrl :: Window a -> Color -> [Prop (ColourPickerCtrl ())] -> IO (ColourPickerCtrl ())\n        colorPickerCtrl parent' color0 props\n          = feed2 props 0 $\n            initialWindow    $ \\iD rect' ps s ->\n            do e <- colorPickerCtrlCreate parent' iD color0 rect' s\n               set e ps\n               return e\n\n    editorC  <- colorPickerCtrl dlog (rgb 255 0 0) [ visible := False ]\n    editorC' <- entry dlog [ font := fontFixed\n                           , text := \"red\"\n                           , visible := False ]\n\n    let newPick = do\n          c <- colorPickerCtrlGetColour editorC\n          let cr_ = colorRed   c / 255.0 :: Float\n              cg_ = colorGreen c / 255.0 :: Float\n              cb_ = colorBlue  c / 255.0 :: Float\n          set editorC' [ text := \"rgb (\" ++ printf \"%0.2f\" cr_ ++ \", \"\n                                         ++ printf \"%0.2f\" cg_ ++ \", \"\n                                         ++ printf \"%0.2f\" cb_ ++ \")\"\n                   ]\n    windowOnEvent editorC [wxEVT_COMMAND_COLOURPICKER_CHANGED] newPick (const newPick)\n\n    typeEditor <- choice dlog [ fontFace := \"Monaco\"\n                              , fontSize := 14 ]\n\n    let typeList = [\"\u2102\", \"\u211d\", \"\u2124\", \"\u2115\", \"Boolean\", \"Color\"]\n    forM_ typeList (itemAppend typeEditor)\n\n    set dlog\n      [ layout := fill $ margin 15 $ column 10 $\n        [ row 5 [ boxed \"Variable\" (hfill $ widget varEditor)\n                , column 10 [ label \" \", label \":\" ]\n                , boxed \"Type\" (widget typeEditor) ]\n        , boxed \"Default value\" $\n          column 0 [ hfill (widget editor)\n                   , hfill (widget editorB)\n                   , row 5 [ widget editorC\n                           , hfill (widget editorC') ]\n                   ]\n        , boxed \"Description\" (hfill (widget descEditor))\n        , row 5 [ widget dlog_ok, hglue, widget dlog_cancel ]\n        ]\n      ]\n\n    let editParam = do\n          mresult <- showModal dlog $ \\stopParamEdit -> do\n            set typeEditor [ on select := do\n                               ix <- get typeEditor selection\n                               case ix of\n                                 4 -> do\n                                   set editor   [ visible := False ]\n                                   set editorB  [ visible := True ]\n                                   set editorC  [ visible := False ]\n                                   set editorC' [ visible := False ]\n                                   windowReFit dlog\n                                 5 -> do\n                                   set editor   [ visible := False ]\n                                   set editorB  [ visible := False ]\n                                   set editorC  [ visible := True ]\n                                   set editorC' [ visible := True ]\n                                   windowReFit dlog\n                                 _ -> do\n                                   set editor   [ visible := True ]\n                                   set editorB  [ visible := False ]\n                                   set editorC  [ visible := False ]\n                                   set editorC' [ visible := False ]\n                                   windowReFit dlog\n                           ]\n            set dlog_ok     [on command := stopParamEdit (Just ())]\n            set dlog_cancel [on command := stopParamEdit Nothing]\n\n          case mresult of\n            Nothing -> pure Nothing\n            Just _ -> do\n              vname <- get varEditor text\n              vdesc <- get descEditor text\n              vtypeIx <- get typeEditor selection\n              let vtype = typeList !! vtypeIx\n              v <- case vtypeIx of\n                4 -> get editorB checked <&> \\case { True -> \"true\"; False -> \"false\" }\n                5 -> get editorC' text\n                _ -> get editor text\n              pure (Just [vname, v, vtype, vdesc])\n\n    selectedRef <- newIORef Set.empty\n\n    set addParam [ on command := do\n                     set varEditor [ text := \"\" ]\n                     set descEditor [ text := \"\" ]\n                     set typeEditor [ selection := 0 ]\n                     set editor [ text := \"\" ]\n                     set editorB [ checked := True ]\n                     set editorC' [ text := \"red\" ]\n                     editParam >>= \\case\n                       Nothing -> pure ()\n                       Just i  -> listViewAddItem lc i\n                 ]\n\n    set delParam [ on command := do\n                     sels <- Set.toList <$> readIORef selectedRef\n                     case sels of\n                       [ix] -> do\n                         ct0 <- length <$> listViewGetItems lc\n                         putStrLn (\"Deleting \" ++ show ix ++ \", count was \" ++ show ct0)\n                         writeIORef selectedRef Set.empty\n                         is <- listViewGetItems lc\n                         listViewSetItems lc (take ix is ++ drop (ix + 1) is)\n                         ct1 <- length <$> listViewGetItems lc\n                         putStrLn (\"Deleted \" ++ show ix ++ \", count was \" ++ show ct1)\n                       _    -> pure ()\n                 ]\n    listViewSetHandler lc $ \\case\n      ListItemSelected ix -> modifyIORef' selectedRef (Set.insert ix)\n      ListItemDeselected ix -> modifyIORef' selectedRef (Set.delete ix)\n      ListItemFocused ix  -> putStrLn (\"focused \" ++ show ix )\n      ListItemActivated ix -> do\n        putStrLn (\"activated ix=\" ++ show ix)\n        [vname, v, vtype, vdesc] <- listViewGetItems lc <&> (!! ix)\n        set varEditor [ text := vname ]\n        set descEditor [ text := vdesc ]\n        let vtypeIx = fromMaybe 0 (lookup vtype (zip typeList [0..]))\n        set typeEditor [ selection := vtypeIx ]\n        case vtypeIx of\n          4 -> set editorB  [ checked := v == \"true\" ]\n          5 -> set editorC' [ text := v ]\n          _ -> set editor [text := v]\n        editParam >>= \\case\n          Nothing -> pure ()\n          Just i  -> do\n            is <- listViewGetItems lc\n            listViewSetItems lc (take ix is ++ [i] ++ drop (ix + 1) is)\n\n      ListBeginDrag ix pt _stop -> putStrLn (\"drag \" ++ show ix ++ \", \" ++ show pt)\n      _ -> pure ()\n\n    -- Create the menus\n\n    -- File menu\n    file <- menuPane      [text := \"&File\"]\n    menuItem file [ text := \"&New\", on command := putStrLn \"TODO\"]\n--    _    <- menuQuit file [ text := \"&Quit\"\n--                          , help := \"Quit FractalStream\"]\n\n    -- Help menu\n    hlp   <- menuHelp      [ text := \"&Help\" ]\n    menuItem hlp [ text := \"blah\" ]\n    about <- menuAbout hlp [text := \"About FractalStream\"]\n\n    -- Viewer status bar\n    status <- statusField   [text := \"Pointer location\"]\n    toolStatus <- statusField [text := \"\"]\n\n    -- Tool menu\n    tools <- menuPane [text := \"&Tool\"]\n    mapM_ (\\(x,y,z) -> menuRadioItem tools [ text := x\n                                           , help := y\n                                           , on command := do\n                                               set toolStatus [text := y]\n                                               z])\n      [ (\"Navigate\",\n         \"Move around a dynamical system, select a point by ctrl-clicking\",\n         do putStrLn \"hi\")\n      , (\"Trace\",\n         \"Follow the orbit of a point\",\n         do putStrLn \"bye\")\n      ]\n\n    draggedTo <- variable [value := Nothing]\n    lastClick <- variable [value := Nothing]\n    pendingResize <- variable [value := False]\n\n    -- Panel and tile for initial view\n    renderId <- newIORef (0 :: Int)\n    viewerTile     <- renderTile' renderId renderAction (width, height) model\n    currentTile    <- variable [value := viewerTile]\n    savedTileImage <- variable [value := Nothing]\n    lastTileImage  <- variable [value := Nothing]\n\n\n    p <- panel f []\n\n\n    -- trigger repaint\n    let triggerRepaint = do\n          repaint p\n          windowRefresh p True -- True=redraw background\n          windowUpdateWindowUI p\n\n    animate <- variable [value := Nothing]\n    let startAnimatingFrom oldModel = do\n            now <- getCurrentTime\n            img <- get savedTileImage value >>= traverse imageCopy\n            set lastTileImage [value := img]\n            set animate [value := Just (now, oldModel, img)]\n\n    set p [ on paintRaw := \\dc r _dirty -> get animate value >>= \\case\n                  Nothing -> do\n                      -- Normal paint. Draw current rendering, then layer\n                      -- tool imagery on top.\n                      viewRect <- windowGetViewRect f\n                      curTile <- get currentTile value\n                      let (w, h) = tileRect curTile\n                      get savedTileImage value >>= \\case\n                          Nothing -> pure ()\n                          Just im -> drawCenteredImage im dc viewRect (w, h)\n                      paintToolLayer lastClick draggedTo dc r viewRect\n\n                  Just (startTime, oldModel, oldImage) -> do\n                      -- Animated paint. Zoom and blend smoothly between\n                      -- the new and old images.\n                      now <- getCurrentTime\n                      let speed :: forall n. Num n => n\n                          speed = 6\n                          blend = min 255 (round (speed * 255 * toRational (diffUTCTime now startTime)))\n                          t = min 1.0 (speed * fromRational (toRational (diffUTCTime now startTime)) :: Double)\n                      when (blend >= 255) (set animate [value := Nothing])\n                      curTile <- get currentTile value\n                      let (w, h) = tileRect curTile\n\n                      gc <- graphicsContextCreate dc\n                      newModel <- get model value\n                      let midModel = interpolateModel t oldModel newModel\n                          withLayer opacity action = do\n                              graphicsContextBeginLayer gc opacity\n                              action\n                              graphicsContextEndLayer gc\n                          restoringContext action = do\n                              graphicsContextPushState gc\n                              action\n                              graphicsContextPopState gc\n\n                      let zoom :: (Double, Double) -> (Double, Double) -> IO () -> IO ()\n                          zoom (scaleX, scaleY) (cx, cy) action = do\n                              restoringContext $ do\n                                  graphicsContextTranslate gc cx cy\n                                  graphicsContextScale gc (sz scaleX scaleY)\n                                  action\n\n                          viewCenterX = fromIntegral w / 2\n                          viewCenterY = fromIntegral h / 2\n                          dx = (fst (modelCenter newModel) - fst (modelCenter oldModel))\n                              / fst (modelPixelDim oldModel)\n                          dy = negate (snd (modelCenter newModel) - snd (modelCenter oldModel))\n                                     / snd (modelPixelDim oldModel)\n\n                      -- draw the old image\n                      let k = 1 / sqrt ( (fst (modelPixelDim oldModel) * snd (modelPixelDim oldModel))\n                                   / (fst (modelPixelDim newModel) * snd (modelPixelDim newModel)))\n                          t' = if (k - 1)^2 < 0.05 then t else (1 - k ** t) / (1 - k)\n                      graphicsContextTranslate gc viewCenterX viewCenterY\n                      graphicsContextScale gc (sz (fst (modelPixelDim oldModel)\n                                                 / fst (modelPixelDim midModel))\n                                                  (snd (modelPixelDim oldModel)\n                                                 / snd (modelPixelDim midModel)))\n                      graphicsContextTranslate gc (negate viewCenterX) (negate viewCenterY)\n                      graphicsContextTranslate gc (negate $ dx * t') (negate $ dy * t')\n\n                      withLayer 1 $ restoringContext $ do\n                              zoom (1.0, 1.0)\n                                   (viewCenterX, viewCenterY)\n\n                              $ case oldImage of\n                                    Nothing -> pure ()\n                                    Just im -> drawImage dc im (WX.pt\n                                                               (round $ negate viewCenterX)\n                                                               (round $ negate viewCenterY)) []\n                      -- draw the new image\n                      withLayer (min 1 t) $ do\n                          let zoomRatioX = fst (modelPixelDim newModel) / fst (modelPixelDim oldModel)\n                              zoomRatioY = snd (modelPixelDim newModel) / snd (modelPixelDim oldModel)\n                          restoringContext $ do\n                              zoom (zoomRatioX, zoomRatioY)\n                                   (viewCenterX + dx, viewCenterY + dy)\n\n                                   $ get savedTileImage value >>= \\case\n                                       Nothing -> pure ()\n                                       Just im -> drawImage dc im (WX.pt\n                                                                  (round $ negate viewCenterX)\n                                                                  (round $ negate viewCenterY)) []\n          ]\n\n    let viewToModel pt = do\n            Size { sizeW = w, sizeH = h } <- get f clientSize\n            let dim = (w,h)\n                fullViewRect = rectangle (Viewport (0,0)) (Viewport dim)\n            modelRect <- modelToRect @(Double,Double) dim <$> get model value\n            pure (convertRect fullViewRect modelRect $ Viewport (pointX pt, pointY pt))\n\n    -- Set click and drag event handlers\n    set p [ on mouse   := \\case\n              MouseLeftDown pt modifiers | isNoShiftAltControlDown modifiers -> do\n                set lastClick [value := Just $ Viewport (pointX pt, pointY pt)]\n                propagateEvent\n\n              MouseLeftUp pt modifiers | isNoShiftAltControlDown modifiers -> do\n                dragBox <- getDragBox lastClick draggedTo\n                case dragBox of\n                    Nothing  -> do\n                        -- Completed a click, recenter to the clicked point.\n                        Size { sizeW = w, sizeH = h } <- get f clientSize\n                        oldModel <- get model value\n                        newCenter <- viewToModel pt\n                        set model [value := oldModel\n                                    { modelCenter = toCoords newCenter }]\n\n                        get currentTile value >>= cancelTile\n                        newViewerTile <- renderTile' renderId renderAction (w, h) model\n                        set currentTile [value := newViewerTile]\n\n                        startAnimatingFrom oldModel\n                        triggerRepaint\n                    Just box -> do\n                        -- Completed a drag. Zoom in to the dragged box, unless\n                        -- the box is pathologically small; in that case, treat\n                        -- the action as if it were a simple click.\n                        selectRegion box\n                        oldModel <- get model value\n                        Size { sizeW = w, sizeH = h } <- get f clientSize\n                        newCenter <- viewToModel (viewportToPoint $ rectCenter box)\n                        let (px, py) = modelPixelDim oldModel\n                            (boxW, boxH) = dimensions box\n                            oldArea = fromIntegral (w * h)\n                            newArea = boxW * boxH\n                            literalScale = sqrt (newArea / oldArea)\n                            scale = if literalScale < 0.001 then 1 else literalScale\n                        set model [value := oldModel\n                                    { modelCenter = toCoords newCenter\n                                    , modelPixelDim = (px * scale, py * scale)\n                                    }]\n                        get currentTile value >>= cancelTile\n                        newViewerTile <- renderTile' renderId renderAction (w, h) model\n                        set currentTile [value := newViewerTile]\n                        startAnimatingFrom oldModel\n                        triggerRepaint\n\n                set draggedTo [value := Nothing]\n                set lastClick [value := Nothing]\n                propagateEvent\n\n              MouseLeftDrag pt modifiers | isNoShiftAltControlDown modifiers -> do\n                set draggedTo [value := Just $ Viewport (pointX pt, pointY pt)]\n                mpt <- viewToModel pt\n                set status [text := show mpt]\n\n                dragBox <- getDragBox lastClick draggedTo\n                case dragBox of\n                    Nothing -> return ()\n                    Just _  -> triggerRepaint\n\n                propagateEvent\n\n              MouseMotion pt modifiers | isNoShiftAltControlDown modifiers -> do\n                mpt <- viewToModel pt\n                set status [text := show mpt]\n                propagateEvent\n\n              -- other mouse events\n              _ -> propagateEvent\n          ]\n\n    -- Add a timer which will check for repainting requests, ~10Hz\n    _ <- timer f [ interval := 100\n                 , enabled := True\n                 , on command := do\n                        curTile <- get currentTile value\n                        ifModified curTile $ do\n                            viewRect <- windowGetViewRect f\n                            tileImage <- generateTileImage curTile viewRect\n                            saved <- imageCopy tileImage\n                            set savedTileImage [value := Just saved]\n                            triggerRepaint\n                 ]\n\n    -- Animation timer. At ~65Hz, check if we are animating between\n    -- two views. If so, step the animation and repaint.\n    _ <- timer f [ interval := 16\n                 , enabled := True\n                 , on command := get animate value >>= \\case\n                         Nothing -> pure ()\n                         Just _  -> triggerRepaint\n                 ]\n\n    -- onResizeTimer is a one-shot timer that fires 100ms after the\n    -- frame has been resized. If another resize event comes in during\n    -- that interval, the timer is reset to 100ms. When the timer fires,\n    -- we kick off a new rendering task to build the contents of the\n    -- window. Using a timer lets us avoid starting hundreds of rendering\n    -- tasks while the user adjusts their window size.\n    onResizeTimer <- timer f [ interval := 100\n                             , enabled := False ]\n    set onResizeTimer [ on command := do\n                              set onResizeTimer [enabled := False] -- one-shot\n                              needResize <- get pendingResize value\n                              when needResize $ do\n                                  set pendingResize [value := False]\n                                  Size { sizeW = w0, sizeH = h0 } <- get f clientSize\n                                  let w = roundUp w0 16\n                                      h = roundUp h0 16\n                                      roundUp x n = case x `mod` n of\n                                          0 -> x\n                                          k -> x + (n - k)\n                                  get currentTile value >>= cancelTile\n                                  newViewerTile <- renderTile' renderId renderAction (w, h) model\n                                  set currentTile [value := newViewerTile]\n                                  -- no animation?\n                                  triggerRepaint\n                      ]\n\n    -- Add the status bar, menu bar, and layout to the frame\n    set f [ statusBar := [status, toolStatus]\n          , menuBar   := [file,tools,hlp]\n          , layout    := fill $ minsize (sz 512 512) $ widget p\n          , on resize := do\n                  set onResizeTimer [enabled := False]\n                  set pendingResize [value := True]\n                  set onResizeTimer [enabled := True]\n                  propagateEvent\n          , on (menu about) :=\n              infoDialog f \"About FractalStream\" $ unlines\n              [ \"Contributors:\"\n              , \"Matt Noonan\"\n              ]\n          ]\n\n\nrenderTile' :: Valued w\n            => IORef Int\n            -> (Word32 -> Word32 -> Complex Double -> Complex Double -> Ptr Word8 -> IO ())  --([(Double, Double)] -> IO [Color])\n            -> (Int, Int)\n            -> w Model\n            -> IO Tile\nrenderTile' renderId action dim model = do\n    iD <- atomicModifyIORef' renderId (\\x -> (x + 1, x + 1))\n    modelRect <- modelToRect dim <$> get model value\n    let action' p q x y c = do\n            curId <- readIORef renderId\n            if (curId == iD) then action p q x y c else pure ()\n    renderTile action' dim modelRect\n\n-- | Paint the state of a tile into a device context.\ngenerateTileImage\n    :: Tile    -- ^ A tile to convert to an image\n    -> Rect    -- ^ The enclosing view rectangle\n    -> IO (Image ())\n\ngenerateTileImage viewerTile _windowRect = do\n    let (width, height) = tileRect viewerTile\n    --let Point { pointX = fWidth, pointY = fHeight } = rectBottomRight windowRect\n    --let (x0, y0) = ( (fWidth  + width ) `div` 2 - width  ,\n    --                 (fHeight + height) `div` 2 - height )\n    --putStrLn \"generateTileImage\"\n    withSynchedTileBuffer viewerTile (imageCreateFromData (sz width height))\n\ndrawCenteredImage :: Image b -> DC d -> Rect -> (Int,Int) -> IO ()\n\ndrawCenteredImage img dc windowRect (width, height) = do\n    let Point { pointX = fWidth, pointY = fHeight } = rectBottomRight windowRect\n    let (x0, y0) = ( (fWidth  + width ) `div` 2 - width  ,\n                     (fHeight + height) `div` 2 - height )\n    drawImage dc img (WX.pt x0 y0) []\n\nviewportToPoint :: Viewport -> Point\nviewportToPoint (Viewport (x,y)) = Point { pointX = x, pointY = y }\n\npaintToolLayer :: Var (Maybe Viewport)\n               -> Var (Maybe Viewport)\n               -> DC d\n               -> Rect\n               -> Rect\n               -> IO ()\npaintToolLayer lastClick draggedTo dc _ _ = dcEncapsulate dc $ do\n    dragBox <- getDragBox lastClick draggedTo\n    case dragBox of\n        Nothing  -> return ()\n        Just box -> do\n            let boxPts = map viewportToPoint (rectPoints box)\n            drawBox dc (rgba 0 128 255 128) white boxPts\n\ngetDragBox :: Var (Maybe Viewport)\n           -> Var (Maybe Viewport)\n           -> IO (Maybe (Rectangle Viewport))\ngetDragBox lastClick draggedTo = do\n    dragSrc <- get lastClick value\n    dragTgt <- get draggedTo value\n    return $ case (dragSrc, dragTgt) of\n        (Just p1, Just p2) -> Just $ rectangle p1 p2\n        _                  -> Nothing\n\ndrawBox :: DC d\n        -> Color\n        -> Color\n        -> [Point]\n        -> IO ()\ndrawBox dc fillColor lineColor coords =\n    polygon dc coords [ brush := brushSolid fillColor\n                      , pen := penColored lineColor 2\n                      ]\n\nselectRegion :: Rectangle Viewport -> IO ()\nselectRegion r = do\n    putStrLn $ \"selected region \" ++ show r\n    return ()\n", "meta": {"hexsha": "638d8d291fbbeca9b64ce4ecd96ba35ede8841e8", "size": 31322, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "fractalstream-ui-wx/src/UI/WX/Viewer.hs", "max_stars_repo_name": "matt-noonan/FractalStream", "max_stars_repo_head_hexsha": "2a51be0750497daa0afaa6750ef4f73e49e81458", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-06T02:46:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T08:06:39.000Z", "max_issues_repo_path": "fractalstream-ui-wx/src/UI/WX/Viewer.hs", "max_issues_repo_name": "matt-noonan/FractalStream", "max_issues_repo_head_hexsha": "2a51be0750497daa0afaa6750ef4f73e49e81458", "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": "fractalstream-ui-wx/src/UI/WX/Viewer.hs", "max_forks_repo_name": "matt-noonan/FractalStream", "max_forks_repo_head_hexsha": "2a51be0750497daa0afaa6750ef4f73e49e81458", "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": 43.0839064649, "max_line_length": 129, "alphanum_fraction": 0.4924334334, "num_tokens": 7020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.22191284268188705}}
{"text": "-----------------------------------------------------------------------------\n-- |\n-- Module      :  Numeric.Statistics.Viterbi.Discrete.Lazy\n-- Copyright   :  (c) A. V. H. McPhail 2011\n-- License     :  BSD3\n--\n-- Maintainer  :  haskell.vivian.mcphail <at> gmail <dot> com\n-- Stability   :  provisional\n-- Portability :  portable\n--\n-- Viterbi Algorithm\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.Statistics.Viterbi.Discrete.Lazy (\n                          ) where\n\n\n-----------------------------------------------------------------------------\n\nimport qualified Data.Array.IArray as I \n\nimport Numeric.LinearAlgebra\n\nimport Numeric.GSL.Statistics\n\nimport Numeric.Statistics\n\nimport System.Random\n\n-----------------------------------------------------------------------------\n\nnewtype Viterbi a = Viterbi {\n      _memory :: Int\n    , _states :: Int\n    \n\n\n\n\ntrain :: Int       -- ^ sequence length", "meta": {"hexsha": "59db5352441c84304909d2ccb5bc670da316df71", "size": 953, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/Statistics/Viterbi/Discrete/Lazy.hs", "max_stars_repo_name": "amcphail/hstatistics", "max_stars_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-05-14T19:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T15:23:53.000Z", "max_issues_repo_path": "lib/Numeric/Statistics/Viterbi/Discrete/Lazy.hs", "max_issues_repo_name": "amcphail/hstatistics", "max_issues_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-12-14T23:36:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T23:18:48.000Z", "max_forks_repo_path": "lib/Numeric/Statistics/Viterbi/Discrete/Lazy.hs", "max_forks_repo_name": "amcphail/hstatistics", "max_forks_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-05-24T22:51:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-13T19:12:30.000Z", "avg_line_length": 23.243902439, "max_line_length": 77, "alphanum_fraction": 0.4323189927, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.21996500622684403}}
{"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE ParallelListComp #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE GeneralisedNewtypeDeriving #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n\n-- module Year2021.DayX where\nmodule DayX where\n\nimport Util\nimport Data.Cyclic (Cyclic, Cyclic2)\nimport qualified Data.Cyclic as Cyclic\nimport Data.Grid (Grid)\nimport qualified Data.Grid as Grid\n\nimport Numeric\nimport Numeric.Bool\nimport Numeric.Char\n\nimport GHC.Generics\nimport GHC.TypeLits as TypeLits\n\nimport qualified Linear as Lin\nimport qualified Linear.V as Lin\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport qualified Linear.Matrix as Mat\n\nimport Debug.Trace\nimport Debug.Pretty.Simple\n\nimport Text.Regex.PCRE\nimport Text.Pretty.Simple\nimport Text.Read (readMaybe)\nimport qualified Text.Megaparsec as Par\nimport qualified Text.Megaparsec.Char as Par\nimport qualified Text.Megaparsec.Char.Lexer as Lex\n\nimport qualified Data.SBV as SBV\nimport qualified Data.SBV.Internals as SBV\nimport Data.String.Here\nimport Data.Tuple\nimport Data.Default\nimport Data.Proxy\nimport Data.Void\nimport Data.Word\nimport Data.Bits\nimport Data.Ratio\nimport Data.Bool\nimport Data.Bifunctor hiding (first, second)\nimport Data.Complex\nimport Data.Foldable\nimport Data.Char\nimport Data.Semigroup\nimport Data.Monoid\nimport Data.Functor\nimport Data.Ord\nimport Data.Function\nimport Data.Function.Memoize\nimport Data.Functor.Identity\nimport Data.Either\nimport Data.Maybe\nimport Data.List\nimport qualified Data.List.Extra as Extra\nimport Data.List.Split\nimport qualified Data.Conduit as Cond\nimport Data.Conduit ((.|))\n\nimport Control.Parallel\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport Control.Arrow\nimport Control.Concurrent\nimport Control.Lens (_1, _2, _3, _4, _5, _6, _7, _8)\nimport qualified Control.Lens as Lens\nimport qualified Numeric.Lens as Lens\nimport Control.Lens.Operators hiding ((??))\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Extra\nimport Control.Monad.Reader\nimport Control.Monad.Writer\nimport Control.Monad.State\nimport Control.Monad.RWS\nimport Control.Monad.Except\nimport Control.Monad.ST\nimport qualified Control.Monad.Combinators as Comb\nimport qualified Control.Monad.Combinators.Expr as Comb\n\nimport System.FilePath\n\nimport Data.Graph.Inductive (Graph, Gr)\nimport qualified Data.Graph.Inductive as Graph\nimport Data.List.PointedList (PointedList)\nimport qualified Data.List.PointedList as PList\nimport qualified Data.List.PointedList.Circular as PCList\nimport Data.DList (DList)\nimport qualified Data.DList as DList\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map.Syntax\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Bimap (Bimap)\nimport qualified Data.Bimap as Bimap\nimport Data.Sequence (Seq((:<|), (:|>)))\nimport qualified Data.Sequence as Seq\nimport Data.Vector.Generic (Vector)\nimport Data.Vector.Generic.Mutable (MVector)\nimport qualified Data.Vector as VecB\nimport qualified Data.Vector.Mutable as VecBM\nimport qualified Data.Vector.Unboxed as VecU\nimport qualified Data.Vector.Unboxed.Mutable as VecUM\nimport qualified Data.Vector.Storable as VecS\nimport qualified Data.Vector.Storable.Mutable as VecSM\nimport qualified Data.Vector.Generic as Vec\nimport qualified Data.Vector.Generic.Mutable as VecM\nimport Data.Tree (Tree)\nimport qualified Data.Tree as Tree\nimport Data.PQueue.Prio.Min (MinPQueue)\nimport qualified Data.Sequence as MinPQ\nimport Data.PQueue.Prio.Max (MaxPQueue)\nimport qualified Data.Sequence as MaxPQ\n\nimport qualified Language.Haskell.TH as TH\nimport qualified Language.Haskell.TH.Syntax as TH\n\nmain = do\n  input <- readFile (replaceExtension __FILE__ \".in\")\n  print input\n\n", "meta": {"hexsha": "1cfa006dd947f956368cae021684115fb7d14787", "size": 4119, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/DayX.hs", "max_stars_repo_name": "mingmingrr/advent-of-code-2018", "max_stars_repo_head_hexsha": "89b6f0474877f954aea0528069b5553d18174a99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-14T06:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-14T06:02:01.000Z", "max_issues_repo_path": "src/DayX.hs", "max_issues_repo_name": "mingmingrr/advent-of-code-2018", "max_issues_repo_head_hexsha": "89b6f0474877f954aea0528069b5553d18174a99", "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": "src/DayX.hs", "max_forks_repo_name": "mingmingrr/advent-of-code-2018", "max_forks_repo_head_hexsha": "89b6f0474877f954aea0528069b5553d18174a99", "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": 28.0204081633, "max_line_length": 57, "alphanum_fraction": 0.8021364409, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.37754068280545827, "lm_q1q2_score": 0.2194655657587773}}
{"text": "{-# LANGUAGE BangPatterns, RecordWildCards #-}\n-- |\n-- Module      : Criterion\n-- Copyright   : (c) 2009-2014 Bryan O'Sullivan\n--\n-- License     : BSD-style\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : GHC\n--\n-- Core benchmarking code.\n\nmodule Criterion.Internal\n    (\n      runAndAnalyse\n    , runAndAnalyseOne\n    , runOne\n    , runFixedIters\n    ) where\n\nimport qualified Data.Aeson as Aeson\nimport Control.DeepSeq (rnf)\nimport Control.Exception (evaluate)\nimport Control.Monad (foldM, forM_, void, when, unless)\nimport Control.Monad.Catch (MonadMask, finally)\nimport Control.Monad.Reader (ask, asks)\nimport Control.Monad.Trans (MonadIO, liftIO)\nimport Control.Monad.Trans.Except\nimport qualified Data.Binary as Binary\nimport Data.Int (Int64)\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport Criterion.Analysis (analyseSample, noteOutliers, analyseSimpleSample)\nimport Criterion.IO (header, headerRoot, critVersion, readJSONReports, writeJSONReports)\nimport Criterion.IO.Printf (note, printError, prolix, writeCsv)\nimport Criterion.Measurement (runBenchmark, runBenchmarkable_, secs)\nimport Criterion.Measurement.Types (hasFixedIters)\nimport Criterion.Monad (Criterion)\nimport Criterion.Report (report)\nimport Criterion.Types hiding (measure)\nimport Criterion.Measurement.Types.Internal (fakeEnvironment)\nimport qualified Data.Map as Map\nimport qualified Data.Vector as V\nimport Statistics.Types (Estimate(..),ConfInt(..),confidenceInterval,cl95,confidenceLevel)\nimport System.Directory (getTemporaryDirectory, removeFile)\nimport System.IO (IOMode(..), hClose, openTempFile, openFile, hPutStr, openBinaryFile)\nimport Text.Printf (printf)\n\n-- | Run a single benchmark.\nrunOne :: Int -> String -> Benchmarkable -> Criterion DataRecord\nrunOne i desc bm = do\n  Config{..} <- ask\n  (meas,timeTaken) <- liftIO $ runBenchmark bm timeLimit\n  when (timeTaken > timeLimit * 1.25) .\n    void $ prolix \"measurement took %s\\n\" (secs timeTaken)\n  return (Measurement i desc meas)\n\n-- | Analyse a single benchmark.\nanalyseOne :: Int -> Bool -> String -> V.Vector Measured -> Criterion DataRecord\nanalyseOne i simple desc meas = do\n  Config{..} <- ask\n  _ <- prolix \"analysing with %d resamples\\n\" resamples\n  erp <- runExceptT $ if simple\n    then analyseSimpleSample i desc meas\n    else analyseSample i desc meas\n  case erp of\n    Left err -> printError \"*** Error: %s\\n\" err\n    Right rpt@Report{..} -> do\n      let SampleAnalysis{..} = reportAnalysis\n          OutlierVariance{..} = anOutlierVar\n          wibble = case ovEffect of\n                     Unaffected -> \"unaffected\" :: String\n                     Slight -> \"slightly inflated\"\n                     Moderate -> \"moderately inflated\"\n                     Severe -> \"severely inflated\"\n          (builtin, others) = splitAt 1 anRegress\n      let r2 n = printf \"%.3f R\\178\" n\n      forM_ builtin $ \\Regression{..} ->\n        case Map.lookup \"iters\" regCoeffs of\n          Nothing -> return ()\n          Just t  -> bs secs \"time\" t >> bs r2 \"\" regRSquare\n      bs secs \"mean\" anMean\n      bs secs \"std dev\" anStdDev\n      forM_ others $ \\Regression{..} -> do\n        _ <- bs r2 (regResponder ++ \":\") regRSquare\n        forM_ (Map.toList regCoeffs) $ \\(prd,val) ->\n          bs (printf \"%.3g\") (\"  \" ++ prd) val\n      writeCsv\n        (desc,\n         estPoint anMean,   fst $ confidenceInterval anMean,   snd $ confidenceInterval anMean,\n         estPoint anStdDev, fst $ confidenceInterval anStdDev, snd $ confidenceInterval anStdDev\n        )\n      when (verbosity == Verbose || (ovEffect > Slight && verbosity > Quiet)) $ do\n        when (verbosity == Verbose) $ noteOutliers reportOutliers\n        _ <- note \"variance introduced by outliers: %d%% (%s)\\n\"\n             (round (ovFraction * 100) :: Int) wibble\n        return ()\n      _ <- note \"\\n\"\n      return (Analysed rpt)\n      where bs :: (Double -> String) -> String -> Estimate ConfInt Double -> Criterion ()\n            bs f metric e@Estimate{..} =\n              note \"%-20s %-10s (%s .. %s%s)\\n\" metric\n                   (f estPoint) (f $ fst $ confidenceInterval e) (f $ snd $ confidenceInterval e)\n                   (let cl = confIntCL estError\n                        str | cl == cl95 = \"\"\n                            | otherwise  = printf \", ci %.3f\" (confidenceLevel cl)\n                    in str\n                   )\n\n{-}\nanalyseOneSimple :: Int -> String -> V.Vector Measured\n                 -> Criterion ()\nanalyseOneSimple i desc meas = do\n    erp <- runExceptT $ analyseSimpleSample i desc meas\n    case erp of\n      Left err -> printError \"*** Error: %s\\n\" err\n      Right (stMean, stDev) -> do\n        bs secs \"mean\" stMean\n        bs secs \"std dev\" stDev\n  where\n    bs :: (Double -> String) -> String -> Estimate ConfInt Double -> Criterion ()\n    bs f metric e@Estimate{..} =\n      note \"%-20s %-10s (%s .. %s%s)\\n\" metric\n           (f estPoint) (f $ fst $ confidenceInterval e) (f $ snd $ confidenceInterval e)\n           (let cl = confIntCL estError\n                str | cl == cl95 = \"\"\n                    | otherwise  = printf \", ci %.3f\" (confidenceLevel cl)\n            in str\n           )\n-}\n\n-- | Run a single benchmark and analyse its performance.\nrunAndAnalyseOne :: Int -> String -> Benchmarkable -> Criterion DataRecord\nrunAndAnalyseOne i desc bm = do\n  Measurement _ _ meas <- runOne i desc bm\n  analyseOne i (hasFixedIters bm) desc meas\n\n-- | Run, and analyse, one or more benchmarks.\nrunAndAnalyse :: (String -> Bool) -- ^ A predicate that chooses\n                                  -- whether to run a benchmark by its\n                                  -- name.\n              -> Benchmark\n              -> Criterion ()\nrunAndAnalyse select bs = do\n  mbJsonFile <- asks jsonFile\n  (jsonFile, handle) <- liftIO $\n    case mbJsonFile of\n      Nothing -> do\n        tmpDir <- getTemporaryDirectory\n        openTempFile tmpDir \"criterion.json\"\n      Just file -> do\n        handle <- openFile file WriteMode\n        return (file, handle)\n  -- The type we write to the file is ReportFileContents, a triple.\n  -- But here we ASSUME that the tuple will become a JSON array.\n  -- This assumption lets us stream the reports to the file incrementally:\n  liftIO $ hPutStr handle $ \"[ \\\"\" ++ headerRoot ++ \"\\\", \" ++\n                             \"\\\"\" ++ critVersion ++ \"\\\", [ \"\n\n  for select bs $ \\idx desc bm -> do\n    _ <- note \"benchmarking %s\\n\" desc\n    Analysed rpt <- runAndAnalyseOne idx desc bm\n    unless (idx == 0) $\n      liftIO $ hPutStr handle \", \"\n    liftIO $ L.hPut handle (Aeson.encode (rpt::Report))\n\n\n\n{-}\n  for select bs $ \\idx desc bm -> do\n    _ <- note \"benchmarking %s\\n\" desc\n    if (hasFixedIters bm)\n    then do\n      measur <- runAndAnalyseOne idx desc bm\n      liftIO $ print measur\n    else do\n      Analysed rpt <- runAndAnalyseOne idx desc bm\n      unless (idx == 0) $\n        liftIO $ hPutStr handle \", \"\n      liftIO $ L.hPut handle (Aeson.encode (rpt::Report))\n-}\n  liftIO $ hPutStr handle \" ] ]\\n\"\n  liftIO $ hClose handle\n\n  rpts <- liftIO $ do\n    res <- readJSONReports jsonFile\n    case res of\n      Left err -> error $ \"error reading file \"++jsonFile++\":\\n  \"++show err\n      Right (_,_,rs) ->\n       case mbJsonFile of\n         Just _ -> return rs\n         _      -> removeFile jsonFile >> return rs\n\n  rawReport rpts\n  report rpts\n  json rpts\n  junit rpts\n\n\n-- | Write out raw binary report files.  This has some bugs, including and not\n-- limited to #68, and may be slated for deprecation.\nrawReport :: [Report] -> Criterion ()\nrawReport reports = do\n  mbRawFile <- asks rawDataFile\n  case mbRawFile of\n    Nothing   -> return ()\n    Just file -> liftIO $ do\n      handle <- openBinaryFile file ReadWriteMode\n      L.hPut handle header\n      forM_ reports $ \\rpt ->\n        L.hPut handle (Binary.encode rpt)\n      hClose handle\n\n\n-- | Run a benchmark without analysing its performance.\nrunFixedIters :: Int64            -- ^ Number of loop iterations to run.\n              -> (String -> Bool) -- ^ A predicate that chooses\n                                  -- whether to run a benchmark by its\n                                  -- name.\n              -> Benchmark\n              -> Criterion ()\nrunFixedIters iters select bs =\n  for select bs $ \\_idx desc bm -> do\n    _ <- note \"benchmarking %s\\n\" desc\n    liftIO $ runBenchmarkable_ bm iters\n\n-- | Iterate over benchmarks.\nfor :: (MonadMask m, MonadIO m) => (String -> Bool) -> Benchmark\n    -> (Int -> String -> Benchmarkable -> m ()) -> m ()\nfor select bs0 handle = go (0::Int) (\"\", bs0) >> return ()\n  where\n    go !idx (pfx, Environment mkenv cleanenv mkbench)\n      | shouldRun pfx mkbench = do\n        e <- liftIO $ do\n          ee <- mkenv\n          evaluate (rnf ee)\n          return ee\n        go idx (pfx, mkbench e) `finally` liftIO (cleanenv e)\n      | otherwise = return idx\n    go idx (pfx, Benchmark desc b)\n      | select desc' = do handle idx desc' b; return $! idx + 1\n      | otherwise    = return idx\n      where desc' = addPrefix pfx desc\n    go idx (pfx, BenchGroup desc bs) =\n      foldM go idx [(addPrefix pfx desc, b) | b <- bs]\n\n    shouldRun pfx mkbench =\n      any (select . addPrefix pfx) . benchNames . mkbench $ fakeEnvironment\n\n-- | Write summary JSON file (if applicable)\njson :: [Report] -> Criterion ()\njson rs\n  = do jsonOpt <- asks jsonFile\n       case jsonOpt of\n         Just fn -> liftIO $ writeJSONReports fn rs\n         Nothing -> return ()\n\n-- | Write summary JUnit file (if applicable)\njunit :: [Report] -> Criterion ()\njunit rs\n  = do junitOpt <- asks junitFile\n       case junitOpt of\n         Just fn -> liftIO $ writeFile fn msg\n         Nothing -> return ()\n  where\n    msg = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" ++\n          printf \"<testsuite name=\\\"Criterion benchmarks\\\" tests=\\\"%d\\\">\\n\"\n          (length rs) ++\n          concatMap single rs ++\n          \"</testsuite>\\n\"\n    single Report{..} = printf \"  <testcase name=\\\"%s\\\" time=\\\"%f\\\" />\\n\"\n               (attrEsc reportName) (estPoint $ anMean $ reportAnalysis)\n    attrEsc = concatMap esc\n      where\n        esc '\\'' = \"&apos;\"\n        esc '\"'  = \"&quot;\"\n        esc '<'  = \"&lt;\"\n        esc '>'  = \"&gt;\"\n        esc '&'  = \"&amp;\"\n        esc c    = [c]\n\n", "meta": {"hexsha": "b96313ef3be3c782d39a693f15f23654b0486390", "size": 10258, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Criterion/Internal.hs", "max_stars_repo_name": "input-output-hk/criterion-2", "max_stars_repo_head_hexsha": "4a99389084cba4eabd3149f37adee2a394d065a9", "max_stars_repo_licenses": ["BSD-2-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": "Criterion/Internal.hs", "max_issues_repo_name": "input-output-hk/criterion-2", "max_issues_repo_head_hexsha": "4a99389084cba4eabd3149f37adee2a394d065a9", "max_issues_repo_licenses": ["BSD-2-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": "Criterion/Internal.hs", "max_forks_repo_name": "input-output-hk/criterion-2", "max_forks_repo_head_hexsha": "4a99389084cba4eabd3149f37adee2a394d065a9", "max_forks_repo_licenses": ["BSD-2-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.5053380783, "max_line_length": 97, "alphanum_fraction": 0.6031390135, "num_tokens": 2691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.370225399544253, "lm_q1q2_score": 0.21942022343723389}}
{"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TypeFamilies #-}\n\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nmodule Arpack.Foreign.Real () where\n\nimport qualified Control.Concurrent.Lock as Lock\nimport Control.Exception (bracket, throwIO)\nimport Data.Maybe (fromMaybe)\nimport qualified Data.Vector.Storable as VS\nimport Data.Vector.Storable.Mutable (IOVector)\nimport qualified Data.Vector.Storable.Mutable as VSM\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types (CChar)\nimport Foreign.Storable.Complex ()\nimport qualified Numeric.LinearAlgebra.Devel as Dense\n\nimport Arpack.Exceptions\nimport Arpack.Foreign.Class\nimport qualified Arpack.Lock as Arpack\nimport Arpack.Options\n\n--\n-- * Foreign functions\n--\n\nforeign import ccall unsafe \"dnaupd_\"\n  dnaupd_ :: Ptr Int32  -- ido\n          -> Ptr CChar  -- bmat\n          -> Ptr Int32  -- n\n          -> Ptr CChar  -- which\n          -> Ptr Int32  -- nev\n          -> Ptr Double -- tol\n          -> Ptr Double -- resid\n          -> Ptr Int32  -- ncv\n          -> Ptr Double -- v\n          -> Ptr Int32  -- ldv\n          -> Ptr Int32  -- iparam\n          -> Ptr Int32  -- ipntr\n          -> Ptr Double -- workd\n          -> Ptr Double -- workl\n          -> Ptr Int32  -- lworkl\n          -> Ptr Int32  -- info\n          -> IO ()\n\nforeign import ccall unsafe \"dneupd_\"\n  dneupd_ :: Ptr Int32  -- rvec\n          -> Ptr CChar  -- howmny\n          -> Ptr Int32  -- select\n          -> Ptr Double -- dr\n          -> Ptr Double -- di\n          -> Ptr Double -- z\n          -> Ptr Int32  -- ldz\n          -> Ptr Double -- sigmar\n          -> Ptr Double -- sigmai\n          -> Ptr Double -- workev\n          -> CString    -- bmat\n          -> Ptr Int32  -- n\n          -> Ptr CChar  -- which\n          -> Ptr Int32  -- nev\n          -> Ptr Double -- tol\n          -> Ptr Double -- resid\n          -> Ptr Int32  -- ncv\n          -> Ptr Double -- v\n          -> Ptr Int32  -- ldv\n          -> Ptr Int32  -- iparam\n          -> Ptr Int32  -- ipntr\n          -> Ptr Double -- workd\n          -> Ptr Double -- workl\n          -> Ptr Int32  -- lworkl\n          -> Ptr Int32  -- info\n          -> IO ()\n\n--\n-- * Types\n--\n\ndata AUPD\n  = AUPD\n    { ido :: {-# UNPACK #-} !(Ptr Int32)\n    , bmat :: {-# UNPACK #-} !(Ptr CChar)\n    , n :: {-# UNPACK #-} !(Ptr Int32)\n    , which :: {-# UNPACK #-} !(Ptr CChar)\n    , nev :: {-# UNPACK #-} !(Ptr Int32)\n    , tol :: {-# UNPACK #-} !(Ptr Double)\n    , resid :: {-# UNPACK #-} !(IOVector Double)\n    , ncv :: {-# UNPACK #-} !(Ptr Int32)\n    , v :: {-# UNPACK #-} !(IOVector Double)\n    , ldv :: {-# UNPACK #-} !(Ptr Int32)\n    , iparam :: {-# UNPACK #-} !(IOVector Int32)\n    , ipntr :: {-# UNPACK #-} !(IOVector Int32)\n    , workd :: {-# UNPACK #-} !(IOVector Double)\n    , workl :: {-# UNPACK #-} !(IOVector Double)\n    , lworkl :: {-# UNPACK #-} !(Ptr Int32)\n    , info :: {-# UNPACK #-} !(Ptr Int32)\n    }\n\nwithAUPD :: Options Double -> Int -> (AUPD -> IO a) -> IO a\nwithAUPD options dim = bracket initAUPD freeAUPD where\n\n  initAUPD = do\n    let\n      _nev = number options\n\n      -- Largest number of basis vectors to use.\n      -- Work per iteration is O(dim * ncv ^ 2).\n\n      _ncv = min dim (4 * _nev)\n\n      _lworkl = 3 * _ncv * _ncv + 6 * _ncv\n\n    ido <- new 0\n    bmat <- newCString \"I\"\n    n <- new (fromIntegral dim)\n    which <- newCString \"SR\"\n    nev <- new (fromIntegral _nev)\n    tol <- new 0\n    resid <- VSM.new dim\n    ncv <- new (fromIntegral _ncv)\n    v <- VSM.new (dim * _ncv)\n    ldv <- new (fromIntegral dim)\n\n    iparam <- VSM.new 11\n    -- shift strategy\n    VSM.write iparam (1 - 1) 1\n    -- maximum number of iterations\n    VSM.write iparam (3 - 1)\n      (fromIntegral (fromMaybe (3 * dim) (maxIterations options)))\n    -- block size\n    VSM.write iparam (4 - 1) 1\n    -- eigenproblem type\n    VSM.write iparam (7 - 1) 1\n\n    ipntr <- VSM.new 14\n    workd <- VSM.new (3 * dim)\n    workl <- VSM.new _lworkl\n    lworkl <- new (fromIntegral _lworkl)\n    info <- new 0\n\n    pure AUPD {..}\n\n  freeAUPD AUPD {..} = do\n    free ido\n    free bmat\n    free n\n    free which\n    free nev\n    free tol\n    free ncv\n    free ldv\n    free lworkl\n    free info\n\ndata EUPD\n  = EUPD\n    { rvec :: {-# UNPACK #-} !(Ptr Int32)\n    , howmny :: {-# UNPACK #-} !(Ptr CChar)\n    , select :: {-# UNPACK #-} !(IOVector Int32)\n    , dr :: {-# UNPACK #-} !(IOVector Double)\n    , di :: {-# UNPACK #-} !(IOVector Double)\n    , z :: {-# UNPACK #-} !(IOVector Double)\n    , ldz :: {-# UNPACK #-} !(Ptr Int32)\n    , sigmar :: {-# UNPACK #-} !(Ptr Double)\n    , sigmai :: {-# UNPACK #-} !(Ptr Double)\n    , workev :: {-# UNPACK #-} !(IOVector Double)\n    }\n\nwithEUPD :: AUPD -> (EUPD -> IO a) -> IO a\nwithEUPD (AUPD {..}) = bracket initEUPD freeEUPD where\n\n  initEUPD = do\n    _nev <- fromIntegral <$> peek nev\n    _ncv <- fromIntegral <$> peek ncv\n    dim <- fromIntegral <$> peek n\n\n    rvec <- new 1\n    howmny <- newCString \"A\"\n    select <- VSM.new _ncv\n    dr <- VSM.new (_nev + 1)\n    di <- VSM.new (_nev + 1)\n    z <- VSM.new (dim * _nev)\n    ldz <- new (fromIntegral dim)\n    sigmar <- malloc\n    sigmai <- malloc\n    workev <- VSM.new (2 * _ncv)\n    pure EUPD {..}\n\n  freeEUPD (EUPD {..}) = do\n    free rvec\n    free howmny\n    free ldz\n    free sigmar\n    free sigmai\n\n--\n-- * Wrappers\n--\n\naupd :: AUPD -> IO ()\naupd (AUPD {..}) =\n  VSM.unsafeWith resid $ \\_resid ->\n  VSM.unsafeWith v $ \\_v ->\n  VSM.unsafeWith iparam $ \\_iparam ->\n  VSM.unsafeWith ipntr $ \\_ipntr ->\n  VSM.unsafeWith workd $ \\_workd ->\n  VSM.unsafeWith workl $ \\_workl ->\n\n  dnaupd_ ido bmat n which nev tol _resid ncv _v ldv\n          _iparam _ipntr _workd _workl lworkl info\n\neupd :: EUPD -> AUPD -> IO ()\neupd (EUPD {..}) (AUPD {..}) =\n  VSM.unsafeWith select $ \\_select ->\n  VSM.unsafeWith dr $ \\_dr ->\n  VSM.unsafeWith di $ \\_di ->\n  VSM.unsafeWith z $ \\_z ->\n  VSM.unsafeWith workev $ \\_workev ->\n  VSM.unsafeWith resid $ \\_resid ->\n  VSM.unsafeWith v $ \\_v ->\n  VSM.unsafeWith iparam $ \\_iparam ->\n  VSM.unsafeWith ipntr $ \\_ipntr ->\n  VSM.unsafeWith workd $ \\_workd ->\n  VSM.unsafeWith workl $ \\_workl ->\n\n  dneupd_ rvec howmny _select _dr _di _z ldz sigmar sigmai _workev\n          bmat n which nev tol _resid ncv _v ldv _iparam _ipntr\n          _workd _workl lworkl info\n\ninstance Arpack Double where\n\n  arpack !opts !dim !multiply\n    -- These variables are all banged because we need to be strict\n    -- in them _before_ we enter the locked segment of code! If we\n    -- wait until we're inside the lock, and evaluating one of these\n    -- variables invokes 'arpack' again, the program will deadlock!\n    = withAUPD opts dim $ \\stateA@(AUPD {..}) -> do\n\n      let\n        loop = do\n          aupd stateA\n          peek ido >>= \\case\n            99 -> do\n              peek info >>= \\case\n                0 -> pure ()\n                1 -> throwIO MaxIterations\n                3 -> throwIO NoShifts\n                i -> throwIO (XYAUPD i)\n\n            i | abs i == 1 -> do\n                  xi <- fromIntegral <$> VSM.read ipntr 0\n                  let\n                    x = VSM.slice (xi - 1) dim workd\n                  yi <- fromIntegral <$> VSM.read ipntr 1\n                  let\n                    y = VSM.slice (yi - 1) dim workd\n                  multiply y x\n                  loop\n\n              | otherwise -> throwIO (Unimplemented i)\n\n        extract = withEUPD stateA $ \\stateE@(EUPD {..}) -> do\n          eupd stateE stateA\n\n          peek info >>= \\case\n            0 -> pure ()\n            1 -> throwIO Reallocate\n            i -> throwIO (XYEUPD i)\n\n          evals <- VS.unsafeFreeze (VSM.slice 0 (number opts) dr)\n          evecs <- VS.unsafeFreeze (VSM.slice 0 (number opts * dim) z)\n          let matrixFromVector = Dense.matrixFromVector Dense.ColumnMajor\n          pure (evals, matrixFromVector dim (number opts) evecs)\n\n      Lock.with Arpack.lock (loop >> extract)\n", "meta": {"hexsha": "87dfd2a7982f71e4ec91e0423b0c09708d95237e", "size": 7962, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Arpack/Foreign/Real.hs", "max_stars_repo_name": "ttuegel/arpack", "max_stars_repo_head_hexsha": "004b7b4444f2ab7b2b1c07ed6aecf279e330f9a5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-17T01:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-17T01:05:40.000Z", "max_issues_repo_path": "src/Arpack/Foreign/Real.hs", "max_issues_repo_name": "ttuegel/arpack", "max_issues_repo_head_hexsha": "004b7b4444f2ab7b2b1c07ed6aecf279e330f9a5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-09-30T09:59:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-30T19:56:06.000Z", "max_forks_repo_path": "src/Arpack/Foreign/Real.hs", "max_forks_repo_name": "ttuegel/arpack", "max_forks_repo_head_hexsha": "004b7b4444f2ab7b2b1c07ed6aecf279e330f9a5", "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": 28.4357142857, "max_line_length": 73, "alphanum_fraction": 0.5424516453, "num_tokens": 2515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.2190816271983836}}
{"text": "{-# LANGUAGE BangPatterns      #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections     #-}\nmodule Releaser.SettingsRouting\n    ( routing\n    , bnNbn\n    , mapProductType\n    , productTypes\n    , ConfigRouting (..)\n    , ConfigProcTimes (..)\n    , queues\n    , isRoutedOver'\n    , machines\n    , allBlocks\n    , procTimes\n    , procTimesConst\n    ) where\n\nimport           Control.Arrow                       (second)\nimport           Data.List                           (nub, sort)\nimport           Data.Text                           (Text)\nimport           Prelude\nimport           SimSim                              hiding (allBlocks, productTypes,\n                                                      queues)\nimport           Statistics.Distribution\nimport           Statistics.Distribution.Exponential\nimport           Statistics.Distribution.Uniform\nimport           System.Random.MWC\n\nimport           Releaser.Routing.Ops\nimport           Releaser.Routing.Type\n\n\nrouting :: ConfigRouting\nrouting =\n  -- routingSingleStageSingleProduct\n  -- routingSingleStage\n  -- routingDiverging2Stages\n  routingDiverging3Stages\n\nprocTimes :: ConfigProcTimes\nprocTimes =\n  -- procTimesDiverging2Stages\n  -- procTimesDiverging3StagesUnif\n  procTimesDiverging3StagesExp\n\nproductTypes :: [ProductType]\nproductTypes = sort $ nub $ map (fst . fst) (configRoutingRoutes routing)\n\n\nisRoutedOver' :: Block -> ProductType -> Bool\nisRoutedOver' bl pt = isRoutedOver (configRoutingRoutes routing) pt bl\n\nbnNbn :: Bool\nbnNbn = False -- True\n\nmapProductType :: ProductType -> ProductType\nmapProductType x | not bnNbn = x\nmapProductType (Product 1) = Product 1\nmapProductType (Product 2) = Product 2\nmapProductType (Product 3) = Product 1\nmapProductType (Product 4) = Product 1\nmapProductType (Product 5) = Product 2\nmapProductType (Product 6) = Product 1\nmapProductType _ = error \"function mapProductType not complete in SettingsRouting\"\n\nallBlocks :: [Block]\nallBlocks = nub $ map (snd . fst) (configRoutingRoutes routing)\n\nqueues :: [Block]\nqueues = filter isQueue allBlocks\n\n\nmachines :: [Block]\nmachines = filter isMachine allBlocks\n\n\n--\n\ndata ConfigProcTimes = ConfigProcTimes\n  { configProcTimesName :: !Text\n  , configProcTimes     :: !ProcTimes\n  }\n\ntest :: IO ()\ntest = do\n  let mkTime = timeFromDouble <$> withSystemRandom (asGenIO $ genContVar (exponential (960 / 80)))\n      nr = 10000\n  ts <- mapM (const mkTime ) [1..nr]\n\n  print (sum ts / fromIntegral nr)\n\n\nprocTimesDiverging3StagesExp :: ConfigProcTimes\nprocTimesDiverging3StagesExp = ConfigProcTimes \"Proc Times diverging 3 stages: Exp\" $\n  map (second $ filter ((`elem` productTypes) . fst)) $ filter ((`elem` allBlocks) . fst)\n  [ (Machine 1, forAllProducts (fmap timeFromDouble . genContVar (exponential (960  / 80))))\n  , (Machine 2, forAllProducts (fmap timeFromDouble . genContVar (exponential (960 / 160))))\n  , (Machine 3, forAllProducts (fmap timeFromDouble . genContVar (exponential (960 / 155))))\n  , (Machine 4, forAllProducts (fmap timeFromDouble . genContVar (exponential (960 / 210))))\n  , (Machine 5, forAllProducts (fmap timeFromDouble . genContVar (exponential (960 / 285))))\n  , (Machine 6, forAllProducts (fmap timeFromDouble . genContVar (exponential (960 / 215))))\n  ]\n\n  where forAllProducts x = map (,x) productTypes\n\nprocTimesDiverging3StagesUnif :: ConfigProcTimes\nprocTimesDiverging3StagesUnif = ConfigProcTimes \"Proc Times diverging 3 stages: Unif\" $\n  map (second $ filter ((`elem` productTypes) . fst)) $ filter ((`elem` allBlocks) . fst)\n  [ (Machine 1, forAllProducts (fmap timeFromDouble . genContVar (uniformDistr (30 / 960) (130 / 960))))\n  , (Machine 2, forAllProducts (fmap timeFromDouble . genContVar (uniformDistr (80 / 960) (240 / 960))))\n  , (Machine 3, forAllProducts (fmap timeFromDouble . genContVar (uniformDistr (50 / 960) (260 / 960))))\n  , (Machine 4, forAllProducts (fmap timeFromDouble . genContVar (uniformDistr (50 / 960) (370 / 960))))\n  , (Machine 5, forAllProducts (fmap timeFromDouble . genContVar (uniformDistr (200 / 960) (370 / 960))))\n  , (Machine 6, forAllProducts (fmap timeFromDouble . genContVar (uniformDistr (110 / 960) (320 / 960))))\n  ]\n\n  where forAllProducts x = map (,x) productTypes\n\n\nprocTimesDiverging2Stages :: ConfigProcTimes\nprocTimesDiverging2Stages = ConfigProcTimes \"Proc Times diverging 2 stages: Unif\" $\n  map (second $ filter ((`elem` productTypes) . fst)) $ filter ((`elem` allBlocks) . fst)\n  [ (Machine 1, [ (Product 1, fmap timeFromDouble . genContVar (uniformDistr (70 / 960) (130 / 960)))\n                , (Product 2, fmap timeFromDouble . genContVar (uniformDistr (70 / 960) (130 / 960)))])\n  , (Machine 2, [(Product 1, fmap timeFromDouble . genContVar (uniformDistr (130 / 960) (170 / 960)))])\n  , (Machine 3, [(Product 2, fmap timeFromDouble . genContVar (uniformDistr (180 / 960) (200 / 960)))])\n  ]\n\nprocTimesConst :: ConfigProcTimes\nprocTimesConst = ConfigProcTimes \"Proc Times diverging 2 stages: Const\" $\n  map (second $ filter ((`elem` productTypes) . fst)) $ filter ((`elem` allBlocks) . fst)\n    [ (Machine 1, [(Product 1, return . const (timeFromDouble (100 / 960))), (Product 2, return . const (timeFromDouble (100 / 960)))])\n    , (Machine 2, [(Product 1, return . const (timeFromDouble (150 / 960)))])\n    , (Machine 3, [(Product 2, return . const (timeFromDouble (190 / 960)))])\n    ]\n", "meta": {"hexsha": "e0683a5fda64980e64db66a2d6872378e843771d", "size": 5355, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Releaser/SettingsRouting.hs", "max_stars_repo_name": "schnecki/borl-releaser", "max_stars_repo_head_hexsha": "8ab5c4d73456daa3f26628315ad7a562b25e42d8", "max_stars_repo_licenses": ["Apache-2.0"], "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/Releaser/SettingsRouting.hs", "max_issues_repo_name": "schnecki/borl-releaser", "max_issues_repo_head_hexsha": "8ab5c4d73456daa3f26628315ad7a562b25e42d8", "max_issues_repo_licenses": ["Apache-2.0"], "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/Releaser/SettingsRouting.hs", "max_forks_repo_name": "schnecki/borl-releaser", "max_forks_repo_head_hexsha": "8ab5c4d73456daa3f26628315ad7a562b25e42d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0875912409, "max_line_length": 135, "alphanum_fraction": 0.6763772176, "num_tokens": 1549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.21869742810229945}}
{"text": "{-# LANGUAGE FlexibleContexts, UndecidableInstances #-}\n\nmodule School.Unit.UnitGradient\n( UnitGradient(..)\n, isGradientFail\n) where\n\nimport Numeric.LinearAlgebra (Container, Matrix, Vector)\n\ndata UnitGradient a =\n   BatchGradient (Matrix a)\n | GradientFail String deriving (Show)\n\ninstance (Container Vector a, Num a, Eq a) => Eq (UnitGradient a) where\n  (BatchGradient g1) == (BatchGradient g2) =\n    g1 == g2\n  (GradientFail _) == (GradientFail _) = True\n  _ == _ = False\n\nisGradientFail :: UnitGradient a -> Bool\nisGradientFail (GradientFail _) = True\nisGradientFail _ = False\n", "meta": {"hexsha": "0b06fabf398fdf30c726af511ccc1dc2dbe48e6e", "size": 581, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/School/Unit/UnitGradient.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "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": "src/School/Unit/UnitGradient.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "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": "src/School/Unit/UnitGradient.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "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": 25.2608695652, "max_line_length": 71, "alphanum_fraction": 0.7246127367, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21751576258908772}}
{"text": "{-# LANGUAGE TypeFamilies, CPP, ViewPatterns, MagicHash, UnboxedTuples, PatternGuards, FlexibleContexts, FlexibleInstances #-}\n{-# OPTIONS_GHC -fno-warn-overlapping-patterns #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Data.Set.Unboxed\n-- Copyright   :  (c) Edward Kmett 2009 (c) Daan Leijen 2002\n-- License     :  BSD3\n-- Maintainer  :  ekmett@gmail.com\n-- Stability   :  experimental\n-- Portability :  non-portable (type families, view patterns, unboxed tuples)\n--\n-- An efficient implementation of sets.\n--\n-- Since many function names (but not the type name) clash with\n-- \"Prelude\" names, this module is usually imported @qualified@, e.g.\n--\n-- >  import Data.Set.Unboxed (USet)\n-- >  import qualified Data.Set.Unboxed as USet\n--\n-- The implementation of 'USet' is based on /size balanced/ binary trees (or\n-- trees of /bounded balance/) as described by:\n--\n--    * Stephen Adams, \\\"/Efficient sets: a balancing act/\\\",\n--  Journal of Functional Programming 3(4):553-562, October 1993,\n--  <http://www.swiss.ai.mit.edu/~adams/BB/>.\n--\n--    * J. Nievergelt and E.M. Reingold,\n--  \\\"/Binary search trees of bounded balance/\\\",\n--  SIAM journal of computing 2(1), March 1973.\n--\n-- Note that the implementation is /left-biased/ -- the elements of a\n-- first argument are always preferred to the second, for example in\n-- 'union' or 'insert'.  Of course, left-biasing can only be observed\n-- when equality is an equivalence relation instead of structural\n-- equality.\n--\n-- Modified from \"Data.Set\" to use type families for automatic unboxing\n--\n-----------------------------------------------------------------------------\n\nmodule Data.Set.Unboxed ( \n            -- * Set type\n              USet          -- instance Eq,Ord,Show,Read\n            , US\n            , Boxed(Boxed, getBoxed)\n            , Size\n\n            -- * Operators\n            , (\\\\)\n\n            -- * Query\n            , null\n            , size\n            , member\n            , notMember\n            , isSubsetOf\n            , isProperSubsetOf\n            \n            -- * Construction\n            , empty\n            , singleton\n            , insert\n            , delete\n            \n            -- * Combine\n            , union, unions\n            , difference\n            , intersection\n            \n            -- * Filter\n            , filter\n            , partition\n            , split\n            , splitMember\n\n            -- * Map\n            , map\n            , mapMonotonic\n\n            -- * Fold\n            , fold\n\n            -- * Min\\/Max\n            , findMin\n            , findMax\n            , deleteMin\n            , deleteMax\n            , deleteFindMin\n            , deleteFindMax\n            , maxView\n            , minView\n\n            -- * Conversion\n\n            -- ** List\n            , elems\n            , toList\n            , fromList\n            \n            -- ** Ordered list\n            , toAscList\n            , fromAscList\n            , fromDistinctAscList\n                        \n            -- * Debugging\n            , showTree\n            , showTreeWith\n            , valid\n            ) where\n\nimport Prelude hiding (filter,foldr,null,map)\nimport qualified Data.List as List\nimport Data.Monoid (Monoid(..))\nimport Data.Word\nimport Data.Int\nimport Data.Complex\n\n{-\n-- just for testing\nimport Test.QuickCheck \nimport Data.List (nub,sort)\nimport qualified Data.List as List\n-}\n\n#if __GLASGOW_HASKELL__\nimport Text.Read\n#endif\n\n{--------------------------------------------------------------------\n  Operators\n--------------------------------------------------------------------}\ninfixl 9 \\\\ --\n\n-- | /O(n+m)/. See 'difference'.\n(\\\\) :: (US a, Ord a) => USet a -> USet a -> USet a\nm1 \\\\ m2 = difference m1 m2\n\n{--------------------------------------------------------------------\n  Sets are size balanced trees\n--------------------------------------------------------------------}\ntype Size     = Int\n\n-- | A set of values @a@.\ndata Set a    = Tip \n              | Bin {-# UNPACK #-} !Size !a !(USet a) !(USet a) \n\nclass US a where\n    data USet a\n\n    -- | Extract and rebox the specialized node format\n    view :: USet a -> Set a\n\n    -- | Apply the view to tip and bin continuations\n    viewk :: b -> (Size -> a -> USet a -> USet a -> b) -> USet a -> b\n    viewk f k x = case view x of\n        Bin s i l r -> k s i l r\n        Tip -> f\n\n    -- | View just the value and left and right child of a bin\n    viewBin :: USet a -> (# a, USet a, USet a #)\n    viewBin x = case view x of \n        Bin _ i l r -> (# i, l, r #)\n        Tip -> error \"Data.Set.Unboxed.viewBin\"\n\n    -- | /O(1)/. The number of elements in the set.\n    size :: USet a -> Size\n    size = viewk 0 size' where \n        size' s _ _ _ = s\n\n    -- | /O(1)/. Is this the empty set?\n    null :: USet a -> Bool\n    null x = size x == 0\n\n    -- | Smart tip constructor\n    tip :: USet a\n\n    -- | Smart bin constructor\n    bin :: Size -> a -> USet a -> USet a -> USet a\n\n    -- | Balance the tree\n    balance :: a -> USet a -> USet a -> USet a\n    balance x l r\n        | sizeL + sizeR <= 1    = bin sizeX x l r\n        | sizeR >= delta*sizeL  = case viewBin r of\n            (# v, ly, ry #) \n                | size ly < ratio*size ry        -> bin_ v (bin_ x l ly) ry\n                | (# x3, t2, t3 #) <- viewBin ly -> bin_ x3 (bin_ x l t2) (bin_ v t3 ry)\n        | sizeL >= delta*sizeR  = case viewBin l of\n            (# v, ly, ry #) \n                | size ry < ratio*size ly        -> bin_ v ly (bin_ x ry r)\n                | (# x3, t2, t3 #) <- viewBin ry -> bin_ x3 (bin_ v ly t2) (bin_ x t3 r)\n        | otherwise             = bin sizeX x l r\n        where\n            sizeL = size l\n            sizeR = size r\n            sizeX = sizeL + sizeR + 1\n        \n\n\ninstance (US a, Ord a) => Monoid (USet a) where\n    mempty  = empty\n    mappend = union\n    mconcat = unions\n\n{-\ninstance US a => Generator (USet a) where\n    type Elem (USet a) = a\n    mapReduce _ (null -> True) = mempty\n    mapReduce f (view -> Bin _s k l r) = mapReduce f l `mappend` f k `mappend` mapReduce f r\n-}\n\n{--------------------------------------------------------------------\n  Query\n--------------------------------------------------------------------}\n-- | /O(log n)/. Is the element in the set?\nmember :: (US a, Ord a) => a -> USet a -> Bool\nmember x = go where\n    cmpx = compare x\n    go = viewk False $ \\_ y l r -> case cmpx y of\n        LT -> go l\n        GT -> go r\n        EQ -> True\n\n-- | /O(log n)/. Is the element not in the set?\nnotMember :: (US a, Ord a) => a -> USet a -> Bool\nnotMember x t = not $ member x t\n\n{--------------------------------------------------------------------\n  Construction\n--------------------------------------------------------------------}\n-- | /O(1)/. The empty set.\nempty :: US a => USet a\nempty = tip\n\n-- | /O(1)/. Create a singleton set.\nsingleton :: US a => a -> USet a\nsingleton x = bin 1 x tip tip\n\n{--------------------------------------------------------------------\n  Deletion\n--------------------------------------------------------------------}\n\n-- | /O(log n)/. Delete an element from a set.\ndelete :: (US a, Ord a) => a -> USet a -> USet a\ndelete x = go where\n    go = viewk tip $ \\ _ y l r -> case compare x y of\n        LT -> balance y (go l) r\n        GT -> balance y l (go r)\n        EQ -> glue l r\n\n{--------------------------------------------------------------------\n  Subset\n--------------------------------------------------------------------}\n-- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).\nisProperSubsetOf :: (US a, Ord a) => USet a -> USet a -> Bool\nisProperSubsetOf s1 s2 = (size s1 < size s2) && (isSubsetOf s1 s2)\n\n-- | /O(n+m)/. Is this a subset?\n-- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.\nisSubsetOf :: (US a, Ord a) => USet a -> USet a -> Bool\nisSubsetOf t1 t2 = (size t1 <= size t2) && (isSubsetOfX t1 t2)\n\nisSubsetOfX :: (US a, Ord a) => USet a -> USet a -> Bool\nisSubsetOfX _ (null -> True)         = False\nisSubsetOfX (null -> True)  _        = True\nisSubsetOfX (view -> Bin _ x l r) t  = found && isSubsetOfX l lt && isSubsetOfX r gt\n  where\n    (lt,found,gt) = splitMember x t\n\n\n{--------------------------------------------------------------------\n  Minimal, Maximal\n--------------------------------------------------------------------}\n-- | /O(log n)/. The minimal element of a set.\nfindMin :: US a => USet a -> a\nfindMin (view -> Bin _ x (null -> True) _) = x\nfindMin (view -> Bin _ _ l _)   = findMin l\nfindMin _ = error \"Data.Set.Unboxed.findMin: empty set has no minimal element\"\n\n-- | /O(log n)/. The maximal element of a set.\nfindMax :: US a => USet a -> a\nfindMax (view -> Bin _ x _ (null -> True))  = x\nfindMax (view -> Bin _ _ _ r)    = findMax r\nfindMax _ = error \"Data.Set.Unboxed.findMax: empty set has no maximal element\"\n\n-- | /O(log n)/. Delete the minimal element.\ndeleteMin :: US a => USet a -> USet a\ndeleteMin (view -> Bin _ _ (null -> True) r) = r\ndeleteMin (view -> Bin _ x l r)   = balance x (deleteMin l) r\ndeleteMin _ = tip\n\n-- | /O(log n)/. Delete the maximal element.\ndeleteMax :: US a => USet a -> USet a\ndeleteMax (view -> Bin _ _ l (null -> True)) = l\ndeleteMax (view -> Bin _ x l r)   = balance x l (deleteMax r)\ndeleteMax _ = tip\n\n{--------------------------------------------------------------------\n  Union. \n--------------------------------------------------------------------}\n-- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).\nunions :: (US a, Ord a) => [USet a] -> USet a\nunions ts\n  = foldlStrict union empty ts\n\n\n-- | /O(n+m)/. The union of two sets, preferring the first set when\n-- equal elements are encountered.\n-- The implementation uses the efficient /hedge-union/ algorithm.\n-- Hedge-union is more efficient on (bigset `union` smallset).\nunion :: (US a, Ord a) => USet a -> USet a -> USet a\nunion (null -> True) t2  = t2\nunion t1 (null -> True)  = t1\nunion t1 t2 = hedgeUnion (const LT) (const GT) t1 t2\n\nhedgeUnion :: (US a, Ord a) => (a -> Ordering) -> (a -> Ordering) -> USet a -> USet a -> USet a\nhedgeUnion _     _     t1 (null -> True)                    = t1\nhedgeUnion cmplo cmphi (null -> True) (view -> Bin _ x l r) = join x (filterGt cmplo l) (filterLt cmphi r)\nhedgeUnion cmplo cmphi (view -> Bin _ x l r) t2            = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2)) (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))\n  where\n    cmpx = compare x\n\n{--------------------------------------------------------------------\n  Difference\n--------------------------------------------------------------------}\n-- | /O(n+m)/. Difference of two sets. \n-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.\ndifference :: (US a, Ord a) => USet a -> USet a -> USet a\ndifference (null -> True) _   = tip\ndifference t1 (null -> True)  = t1\ndifference t1 t2   = hedgeDiff (const LT) (const GT) t1 t2\n\nhedgeDiff :: (US a, Ord a) => (a -> Ordering) -> (a -> Ordering) -> USet a -> USet a -> USet a\nhedgeDiff _ _ (null -> True) _ = tip\nhedgeDiff cmplo cmphi (view -> Bin _ x l r) (null -> True) = join x (filterGt cmplo l) (filterLt cmphi r)\nhedgeDiff cmplo cmphi t (view -> Bin _ x l r) = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l) (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)\n  where\n    cmpx = compare x\n\n{--------------------------------------------------------------------\n  Intersection\n--------------------------------------------------------------------}\n-- | /O(n+m)/. The intersection of two sets.\n-- Elements of the result come from the first set, so for example\n--\n-- > import qualified Data.Set as S\n-- > data AB = A | B deriving Show\n-- > instance Ord AB where compare _ _ = EQ\n-- > instance Eq AB where _ == _ = True\n-- > main = print (S.singleton A `S.intersection` S.singleton B,\n-- >               S.singleton B `S.intersection` S.singleton A)\n--\n-- prints @(fromList [A],fromList [B])@.\nintersection :: (US a, Ord a) => USet a -> USet a -> USet a\nintersection (null -> True) _ = tip\nintersection _ (null -> True) = tip\nintersection t1@(view -> Bin s1 x1 l1 r1) t2@(view -> Bin s2 x2 l2 r2) =\n   if s1 >= s2 then\n      let (lt,found,gt) = splitLookup x2 t1\n          tl            = intersection lt l2\n          tr            = intersection gt r2\n      in case found of\n      Just x -> join x tl tr\n      Nothing -> merge tl tr\n   else let (lt,found,gt) = splitMember x1 t2\n            tl            = intersection l1 lt\n            tr            = intersection r1 gt\n        in if found then join x1 tl tr\n           else merge tl tr\n\n{--------------------------------------------------------------------\n  Filter and partition\n--------------------------------------------------------------------}\n-- | /O(n)/. Filter all elements that satisfy the predicate.\nfilter :: (US a, Ord a) => (a -> Bool) -> USet a -> USet a\nfilter p = go where\n    go = viewk tip \n        (\\_ x l r -> \n            if p x \n            then join x (go l) (go r) \n            else merge (go l) (go r)\n        ) \n\n-- | /O(n)/. Partition the set into two sets, one with all elements that satisfy\n-- the predicate and one with all elements that don't satisfy the predicate.\n-- See also 'split'.\npartition :: (US a, Ord a) => (a -> Bool) -> USet a -> (USet a,USet a)\npartition p = go where\n    go = viewk (tip,tip) \n        (\\_ x l r -> \n            let \n                (l1,l2) = go l\n                (r1,r2) = go r\n            in if p x \n            then (join x l1 r1,merge l2 r2)\n            else (merge l1 r1,join x l2 r2)\n        )\n\n{----------------------------------------------------------------------\n  Map\n----------------------------------------------------------------------}\n\n-- | /O(n*log n)/. \n-- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.\n-- \n-- It's worth noting that the size of the result may be smaller if,\n-- for some @(x,y)@, @x \\/= y && f x == f y@\n\nmap :: (US a, US b, Ord a, Ord b) => (a->b) -> USet a -> USet b\nmap f = fromList . List.map f . toList\n\n-- | /O(n)/. The \n--\n-- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.\n-- /The precondition is not checked./\n-- Semi-formally, we have:\n-- \n-- > and [x < y ==> f x < f y | x <- ls, y <- ls] \n-- >                     ==> mapMonotonic f s == map f s\n-- >     where ls = toList s\n\nmapMonotonic :: (US a, US b) => (a->b) -> USet a -> USet b\nmapMonotonic f (view -> Bin sz x l r) = bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)\nmapMonotonic _ _ = tip\n\n\n{--------------------------------------------------------------------\n  Fold\n--------------------------------------------------------------------}\n-- | /O(n)/. Fold over the elements of a set in an unspecified order.\nfold :: US a => (a -> b -> b) -> b -> USet a -> b\nfold f z s = foldr f z s\n\n-- | /O(n)/. Post-order fold.\nfoldr :: US a => (a -> b -> b) -> b -> USet a -> b\n--foldr f z (view -> Bin _ x l r) = foldr f (f x (foldr f z r)) l\n--foldr _ z _ = z\n\nfoldr f z x | null x                     = z\n            | (# x, l, r #) <- viewBin x = foldr f (f x (foldr f z r)) l \n\n{--------------------------------------------------------------------\n  List variations \n--------------------------------------------------------------------}\n-- | /O(n)/. The elements of a set.\nelems :: US a => USet a -> [a]\nelems x = toList x\n\n{--------------------------------------------------------------------\n  Lists \n--------------------------------------------------------------------}\n-- | /O(n)/. Convert the set to a list of elements.\ntoList :: US a => USet a -> [a]\ntoList x = toAscList x\n\n-- | /O(n)/. Convert the set to an ascending list of elements.\ntoAscList :: US a => USet a -> [a]\ntoAscList = foldr (:) []\n\n\n-- | /O(n*log n)/. Create a set from a list of elements.\nfromList :: (US a, Ord a) => [a] -> USet a \nfromList = foldlStrict ins empty\n  where\n    ins t x = insert x t\n\n{--------------------------------------------------------------------\n  Building trees from ascending/descending lists can be done in linear time.\n  \n  Note that if [xs] is ascending that: \n    fromAscList xs == fromList xs\n--------------------------------------------------------------------}\n-- | /O(n)/. Build a set from an ascending list in linear time.\n-- /The precondition (input list is ascending) is not checked./\nfromAscList :: (US a, Eq a) => [a] -> USet a \nfromAscList xs\n  = fromDistinctAscList (combineEq xs)\n  where\n  -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]\n  combineEq xs'\n    = case xs' of\n        []     -> []\n        [x]    -> [x]\n        (x:xx) -> combineEq' x xx\n\n  combineEq' z [] = [z]\n  combineEq' z (x:xs')\n    | z==x      =   combineEq' z xs'\n    | otherwise = z:combineEq' x xs'\n\n\n-- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.\n-- /The precondition (input list is strictly ascending) is not checked./\nfromDistinctAscList :: US a => [a] -> USet a \nfromDistinctAscList xs\n  = build const (length xs) xs\n  where\n    -- 1) use continutations so that we use heap space instead of stack space.\n    -- 2) special case for n==5 to build bushier trees. \n    build c 0 xs'  = c tip xs'\n    build c 5 xs'  = case xs' of\n                       (x1:x2:x3:x4:x5:xx) \n                            -> c (bin_ x4 (bin_ x2 (singleton x1) (singleton x3)) (singleton x5)) xx\n                       _ -> error \"Data.Set.Unboxed.fromDistinctAscList build 5\"\n    build c n xs'  = seq nr $ build (buildR nr c) nl xs'\n                   where\n                     nl = n `div` 2\n                     nr = n - nl - 1\n\n    buildR n c l (x:ys) = build (buildB l x c) n ys\n    buildR _ _ _ []     = error \"Data.Set.Unboxed.fromDistinctAscList buildR []\"\n    buildB l x c r zs   = c (bin_ x l r) zs\n\n{--------------------------------------------------------------------\n  Eq converts the set to a list. In a lazy setting, this \n  actually seems one of the faster methods to compare two trees \n  and it is certainly the simplest :-)\n--------------------------------------------------------------------}\ninstance (US a, Eq a) => Eq (USet a) where\n  t1 == t2  = (size t1 == size t2) && (toAscList t1 == toAscList t2)\n\n{--------------------------------------------------------------------\n  Ord \n--------------------------------------------------------------------}\n\ninstance (US a, Ord a) => Ord (USet a) where\n    compare s1 s2 = compare (toAscList s1) (toAscList s2) \n\n{--------------------------------------------------------------------\n  Show\n--------------------------------------------------------------------}\ninstance (US a, Show a) => Show (USet a) where\n  showsPrec p xs = showParen (p > 10) $\n    showString \"fromList \" . shows (toList xs)\n\n{--------------------------------------------------------------------\n  Read\n--------------------------------------------------------------------}\ninstance (US a, Read a, Ord a) => Read (USet a) where\n#ifdef __GLASGOW_HASKELL__\n  readPrec = parens $ prec 10 $ do\n    Ident \"fromList\" <- lexP\n    fromList `fmap` readPrec\n\n  readListPrec = readListPrecDefault\n#else\n  readsPrec p = readParen (p > 10) $ \\ r -> do\n    (\"fromList\",s) <- lex r\n    (xs,t) <- reads s\n    return (fromList xs,t)\n#endif\n\n{--------------------------------------------------------------------\n  Utility functions that return sub-ranges of the original\n  tree. Some functions take a comparison function as argument to\n  allow comparisons against infinite values. A function [cmplo x]\n  should be read as [compare lo x].\n\n  [trim cmplo cmphi t]  A tree that is either empty or where [cmplo x == LT]\n                        and [cmphi x == GT] for the value [x] of the root.\n  [filterGt cmp t]      A tree where for all values [k]. [cmp k == LT]\n  [filterLt cmp t]      A tree where for all values [k]. [cmp k == GT]\n\n  [split k t]           Returns two trees [l] and [r] where all values\n                        in [l] are <[k] and all keys in [r] are >[k].\n  [splitMember k t]     Just like [split] but also returns whether [k]\n                        was found in the tree.\n--------------------------------------------------------------------}\n\n{--------------------------------------------------------------------\n  [trim lo hi t] trims away all subtrees that surely contain no\n  values between the range [lo] to [hi]. The returned tree is either\n  empty or the key of the root is between @lo@ and @hi@.\n--------------------------------------------------------------------}\ntrim :: US a => (a -> Ordering) -> (a -> Ordering) -> USet a -> USet a\ntrim cmplo cmphi t@(view -> Bin _ x l r)\n  = case cmplo x of\n      LT -> case cmphi x of\n              GT -> t\n              _  -> trim cmplo cmphi l\n      _  -> trim cmplo cmphi r\ntrim _     _     _ = tip\n\n{--------------------------------------------------------------------\n  [filterGt x t] filter all values >[x] from tree [t]\n  [filterLt x t] filter all values <[x] from tree [t]\n--------------------------------------------------------------------}\nfilterGt :: US a => (a -> Ordering) -> USet a -> USet a\nfilterGt cmp (view -> Bin _ x l r)\n  = case cmp x of\n      LT -> join x (filterGt cmp l) r\n      GT -> filterGt cmp r\n      EQ -> r\nfilterGt _ _ = tip\n      \nfilterLt :: US a => (a -> Ordering) -> USet a -> USet a\nfilterLt cmp (view -> Bin _ x l r)\n  = case cmp x of\n      LT -> filterLt cmp l\n      GT -> join x l (filterLt cmp r)\n      EQ -> l\nfilterLt _ _ = tip\n\n\n{--------------------------------------------------------------------\n  Split\n--------------------------------------------------------------------}\n-- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@\n-- where @set1@ comprises the elements of @set@ less than @x@ and @set2@\n-- comprises the elements of @set@ greater than @x@.\nsplit :: (US a, Ord a) => a -> USet a -> (USet a,USet a)\nsplit x (view -> Bin _ y l r)\n  = case compare x y of\n      LT -> let (lt,gt) = split x l in (lt,join y gt r)\n      GT -> let (lt,gt) = split x r in (join y l lt,gt)\n      EQ -> (l,r)\nsplit _ _ = (tip,tip)\n\n-- | /O(log n)/. Performs a 'split' but also returns whether the pivot\n-- element was found in the original set.\nsplitMember :: (US a, Ord a) => a -> USet a -> (USet a,Bool,USet a)\nsplitMember x t = let (l,m,r) = splitLookup x t in\n     (l,maybe False (const True) m,r)\n\n-- | /O(log n)/. Performs a 'split' but also returns the pivot\n-- element that was found in the original set.\nsplitLookup :: (US a, Ord a) => a -> USet a -> (USet a,Maybe a,USet a)\nsplitLookup x (view -> Bin _ y l r)\n   = case compare x y of\n       LT -> let (lt,found,gt) = splitLookup x l in (lt,found,join y gt r)\n       GT -> let (lt,found,gt) = splitLookup x r in (join y l lt,found,gt)\n       EQ -> (l,Just y,r)\nsplitLookup _ _ = (tip,Nothing,tip)\n\n{--------------------------------------------------------------------\n  Utility functions that maintain the balance properties of the tree.\n  All constructors assume that all values in [l] < [x] and all values\n  in [r] > [x], and that [l] and [r] are valid trees.\n  \n  In order of sophistication:\n    [Bin sz x l r]    The type constructor.\n    [bin_ x l r]      Maintains the correct size, assumes that both [l]\n                      and [r] are balanced with respect to each other.\n    [balance x l r]   Restores the balance and size.\n                      Assumes that the original tree was balanced and\n                      that [l] or [r] has changed by at most one element.\n    [join x l r]      Restores balance and size. \n\n  Furthermore, we can construct a new tree from two trees. Both operations\n  assume that all values in [l] < all values in [r] and that [l] and [r]\n  are valid:\n    [glue l r]        Glues [l] and [r] together. Assumes that [l] and\n                      [r] are already balanced with respect to each other.\n    [merge l r]       Merges two trees and restores balance.\n\n  Note: in contrast to Adam's paper, we use (<=) comparisons instead\n  of (<) comparisons in [join], [merge] and [balance]. \n  Quickcheck (on [difference]) showed that this was necessary in order \n  to maintain the invariants. It is quite unsatisfactory that I haven't \n  been able to find out why this is actually the case! Fortunately, it \n  doesn't hurt to be a bit more conservative.\n--------------------------------------------------------------------}\n\n{--------------------------------------------------------------------\n  Join \n--------------------------------------------------------------------}\njoin :: US a => a -> USet a -> USet a -> USet a\njoin x (null -> True) r  = insertMin x r\njoin x l (null -> True)  = insertMax x l\njoin x l@(view -> Bin sizeL y ly ry) r@(view -> Bin sizeR z lz rz)\n  | delta*sizeL <= sizeR  = balance z (join x l lz) rz\n  | delta*sizeR <= sizeL  = balance y ly (join x ry r)\n  | otherwise             = bin_ x l r\n\n\n-- insertMin and insertMax don't perform potentially expensive comparisons.\ninsertMax,insertMin :: US a => a -> USet a -> USet a \ninsertMax x t\n  = case view t of\n      Bin _ y l r -> balance y l (insertMax x r)\n      _ -> singleton x\n             \ninsertMin x t\n  = case view t of\n      Bin _ y l r -> balance y (insertMin x l) r\n      _ -> singleton x\n             \n{--------------------------------------------------------------------\n  [merge l r]: merges two trees.\n--------------------------------------------------------------------}\nmerge :: US a => USet a -> USet a -> USet a\nmerge (null -> True) r   = r\nmerge l (null -> True)   = l\nmerge l@(view -> Bin sizeL x lx rx) r@(view -> Bin sizeR y ly ry)\n  | delta*sizeL <= sizeR = balance y (merge l ly) ry\n  | delta*sizeR <= sizeL = balance x lx (merge rx r)\n  | otherwise            = glue l r\n\n{--------------------------------------------------------------------\n  [glue l r]: glues two trees together.\n  Assumes that [l] and [r] are already balanced with respect to each other.\n--------------------------------------------------------------------}\nglue :: US a => USet a -> USet a -> USet a\nglue (null -> True) r = r\nglue l (null -> True) = l\nglue l r   \n  | size l > size r = let (m,l') = deleteFindMax l in balance m l' r\n  | otherwise       = let (m,r') = deleteFindMin r in balance m l r'\n\n\n-- | /O(log n)/. Delete and find the minimal element.\n-- \n-- > deleteFindMin set = (findMin set, deleteMin set)\n\ndeleteFindMin :: US a => USet a -> (a,USet a)\ndeleteFindMin t \n  = case view t of\n      Bin _ x (null -> True) r -> (x,r)\n      Bin _ x l r   -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)\n      Tip           -> (error \"Data.Set.Unboxed.deleteFindMin: can not return the minimal element of an empty set\", tip)\n\n-- | /O(log n)/. Delete and find the maximal element.\n-- \n-- > deleteFindMax set = (findMax set, deleteMax set)\ndeleteFindMax :: US a => USet a -> (a,USet a)\ndeleteFindMax t\n  = case view t of\n      Bin _ x l (null -> True) -> (x,l)\n      Bin _ x l r   -> let (xm,r') = deleteFindMax r in (xm,balance x l r')\n      _ -> (error \"Data.Set.Unboxed.deleteFindMax: can not return the maximal element of an empty set\", tip)\n\n-- | /O(log n)/. Retrieves the minimal key of the set, and the set\n-- stripped of that element, or 'Nothing' if passed an empty set.\nminView :: US a => USet a -> Maybe (a, USet a)\nminView (null -> True) = Nothing\nminView x = Just (deleteFindMin x)\n\n-- | /O(log n)/. Retrieves the maximal key of the set, and the set\n-- stripped of that element, or 'Nothing' if passed an empty set.\nmaxView :: US a => USet a -> Maybe (a, USet a)\nmaxView (null -> True) = Nothing\nmaxView x = Just (deleteFindMax x)\n\n{--------------------------------------------------------------------\n  [balance x l r] balances two trees with value x.\n  The sizes of the trees should balance after decreasing the\n  size of one of them. (a rotation).\n\n  [delta] is the maximal relative difference between the sizes of\n          two trees, it corresponds with the [w] in Adams' paper,\n          or equivalently, [1/delta] corresponds with the $\\alpha$\n          in Nievergelt's paper. Adams shows that [delta] should\n          be larger than 3.745 in order to garantee that the\n          rotations can always restore balance.         \n\n  [ratio] is the ratio between an outer and inner sibling of the\n          heavier subtree in an unbalanced setting. It determines\n          whether a double or single rotation should be performed\n          to restore balance. It is correspondes with the inverse\n          of $\\alpha$ in Adam's article.\n\n  Note that:\n  - [delta] should be larger than 4.646 with a [ratio] of 2.\n  - [delta] should be larger than 3.745 with a [ratio] of 1.534.\n  \n  - A lower [delta] leads to a more 'perfectly' balanced tree.\n  - A higher [delta] performs less rebalancing.\n\n  - Balancing is automatic for random data and a balancing\n    scheme is only necessary to avoid pathological worst cases.\n    Almost any choice will do in practice\n    \n  - Allthough it seems that a rather large [delta] may perform better \n    than smaller one, measurements have shown that the smallest [delta]\n    of 4 is actually the fastest on a wide range of operations. It\n    especially improves performance on worst-case scenarios like\n    a sequence of ordered insertions.\n\n  Note: in contrast to Adams' paper, we use a ratio of (at least) 2\n  to decide whether a single or double rotation is needed. Allthough\n  he actually proves that this ratio is needed to maintain the\n  invariants, his implementation uses a (invalid) ratio of 1. \n  He is aware of the problem though since he has put a comment in his \n  original source code that he doesn't care about generating a \n  slightly inbalanced tree since it doesn't seem to matter in practice. \n  However (since we use quickcheck :-) we will stick to strictly balanced \n  trees.\n--------------------------------------------------------------------}\ndelta,ratio :: Int\ndelta = 4\nratio = 2\n\n\n\n{--------------------------------------------------------------------\n  Utilities\n--------------------------------------------------------------------}\nfoldlStrict :: (a -> b -> a) -> a -> [b] -> a\nfoldlStrict f z xs\n  = case xs of\n      []     -> z\n      (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)\n\n\n{--------------------------------------------------------------------\n  Debugging\n--------------------------------------------------------------------}\n-- | /O(n)/. Show the tree that implements the set. The tree is shown\n-- in a compressed, hanging format.\nshowTree :: (US a, Show a) => USet a -> String\nshowTree s\n  = showTreeWith True False s\n\n\n{- | /O(n)/. The expression (@showTreeWith hang wide map@) shows\n the tree that implements the set. If @hang@ is\n @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If\n @wide@ is 'True', an extra wide version is shown.\n\n> Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]\n> 4\n> +--2\n> |  +--1\n> |  +--3\n> +--5\n> \n> Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]\n> 4\n> |\n> +--2\n> |  |\n> |  +--1\n> |  |\n> |  +--3\n> |\n> +--5\n> \n> Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]\n> +--5\n> |\n> 4\n> |\n> |  +--3\n> |  |\n> +--2\n>    |\n>    +--1\n\n-}\nshowTreeWith :: (US a, Show a) => Bool -> Bool -> USet a -> String\nshowTreeWith hang wide t\n  | hang      = (showsTreeHang wide [] t) \"\"\n  | otherwise = (showsTree wide [] [] t) \"\"\n\nshowsTree :: (US a, Show a) => Bool -> [String] -> [String] -> USet a -> ShowS\nshowsTree wide lbars rbars t\n  = case view t of\n      Tip -> showsBars lbars . showString \"|\\n\"\n      Bin _ x (null -> True) (null -> True)\n          -> showsBars lbars . shows x . showString \"\\n\" \n      Bin _ x l r\n          -> showsTree wide (withBar rbars) (withEmpty rbars) r .\n             showWide wide rbars .\n             showsBars lbars . shows x . showString \"\\n\" .\n             showWide wide lbars .\n             showsTree wide (withEmpty lbars) (withBar lbars) l\n\nshowsTreeHang :: (US a, Show a) => Bool -> [String] -> USet a -> ShowS\nshowsTreeHang wide bars t\n  = case view t of\n      Tip -> showsBars bars . showString \"|\\n\" \n      Bin _ x (null -> True) (null -> True) \n          -> showsBars bars . shows x . showString \"\\n\" \n      Bin _ x l r\n          -> showsBars bars . shows x . showString \"\\n\" . \n             showWide wide bars .\n             showsTreeHang wide (withBar bars) l .\n             showWide wide bars .\n             showsTreeHang wide (withEmpty bars) r\n\nshowWide :: Bool -> [String] -> String -> String\nshowWide wide bars \n  | wide      = showString (concat (reverse bars)) . showString \"|\\n\" \n  | otherwise = id\n\nshowsBars :: [String] -> ShowS\nshowsBars bars\n  = case bars of\n      [] -> id\n      _  -> showString (concat (reverse (tail bars))) . showString node\n\nnode :: String\nnode           = \"+--\"\n\nwithBar, withEmpty :: [String] -> [String]\nwithBar bars   = \"|  \":bars\nwithEmpty bars = \"   \":bars\n\n{--------------------------------------------------------------------\n  Assertions\n--------------------------------------------------------------------}\n-- | /O(n)/. Test if the internal set structure is valid.\nvalid :: (US a, Ord a) => USet a -> Bool\nvalid t\n  = balanced t && ordered t && validsize t\n\nordered :: (US a, Ord a) => USet a -> Bool\nordered t\n  = bounded (const True) (const True) t\n  where\n    bounded lo hi t'\n      = case view t' of\n          Bin _ x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r\n          _ -> True\n\nbalanced :: US a => USet a -> Bool\nbalanced t\n  = case view t of\n      Bin _ _ l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&\n                     balanced l && balanced r\n      _ -> True\n\nvalidsize :: US a => USet a -> Bool\nvalidsize t\n  = (realsize t == Just (size t))\n  where\n    realsize t'\n      = case view t' of\n          Bin sz _ l r -> case (realsize l,realsize r) of\n                            (Just n,Just m)  | n+m+1 == sz  -> Just sz\n                            _                -> Nothing\n          _ -> Just 0\n\n{-\n{--------------------------------------------------------------------\n  Testing\n--------------------------------------------------------------------}\ntestTree :: [Int] -> USet Int\ntestTree xs   = fromList xs\ntest1 = testTree [1..20]\ntest2 = testTree [30,29..10]\ntest3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]\n\n{--------------------------------------------------------------------\n  QuickCheck\n--------------------------------------------------------------------}\n\n{-\nqcheck prop\n  = check config prop\n  where\n    config = Config\n      { configMaxTest = 500\n      , configMaxFail = 5000\n      , configSize    = \\n -> (div n 2 + 3)\n      , configEvery   = \\n args -> let s = show n in s ++ [ '\\b' | _ <- s ]\n      }\n-}\n\n\n{--------------------------------------------------------------------\n  Arbitrary, reasonably balanced trees\n--------------------------------------------------------------------}\ninstance (US a, Enum a) => Arbitrary (USet a) where\n  arbitrary = sized (arbtree 0 maxkey)\n            where maxkey  = 10000\n\narbtree :: (US a, Enum a) => Int -> Int -> Int -> Gen (USet a)\narbtree lo hi n\n  | n <= 0        = return tip\n  | lo >= hi      = return tip\n  | otherwise     = do{ i  <- choose (lo,hi)\n                      ; m  <- choose (1,30)\n                      ; let (ml,mr)  | m==(1::Int)= (1,2)\n                                     | m==2       = (2,1)\n                                     | m==3       = (1,1)\n                                     | otherwise  = (2,2)\n                      ; l  <- arbtree lo (i-1) (n `div` ml)\n                      ; r  <- arbtree (i+1) hi (n `div` mr)\n                      ; return (bin_ (toEnum i) l r)\n                      }  \n\n\n{--------------------------------------------------------------------\n  Valid tree's\n--------------------------------------------------------------------}\nforValid :: (US a, Enum a,Show a,Testable b) => (USet a -> b) -> Property\nforValid f\n  = forAll arbitrary $ \\t -> \n--    classify (balanced t) \"balanced\" $\n    classify (size t == 0) \"empty\" $\n    classify (size t > 0  && size t <= 10) \"small\" $\n    classify (size t > 10 && size t <= 64) \"medium\" $\n    classify (size t > 64) \"large\" $\n    balanced t ==> f t\n\nforValidIntTree :: Testable a => (USet Int -> a) -> Property\nforValidIntTree f\n  = forValid f\n\nforValidUnitTree :: Testable a => (USet Int -> a) -> Property\nforValidUnitTree f\n  = forValid f\n\n\nprop_Valid \n  = forValidUnitTree $ \\t -> valid t\n\n{--------------------------------------------------------------------\n  Single, Insert, Delete\n--------------------------------------------------------------------}\nprop_Single :: Int -> Bool\nprop_Single x\n  = (insert x empty == singleton x)\n\nprop_InsertValid :: Int -> Property\nprop_InsertValid k\n  = forValidUnitTree $ \\t -> valid (insert k t)\n\nprop_InsertDelete :: Int -> USet Int -> Property\nprop_InsertDelete k t\n  = not (member k t) ==> delete k (insert k t) == t\n\nprop_DeleteValid :: Int -> Property\nprop_DeleteValid k\n  = forValidUnitTree $ \\t -> \n    valid (delete k (insert k t))\n\n{--------------------------------------------------------------------\n  Balance\n--------------------------------------------------------------------}\nprop_Join :: Int -> Property \nprop_Join x\n  = forValidUnitTree $ \\t ->\n    let (l,r) = split x t\n    in valid (join x l r)\n\nprop_Merge :: Int -> Property \nprop_Merge x\n  = forValidUnitTree $ \\t ->\n    let (l,r) = split x t\n    in valid (merge l r)\n\n\n{--------------------------------------------------------------------\n  Union\n--------------------------------------------------------------------}\nprop_UnionValid :: Property\nprop_UnionValid\n  = forValidUnitTree $ \\t1 ->\n    forValidUnitTree $ \\t2 ->\n    valid (union t1 t2)\n\nprop_UnionInsert :: Int -> USet Int -> Bool\nprop_UnionInsert x t\n  = union t (singleton x) == insert x t\n\nprop_UnionAssoc :: USet Int -> USet Int -> USet Int -> Bool\nprop_UnionAssoc t1 t2 t3\n  = union t1 (union t2 t3) == union (union t1 t2) t3\n\nprop_UnionComm :: USet Int -> USet Int -> Bool\nprop_UnionComm t1 t2\n  = (union t1 t2 == union t2 t1)\n\n\nprop_DiffValid\n  = forValidUnitTree $ \\t1 ->\n    forValidUnitTree $ \\t2 ->\n    valid (difference t1 t2)\n\nprop_Diff :: [Int] -> [Int] -> Bool\nprop_Diff xs ys\n  =  toAscList (difference (fromList xs) (fromList ys))\n    == List.sort ((List.\\\\) (nub xs)  (nub ys))\n\nprop_IntValid\n  = forValidUnitTree $ \\t1 ->\n    forValidUnitTree $ \\t2 ->\n    valid (intersection t1 t2)\n\nprop_Int :: [Int] -> [Int] -> Bool\nprop_Int xs ys\n  =  toAscList (intersection (fromList xs) (fromList ys))\n    == List.sort (nub ((List.intersect) (xs)  (ys)))\n\n{--------------------------------------------------------------------\n  Lists\n--------------------------------------------------------------------}\nprop_Ordered\n  = forAll (choose (5,100)) $ \\n ->\n    let xs = [0..n::Int]\n    in fromAscList xs == fromList xs\n\nprop_List :: [Int] -> Bool\nprop_List xs\n  = (sort (nub xs) == toList (fromList xs))\n-}\n\n-- | /O(log n)/. Insert an element in a set.\n-- If the set already contains an element equal to the given value,\n-- it is replaced with the new value.\ninsert :: (US a, Ord a) => a -> USet a -> USet a\ninsert x = go where\n    cmpx = compare x\n    go = viewk (singleton x) $ \\sz y l r -> case cmpx y of\n        LT -> balance y (go l) r\n        GT -> balance y l (go r)\n        EQ -> bin sz x l r\n\nbin_ :: US a => a -> USet a -> USet a -> USet a\nbin_ x l r = bin (size l + size r + 1) x l r\n\nnewtype Boxed a = Boxed { getBoxed :: a } deriving (Eq,Ord,Show,Read,Bounded)\n\n{-- everything below this point AUTOMATICALLY GENERATED by instances.pl. Don't edit by hand! --}\n\n{- #include \"UnboxedInstances.hs\" -}\n\ninstance US Int where\n    data USet Int = IntTip | IntBin {-# UNPACK #-} !Size {-# UNPACK #-} !Int !(USet Int) !(USet Int)\n    view IntTip = Tip\n    view (IntBin s a l r) = Bin s (a) l r\n    tip = IntTip\n    bin s (a) = IntBin s a\n\ninstance US Char where\n    data USet Char = CharTip | CharBin {-# UNPACK #-} !Size {-# UNPACK #-} !Char !(USet Char) !(USet Char)\n    view CharTip = Tip\n    view (CharBin s a l r) = Bin s (a) l r\n    tip = CharTip\n    bin s (a) = CharBin s a\n\ninstance US Int8 where\n    data USet Int8 = Int8Tip | Int8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int8 !(USet Int8) !(USet Int8)\n    view Int8Tip = Tip\n    view (Int8Bin s a l r) = Bin s (a) l r\n    tip = Int8Tip\n    bin s (a) = Int8Bin s a\n\ninstance US Int16 where\n    data USet Int16 = Int16Tip | Int16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int16 !(USet Int16) !(USet Int16)\n    view Int16Tip = Tip\n    view (Int16Bin s a l r) = Bin s (a) l r\n    tip = Int16Tip\n    bin s (a) = Int16Bin s a\n\ninstance US Int32 where\n    data USet Int32 = Int32Tip | Int32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int32 !(USet Int32) !(USet Int32)\n    view Int32Tip = Tip\n    view (Int32Bin s a l r) = Bin s (a) l r\n    tip = Int32Tip\n    bin s (a) = Int32Bin s a\n\ninstance US Int64 where\n    data USet Int64 = Int64Tip | Int64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int64 !(USet Int64) !(USet Int64)\n    view Int64Tip = Tip\n    view (Int64Bin s a l r) = Bin s (a) l r\n    tip = Int64Tip\n    bin s (a) = Int64Bin s a\n\ninstance US Word8 where\n    data USet Word8 = Word8Tip | Word8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word8 !(USet Word8) !(USet Word8)\n    view Word8Tip = Tip\n    view (Word8Bin s a l r) = Bin s (a) l r\n    tip = Word8Tip\n    bin s (a) = Word8Bin s a\n\ninstance US Word16 where\n    data USet Word16 = Word16Tip | Word16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word16 !(USet Word16) !(USet Word16)\n    view Word16Tip = Tip\n    view (Word16Bin s a l r) = Bin s (a) l r\n    tip = Word16Tip\n    bin s (a) = Word16Bin s a\n\ninstance US Word32 where\n    data USet Word32 = Word32Tip | Word32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word32 !(USet Word32) !(USet Word32)\n    view Word32Tip = Tip\n    view (Word32Bin s a l r) = Bin s (a) l r\n    tip = Word32Tip\n    bin s (a) = Word32Bin s a\n\ninstance US Word64 where\n    data USet Word64 = Word64Tip | Word64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word64 !(USet Word64) !(USet Word64)\n    view Word64Tip = Tip\n    view (Word64Bin s a l r) = Bin s (a) l r\n    tip = Word64Tip\n    bin s (a) = Word64Bin s a\n\ninstance US Double where\n    data USet Double = DoubleTip | DoubleBin {-# UNPACK #-} !Size {-# UNPACK #-} !Double !(USet Double) !(USet Double)\n    view DoubleTip = Tip\n    view (DoubleBin s a l r) = Bin s (a) l r\n    tip = DoubleTip\n    bin s (a) = DoubleBin s a\n\ninstance US Float where\n    data USet Float = FloatTip | FloatBin {-# UNPACK #-} !Size {-# UNPACK #-} !Float !(USet Float) !(USet Float)\n    view FloatTip = Tip\n    view (FloatBin s a l r) = Bin s (a) l r\n    tip = FloatTip\n    bin s (a) = FloatBin s a\n\ninstance US Integer where\n    data USet Integer = IntegerTip | IntegerBin {-# UNPACK #-} !Size !Integer !(USet Integer) !(USet Integer)\n    view IntegerTip = Tip\n    view (IntegerBin s a l r) = Bin s (a) l r\n    tip = IntegerTip\n    bin s (a) = IntegerBin s a\n\ninstance US (Boxed a) where\n    data USet (Boxed a) = BoxedTip | BoxedBin {-# UNPACK #-} !Size (Boxed a) !(USet (Boxed a)) !(USet (Boxed a))\n    view BoxedTip = Tip\n    view (BoxedBin s a l r) = Bin s (a) l r\n    tip = BoxedTip\n    bin s (a) = BoxedBin s a\n\ninstance US (Int,Int) where\n    data USet (Int,Int) = IntIntTip | IntIntBin {-# UNPACK #-} !Size {-# UNPACK #-} !Int{-# UNPACK #-} !Int !(USet (Int,Int)) !(USet (Int,Int))\n    view IntIntTip = Tip\n    view (IntIntBin s a b l r) = Bin s (a,b) l r\n    tip = IntIntTip\n    bin s (a,b) = IntIntBin s a b\n\ninstance US (Int,Int,Int) where\n    data USet (Int,Int,Int) = IntIntIntTip | IntIntIntBin {-# UNPACK #-} !Size {-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int !(USet (Int,Int,Int)) !(USet (Int,Int,Int))\n    view IntIntIntTip = Tip\n    view (IntIntIntBin s a b c l r) = Bin s (a,b,c) l r\n    tip = IntIntIntTip\n    bin s (a,b,c) = IntIntIntBin s a b c\n\ninstance US (Int,Int,Int,Int) where\n    data USet (Int,Int,Int,Int) = IntIntIntIntTip | IntIntIntIntBin {-# UNPACK #-} !Size {-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int !(USet (Int,Int,Int,Int)) !(USet (Int,Int,Int,Int))\n    view IntIntIntIntTip = Tip\n    view (IntIntIntIntBin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = IntIntIntIntTip\n    bin s (a,b,c,d) = IntIntIntIntBin s a b c d\n\ninstance US (Int,Int,Int,Int,Int) where\n    data USet (Int,Int,Int,Int,Int) = IntIntIntIntIntTip | IntIntIntIntIntBin {-# UNPACK #-} !Size {-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int !(USet (Int,Int,Int,Int,Int)) !(USet (Int,Int,Int,Int,Int))\n    view IntIntIntIntIntTip = Tip\n    view (IntIntIntIntIntBin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = IntIntIntIntIntTip\n    bin s (a,b,c,d,e) = IntIntIntIntIntBin s a b c d e\n\ninstance US (Int,Int,Int,Int,Int,Int) where\n    data USet (Int,Int,Int,Int,Int,Int) = IntIntIntIntIntIntTip | IntIntIntIntIntIntBin {-# UNPACK #-} !Size {-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int !(USet (Int,Int,Int,Int,Int,Int)) !(USet (Int,Int,Int,Int,Int,Int))\n    view IntIntIntIntIntIntTip = Tip\n    view (IntIntIntIntIntIntBin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = IntIntIntIntIntIntTip\n    bin s (a,b,c,d,e,f) = IntIntIntIntIntIntBin s a b c d e f\n\ninstance US (Int,Int,Int,Int,Int,Int,Int) where\n    data USet (Int,Int,Int,Int,Int,Int,Int) = IntIntIntIntIntIntIntTip | IntIntIntIntIntIntIntBin {-# UNPACK #-} !Size {-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int !(USet (Int,Int,Int,Int,Int,Int,Int)) !(USet (Int,Int,Int,Int,Int,Int,Int))\n    view IntIntIntIntIntIntIntTip = Tip\n    view (IntIntIntIntIntIntIntBin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = IntIntIntIntIntIntIntTip\n    bin s (a,b,c,d,e,f,g) = IntIntIntIntIntIntIntBin s a b c d e f g\n\ninstance US (Int,Int,Int,Int,Int,Int,Int,Int) where\n    data USet (Int,Int,Int,Int,Int,Int,Int,Int) = IntIntIntIntIntIntIntIntTip | IntIntIntIntIntIntIntIntBin {-# UNPACK #-} !Size {-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int !(USet (Int,Int,Int,Int,Int,Int,Int,Int)) !(USet (Int,Int,Int,Int,Int,Int,Int,Int))\n    view IntIntIntIntIntIntIntIntTip = Tip\n    view (IntIntIntIntIntIntIntIntBin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = IntIntIntIntIntIntIntIntTip\n    bin s (a,b,c,d,e,f,g,h) = IntIntIntIntIntIntIntIntBin s a b c d e f g h\n\ninstance US (Int,Int,Int,Int,Int,Int,Int,Int,Int) where\n    data USet (Int,Int,Int,Int,Int,Int,Int,Int,Int) = IntIntIntIntIntIntIntIntIntTip | IntIntIntIntIntIntIntIntIntBin {-# UNPACK #-} !Size {-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int{-# UNPACK #-} !Int !(USet (Int,Int,Int,Int,Int,Int,Int,Int,Int)) !(USet (Int,Int,Int,Int,Int,Int,Int,Int,Int))\n    view IntIntIntIntIntIntIntIntIntTip = Tip\n    view (IntIntIntIntIntIntIntIntIntBin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = IntIntIntIntIntIntIntIntIntTip\n    bin s (a,b,c,d,e,f,g,h,i) = IntIntIntIntIntIntIntIntIntBin s a b c d e f g h i\n\ninstance US (Char,Char) where\n    data USet (Char,Char) = CharCharTip | CharCharBin {-# UNPACK #-} !Size {-# UNPACK #-} !Char{-# UNPACK #-} !Char !(USet (Char,Char)) !(USet (Char,Char))\n    view CharCharTip = Tip\n    view (CharCharBin s a b l r) = Bin s (a,b) l r\n    tip = CharCharTip\n    bin s (a,b) = CharCharBin s a b\n\ninstance US (Char,Char,Char) where\n    data USet (Char,Char,Char) = CharCharCharTip | CharCharCharBin {-# UNPACK #-} !Size {-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char !(USet (Char,Char,Char)) !(USet (Char,Char,Char))\n    view CharCharCharTip = Tip\n    view (CharCharCharBin s a b c l r) = Bin s (a,b,c) l r\n    tip = CharCharCharTip\n    bin s (a,b,c) = CharCharCharBin s a b c\n\ninstance US (Char,Char,Char,Char) where\n    data USet (Char,Char,Char,Char) = CharCharCharCharTip | CharCharCharCharBin {-# UNPACK #-} !Size {-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char !(USet (Char,Char,Char,Char)) !(USet (Char,Char,Char,Char))\n    view CharCharCharCharTip = Tip\n    view (CharCharCharCharBin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = CharCharCharCharTip\n    bin s (a,b,c,d) = CharCharCharCharBin s a b c d\n\ninstance US (Char,Char,Char,Char,Char) where\n    data USet (Char,Char,Char,Char,Char) = CharCharCharCharCharTip | CharCharCharCharCharBin {-# UNPACK #-} !Size {-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char !(USet (Char,Char,Char,Char,Char)) !(USet (Char,Char,Char,Char,Char))\n    view CharCharCharCharCharTip = Tip\n    view (CharCharCharCharCharBin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = CharCharCharCharCharTip\n    bin s (a,b,c,d,e) = CharCharCharCharCharBin s a b c d e\n\ninstance US (Char,Char,Char,Char,Char,Char) where\n    data USet (Char,Char,Char,Char,Char,Char) = CharCharCharCharCharCharTip | CharCharCharCharCharCharBin {-# UNPACK #-} !Size {-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char !(USet (Char,Char,Char,Char,Char,Char)) !(USet (Char,Char,Char,Char,Char,Char))\n    view CharCharCharCharCharCharTip = Tip\n    view (CharCharCharCharCharCharBin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = CharCharCharCharCharCharTip\n    bin s (a,b,c,d,e,f) = CharCharCharCharCharCharBin s a b c d e f\n\ninstance US (Char,Char,Char,Char,Char,Char,Char) where\n    data USet (Char,Char,Char,Char,Char,Char,Char) = CharCharCharCharCharCharCharTip | CharCharCharCharCharCharCharBin {-# UNPACK #-} !Size {-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char !(USet (Char,Char,Char,Char,Char,Char,Char)) !(USet (Char,Char,Char,Char,Char,Char,Char))\n    view CharCharCharCharCharCharCharTip = Tip\n    view (CharCharCharCharCharCharCharBin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = CharCharCharCharCharCharCharTip\n    bin s (a,b,c,d,e,f,g) = CharCharCharCharCharCharCharBin s a b c d e f g\n\ninstance US (Char,Char,Char,Char,Char,Char,Char,Char) where\n    data USet (Char,Char,Char,Char,Char,Char,Char,Char) = CharCharCharCharCharCharCharCharTip | CharCharCharCharCharCharCharCharBin {-# UNPACK #-} !Size {-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char !(USet (Char,Char,Char,Char,Char,Char,Char,Char)) !(USet (Char,Char,Char,Char,Char,Char,Char,Char))\n    view CharCharCharCharCharCharCharCharTip = Tip\n    view (CharCharCharCharCharCharCharCharBin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = CharCharCharCharCharCharCharCharTip\n    bin s (a,b,c,d,e,f,g,h) = CharCharCharCharCharCharCharCharBin s a b c d e f g h\n\ninstance US (Char,Char,Char,Char,Char,Char,Char,Char,Char) where\n    data USet (Char,Char,Char,Char,Char,Char,Char,Char,Char) = CharCharCharCharCharCharCharCharCharTip | CharCharCharCharCharCharCharCharCharBin {-# UNPACK #-} !Size {-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char{-# UNPACK #-} !Char !(USet (Char,Char,Char,Char,Char,Char,Char,Char,Char)) !(USet (Char,Char,Char,Char,Char,Char,Char,Char,Char))\n    view CharCharCharCharCharCharCharCharCharTip = Tip\n    view (CharCharCharCharCharCharCharCharCharBin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = CharCharCharCharCharCharCharCharCharTip\n    bin s (a,b,c,d,e,f,g,h,i) = CharCharCharCharCharCharCharCharCharBin s a b c d e f g h i\n\ninstance US (Int8,Int8) where\n    data USet (Int8,Int8) = Int8Int8Tip | Int8Int8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int8{-# UNPACK #-} !Int8 !(USet (Int8,Int8)) !(USet (Int8,Int8))\n    view Int8Int8Tip = Tip\n    view (Int8Int8Bin s a b l r) = Bin s (a,b) l r\n    tip = Int8Int8Tip\n    bin s (a,b) = Int8Int8Bin s a b\n\ninstance US (Int8,Int8,Int8) where\n    data USet (Int8,Int8,Int8) = Int8Int8Int8Tip | Int8Int8Int8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8 !(USet (Int8,Int8,Int8)) !(USet (Int8,Int8,Int8))\n    view Int8Int8Int8Tip = Tip\n    view (Int8Int8Int8Bin s a b c l r) = Bin s (a,b,c) l r\n    tip = Int8Int8Int8Tip\n    bin s (a,b,c) = Int8Int8Int8Bin s a b c\n\ninstance US (Int8,Int8,Int8,Int8) where\n    data USet (Int8,Int8,Int8,Int8) = Int8Int8Int8Int8Tip | Int8Int8Int8Int8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8 !(USet (Int8,Int8,Int8,Int8)) !(USet (Int8,Int8,Int8,Int8))\n    view Int8Int8Int8Int8Tip = Tip\n    view (Int8Int8Int8Int8Bin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = Int8Int8Int8Int8Tip\n    bin s (a,b,c,d) = Int8Int8Int8Int8Bin s a b c d\n\ninstance US (Int8,Int8,Int8,Int8,Int8) where\n    data USet (Int8,Int8,Int8,Int8,Int8) = Int8Int8Int8Int8Int8Tip | Int8Int8Int8Int8Int8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8 !(USet (Int8,Int8,Int8,Int8,Int8)) !(USet (Int8,Int8,Int8,Int8,Int8))\n    view Int8Int8Int8Int8Int8Tip = Tip\n    view (Int8Int8Int8Int8Int8Bin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = Int8Int8Int8Int8Int8Tip\n    bin s (a,b,c,d,e) = Int8Int8Int8Int8Int8Bin s a b c d e\n\ninstance US (Int8,Int8,Int8,Int8,Int8,Int8) where\n    data USet (Int8,Int8,Int8,Int8,Int8,Int8) = Int8Int8Int8Int8Int8Int8Tip | Int8Int8Int8Int8Int8Int8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8 !(USet (Int8,Int8,Int8,Int8,Int8,Int8)) !(USet (Int8,Int8,Int8,Int8,Int8,Int8))\n    view Int8Int8Int8Int8Int8Int8Tip = Tip\n    view (Int8Int8Int8Int8Int8Int8Bin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = Int8Int8Int8Int8Int8Int8Tip\n    bin s (a,b,c,d,e,f) = Int8Int8Int8Int8Int8Int8Bin s a b c d e f\n\ninstance US (Int8,Int8,Int8,Int8,Int8,Int8,Int8) where\n    data USet (Int8,Int8,Int8,Int8,Int8,Int8,Int8) = Int8Int8Int8Int8Int8Int8Int8Tip | Int8Int8Int8Int8Int8Int8Int8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8 !(USet (Int8,Int8,Int8,Int8,Int8,Int8,Int8)) !(USet (Int8,Int8,Int8,Int8,Int8,Int8,Int8))\n    view Int8Int8Int8Int8Int8Int8Int8Tip = Tip\n    view (Int8Int8Int8Int8Int8Int8Int8Bin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = Int8Int8Int8Int8Int8Int8Int8Tip\n    bin s (a,b,c,d,e,f,g) = Int8Int8Int8Int8Int8Int8Int8Bin s a b c d e f g\n\ninstance US (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8) where\n    data USet (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8) = Int8Int8Int8Int8Int8Int8Int8Int8Tip | Int8Int8Int8Int8Int8Int8Int8Int8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8 !(USet (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8)) !(USet (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8))\n    view Int8Int8Int8Int8Int8Int8Int8Int8Tip = Tip\n    view (Int8Int8Int8Int8Int8Int8Int8Int8Bin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = Int8Int8Int8Int8Int8Int8Int8Int8Tip\n    bin s (a,b,c,d,e,f,g,h) = Int8Int8Int8Int8Int8Int8Int8Int8Bin s a b c d e f g h\n\ninstance US (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8) where\n    data USet (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8) = Int8Int8Int8Int8Int8Int8Int8Int8Int8Tip | Int8Int8Int8Int8Int8Int8Int8Int8Int8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8{-# UNPACK #-} !Int8 !(USet (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8)) !(USet (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8))\n    view Int8Int8Int8Int8Int8Int8Int8Int8Int8Tip = Tip\n    view (Int8Int8Int8Int8Int8Int8Int8Int8Int8Bin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = Int8Int8Int8Int8Int8Int8Int8Int8Int8Tip\n    bin s (a,b,c,d,e,f,g,h,i) = Int8Int8Int8Int8Int8Int8Int8Int8Int8Bin s a b c d e f g h i\n\ninstance US (Int16,Int16) where\n    data USet (Int16,Int16) = Int16Int16Tip | Int16Int16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int16{-# UNPACK #-} !Int16 !(USet (Int16,Int16)) !(USet (Int16,Int16))\n    view Int16Int16Tip = Tip\n    view (Int16Int16Bin s a b l r) = Bin s (a,b) l r\n    tip = Int16Int16Tip\n    bin s (a,b) = Int16Int16Bin s a b\n\ninstance US (Int16,Int16,Int16) where\n    data USet (Int16,Int16,Int16) = Int16Int16Int16Tip | Int16Int16Int16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16 !(USet (Int16,Int16,Int16)) !(USet (Int16,Int16,Int16))\n    view Int16Int16Int16Tip = Tip\n    view (Int16Int16Int16Bin s a b c l r) = Bin s (a,b,c) l r\n    tip = Int16Int16Int16Tip\n    bin s (a,b,c) = Int16Int16Int16Bin s a b c\n\ninstance US (Int16,Int16,Int16,Int16) where\n    data USet (Int16,Int16,Int16,Int16) = Int16Int16Int16Int16Tip | Int16Int16Int16Int16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16 !(USet (Int16,Int16,Int16,Int16)) !(USet (Int16,Int16,Int16,Int16))\n    view Int16Int16Int16Int16Tip = Tip\n    view (Int16Int16Int16Int16Bin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = Int16Int16Int16Int16Tip\n    bin s (a,b,c,d) = Int16Int16Int16Int16Bin s a b c d\n\ninstance US (Int16,Int16,Int16,Int16,Int16) where\n    data USet (Int16,Int16,Int16,Int16,Int16) = Int16Int16Int16Int16Int16Tip | Int16Int16Int16Int16Int16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16 !(USet (Int16,Int16,Int16,Int16,Int16)) !(USet (Int16,Int16,Int16,Int16,Int16))\n    view Int16Int16Int16Int16Int16Tip = Tip\n    view (Int16Int16Int16Int16Int16Bin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = Int16Int16Int16Int16Int16Tip\n    bin s (a,b,c,d,e) = Int16Int16Int16Int16Int16Bin s a b c d e\n\ninstance US (Int16,Int16,Int16,Int16,Int16,Int16) where\n    data USet (Int16,Int16,Int16,Int16,Int16,Int16) = Int16Int16Int16Int16Int16Int16Tip | Int16Int16Int16Int16Int16Int16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16 !(USet (Int16,Int16,Int16,Int16,Int16,Int16)) !(USet (Int16,Int16,Int16,Int16,Int16,Int16))\n    view Int16Int16Int16Int16Int16Int16Tip = Tip\n    view (Int16Int16Int16Int16Int16Int16Bin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = Int16Int16Int16Int16Int16Int16Tip\n    bin s (a,b,c,d,e,f) = Int16Int16Int16Int16Int16Int16Bin s a b c d e f\n\ninstance US (Int16,Int16,Int16,Int16,Int16,Int16,Int16) where\n    data USet (Int16,Int16,Int16,Int16,Int16,Int16,Int16) = Int16Int16Int16Int16Int16Int16Int16Tip | Int16Int16Int16Int16Int16Int16Int16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16 !(USet (Int16,Int16,Int16,Int16,Int16,Int16,Int16)) !(USet (Int16,Int16,Int16,Int16,Int16,Int16,Int16))\n    view Int16Int16Int16Int16Int16Int16Int16Tip = Tip\n    view (Int16Int16Int16Int16Int16Int16Int16Bin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = Int16Int16Int16Int16Int16Int16Int16Tip\n    bin s (a,b,c,d,e,f,g) = Int16Int16Int16Int16Int16Int16Int16Bin s a b c d e f g\n\ninstance US (Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16) where\n    data USet (Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16) = Int16Int16Int16Int16Int16Int16Int16Int16Tip | Int16Int16Int16Int16Int16Int16Int16Int16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16 !(USet (Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16)) !(USet (Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16))\n    view Int16Int16Int16Int16Int16Int16Int16Int16Tip = Tip\n    view (Int16Int16Int16Int16Int16Int16Int16Int16Bin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = Int16Int16Int16Int16Int16Int16Int16Int16Tip\n    bin s (a,b,c,d,e,f,g,h) = Int16Int16Int16Int16Int16Int16Int16Int16Bin s a b c d e f g h\n\ninstance US (Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16) where\n    data USet (Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16) = Int16Int16Int16Int16Int16Int16Int16Int16Int16Tip | Int16Int16Int16Int16Int16Int16Int16Int16Int16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16{-# UNPACK #-} !Int16 !(USet (Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16)) !(USet (Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16,Int16))\n    view Int16Int16Int16Int16Int16Int16Int16Int16Int16Tip = Tip\n    view (Int16Int16Int16Int16Int16Int16Int16Int16Int16Bin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = Int16Int16Int16Int16Int16Int16Int16Int16Int16Tip\n    bin s (a,b,c,d,e,f,g,h,i) = Int16Int16Int16Int16Int16Int16Int16Int16Int16Bin s a b c d e f g h i\n\ninstance US (Int32,Int32) where\n    data USet (Int32,Int32) = Int32Int32Tip | Int32Int32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int32{-# UNPACK #-} !Int32 !(USet (Int32,Int32)) !(USet (Int32,Int32))\n    view Int32Int32Tip = Tip\n    view (Int32Int32Bin s a b l r) = Bin s (a,b) l r\n    tip = Int32Int32Tip\n    bin s (a,b) = Int32Int32Bin s a b\n\ninstance US (Int32,Int32,Int32) where\n    data USet (Int32,Int32,Int32) = Int32Int32Int32Tip | Int32Int32Int32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32 !(USet (Int32,Int32,Int32)) !(USet (Int32,Int32,Int32))\n    view Int32Int32Int32Tip = Tip\n    view (Int32Int32Int32Bin s a b c l r) = Bin s (a,b,c) l r\n    tip = Int32Int32Int32Tip\n    bin s (a,b,c) = Int32Int32Int32Bin s a b c\n\ninstance US (Int32,Int32,Int32,Int32) where\n    data USet (Int32,Int32,Int32,Int32) = Int32Int32Int32Int32Tip | Int32Int32Int32Int32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32 !(USet (Int32,Int32,Int32,Int32)) !(USet (Int32,Int32,Int32,Int32))\n    view Int32Int32Int32Int32Tip = Tip\n    view (Int32Int32Int32Int32Bin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = Int32Int32Int32Int32Tip\n    bin s (a,b,c,d) = Int32Int32Int32Int32Bin s a b c d\n\ninstance US (Int32,Int32,Int32,Int32,Int32) where\n    data USet (Int32,Int32,Int32,Int32,Int32) = Int32Int32Int32Int32Int32Tip | Int32Int32Int32Int32Int32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32 !(USet (Int32,Int32,Int32,Int32,Int32)) !(USet (Int32,Int32,Int32,Int32,Int32))\n    view Int32Int32Int32Int32Int32Tip = Tip\n    view (Int32Int32Int32Int32Int32Bin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = Int32Int32Int32Int32Int32Tip\n    bin s (a,b,c,d,e) = Int32Int32Int32Int32Int32Bin s a b c d e\n\ninstance US (Int32,Int32,Int32,Int32,Int32,Int32) where\n    data USet (Int32,Int32,Int32,Int32,Int32,Int32) = Int32Int32Int32Int32Int32Int32Tip | Int32Int32Int32Int32Int32Int32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32 !(USet (Int32,Int32,Int32,Int32,Int32,Int32)) !(USet (Int32,Int32,Int32,Int32,Int32,Int32))\n    view Int32Int32Int32Int32Int32Int32Tip = Tip\n    view (Int32Int32Int32Int32Int32Int32Bin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = Int32Int32Int32Int32Int32Int32Tip\n    bin s (a,b,c,d,e,f) = Int32Int32Int32Int32Int32Int32Bin s a b c d e f\n\ninstance US (Int32,Int32,Int32,Int32,Int32,Int32,Int32) where\n    data USet (Int32,Int32,Int32,Int32,Int32,Int32,Int32) = Int32Int32Int32Int32Int32Int32Int32Tip | Int32Int32Int32Int32Int32Int32Int32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32 !(USet (Int32,Int32,Int32,Int32,Int32,Int32,Int32)) !(USet (Int32,Int32,Int32,Int32,Int32,Int32,Int32))\n    view Int32Int32Int32Int32Int32Int32Int32Tip = Tip\n    view (Int32Int32Int32Int32Int32Int32Int32Bin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = Int32Int32Int32Int32Int32Int32Int32Tip\n    bin s (a,b,c,d,e,f,g) = Int32Int32Int32Int32Int32Int32Int32Bin s a b c d e f g\n\ninstance US (Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32) where\n    data USet (Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32) = Int32Int32Int32Int32Int32Int32Int32Int32Tip | Int32Int32Int32Int32Int32Int32Int32Int32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32 !(USet (Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32)) !(USet (Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32))\n    view Int32Int32Int32Int32Int32Int32Int32Int32Tip = Tip\n    view (Int32Int32Int32Int32Int32Int32Int32Int32Bin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = Int32Int32Int32Int32Int32Int32Int32Int32Tip\n    bin s (a,b,c,d,e,f,g,h) = Int32Int32Int32Int32Int32Int32Int32Int32Bin s a b c d e f g h\n\ninstance US (Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32) where\n    data USet (Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32) = Int32Int32Int32Int32Int32Int32Int32Int32Int32Tip | Int32Int32Int32Int32Int32Int32Int32Int32Int32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32{-# UNPACK #-} !Int32 !(USet (Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32)) !(USet (Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32))\n    view Int32Int32Int32Int32Int32Int32Int32Int32Int32Tip = Tip\n    view (Int32Int32Int32Int32Int32Int32Int32Int32Int32Bin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = Int32Int32Int32Int32Int32Int32Int32Int32Int32Tip\n    bin s (a,b,c,d,e,f,g,h,i) = Int32Int32Int32Int32Int32Int32Int32Int32Int32Bin s a b c d e f g h i\n\ninstance US (Int64,Int64) where\n    data USet (Int64,Int64) = Int64Int64Tip | Int64Int64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int64{-# UNPACK #-} !Int64 !(USet (Int64,Int64)) !(USet (Int64,Int64))\n    view Int64Int64Tip = Tip\n    view (Int64Int64Bin s a b l r) = Bin s (a,b) l r\n    tip = Int64Int64Tip\n    bin s (a,b) = Int64Int64Bin s a b\n\ninstance US (Int64,Int64,Int64) where\n    data USet (Int64,Int64,Int64) = Int64Int64Int64Tip | Int64Int64Int64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64 !(USet (Int64,Int64,Int64)) !(USet (Int64,Int64,Int64))\n    view Int64Int64Int64Tip = Tip\n    view (Int64Int64Int64Bin s a b c l r) = Bin s (a,b,c) l r\n    tip = Int64Int64Int64Tip\n    bin s (a,b,c) = Int64Int64Int64Bin s a b c\n\ninstance US (Int64,Int64,Int64,Int64) where\n    data USet (Int64,Int64,Int64,Int64) = Int64Int64Int64Int64Tip | Int64Int64Int64Int64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64 !(USet (Int64,Int64,Int64,Int64)) !(USet (Int64,Int64,Int64,Int64))\n    view Int64Int64Int64Int64Tip = Tip\n    view (Int64Int64Int64Int64Bin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = Int64Int64Int64Int64Tip\n    bin s (a,b,c,d) = Int64Int64Int64Int64Bin s a b c d\n\ninstance US (Int64,Int64,Int64,Int64,Int64) where\n    data USet (Int64,Int64,Int64,Int64,Int64) = Int64Int64Int64Int64Int64Tip | Int64Int64Int64Int64Int64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64 !(USet (Int64,Int64,Int64,Int64,Int64)) !(USet (Int64,Int64,Int64,Int64,Int64))\n    view Int64Int64Int64Int64Int64Tip = Tip\n    view (Int64Int64Int64Int64Int64Bin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = Int64Int64Int64Int64Int64Tip\n    bin s (a,b,c,d,e) = Int64Int64Int64Int64Int64Bin s a b c d e\n\ninstance US (Int64,Int64,Int64,Int64,Int64,Int64) where\n    data USet (Int64,Int64,Int64,Int64,Int64,Int64) = Int64Int64Int64Int64Int64Int64Tip | Int64Int64Int64Int64Int64Int64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64 !(USet (Int64,Int64,Int64,Int64,Int64,Int64)) !(USet (Int64,Int64,Int64,Int64,Int64,Int64))\n    view Int64Int64Int64Int64Int64Int64Tip = Tip\n    view (Int64Int64Int64Int64Int64Int64Bin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = Int64Int64Int64Int64Int64Int64Tip\n    bin s (a,b,c,d,e,f) = Int64Int64Int64Int64Int64Int64Bin s a b c d e f\n\ninstance US (Int64,Int64,Int64,Int64,Int64,Int64,Int64) where\n    data USet (Int64,Int64,Int64,Int64,Int64,Int64,Int64) = Int64Int64Int64Int64Int64Int64Int64Tip | Int64Int64Int64Int64Int64Int64Int64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64 !(USet (Int64,Int64,Int64,Int64,Int64,Int64,Int64)) !(USet (Int64,Int64,Int64,Int64,Int64,Int64,Int64))\n    view Int64Int64Int64Int64Int64Int64Int64Tip = Tip\n    view (Int64Int64Int64Int64Int64Int64Int64Bin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = Int64Int64Int64Int64Int64Int64Int64Tip\n    bin s (a,b,c,d,e,f,g) = Int64Int64Int64Int64Int64Int64Int64Bin s a b c d e f g\n\ninstance US (Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64) where\n    data USet (Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64) = Int64Int64Int64Int64Int64Int64Int64Int64Tip | Int64Int64Int64Int64Int64Int64Int64Int64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64 !(USet (Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64)) !(USet (Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64))\n    view Int64Int64Int64Int64Int64Int64Int64Int64Tip = Tip\n    view (Int64Int64Int64Int64Int64Int64Int64Int64Bin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = Int64Int64Int64Int64Int64Int64Int64Int64Tip\n    bin s (a,b,c,d,e,f,g,h) = Int64Int64Int64Int64Int64Int64Int64Int64Bin s a b c d e f g h\n\ninstance US (Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64) where\n    data USet (Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64) = Int64Int64Int64Int64Int64Int64Int64Int64Int64Tip | Int64Int64Int64Int64Int64Int64Int64Int64Int64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64{-# UNPACK #-} !Int64 !(USet (Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64)) !(USet (Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64,Int64))\n    view Int64Int64Int64Int64Int64Int64Int64Int64Int64Tip = Tip\n    view (Int64Int64Int64Int64Int64Int64Int64Int64Int64Bin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = Int64Int64Int64Int64Int64Int64Int64Int64Int64Tip\n    bin s (a,b,c,d,e,f,g,h,i) = Int64Int64Int64Int64Int64Int64Int64Int64Int64Bin s a b c d e f g h i\n\ninstance US (Word8,Word8) where\n    data USet (Word8,Word8) = Word8Word8Tip | Word8Word8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word8{-# UNPACK #-} !Word8 !(USet (Word8,Word8)) !(USet (Word8,Word8))\n    view Word8Word8Tip = Tip\n    view (Word8Word8Bin s a b l r) = Bin s (a,b) l r\n    tip = Word8Word8Tip\n    bin s (a,b) = Word8Word8Bin s a b\n\ninstance US (Word8,Word8,Word8) where\n    data USet (Word8,Word8,Word8) = Word8Word8Word8Tip | Word8Word8Word8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8 !(USet (Word8,Word8,Word8)) !(USet (Word8,Word8,Word8))\n    view Word8Word8Word8Tip = Tip\n    view (Word8Word8Word8Bin s a b c l r) = Bin s (a,b,c) l r\n    tip = Word8Word8Word8Tip\n    bin s (a,b,c) = Word8Word8Word8Bin s a b c\n\ninstance US (Word8,Word8,Word8,Word8) where\n    data USet (Word8,Word8,Word8,Word8) = Word8Word8Word8Word8Tip | Word8Word8Word8Word8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8 !(USet (Word8,Word8,Word8,Word8)) !(USet (Word8,Word8,Word8,Word8))\n    view Word8Word8Word8Word8Tip = Tip\n    view (Word8Word8Word8Word8Bin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = Word8Word8Word8Word8Tip\n    bin s (a,b,c,d) = Word8Word8Word8Word8Bin s a b c d\n\ninstance US (Word8,Word8,Word8,Word8,Word8) where\n    data USet (Word8,Word8,Word8,Word8,Word8) = Word8Word8Word8Word8Word8Tip | Word8Word8Word8Word8Word8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8 !(USet (Word8,Word8,Word8,Word8,Word8)) !(USet (Word8,Word8,Word8,Word8,Word8))\n    view Word8Word8Word8Word8Word8Tip = Tip\n    view (Word8Word8Word8Word8Word8Bin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = Word8Word8Word8Word8Word8Tip\n    bin s (a,b,c,d,e) = Word8Word8Word8Word8Word8Bin s a b c d e\n\ninstance US (Word8,Word8,Word8,Word8,Word8,Word8) where\n    data USet (Word8,Word8,Word8,Word8,Word8,Word8) = Word8Word8Word8Word8Word8Word8Tip | Word8Word8Word8Word8Word8Word8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8 !(USet (Word8,Word8,Word8,Word8,Word8,Word8)) !(USet (Word8,Word8,Word8,Word8,Word8,Word8))\n    view Word8Word8Word8Word8Word8Word8Tip = Tip\n    view (Word8Word8Word8Word8Word8Word8Bin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = Word8Word8Word8Word8Word8Word8Tip\n    bin s (a,b,c,d,e,f) = Word8Word8Word8Word8Word8Word8Bin s a b c d e f\n\ninstance US (Word8,Word8,Word8,Word8,Word8,Word8,Word8) where\n    data USet (Word8,Word8,Word8,Word8,Word8,Word8,Word8) = Word8Word8Word8Word8Word8Word8Word8Tip | Word8Word8Word8Word8Word8Word8Word8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8 !(USet (Word8,Word8,Word8,Word8,Word8,Word8,Word8)) !(USet (Word8,Word8,Word8,Word8,Word8,Word8,Word8))\n    view Word8Word8Word8Word8Word8Word8Word8Tip = Tip\n    view (Word8Word8Word8Word8Word8Word8Word8Bin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = Word8Word8Word8Word8Word8Word8Word8Tip\n    bin s (a,b,c,d,e,f,g) = Word8Word8Word8Word8Word8Word8Word8Bin s a b c d e f g\n\ninstance US (Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8) where\n    data USet (Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8) = Word8Word8Word8Word8Word8Word8Word8Word8Tip | Word8Word8Word8Word8Word8Word8Word8Word8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8 !(USet (Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8)) !(USet (Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8))\n    view Word8Word8Word8Word8Word8Word8Word8Word8Tip = Tip\n    view (Word8Word8Word8Word8Word8Word8Word8Word8Bin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = Word8Word8Word8Word8Word8Word8Word8Word8Tip\n    bin s (a,b,c,d,e,f,g,h) = Word8Word8Word8Word8Word8Word8Word8Word8Bin s a b c d e f g h\n\ninstance US (Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8) where\n    data USet (Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8) = Word8Word8Word8Word8Word8Word8Word8Word8Word8Tip | Word8Word8Word8Word8Word8Word8Word8Word8Word8Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8{-# UNPACK #-} !Word8 !(USet (Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8)) !(USet (Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8,Word8))\n    view Word8Word8Word8Word8Word8Word8Word8Word8Word8Tip = Tip\n    view (Word8Word8Word8Word8Word8Word8Word8Word8Word8Bin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = Word8Word8Word8Word8Word8Word8Word8Word8Word8Tip\n    bin s (a,b,c,d,e,f,g,h,i) = Word8Word8Word8Word8Word8Word8Word8Word8Word8Bin s a b c d e f g h i\n\ninstance US (Word16,Word16) where\n    data USet (Word16,Word16) = Word16Word16Tip | Word16Word16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word16{-# UNPACK #-} !Word16 !(USet (Word16,Word16)) !(USet (Word16,Word16))\n    view Word16Word16Tip = Tip\n    view (Word16Word16Bin s a b l r) = Bin s (a,b) l r\n    tip = Word16Word16Tip\n    bin s (a,b) = Word16Word16Bin s a b\n\ninstance US (Word16,Word16,Word16) where\n    data USet (Word16,Word16,Word16) = Word16Word16Word16Tip | Word16Word16Word16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16 !(USet (Word16,Word16,Word16)) !(USet (Word16,Word16,Word16))\n    view Word16Word16Word16Tip = Tip\n    view (Word16Word16Word16Bin s a b c l r) = Bin s (a,b,c) l r\n    tip = Word16Word16Word16Tip\n    bin s (a,b,c) = Word16Word16Word16Bin s a b c\n\ninstance US (Word16,Word16,Word16,Word16) where\n    data USet (Word16,Word16,Word16,Word16) = Word16Word16Word16Word16Tip | Word16Word16Word16Word16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16 !(USet (Word16,Word16,Word16,Word16)) !(USet (Word16,Word16,Word16,Word16))\n    view Word16Word16Word16Word16Tip = Tip\n    view (Word16Word16Word16Word16Bin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = Word16Word16Word16Word16Tip\n    bin s (a,b,c,d) = Word16Word16Word16Word16Bin s a b c d\n\ninstance US (Word16,Word16,Word16,Word16,Word16) where\n    data USet (Word16,Word16,Word16,Word16,Word16) = Word16Word16Word16Word16Word16Tip | Word16Word16Word16Word16Word16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16 !(USet (Word16,Word16,Word16,Word16,Word16)) !(USet (Word16,Word16,Word16,Word16,Word16))\n    view Word16Word16Word16Word16Word16Tip = Tip\n    view (Word16Word16Word16Word16Word16Bin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = Word16Word16Word16Word16Word16Tip\n    bin s (a,b,c,d,e) = Word16Word16Word16Word16Word16Bin s a b c d e\n\ninstance US (Word16,Word16,Word16,Word16,Word16,Word16) where\n    data USet (Word16,Word16,Word16,Word16,Word16,Word16) = Word16Word16Word16Word16Word16Word16Tip | Word16Word16Word16Word16Word16Word16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16 !(USet (Word16,Word16,Word16,Word16,Word16,Word16)) !(USet (Word16,Word16,Word16,Word16,Word16,Word16))\n    view Word16Word16Word16Word16Word16Word16Tip = Tip\n    view (Word16Word16Word16Word16Word16Word16Bin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = Word16Word16Word16Word16Word16Word16Tip\n    bin s (a,b,c,d,e,f) = Word16Word16Word16Word16Word16Word16Bin s a b c d e f\n\ninstance US (Word16,Word16,Word16,Word16,Word16,Word16,Word16) where\n    data USet (Word16,Word16,Word16,Word16,Word16,Word16,Word16) = Word16Word16Word16Word16Word16Word16Word16Tip | Word16Word16Word16Word16Word16Word16Word16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16 !(USet (Word16,Word16,Word16,Word16,Word16,Word16,Word16)) !(USet (Word16,Word16,Word16,Word16,Word16,Word16,Word16))\n    view Word16Word16Word16Word16Word16Word16Word16Tip = Tip\n    view (Word16Word16Word16Word16Word16Word16Word16Bin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = Word16Word16Word16Word16Word16Word16Word16Tip\n    bin s (a,b,c,d,e,f,g) = Word16Word16Word16Word16Word16Word16Word16Bin s a b c d e f g\n\ninstance US (Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16) where\n    data USet (Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16) = Word16Word16Word16Word16Word16Word16Word16Word16Tip | Word16Word16Word16Word16Word16Word16Word16Word16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16 !(USet (Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16)) !(USet (Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16))\n    view Word16Word16Word16Word16Word16Word16Word16Word16Tip = Tip\n    view (Word16Word16Word16Word16Word16Word16Word16Word16Bin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = Word16Word16Word16Word16Word16Word16Word16Word16Tip\n    bin s (a,b,c,d,e,f,g,h) = Word16Word16Word16Word16Word16Word16Word16Word16Bin s a b c d e f g h\n\ninstance US (Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16) where\n    data USet (Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16) = Word16Word16Word16Word16Word16Word16Word16Word16Word16Tip | Word16Word16Word16Word16Word16Word16Word16Word16Word16Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16{-# UNPACK #-} !Word16 !(USet (Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16)) !(USet (Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16,Word16))\n    view Word16Word16Word16Word16Word16Word16Word16Word16Word16Tip = Tip\n    view (Word16Word16Word16Word16Word16Word16Word16Word16Word16Bin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = Word16Word16Word16Word16Word16Word16Word16Word16Word16Tip\n    bin s (a,b,c,d,e,f,g,h,i) = Word16Word16Word16Word16Word16Word16Word16Word16Word16Bin s a b c d e f g h i\n\ninstance US (Word32,Word32) where\n    data USet (Word32,Word32) = Word32Word32Tip | Word32Word32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word32{-# UNPACK #-} !Word32 !(USet (Word32,Word32)) !(USet (Word32,Word32))\n    view Word32Word32Tip = Tip\n    view (Word32Word32Bin s a b l r) = Bin s (a,b) l r\n    tip = Word32Word32Tip\n    bin s (a,b) = Word32Word32Bin s a b\n\ninstance US (Word32,Word32,Word32) where\n    data USet (Word32,Word32,Word32) = Word32Word32Word32Tip | Word32Word32Word32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32 !(USet (Word32,Word32,Word32)) !(USet (Word32,Word32,Word32))\n    view Word32Word32Word32Tip = Tip\n    view (Word32Word32Word32Bin s a b c l r) = Bin s (a,b,c) l r\n    tip = Word32Word32Word32Tip\n    bin s (a,b,c) = Word32Word32Word32Bin s a b c\n\ninstance US (Word32,Word32,Word32,Word32) where\n    data USet (Word32,Word32,Word32,Word32) = Word32Word32Word32Word32Tip | Word32Word32Word32Word32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32 !(USet (Word32,Word32,Word32,Word32)) !(USet (Word32,Word32,Word32,Word32))\n    view Word32Word32Word32Word32Tip = Tip\n    view (Word32Word32Word32Word32Bin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = Word32Word32Word32Word32Tip\n    bin s (a,b,c,d) = Word32Word32Word32Word32Bin s a b c d\n\ninstance US (Word32,Word32,Word32,Word32,Word32) where\n    data USet (Word32,Word32,Word32,Word32,Word32) = Word32Word32Word32Word32Word32Tip | Word32Word32Word32Word32Word32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32 !(USet (Word32,Word32,Word32,Word32,Word32)) !(USet (Word32,Word32,Word32,Word32,Word32))\n    view Word32Word32Word32Word32Word32Tip = Tip\n    view (Word32Word32Word32Word32Word32Bin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = Word32Word32Word32Word32Word32Tip\n    bin s (a,b,c,d,e) = Word32Word32Word32Word32Word32Bin s a b c d e\n\ninstance US (Word32,Word32,Word32,Word32,Word32,Word32) where\n    data USet (Word32,Word32,Word32,Word32,Word32,Word32) = Word32Word32Word32Word32Word32Word32Tip | Word32Word32Word32Word32Word32Word32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32 !(USet (Word32,Word32,Word32,Word32,Word32,Word32)) !(USet (Word32,Word32,Word32,Word32,Word32,Word32))\n    view Word32Word32Word32Word32Word32Word32Tip = Tip\n    view (Word32Word32Word32Word32Word32Word32Bin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = Word32Word32Word32Word32Word32Word32Tip\n    bin s (a,b,c,d,e,f) = Word32Word32Word32Word32Word32Word32Bin s a b c d e f\n\ninstance US (Word32,Word32,Word32,Word32,Word32,Word32,Word32) where\n    data USet (Word32,Word32,Word32,Word32,Word32,Word32,Word32) = Word32Word32Word32Word32Word32Word32Word32Tip | Word32Word32Word32Word32Word32Word32Word32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32 !(USet (Word32,Word32,Word32,Word32,Word32,Word32,Word32)) !(USet (Word32,Word32,Word32,Word32,Word32,Word32,Word32))\n    view Word32Word32Word32Word32Word32Word32Word32Tip = Tip\n    view (Word32Word32Word32Word32Word32Word32Word32Bin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = Word32Word32Word32Word32Word32Word32Word32Tip\n    bin s (a,b,c,d,e,f,g) = Word32Word32Word32Word32Word32Word32Word32Bin s a b c d e f g\n\ninstance US (Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32) where\n    data USet (Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32) = Word32Word32Word32Word32Word32Word32Word32Word32Tip | Word32Word32Word32Word32Word32Word32Word32Word32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32 !(USet (Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32)) !(USet (Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32))\n    view Word32Word32Word32Word32Word32Word32Word32Word32Tip = Tip\n    view (Word32Word32Word32Word32Word32Word32Word32Word32Bin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = Word32Word32Word32Word32Word32Word32Word32Word32Tip\n    bin s (a,b,c,d,e,f,g,h) = Word32Word32Word32Word32Word32Word32Word32Word32Bin s a b c d e f g h\n\ninstance US (Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32) where\n    data USet (Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32) = Word32Word32Word32Word32Word32Word32Word32Word32Word32Tip | Word32Word32Word32Word32Word32Word32Word32Word32Word32Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32{-# UNPACK #-} !Word32 !(USet (Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32)) !(USet (Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32,Word32))\n    view Word32Word32Word32Word32Word32Word32Word32Word32Word32Tip = Tip\n    view (Word32Word32Word32Word32Word32Word32Word32Word32Word32Bin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = Word32Word32Word32Word32Word32Word32Word32Word32Word32Tip\n    bin s (a,b,c,d,e,f,g,h,i) = Word32Word32Word32Word32Word32Word32Word32Word32Word32Bin s a b c d e f g h i\n\ninstance US (Word64,Word64) where\n    data USet (Word64,Word64) = Word64Word64Tip | Word64Word64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word64{-# UNPACK #-} !Word64 !(USet (Word64,Word64)) !(USet (Word64,Word64))\n    view Word64Word64Tip = Tip\n    view (Word64Word64Bin s a b l r) = Bin s (a,b) l r\n    tip = Word64Word64Tip\n    bin s (a,b) = Word64Word64Bin s a b\n\ninstance US (Word64,Word64,Word64) where\n    data USet (Word64,Word64,Word64) = Word64Word64Word64Tip | Word64Word64Word64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64 !(USet (Word64,Word64,Word64)) !(USet (Word64,Word64,Word64))\n    view Word64Word64Word64Tip = Tip\n    view (Word64Word64Word64Bin s a b c l r) = Bin s (a,b,c) l r\n    tip = Word64Word64Word64Tip\n    bin s (a,b,c) = Word64Word64Word64Bin s a b c\n\ninstance US (Word64,Word64,Word64,Word64) where\n    data USet (Word64,Word64,Word64,Word64) = Word64Word64Word64Word64Tip | Word64Word64Word64Word64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64 !(USet (Word64,Word64,Word64,Word64)) !(USet (Word64,Word64,Word64,Word64))\n    view Word64Word64Word64Word64Tip = Tip\n    view (Word64Word64Word64Word64Bin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = Word64Word64Word64Word64Tip\n    bin s (a,b,c,d) = Word64Word64Word64Word64Bin s a b c d\n\ninstance US (Word64,Word64,Word64,Word64,Word64) where\n    data USet (Word64,Word64,Word64,Word64,Word64) = Word64Word64Word64Word64Word64Tip | Word64Word64Word64Word64Word64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64 !(USet (Word64,Word64,Word64,Word64,Word64)) !(USet (Word64,Word64,Word64,Word64,Word64))\n    view Word64Word64Word64Word64Word64Tip = Tip\n    view (Word64Word64Word64Word64Word64Bin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = Word64Word64Word64Word64Word64Tip\n    bin s (a,b,c,d,e) = Word64Word64Word64Word64Word64Bin s a b c d e\n\ninstance US (Word64,Word64,Word64,Word64,Word64,Word64) where\n    data USet (Word64,Word64,Word64,Word64,Word64,Word64) = Word64Word64Word64Word64Word64Word64Tip | Word64Word64Word64Word64Word64Word64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64 !(USet (Word64,Word64,Word64,Word64,Word64,Word64)) !(USet (Word64,Word64,Word64,Word64,Word64,Word64))\n    view Word64Word64Word64Word64Word64Word64Tip = Tip\n    view (Word64Word64Word64Word64Word64Word64Bin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = Word64Word64Word64Word64Word64Word64Tip\n    bin s (a,b,c,d,e,f) = Word64Word64Word64Word64Word64Word64Bin s a b c d e f\n\ninstance US (Word64,Word64,Word64,Word64,Word64,Word64,Word64) where\n    data USet (Word64,Word64,Word64,Word64,Word64,Word64,Word64) = Word64Word64Word64Word64Word64Word64Word64Tip | Word64Word64Word64Word64Word64Word64Word64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64 !(USet (Word64,Word64,Word64,Word64,Word64,Word64,Word64)) !(USet (Word64,Word64,Word64,Word64,Word64,Word64,Word64))\n    view Word64Word64Word64Word64Word64Word64Word64Tip = Tip\n    view (Word64Word64Word64Word64Word64Word64Word64Bin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = Word64Word64Word64Word64Word64Word64Word64Tip\n    bin s (a,b,c,d,e,f,g) = Word64Word64Word64Word64Word64Word64Word64Bin s a b c d e f g\n\ninstance US (Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64) where\n    data USet (Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64) = Word64Word64Word64Word64Word64Word64Word64Word64Tip | Word64Word64Word64Word64Word64Word64Word64Word64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64 !(USet (Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64)) !(USet (Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64))\n    view Word64Word64Word64Word64Word64Word64Word64Word64Tip = Tip\n    view (Word64Word64Word64Word64Word64Word64Word64Word64Bin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = Word64Word64Word64Word64Word64Word64Word64Word64Tip\n    bin s (a,b,c,d,e,f,g,h) = Word64Word64Word64Word64Word64Word64Word64Word64Bin s a b c d e f g h\n\ninstance US (Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64) where\n    data USet (Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64) = Word64Word64Word64Word64Word64Word64Word64Word64Word64Tip | Word64Word64Word64Word64Word64Word64Word64Word64Word64Bin {-# UNPACK #-} !Size {-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64{-# UNPACK #-} !Word64 !(USet (Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64)) !(USet (Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64,Word64))\n    view Word64Word64Word64Word64Word64Word64Word64Word64Word64Tip = Tip\n    view (Word64Word64Word64Word64Word64Word64Word64Word64Word64Bin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = Word64Word64Word64Word64Word64Word64Word64Word64Word64Tip\n    bin s (a,b,c,d,e,f,g,h,i) = Word64Word64Word64Word64Word64Word64Word64Word64Word64Bin s a b c d e f g h i\n\ninstance US (Double,Double) where\n    data USet (Double,Double) = DoubleDoubleTip | DoubleDoubleBin {-# UNPACK #-} !Size {-# UNPACK #-} !Double{-# UNPACK #-} !Double !(USet (Double,Double)) !(USet (Double,Double))\n    view DoubleDoubleTip = Tip\n    view (DoubleDoubleBin s a b l r) = Bin s (a,b) l r\n    tip = DoubleDoubleTip\n    bin s (a,b) = DoubleDoubleBin s a b\n\ninstance US (Double,Double,Double) where\n    data USet (Double,Double,Double) = DoubleDoubleDoubleTip | DoubleDoubleDoubleBin {-# UNPACK #-} !Size {-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double !(USet (Double,Double,Double)) !(USet (Double,Double,Double))\n    view DoubleDoubleDoubleTip = Tip\n    view (DoubleDoubleDoubleBin s a b c l r) = Bin s (a,b,c) l r\n    tip = DoubleDoubleDoubleTip\n    bin s (a,b,c) = DoubleDoubleDoubleBin s a b c\n\ninstance US (Double,Double,Double,Double) where\n    data USet (Double,Double,Double,Double) = DoubleDoubleDoubleDoubleTip | DoubleDoubleDoubleDoubleBin {-# UNPACK #-} !Size {-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double !(USet (Double,Double,Double,Double)) !(USet (Double,Double,Double,Double))\n    view DoubleDoubleDoubleDoubleTip = Tip\n    view (DoubleDoubleDoubleDoubleBin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = DoubleDoubleDoubleDoubleTip\n    bin s (a,b,c,d) = DoubleDoubleDoubleDoubleBin s a b c d\n\ninstance US (Double,Double,Double,Double,Double) where\n    data USet (Double,Double,Double,Double,Double) = DoubleDoubleDoubleDoubleDoubleTip | DoubleDoubleDoubleDoubleDoubleBin {-# UNPACK #-} !Size {-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double !(USet (Double,Double,Double,Double,Double)) !(USet (Double,Double,Double,Double,Double))\n    view DoubleDoubleDoubleDoubleDoubleTip = Tip\n    view (DoubleDoubleDoubleDoubleDoubleBin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = DoubleDoubleDoubleDoubleDoubleTip\n    bin s (a,b,c,d,e) = DoubleDoubleDoubleDoubleDoubleBin s a b c d e\n\ninstance US (Double,Double,Double,Double,Double,Double) where\n    data USet (Double,Double,Double,Double,Double,Double) = DoubleDoubleDoubleDoubleDoubleDoubleTip | DoubleDoubleDoubleDoubleDoubleDoubleBin {-# UNPACK #-} !Size {-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double !(USet (Double,Double,Double,Double,Double,Double)) !(USet (Double,Double,Double,Double,Double,Double))\n    view DoubleDoubleDoubleDoubleDoubleDoubleTip = Tip\n    view (DoubleDoubleDoubleDoubleDoubleDoubleBin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = DoubleDoubleDoubleDoubleDoubleDoubleTip\n    bin s (a,b,c,d,e,f) = DoubleDoubleDoubleDoubleDoubleDoubleBin s a b c d e f\n\ninstance US (Double,Double,Double,Double,Double,Double,Double) where\n    data USet (Double,Double,Double,Double,Double,Double,Double) = DoubleDoubleDoubleDoubleDoubleDoubleDoubleTip | DoubleDoubleDoubleDoubleDoubleDoubleDoubleBin {-# UNPACK #-} !Size {-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double !(USet (Double,Double,Double,Double,Double,Double,Double)) !(USet (Double,Double,Double,Double,Double,Double,Double))\n    view DoubleDoubleDoubleDoubleDoubleDoubleDoubleTip = Tip\n    view (DoubleDoubleDoubleDoubleDoubleDoubleDoubleBin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = DoubleDoubleDoubleDoubleDoubleDoubleDoubleTip\n    bin s (a,b,c,d,e,f,g) = DoubleDoubleDoubleDoubleDoubleDoubleDoubleBin s a b c d e f g\n\ninstance US (Double,Double,Double,Double,Double,Double,Double,Double) where\n    data USet (Double,Double,Double,Double,Double,Double,Double,Double) = DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleTip | DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleBin {-# UNPACK #-} !Size {-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double !(USet (Double,Double,Double,Double,Double,Double,Double,Double)) !(USet (Double,Double,Double,Double,Double,Double,Double,Double))\n    view DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleTip = Tip\n    view (DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleBin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleTip\n    bin s (a,b,c,d,e,f,g,h) = DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleBin s a b c d e f g h\n\ninstance US (Double,Double,Double,Double,Double,Double,Double,Double,Double) where\n    data USet (Double,Double,Double,Double,Double,Double,Double,Double,Double) = DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleTip | DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleBin {-# UNPACK #-} !Size {-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double{-# UNPACK #-} !Double !(USet (Double,Double,Double,Double,Double,Double,Double,Double,Double)) !(USet (Double,Double,Double,Double,Double,Double,Double,Double,Double))\n    view DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleTip = Tip\n    view (DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleBin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleTip\n    bin s (a,b,c,d,e,f,g,h,i) = DoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleDoubleBin s a b c d e f g h i\n\ninstance US (Float,Float) where\n    data USet (Float,Float) = FloatFloatTip | FloatFloatBin {-# UNPACK #-} !Size {-# UNPACK #-} !Float{-# UNPACK #-} !Float !(USet (Float,Float)) !(USet (Float,Float))\n    view FloatFloatTip = Tip\n    view (FloatFloatBin s a b l r) = Bin s (a,b) l r\n    tip = FloatFloatTip\n    bin s (a,b) = FloatFloatBin s a b\n\ninstance US (Float,Float,Float) where\n    data USet (Float,Float,Float) = FloatFloatFloatTip | FloatFloatFloatBin {-# UNPACK #-} !Size {-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float !(USet (Float,Float,Float)) !(USet (Float,Float,Float))\n    view FloatFloatFloatTip = Tip\n    view (FloatFloatFloatBin s a b c l r) = Bin s (a,b,c) l r\n    tip = FloatFloatFloatTip\n    bin s (a,b,c) = FloatFloatFloatBin s a b c\n\ninstance US (Float,Float,Float,Float) where\n    data USet (Float,Float,Float,Float) = FloatFloatFloatFloatTip | FloatFloatFloatFloatBin {-# UNPACK #-} !Size {-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float !(USet (Float,Float,Float,Float)) !(USet (Float,Float,Float,Float))\n    view FloatFloatFloatFloatTip = Tip\n    view (FloatFloatFloatFloatBin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = FloatFloatFloatFloatTip\n    bin s (a,b,c,d) = FloatFloatFloatFloatBin s a b c d\n\ninstance US (Float,Float,Float,Float,Float) where\n    data USet (Float,Float,Float,Float,Float) = FloatFloatFloatFloatFloatTip | FloatFloatFloatFloatFloatBin {-# UNPACK #-} !Size {-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float !(USet (Float,Float,Float,Float,Float)) !(USet (Float,Float,Float,Float,Float))\n    view FloatFloatFloatFloatFloatTip = Tip\n    view (FloatFloatFloatFloatFloatBin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = FloatFloatFloatFloatFloatTip\n    bin s (a,b,c,d,e) = FloatFloatFloatFloatFloatBin s a b c d e\n\ninstance US (Float,Float,Float,Float,Float,Float) where\n    data USet (Float,Float,Float,Float,Float,Float) = FloatFloatFloatFloatFloatFloatTip | FloatFloatFloatFloatFloatFloatBin {-# UNPACK #-} !Size {-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float !(USet (Float,Float,Float,Float,Float,Float)) !(USet (Float,Float,Float,Float,Float,Float))\n    view FloatFloatFloatFloatFloatFloatTip = Tip\n    view (FloatFloatFloatFloatFloatFloatBin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = FloatFloatFloatFloatFloatFloatTip\n    bin s (a,b,c,d,e,f) = FloatFloatFloatFloatFloatFloatBin s a b c d e f\n\ninstance US (Float,Float,Float,Float,Float,Float,Float) where\n    data USet (Float,Float,Float,Float,Float,Float,Float) = FloatFloatFloatFloatFloatFloatFloatTip | FloatFloatFloatFloatFloatFloatFloatBin {-# UNPACK #-} !Size {-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float !(USet (Float,Float,Float,Float,Float,Float,Float)) !(USet (Float,Float,Float,Float,Float,Float,Float))\n    view FloatFloatFloatFloatFloatFloatFloatTip = Tip\n    view (FloatFloatFloatFloatFloatFloatFloatBin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = FloatFloatFloatFloatFloatFloatFloatTip\n    bin s (a,b,c,d,e,f,g) = FloatFloatFloatFloatFloatFloatFloatBin s a b c d e f g\n\ninstance US (Float,Float,Float,Float,Float,Float,Float,Float) where\n    data USet (Float,Float,Float,Float,Float,Float,Float,Float) = FloatFloatFloatFloatFloatFloatFloatFloatTip | FloatFloatFloatFloatFloatFloatFloatFloatBin {-# UNPACK #-} !Size {-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float !(USet (Float,Float,Float,Float,Float,Float,Float,Float)) !(USet (Float,Float,Float,Float,Float,Float,Float,Float))\n    view FloatFloatFloatFloatFloatFloatFloatFloatTip = Tip\n    view (FloatFloatFloatFloatFloatFloatFloatFloatBin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = FloatFloatFloatFloatFloatFloatFloatFloatTip\n    bin s (a,b,c,d,e,f,g,h) = FloatFloatFloatFloatFloatFloatFloatFloatBin s a b c d e f g h\n\ninstance US (Float,Float,Float,Float,Float,Float,Float,Float,Float) where\n    data USet (Float,Float,Float,Float,Float,Float,Float,Float,Float) = FloatFloatFloatFloatFloatFloatFloatFloatFloatTip | FloatFloatFloatFloatFloatFloatFloatFloatFloatBin {-# UNPACK #-} !Size {-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float{-# UNPACK #-} !Float !(USet (Float,Float,Float,Float,Float,Float,Float,Float,Float)) !(USet (Float,Float,Float,Float,Float,Float,Float,Float,Float))\n    view FloatFloatFloatFloatFloatFloatFloatFloatFloatTip = Tip\n    view (FloatFloatFloatFloatFloatFloatFloatFloatFloatBin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = FloatFloatFloatFloatFloatFloatFloatFloatFloatTip\n    bin s (a,b,c,d,e,f,g,h,i) = FloatFloatFloatFloatFloatFloatFloatFloatFloatBin s a b c d e f g h i\n\ninstance US (Integer,Integer) where\n    data USet (Integer,Integer) = IntegerIntegerTip | IntegerIntegerBin {-# UNPACK #-} !Size !Integer!Integer !(USet (Integer,Integer)) !(USet (Integer,Integer))\n    view IntegerIntegerTip = Tip\n    view (IntegerIntegerBin s a b l r) = Bin s (a,b) l r\n    tip = IntegerIntegerTip\n    bin s (a,b) = IntegerIntegerBin s a b\n\ninstance US (Integer,Integer,Integer) where\n    data USet (Integer,Integer,Integer) = IntegerIntegerIntegerTip | IntegerIntegerIntegerBin {-# UNPACK #-} !Size !Integer!Integer!Integer !(USet (Integer,Integer,Integer)) !(USet (Integer,Integer,Integer))\n    view IntegerIntegerIntegerTip = Tip\n    view (IntegerIntegerIntegerBin s a b c l r) = Bin s (a,b,c) l r\n    tip = IntegerIntegerIntegerTip\n    bin s (a,b,c) = IntegerIntegerIntegerBin s a b c\n\ninstance US (Integer,Integer,Integer,Integer) where\n    data USet (Integer,Integer,Integer,Integer) = IntegerIntegerIntegerIntegerTip | IntegerIntegerIntegerIntegerBin {-# UNPACK #-} !Size !Integer!Integer!Integer!Integer !(USet (Integer,Integer,Integer,Integer)) !(USet (Integer,Integer,Integer,Integer))\n    view IntegerIntegerIntegerIntegerTip = Tip\n    view (IntegerIntegerIntegerIntegerBin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = IntegerIntegerIntegerIntegerTip\n    bin s (a,b,c,d) = IntegerIntegerIntegerIntegerBin s a b c d\n\ninstance US (Integer,Integer,Integer,Integer,Integer) where\n    data USet (Integer,Integer,Integer,Integer,Integer) = IntegerIntegerIntegerIntegerIntegerTip | IntegerIntegerIntegerIntegerIntegerBin {-# UNPACK #-} !Size !Integer!Integer!Integer!Integer!Integer !(USet (Integer,Integer,Integer,Integer,Integer)) !(USet (Integer,Integer,Integer,Integer,Integer))\n    view IntegerIntegerIntegerIntegerIntegerTip = Tip\n    view (IntegerIntegerIntegerIntegerIntegerBin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = IntegerIntegerIntegerIntegerIntegerTip\n    bin s (a,b,c,d,e) = IntegerIntegerIntegerIntegerIntegerBin s a b c d e\n\ninstance US (Integer,Integer,Integer,Integer,Integer,Integer) where\n    data USet (Integer,Integer,Integer,Integer,Integer,Integer) = IntegerIntegerIntegerIntegerIntegerIntegerTip | IntegerIntegerIntegerIntegerIntegerIntegerBin {-# UNPACK #-} !Size !Integer!Integer!Integer!Integer!Integer!Integer !(USet (Integer,Integer,Integer,Integer,Integer,Integer)) !(USet (Integer,Integer,Integer,Integer,Integer,Integer))\n    view IntegerIntegerIntegerIntegerIntegerIntegerTip = Tip\n    view (IntegerIntegerIntegerIntegerIntegerIntegerBin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = IntegerIntegerIntegerIntegerIntegerIntegerTip\n    bin s (a,b,c,d,e,f) = IntegerIntegerIntegerIntegerIntegerIntegerBin s a b c d e f\n\ninstance US (Integer,Integer,Integer,Integer,Integer,Integer,Integer) where\n    data USet (Integer,Integer,Integer,Integer,Integer,Integer,Integer) = IntegerIntegerIntegerIntegerIntegerIntegerIntegerTip | IntegerIntegerIntegerIntegerIntegerIntegerIntegerBin {-# UNPACK #-} !Size !Integer!Integer!Integer!Integer!Integer!Integer!Integer !(USet (Integer,Integer,Integer,Integer,Integer,Integer,Integer)) !(USet (Integer,Integer,Integer,Integer,Integer,Integer,Integer))\n    view IntegerIntegerIntegerIntegerIntegerIntegerIntegerTip = Tip\n    view (IntegerIntegerIntegerIntegerIntegerIntegerIntegerBin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = IntegerIntegerIntegerIntegerIntegerIntegerIntegerTip\n    bin s (a,b,c,d,e,f,g) = IntegerIntegerIntegerIntegerIntegerIntegerIntegerBin s a b c d e f g\n\ninstance US (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer) where\n    data USet (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer) = IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerTip | IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerBin {-# UNPACK #-} !Size !Integer!Integer!Integer!Integer!Integer!Integer!Integer!Integer !(USet (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer)) !(USet (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer))\n    view IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerTip = Tip\n    view (IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerBin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerTip\n    bin s (a,b,c,d,e,f,g,h) = IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerBin s a b c d e f g h\n\ninstance US (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer) where\n    data USet (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer) = IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerTip | IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerBin {-# UNPACK #-} !Size !Integer!Integer!Integer!Integer!Integer!Integer!Integer!Integer!Integer !(USet (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer)) !(USet (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer))\n    view IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerTip = Tip\n    view (IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerBin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerTip\n    bin s (a,b,c,d,e,f,g,h,i) = IntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerIntegerBin s a b c d e f g h i\n\ninstance US (Boxed a,Boxed b) where\n    data USet (Boxed a,Boxed b) = BoxedBoxedTip | BoxedBoxedBin {-# UNPACK #-} !Size (Boxed a)(Boxed b) !(USet (Boxed a,Boxed b)) !(USet (Boxed a,Boxed b))\n    view BoxedBoxedTip = Tip\n    view (BoxedBoxedBin s a b l r) = Bin s (a,b) l r\n    tip = BoxedBoxedTip\n    bin s (a,b) = BoxedBoxedBin s a b\n\ninstance US (Boxed a,Boxed b,Boxed c) where\n    data USet (Boxed a,Boxed b,Boxed c) = BoxedBoxedBoxedTip | BoxedBoxedBoxedBin {-# UNPACK #-} !Size (Boxed a)(Boxed b)(Boxed c) !(USet (Boxed a,Boxed b,Boxed c)) !(USet (Boxed a,Boxed b,Boxed c))\n    view BoxedBoxedBoxedTip = Tip\n    view (BoxedBoxedBoxedBin s a b c l r) = Bin s (a,b,c) l r\n    tip = BoxedBoxedBoxedTip\n    bin s (a,b,c) = BoxedBoxedBoxedBin s a b c\n\ninstance US (Boxed a,Boxed b,Boxed c,Boxed d) where\n    data USet (Boxed a,Boxed b,Boxed c,Boxed d) = BoxedBoxedBoxedBoxedTip | BoxedBoxedBoxedBoxedBin {-# UNPACK #-} !Size (Boxed a)(Boxed b)(Boxed c)(Boxed d) !(USet (Boxed a,Boxed b,Boxed c,Boxed d)) !(USet (Boxed a,Boxed b,Boxed c,Boxed d))\n    view BoxedBoxedBoxedBoxedTip = Tip\n    view (BoxedBoxedBoxedBoxedBin s a b c d l r) = Bin s (a,b,c,d) l r\n    tip = BoxedBoxedBoxedBoxedTip\n    bin s (a,b,c,d) = BoxedBoxedBoxedBoxedBin s a b c d\n\ninstance US (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e) where\n    data USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e) = BoxedBoxedBoxedBoxedBoxedTip | BoxedBoxedBoxedBoxedBoxedBin {-# UNPACK #-} !Size (Boxed a)(Boxed b)(Boxed c)(Boxed d)(Boxed e) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e)) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e))\n    view BoxedBoxedBoxedBoxedBoxedTip = Tip\n    view (BoxedBoxedBoxedBoxedBoxedBin s a b c d e l r) = Bin s (a,b,c,d,e) l r\n    tip = BoxedBoxedBoxedBoxedBoxedTip\n    bin s (a,b,c,d,e) = BoxedBoxedBoxedBoxedBoxedBin s a b c d e\n\ninstance US (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f) where\n    data USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f) = BoxedBoxedBoxedBoxedBoxedBoxedTip | BoxedBoxedBoxedBoxedBoxedBoxedBin {-# UNPACK #-} !Size (Boxed a)(Boxed b)(Boxed c)(Boxed d)(Boxed e)(Boxed f) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f)) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f))\n    view BoxedBoxedBoxedBoxedBoxedBoxedTip = Tip\n    view (BoxedBoxedBoxedBoxedBoxedBoxedBin s a b c d e f l r) = Bin s (a,b,c,d,e,f) l r\n    tip = BoxedBoxedBoxedBoxedBoxedBoxedTip\n    bin s (a,b,c,d,e,f) = BoxedBoxedBoxedBoxedBoxedBoxedBin s a b c d e f\n\ninstance US (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g) where\n    data USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g) = BoxedBoxedBoxedBoxedBoxedBoxedBoxedTip | BoxedBoxedBoxedBoxedBoxedBoxedBoxedBin {-# UNPACK #-} !Size (Boxed a)(Boxed b)(Boxed c)(Boxed d)(Boxed e)(Boxed f)(Boxed g) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g)) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g))\n    view BoxedBoxedBoxedBoxedBoxedBoxedBoxedTip = Tip\n    view (BoxedBoxedBoxedBoxedBoxedBoxedBoxedBin s a b c d e f g l r) = Bin s (a,b,c,d,e,f,g) l r\n    tip = BoxedBoxedBoxedBoxedBoxedBoxedBoxedTip\n    bin s (a,b,c,d,e,f,g) = BoxedBoxedBoxedBoxedBoxedBoxedBoxedBin s a b c d e f g\n\ninstance US (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g,Boxed h) where\n    data USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g,Boxed h) = BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedTip | BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBin {-# UNPACK #-} !Size (Boxed a)(Boxed b)(Boxed c)(Boxed d)(Boxed e)(Boxed f)(Boxed g)(Boxed h) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g,Boxed h)) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g,Boxed h))\n    view BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedTip = Tip\n    view (BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBin s a b c d e f g h l r) = Bin s (a,b,c,d,e,f,g,h) l r\n    tip = BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedTip\n    bin s (a,b,c,d,e,f,g,h) = BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBin s a b c d e f g h\n\ninstance US (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g,Boxed h,Boxed i) where\n    data USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g,Boxed h,Boxed i) = BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedTip | BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBin {-# UNPACK #-} !Size (Boxed a)(Boxed b)(Boxed c)(Boxed d)(Boxed e)(Boxed f)(Boxed g)(Boxed h)(Boxed i) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g,Boxed h,Boxed i)) !(USet (Boxed a,Boxed b,Boxed c,Boxed d,Boxed e,Boxed f,Boxed g,Boxed h,Boxed i))\n    view BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedTip = Tip\n    view (BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBin s a b c d e f g h i l r) = Bin s (a,b,c,d,e,f,g,h,i) l r\n    tip = BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedTip\n    bin s (a,b,c,d,e,f,g,h,i) = BoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBoxedBin s a b c d e f g h i\n\n", "meta": {"hexsha": "765f047120931bbdc30c8614c8272a3a13119b6d", "size": 114495, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Set/Unboxed.hs", "max_stars_repo_name": "ekmett/unboxed-containers", "max_stars_repo_head_hexsha": "174323709e251c7db8232fd20419af43637a63ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-11-08T11:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T03:10:39.000Z", "max_issues_repo_path": "Data/Set/Unboxed.hs", "max_issues_repo_name": "ekmett/unboxed-containers", "max_issues_repo_head_hexsha": "174323709e251c7db8232fd20419af43637a63ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-15T23:42:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T23:42:31.000Z", "max_forks_repo_path": "Data/Set/Unboxed.hs", "max_forks_repo_name": "ekmett/unboxed-containers", "max_forks_repo_head_hexsha": "174323709e251c7db8232fd20419af43637a63ff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-04-06T08:26:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T03:10:39.000Z", "avg_line_length": 57.1903096903, "max_line_length": 564, "alphanum_fraction": 0.6305428185, "num_tokens": 38929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.21703145130556092}}
{"text": "{-# OPTIONS_GHC  -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}\n{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}\n\n\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n-- | \n-- | Module : Test approx median\n-- | Creator: Xiao Ling\n-- | Created: 12/14/2015\n-- | see    : http://www.serpentine.com/criterion/tutorial.html\n-- |\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n\n\nmodule TapproxMedian where \n\n\nimport Control.Monad.Random.Class\nimport Control.Monad.Random\nimport Control.Monad.State\nimport Control.Monad.Reader\n\nimport Data.Conduit\nimport qualified Data.Conduit.List as Cl\n\n\n\nimport Core\nimport Statistics\nimport ApproxMedian\n\n\n{-----------------------------------------------------------------------------\n  Benchmark  counter vs counter'\n------------------------------------------------------------------------------}\n\nmain :: IO ()\nmain = return ()\n\n\n\n", "meta": {"hexsha": "0260182dd3559a8831c5e6396ae03f8e9d14bc79", "size": 1295, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/TapproxMedian.hs", "max_stars_repo_name": "lingxiao/CIS700", "max_stars_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "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": "test/TapproxMedian.hs", "max_issues_repo_name": "lingxiao/CIS700", "max_issues_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "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": "test/TapproxMedian.hs", "max_forks_repo_name": "lingxiao/CIS700", "max_forks_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "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": 29.4318181818, "max_line_length": 122, "alphanum_fraction": 0.4254826255, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21678555428705867}}
{"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<m) then (n:(fromTo (n+1) m)) else (n:[])\n\nbigSum :: (Int -> ((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<m) then ((s 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<hi)\n\nrunP :: (a -> ((((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<m) then ((s n lastx)>>=(\\(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<ratio;\n (sigmaNext::Double) = if accept then (sigma*((min 1.400 (1+(5.000/i)))**3)) else (sigma*(max 0.714 (1-(5.000/i))));\n } in return (if accept then ((((xstar,((sigmaNext,(((i+1),(iaccept+1))))))),pstar)) else ((((xi,((sigmaNext,(((i+1),iaccept)))))),pi)))))\n\nrwmIni :: (a -> ((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<ratio;\n (sigmaNext::Double) = sigma;\n } in return (if accept then ((((xstar,sigmaNext)),((pstar,gradientStar)))) else ((((xi,sigmaNext)),((pi,gradienti)))))))\n\nmalaIni :: (BayNum b) => (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 ((x<hi)&&(x>lo)) 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<p))\n\nbernoulli01 :: (Double -> (Prob Int))\nbernoulli01 = \\((p::Double)) -> unit>>=(\\((u::Double)) -> if (u<p) then (return 1) else (return 0))\n\nbernoulliLogPdf :: (Double -> ((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<p))))>>=(\\((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<y) xs);\n } in (unround under)/(unround total)\n\ngammaLogPdf :: (Double -> ((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 DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\nmodule DFT.FFI where\n\nimport qualified Foreign.C.Types as C\nimport Foreign.C.String (CString)\nimport Foreign.Ptr (Ptr)\nimport Data.Complex (Complex)\n\n#include <fftw3.h>\n\n\ntype FFTWFlag = C.CUInt\n\n#{enum FFTWFlag,\n , c_measure         = FFTW_MEASURE\n , c_destroy_input   = FFTW_DESTROY_INPUT\n , c_unaligned       = FFTW_UNALIGNED\n , c_conserve_memory = FFTW_CONSERVE_MEMORY\n , c_exhaustive      = FFTW_EXHAUSTIVE\n , c_preserve_input  = FFTW_PRESERVE_INPUT\n , c_patient         = FFTW_PATIENT\n , c_estimate        = FFTW_ESTIMATE\n }\n\n\ntype FFTWSign = C.CInt\n\n#{enum FFTWSign,\n , c_forward = FFTW_FORWARD\n , c_backward = FFTW_BACKWARD\n }\n\n\ntype FFTWKind = C.CInt\n\n#{enum FFTWKind,\n , c_r2hc    = FFTW_R2HC\n , c_hc2r    = FFTW_HC2R\n , c_dht     = FFTW_DHT\n , c_redft00 = FFTW_REDFT00\n , c_redft10 = FFTW_REDFT10\n , c_redft01 = FFTW_REDFT01\n , c_redft11 = FFTW_REDFT11\n , c_rodft00 = FFTW_RODFT00\n , c_rodft10 = FFTW_RODFT10\n , c_rodft01 = FFTW_RODFT01\n , c_rodft11 = FFTW_RODFT11\n }\n\n\n-- | A plan is an opaque foreign object.\ntype Plan = Ptr FFTWPlan\n\ntype FFTWPlan = ()\n\n-- We use \"safe\" calls for anything which could take a while so that it won't block\n-- other Haskell threads.\n\n-- | Simple plan execution\nforeign import ccall safe \"fftw3.h fftw_execute\" c_execute\n    :: Plan -> IO ()\n    \n\n-- Execute a plan on different memory than the plan was created for.\n-- Alignment /must/ be the same.  If we parallelize a transform of\n-- multi-dimensional data by making separate calls within an un-transformed\n-- dimension, it is possible that the alignment constraint would not be\n-- fulfilled.  However, this only poses a problem for real transforms with odd\n-- transform dimension.\nforeign import ccall safe \"fftw3.h fftw_execute_dft\" c_execute_dft\n    :: Plan -> Ptr (Complex Double) -> Ptr (Complex Double) -> IO ()\nforeign import ccall safe \"fftw3.h fftw_execute_dft_r2c\" c_execute_dft_r2c\n    :: Plan -> Ptr Double -> Ptr (Complex Double) -> IO ()\nforeign import ccall safe \"fftw3.h fftw_execute_dft_c2r\" c_execute_dft_c2r\n    :: Plan -> Ptr (Complex Double) -> Ptr Double -> IO ()\nforeign import ccall safe \"fftw3.h fftw_execute_r2r\" c_execute_r2r\n    :: Plan -> Ptr Double -> Ptr Double -> IO ()\n\nforeign import ccall safe \"fftw3.h fftw_export_wisdom_to_string\"\n        c_export_wisdom_string :: IO CString\n        \nforeign import ccall safe \"fftw3.h fftw_export_wisdom_to_filename\"\n        c_export_wisdom_filename :: CString -> IO C.CInt\n\nforeign import ccall safe \"fftw3.h fftw_import_wisdom_from_string\"\n        c_import_wisdom_string :: CString -> IO C.CInt\n        \nforeign import ccall safe \"fftw3.h fftw_import_wisdom_from_filename\"\n        c_import_wisdom_filename :: CString -> IO C.CInt\n\nforeign import ccall safe \"fftw3.h fftw_import_system_wisdom\"\n        c_import_wisdom_system :: IO C.CInt\n\n-- | Frees memory allocated by 'fftw_malloc'.  Currently, we only need this to\n-- free the wisdom string.\nforeign import ccall safe \"fftw3.h fftw_free\" c_free :: Ptr a -> IO ()\n\n\nforeign import ccall safe \"fftw3.h fftw_destroy_plan\" c_destroy_plan ::  Plan -> IO ()\n\nforeign import ccall safe \"fftw3.h fftw_cleanup\" c_cleanup :: IO ()\n\nforeign import ccall safe \"fftw3.h fftw_plan_dft_2d\" c_plan_dft_2d :: C.CInt -> C.CInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> C.CInt -> FFTWFlag -> IO Plan\n\nforeign import ccall safe \"fftw3.h fftw_plan_dft_1d\" c_plan_dft_1d :: C.CInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> C.CInt -> FFTWFlag -> IO Plan\n\nforeign import ccall safe \"fftw3.h fftw_plan_dft_r2c_1d\" c_plan_dft_r2c_1d :: C.CInt -> Ptr C.CDouble -> Ptr (Complex Double) -> FFTWFlag -> IO Plan\n\nforeign import ccall safe \"fftw3.h fftw_plan_many_dft\" c_plan_many_dft :: C.CInt -> Ptr C.CInt -> C.CInt -> Ptr (Complex Double) -> Ptr C.CInt -> C.CInt -> C.CInt -> Ptr (Complex Double) -> Ptr C.CInt -> C.CInt -> C.CInt -> C.CInt -> FFTWFlag -> IO Plan\n\nforeign import ccall safe \"fftw3.h fftw_plan_dft_r2c_2d\" c_plan_dft_r2c_2d :: C.CInt -> C.CInt -> Ptr C.CDouble -> Ptr (Complex Double) -> FFTWFlag -> IO Plan\n", "meta": {"hexsha": "3098464c8404374e4e64bd4a0b0d0d5df82fbde6", "size": 4115, "ext": "hsc", "lang": "Haskell", "max_stars_repo_path": "src/DFT/FFI.hsc", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "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": "src/DFT/FFI.hsc", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/DFT/FFI.hsc", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 36.4159292035, "max_line_length": 253, "alphanum_fraction": 0.7190765492, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21649116269402044}}
{"text": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, MultiParamTypeClasses, FlexibleInstances #-}\n\n{-| Various utiliy signal processing functions -}\nmodule SDR.Util (\n    -- * Classes\n    Mult,\n    mult,\n\n    -- * Conversion to floating point for reception\n    -- ** RTLSDR\n    interleavedIQUnsigned256ToFloat,\n    interleavedIQUnsignedByteToFloat,\n    interleavedIQUnsignedByteToFloatSSE,\n    interleavedIQUnsignedByteToFloatAVX,\n    interleavedIQUnsignedByteToFloatFast,\n\n    -- ** BladeRF\n    interleavedIQSigned2048ToFloat,\n    interleavedIQSignedWordToFloat,\n    interleavedIQSignedWordToFloatSSE,\n    interleavedIQSignedWordToFloatAVX,\n    interleavedIQSignedWordToFloatFast,\n\n    -- * Conversion from floating point for transmission\n    -- ** BladeRF\n    complexFloatToInterleavedIQSigned2048,\n    complexFloatToInterleavedIQSignedWord,\n\n    -- * Scaling\n    scaleC,\n    scaleCSSE,\n    scaleCAVX,\n    scaleFast,\n\n    -- * Mapping over complex numbers\n    cplxMap,\n\n    -- * Frequency shifting\n    halfBandUp,\n    quarterBandUp,\n\n    -- * Data streams\n    streamString,\n    streamRandom,\n\n    -- * Automatic gain control\n    agc,\n    agcPipe,\n\n    -- * Squashing initialization into the Pipe\n    combineInit,\n    combineInitTrans\n    ) where\n\nimport           Foreign.C.Types\nimport           Data.Complex\nimport qualified Data.Vector.Generic          as VG   \nimport qualified Data.Vector.Generic.Mutable  as VGM\nimport qualified Data.Vector.Storable         as VS   \nimport qualified Data.Vector.Storable.Mutable as VSM  \nimport           Control.Monad.Primitive\nimport           Data.Coerce\nimport           Foreign.Ptr\nimport           System.IO.Unsafe\nimport           Foreign.Storable.Complex\nimport           Control.Monad\nimport qualified System.Random.MWC as R\nimport           Data.Bits\nimport           Pipes\nimport qualified Pipes.Prelude as P\nimport           Data.Word\nimport           Foreign.Storable\nimport           Control.Arrow as A\nimport           Data.Tuple\n\nimport           SDR.CPUID\nimport           SDR.VectorUtils\nimport           SDR.PipeUtils\n\n-- | A class for things that can be multiplied by a scalar.\nclass Mult a b where\n    mult :: a -> b -> a\n\ninstance (Num a) => Mult a a where\n    mult = (*)\n\ninstance (Num a) => Mult (Complex a) a where\n    mult (x :+ y) z = (x * z) :+ (y * z)\n\n-- | Create a vector of complex floating samples from a vector of interleaved I Q components. Each input element ranges from 0 to 255. This is the format that RTLSDR devices use.\n{-# INLINE interleavedIQUnsigned256ToFloat #-}\ninterleavedIQUnsigned256ToFloat :: (Num a, Integral a, Num b, Fractional b, VG.Vector v1 a, VG.Vector v2 (Complex b)) => v1 a -> v2 (Complex b)\ninterleavedIQUnsigned256ToFloat input = VG.generate (VG.length input `quot` 2) convert\n    where\n    {-# INLINE convert #-}\n    convert idx  = convert' (input `VG.unsafeIndex` (2 * idx)) :+ convert' (input `VG.unsafeIndex` (2 * idx + 1))\n    {-# INLINE convert' #-}\n    convert' val = (fromIntegral val - 128) / 128\n\nforeign import ccall unsafe \"convertC\"\n    convertC_c :: CInt -> Ptr CUChar -> Ptr CFloat -> IO ()\n\n-- | Same as `interleavedIQUnsigned256ToFloat` but written in C and specialized for unsigned byte inputs and Float outputs.\ninterleavedIQUnsignedByteToFloat :: VS.Vector CUChar -> VS.Vector (Complex Float)\ninterleavedIQUnsignedByteToFloat inBuf = unsafePerformIO $ do\n    outBuf <- VGM.new $ VG.length inBuf `quot` 2\n    VS.unsafeWith inBuf $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            convertC_c (fromIntegral $ VG.length inBuf) iPtr oPtr\n    VG.freeze outBuf\n\nforeign import ccall unsafe \"convertCSSE\"\n    convertCSSE_c :: CInt -> Ptr CUChar -> Ptr CFloat -> IO ()\n\n-- | Same as `interleavedIQUnsigned256ToFloat` but written in C using SSE intrinsics and specialized for unsigned byte inputs and Float outputs.\ninterleavedIQUnsignedByteToFloatSSE :: VS.Vector CUChar -> VS.Vector (Complex Float)\ninterleavedIQUnsignedByteToFloatSSE inBuf = unsafePerformIO $ do\n    outBuf <- VGM.new $ VG.length inBuf `quot` 2\n    VS.unsafeWith inBuf $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            convertCSSE_c (fromIntegral $ VG.length inBuf) iPtr oPtr\n    VG.freeze outBuf\n\nforeign import ccall unsafe \"convertCAVX\"\n    convertCAVX_c :: CInt -> Ptr CUChar -> Ptr CFloat -> IO ()\n\n-- | Same as `interleavedIQUnsigned256ToFloat` but written in C using AVX intrinsics and specialized for unsigned byte inputs and Float outputs.\ninterleavedIQUnsignedByteToFloatAVX :: VS.Vector CUChar -> VS.Vector (Complex Float)\ninterleavedIQUnsignedByteToFloatAVX inBuf = unsafePerformIO $ do\n    outBuf <- VGM.new $ VG.length inBuf `quot` 2\n    VS.unsafeWith inBuf $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            convertCAVX_c (fromIntegral $ VG.length inBuf) iPtr oPtr\n    VG.freeze outBuf\n\n-- | Same as `interleavedIQUnsigned256ToFloat` but uses the fastest SIMD instruction set your processor supports and specialized for unsigned byte inputs and Float outputs.\ninterleavedIQUnsignedByteToFloatFast :: CPUInfo -> VS.Vector CUChar -> VS.Vector (Complex Float)\ninterleavedIQUnsignedByteToFloatFast info = featureSelect info interleavedIQUnsignedByteToFloat [(hasAVX2, interleavedIQUnsignedByteToFloatAVX), (hasSSE42, interleavedIQUnsignedByteToFloatSSE)]\n\n-- | Create a vector of complex float samples from a vector of interleaved I Q components. Each input element ranges from -2048 to 2047. This is the format that the BladeRF uses.\n{-# INLINE interleavedIQSigned2048ToFloat #-}\ninterleavedIQSigned2048ToFloat :: (Num a, Integral a, Num b, Fractional b, VG.Vector v1 a, VG.Vector v2 (Complex b)) => v1 a -> v2 (Complex b)\ninterleavedIQSigned2048ToFloat input = VG.generate (VG.length input `quot` 2) convert\n    where\n    {-# INLINE convert #-}\n    convert idx  = convert' (input `VG.unsafeIndex` (2 * idx)) :+ convert' (input `VG.unsafeIndex` (2 * idx + 1))\n    {-# INLINE convert' #-}\n    convert' val = fromIntegral val / 2048\n\nforeign import ccall unsafe \"convertCBladeRF\"\n    convertCBladeRF_c :: CInt -> Ptr CShort -> Ptr CFloat -> IO ()\n\n-- | Same as `interleavedIQUnsigned256ToFloat` but written in C and specialized for signed short inputs and Float outputs.\ninterleavedIQSignedWordToFloat :: VS.Vector CShort -> VS.Vector (Complex Float)\ninterleavedIQSignedWordToFloat inBuf = unsafePerformIO $ do\n    outBuf <- VGM.new $ VG.length inBuf `quot` 2\n    VS.unsafeWith inBuf $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            convertCBladeRF_c (fromIntegral $ VG.length inBuf) iPtr oPtr\n    VG.freeze outBuf\n\nforeign import ccall unsafe \"convertCSSEBladeRF\"\n    convertCSSEBladeRF_c :: CInt -> Ptr CShort -> Ptr CFloat -> IO ()\n\n-- | Same as `interleavedIQUnsigned256ToFloat` but written in C using SSE intrinsics and specialized for signed short inputs and Float outputs.\ninterleavedIQSignedWordToFloatSSE :: VS.Vector CShort -> VS.Vector (Complex Float)\ninterleavedIQSignedWordToFloatSSE inBuf = unsafePerformIO $ do\n    outBuf <- VGM.new $ VG.length inBuf `quot` 2\n    VS.unsafeWith inBuf $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            convertCSSEBladeRF_c (fromIntegral $ VG.length inBuf) iPtr oPtr\n    VG.freeze outBuf\n\nforeign import ccall unsafe \"convertCAVXBladeRF\"\n    convertCAVXBladeRF_c :: CInt -> Ptr CShort -> Ptr CFloat -> IO ()\n\n-- | Same as `interleavedIQUnsigned256ToFloat` but written in C using AVX intrinsics and specialized for signed short inputs and Float outputs.\ninterleavedIQSignedWordToFloatAVX :: VS.Vector CShort -> VS.Vector (Complex Float)\ninterleavedIQSignedWordToFloatAVX inBuf = unsafePerformIO $ do\n    outBuf <- VGM.new $ VG.length inBuf `quot` 2\n    VS.unsafeWith inBuf $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            convertCAVXBladeRF_c (fromIntegral $ VG.length inBuf) iPtr oPtr\n    VG.freeze outBuf\n\n-- | Same as `interleavedIQSigned2048ToFloat` but uses the fastest SIMD instruction set your processor supports and specialized for signed short inputs and Float outputs.\ninterleavedIQSignedWordToFloatFast :: CPUInfo -> VS.Vector CShort -> VS.Vector (Complex Float)\ninterleavedIQSignedWordToFloatFast info = featureSelect info interleavedIQSignedWordToFloat [(hasAVX2, interleavedIQSignedWordToFloatAVX), (hasSSE42, interleavedIQSignedWordToFloatSSE)]\n\n-- | Create a vector of interleaved I Q component integral samples from a vector of complex Floats. Each input ranges from -2048 to 2047. This is the format the BladeRF uses.\ncomplexFloatToInterleavedIQSigned2048 :: (Integral b, RealFrac a, VG.Vector v1 (Complex a), VG.Vector v2 b) => v1 (Complex a) -> v2 b\ncomplexFloatToInterleavedIQSigned2048 input = VG.generate (VG.length input * 2) convert\n    where\n    {-# INLINE convert #-}\n    convert idx  \n        | even idx = convert' $ realPart (input `VG.unsafeIndex` (idx `quot` 2))\n        | odd  idx = convert' $ imagPart (input `VG.unsafeIndex` (idx `quot` 2))\n    {-# INLINE convert' #-}\n    convert' val = round $ val * 2048\n\nforeign import ccall unsafe \"convertBladeRFTransmit\"\n    convertBladeRFTransmit_c :: CInt -> Ptr CFloat -> Ptr CShort -> IO ()\n\n-- | Same as `complexFloatToInterleavedIQSigned2048` but written in C and specialized for Float inputs and signed short outputs.\ncomplexFloatToInterleavedIQSignedWord :: VS.Vector (Complex Float) -> VS.Vector CShort\ncomplexFloatToInterleavedIQSignedWord inBuf = unsafePerformIO $ do\n    outBuf <- VGM.new $ VG.length inBuf * 2\n    VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n        VSM.unsafeWith outBuf $ \\oPtr -> \n            convertBladeRFTransmit_c (fromIntegral $ VG.length inBuf * 2) iPtr oPtr\n    VG.freeze outBuf\n    \n-- | Scaling\nforeign import ccall unsafe \"scale\"\n    scale_c :: CInt -> CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\n-- | Scale a vector, written in C\nscaleC :: Float                      -- ^ Scale factor\n       -> VS.Vector Float            -- ^ Input vector\n       -> VS.MVector RealWorld Float -- ^ Output vector\n       -> IO ()\nscaleC factor inBuf outBuf = \n    VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            scale_c (fromIntegral (VG.length inBuf)) (coerce factor) iPtr oPtr\n\nforeign import ccall unsafe \"scaleSSE\"\n    scaleSSE_c :: CInt -> CFloat -> Ptr CFloat -> Ptr CFloat-> IO ()\n\n-- | Scale a vector, written in C using SSE intrinsics\nscaleCSSE :: Float                      -- ^ Scale factor\n          -> VS.Vector Float            -- ^ Input vector\n          -> VS.MVector RealWorld Float -- ^ Output vector\n          -> IO ()\nscaleCSSE factor inBuf outBuf = \n    VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            scaleSSE_c (fromIntegral (VG.length inBuf)) (coerce factor) iPtr oPtr\n\nforeign import ccall unsafe \"scaleAVX\"\n    scaleAVX_c :: CInt -> CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\n-- | Scale a vector, written in C using AVX intrinsics\nscaleCAVX :: Float                      -- ^ Scale factor\n          -> VS.Vector Float            -- ^ Input vector\n          -> VS.MVector RealWorld Float -- ^ Output vector\n          -> IO ()\nscaleCAVX factor inBuf outBuf = \n    VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            scaleAVX_c (fromIntegral (VG.length inBuf)) (coerce factor) iPtr oPtr\n\n-- | Scale a vector. Uses the fastest SIMD instruction set your processor supports.\nscaleFast :: CPUInfo -> Float -> VS.Vector Float -> VS.MVector RealWorld Float -> IO ()\nscaleFast info = featureSelect info scaleC [(hasAVX, scaleCAVX), (hasSSE42, scaleCSSE)]\n\n-- | Apply a function to both parts of a complex number\ncplxMap :: (a -> b)  -- ^ The function\n        -> Complex a -- ^ Input complex number\n        -> Complex b -- ^ Output complex number\ncplxMap f (x :+ y) = f x :+ f y\n\n-- | Multiplication by this vector shifts all frequencies up by 1/2 of the sampling frequency\nhalfBandUp :: (VG.Vector v n, Num n) \n           => Int -- ^ The length of the Vector\n           -> v n \nhalfBandUp size = VG.generate size func\n    where\n    func idx \n        | even idx  = 1\n        | otherwise = -1\n\n-- | Multiplication by this vector shifts all frequencies up by 1/4 of the sampling frequency\nquarterBandUp :: (VG.Vector v (Complex n), Num n) \n              => Int -- ^ The length of the Vector\n              -> v (Complex n)\nquarterBandUp size = VG.generate size func\n    where\n    func idx \n        | m == 0 = 1    :+ 0\n        | m == 1 = 0    :+ 1\n        | m == 2 = (-1) :+ 0\n        | m == 3 = 0    :+ (-1)\n        where\n        m = idx `mod` 4\n\n-- | A Producer that streams vectors of the bits that make up the string argument concatenated repeatedly. Each bit is encoded as a float with value (+1) for 1 and (-1) for 0.\nstreamString :: forall m b. (FiniteBits b, Monad m) \n             => [b] -- ^ The string whose bits are to be streamed\n             -> Int -- ^ The size of each streamed vector\n             -> Producer (VS.Vector Float) m ()\nstreamString str size = P.unfoldr (return . Right . func) (str, 0)\n    where\n    bitsPerChar = finiteBitSize (undefined :: b)\n    toFloat :: Bool -> Float\n    toFloat x   = if x then 1 else (-1)\n    func = vUnfoldr size funcy \n        where\n        funcy ([], offsetChar) = funcy (str, 0)\n        funcy (rem@(x:xs), offsetChar)\n            | offsetChar == bitsPerChar = funcy (xs, 0)\n            | otherwise                 = (toFloat $ testBit x offsetChar, (rem, offsetChar + 1))\n\n-- | A Producer that streams vectors of random bits. Each bit is encoded as a float with value (+1) for 1 and (-1) for 0.\nstreamRandom :: forall m. PrimMonad m \n             => Int -- ^ The size of each streamed vector\n             -> Producer (VS.Vector Float) m ()\nstreamRandom size = do\n    gen   <- lift R.create \n    start <- lift $ R.uniform gen\n    P.unfoldr (liftM Right . func gen) (start, 0)\n    where\n    toFloat :: Bool -> Float\n    toFloat x   = if x then 1 else (-1)\n    func :: R.Gen (PrimState m) -> (Word64, Int) -> m (VS.Vector Float, (Word64, Int))\n    func gen = vUnfoldrM size funcy \n        where\n        funcy (current, offset) = do\n            let res =  toFloat $ testBit current offset\n            if offset == 63 then do\n                current' <- R.uniform gen\n                return (res, (current', 0))\n            else return (res, (current, offset+1))\n\n(a :+ b) `cdiv` y = (a/y) :+ (b/y)\n(a :+ b) `cmul` y = (a*y) :+ (b*y)\n\n-- | Simple automatic gain control \nagc :: (Num a, Storable a, RealFloat a) \n    => a                          -- ^ a\n    -> a                          -- ^ reference\n    -> a                          -- ^ initial state\n    -> VS.Vector (Complex a)      -- ^ input vector\n    -> (a, VS.Vector (Complex a)) -- ^ (final state, output vector)\nagc mu reference state input = A.first snd $ swap $ vUnfoldr (VS.length input) go (0, state)\n    where\n    go (offset, state) = \n        let\n            corrected = (input VS.! offset) `cmul` state\n            state'    = state + mu * (reference - magnitude corrected)\n        in  (corrected, (offset + 1, state'))\n\n-- | Simple automatic gain control pipe\nagcPipe :: (Num a, Storable a, RealFloat a, Monad m)\n        => a -- ^ a\n        -> a -- ^ reference\n        -> Pipe (VS.Vector (Complex a)) (VS.Vector (Complex a)) m ()\nagcPipe mu reference = pMapAccum (agc mu reference) 1\n\n-- | Specializes to combineInit :: IO (Pipe a b IO ()) -> Pipe a b IO ()\ncombineInit :: (Monad m, MonadTrans t, Monad (t m)) => m (t m a) -> t m a\ncombineInit = join . lift\n\n-- | Specializes to combineInitTrans :: EitherT String IO (Pipe a b IO ()) -> Pipe a b (EitherT String IO) ()\ncombineInitTrans :: (Monad (t1 m), Monad (t (t1 m)), MonadTrans t, Monad m, MFunctor t, MonadTrans t1) => (t1 m) ((t m) a) -> t (t1 m) a\ncombineInitTrans = combineInit . fmap (hoist lift)\n\n", "meta": {"hexsha": "1a4e6606644d438cda67e562b546e70e0e178d4a", "size": 15846, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "hs_sources/SDR/Util.hs", "max_stars_repo_name": "adamwalker/sdr", "max_stars_repo_head_hexsha": "c7d4d7dacb41039976e11df93adb10d3570cb8ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 94, "max_stars_repo_stars_event_min_datetime": "2015-05-10T02:13:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T16:32:22.000Z", "max_issues_repo_path": "hs_sources/SDR/Util.hs", "max_issues_repo_name": "peixian/sdr", "max_issues_repo_head_hexsha": "55bc865ea6c6df2d7e6e9fe6c4c3d02f76a5b2ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-05-05T19:20:46.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-02T04:19:15.000Z", "max_forks_repo_path": "hs_sources/SDR/Util.hs", "max_forks_repo_name": "adamwalker/sdr", "max_forks_repo_head_hexsha": "c7d4d7dacb41039976e11df93adb10d3570cb8ce", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-07-12T11:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T07:41:21.000Z", "avg_line_length": 44.2625698324, "max_line_length": 193, "alphanum_fraction": 0.6610501073, "num_tokens": 4376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.3242354120407358, "lm_q1q2_score": 0.21461883639041168}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n-- | The \"pair of vectors\" implementation of vectors of dual numbers.\n-- This is much faster than \"vector of pairs\" implementation, but terribly\n-- hard to use in case of scalar dual numbers, in particular to efficiently\n-- construct in @ST@ such pairs of vectors from monadic operations that create\n-- vector elements (a bit easier in @IO@, but so far we managed to avoid @IO@).\n-- For this reason, this representation is currently used only to represent\n-- the inputs of functions, that is, dual numbers with initial values\n-- of parameters and, in case of dual components that are delta-expressions,\n-- with @Delta@ variables assigned to each.\nmodule HordeAd.Core.PairOfVectors\n  ( DualNumberVariables\n  , makeDualNumberVariables, var0, vars, var1, var2, varX, varS\n  , ifoldMDual', foldMDual', ifoldlDual', foldlDual'\n  ) where\n\nimport Prelude\n\nimport qualified Data.Array.DynamicS as OT\nimport qualified Data.Array.ShapedS as OS\nimport qualified Data.Strict.Vector as Data.Vector\nimport qualified Data.Vector.Generic as V\nimport           GHC.Exts (inline)\nimport           Numeric.LinearAlgebra (Matrix, Vector)\n\nimport HordeAd.Core.DualClass (Dual)\nimport HordeAd.Core.DualNumber\n\n-- These are optimized as \"pair of vectors\" representing vectors of @DualNumber@\n-- in an efficient way (especially, or only, with gradient descent,\n-- where the vectors are reused in some ways).\n\ntype DualNumberVariables d r =\n  ( Domain0 r\n  , Data.Vector.Vector (Dual d r)\n  , Domain1 r\n  , Data.Vector.Vector (Dual d (Vector r))\n  , Domain2 r\n  , Data.Vector.Vector (Dual d (Matrix r))\n  , DomainX r\n  , Data.Vector.Vector (Dual d (OT.Array r))\n  )\n\nmakeDualNumberVariables\n  :: Domains r\n  -> ( Data.Vector.Vector (Dual d r)\n     , Data.Vector.Vector (Dual d (Vector r))\n     , Data.Vector.Vector (Dual d (Matrix r))\n     , Data.Vector.Vector (Dual d (OT.Array r)) )\n  -> DualNumberVariables d r\n{-# INLINE makeDualNumberVariables #-}\nmakeDualNumberVariables (params0, params1, params2, paramsX)\n                        (vs0, vs1, vs2, vsX)\n  = (params0, vs0, params1, vs1, params2, vs2, paramsX, vsX)\n\nvar0 :: IsScalar d r => DualNumberVariables d r -> Int -> DualNumber d r\nvar0 (vValue, vVar, _, _, _, _, _, _) i = D (vValue V.! i) (vVar V.! i)\n\n-- Unsafe, but handy for toy examples.\nvars :: IsScalar d r => DualNumberVariables d r -> [DualNumber d r]\nvars vec = map ( var0 vec) [0 ..]\n\nvar1 :: DualNumberVariables d r -> Int -> DualNumber d (Vector r)\nvar1 (_, _, vValue, vVar, _, _, _, _) i = D (vValue V.! i) (vVar V.! i)\n\nvar2 :: DualNumberVariables d r -> Int -> DualNumber d (Matrix r)\nvar2 (_, _, _, _, vValue, vVar, _, _) i = D (vValue V.! i) (vVar V.! i)\n\nvarX :: DualNumberVariables d r -> Int -> DualNumber d (OT.Array r)\nvarX (_, _, _, _, _, _, vValue, vVar) i = D (vValue V.! i) (vVar V.! i)\n\nvarS :: (IsScalar d r, OS.Shape sh)\n     => DualNumberVariables d r -> Int -> DualNumber d (OS.Array sh r)\nvarS (_, _, _, _, _, _, vValue, vVar) i =\n  inline fromXS $ D (vValue V.! i) (vVar V.! i)\n\nifoldMDual' :: forall a d r m. (Monad m, IsScalar d r)\n             => (a -> Int -> DualNumber d r -> m a)\n             -> a\n             -> DualNumberVariables d r\n             -> m a\n{-# INLINE ifoldMDual' #-}\nifoldMDual' f a (vecR, vecD, _, _, _, _, _, _) = do\n  let g :: a -> Int -> r -> m a\n      g !acc i valX = do\n        let !b = D valX (vecD V.! i)\n        f acc i b\n  V.ifoldM' g a vecR\n\nfoldMDual' :: forall a d r m. (Monad m, IsScalar d r)\n            => (a -> DualNumber d r -> m a)\n            -> a\n            -> DualNumberVariables d r\n            -> m a\n{-# INLINE foldMDual' #-}\nfoldMDual' f a (vecR, vecD, _, _, _, _, _, _) = do\n  let g :: a -> Int -> r -> m a\n      g !acc i valX = do\n        let !b = D valX (vecD V.! i)\n        f acc b\n  V.ifoldM' g a vecR\n\nifoldlDual' :: forall a d r. IsScalar d r\n             => (a -> Int -> DualNumber d r -> a)\n             -> a\n             -> DualNumberVariables d r\n             -> a\n{-# INLINE ifoldlDual' #-}\nifoldlDual' f a (vecR, vecD, _, _, _, _, _, _) = do\n  let g :: a -> Int -> r -> a\n      g !acc i valX =\n        let !b = D valX (vecD V.! i)\n        in f acc i b\n  V.ifoldl' g a vecR\n\nfoldlDual' :: forall a d r. IsScalar d r\n            => (a -> DualNumber d r -> a)\n            -> a\n            -> DualNumberVariables d r\n            -> a\n{-# INLINE foldlDual' #-}\nfoldlDual' f a (vecR, vecD, _, _, _, _, _, _) = do\n  let g :: a -> Int -> r -> a\n      g !acc i valX =\n        let !b = D valX (vecD V.! i)\n        in f acc b\n  V.ifoldl' g a vecR\n", "meta": {"hexsha": "30701bc9e5d2c12a5de4d41c0e3463487e9fb860", "size": 4552, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Core/PairOfVectors.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/PairOfVectors.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/PairOfVectors.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.5625, "max_line_length": 80, "alphanum_fraction": 0.6041300527, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.21237370108975762}}
{"text": "{- |\n   Description :  Parse arguments needed for the bmm simulator\n   Copyright   :  (c) Dominik Schrempf 2017\n   License     :  GPLv3\n\n   Maintainer  :  dominik.schrempf@gmail.com\n   Stability   :  unstable\n   Portability :  non-portable (not tested)\n\nProvides a data type with all options and a parser.\n\n* Changelog\n\n-}\n\nmodule ArgParse\n  ( BMMArgs(..)\n  , parseBMMArgs\n  ) where\n\nimport qualified Data.Attoparsec.Text         as A\nimport           Data.Semigroup               ((<>))\nimport           Data.Text                    (pack, unpack)\nimport qualified Defaults                     as Def\nimport           DNAModel                     (DNAModelSpec(..))\nimport           RateMatrix                   (StationaryDist)\nimport           Numeric.LinearAlgebra        (norm_1, size, vector)\nimport           Options.Applicative\nimport qualified Text.PrettyPrint.ANSI.Leijen as Doc\nimport           Tools                        (nearlyEq)\n\n-- Convenience function to read in more complicated command line options with\n-- attoparsec and optparse\n-- (https://github.com/pcapriotti/optparse-applicative#option-readers).\nattoReadM :: A.Parser a -> ReadM a\nattoReadM p = eitherReader (A.parseOnly p . pack)\n\n-- | Combined option and argument data structure.\ndata BMMArgs = BMMArgs\n  { -- | Name of output counts file.\n    outFileName    :: String\n    -- | Mutation model specification.\n  , dnaModelSpec   :: DNAModelSpec\n    -- | Shape parameter of gamma rate heterogeneity.\n  , gammaShape     :: Maybe Double\n    -- | Number of gamma rate heterogeneity categories.\n  , gammaNCat      :: Maybe Int\n    -- | Virtual population size of boundary mutation model.\n  , popSize        :: Int\n    -- | Heterozygosity value (2Nu).\n  , heterozygosity :: Double\n    -- | Tree height in boundary mutation model units.\n  , treeHeight     :: Double\n    -- | Tree type or scenario (ILS, Yule).\n  , treeType       :: String\n    -- | Yule speciation rate.\n  , treeYuleRate   :: Maybe Double\n    -- | Number of sites to simulate.\n  , nSites         :: Int\n    -- | Seed of the random number generator.\n  , seed           :: String }\n\n-- Composition of all options.\nbmSimOptions :: Parser BMMArgs\nbmSimOptions = BMMArgs\n  <$> outFileNameOpt\n  <*> dnaModelOpt\n  <*> gammaShapeOpt\n  <*> gammaNCatOpt\n  <*> popSizeOpt\n  <*> heterozygosityOpt\n  <*> treeHeightOpt\n  <*> treeTypeOpt\n  <*> treeYuleRateOpt\n  <*> nSitesOpt\n  <*> seedOpt\n\n-- | The impure IO action that reads the arguments and prints out help if\n-- needed. Maybe put this into Main.hs?\nparseBMMArgs :: IO BMMArgs\nparseBMMArgs = execParser $\n  info (helper <*> bmSimOptions)\n  (fullDesc\n    <> progDesc \"Simulate count files using the boundary mutation model.\"\n    <> header \"Boundary mutation model simulator\"\n    <> footerDoc models )\n  where\n    models = Just $ foldl1 (Doc.<$>) (map Doc.text strs)\n    strs   = [ \"Available mutation models:\"\n\n             , \"  - HKY model with transition to transversion ratio kappa and a state frequency vector.\"\n             , \"    Specified with \\\"-m HKY[DOUBLE][DOUBLE,DOUBLE,DOUBLE,DOUBLE]\\\".\"\n             , \"  - GTR model with five rate parameters and state frequency vector.\"\n             , \"    Specified with \\\"-m HKY[DOUBLE,DOUBLE,DOUBLE,DOUBLE,DOUBLE][DOUBLE,DOUBLE,DOUBLE,DOUBLE]\\\".\"\n             , \"\"\n             , \"Note: The state frequency vector has to sum up to 1.0 and only has three free parameters.\" ]\n\n-- General things and options.\noutFileNameOpt :: Parser String\noutFileNameOpt = strOption\n  ( long \"output\"\n    <> short 'o'\n    <> metavar \"NAME\"\n    <> value Def.outFileName\n    <> showDefault\n    <> help \"Write output files to NAME.[cf.gz|log|tree]\" )\n\n-- Read a stationary frequency of the form `pi_A,pi_C,pi_G,...`.\nparseStateFreq :: A.Parser StationaryDist\nparseStateFreq = do\n  _ <- A.char '['\n  f <- vector <$> A.sepBy A.double (A.char ',')\n  _ <- A.char ']'\n  if size f /= nAlleles\n    then error \"Length of stationary frequency vector is faulty, only DNA models are supported.\"\n  else if nearlyEq 1e-6 (norm_1 f) 1.0 then return f\n    else error $ \"Stationary frequencies sum to \" ++ show (norm_1 f) ++ \" but should sum to 1.0.\"\n    -- Nucleotide count hard coded. See `BndState.nAlleles`. However, I cannot\n    -- take different numbers depending on the mutation model because optparse has\n    -- an applicative interface and not a monadic one. Also, allowing vectors of\n    -- arbitrary size is undesirable because of meaningless error messages.\n    where nAlleles = 4\n\ndnaModelOpt :: Parser DNAModelSpec\ndnaModelOpt = option (attoReadM parseDNAModelSpec)\n  ( long \"mutation-model\"\n    <> short 'm'\n    <> metavar \"MODEL\"\n    <> value Def.dnaModelSpec\n    <> showDefault\n    <> help \"Set the mutation model; available models are shown below\" )\n\nparseParams :: A.Parser [Double]\nparseParams = do\n  _ <- A.char '['\n  params <- A.sepBy1 A.double (A.char ',')\n  _ <- A.char ']'\n  return params\n\nparseDNAModelSpec :: A.Parser DNAModelSpec\nparseDNAModelSpec = do\n  m  <- A.takeWhile (/= '[')\n  case unpack m of\n       \"JC\" -> return JC\n       \"HKY\" -> do\n         ps <- parseParams\n         f  <- parseStateFreq\n         if length ps /= 1\n           then error \"HKY model only has one parameter, kappa.\"\n           else return $ HKY (head ps) f\n       \"GTR\" -> do\n         ps <- parseParams\n         f  <- parseStateFreq\n         if length ps /= 5\n           then error \"GTR model has five parameters.\"\n           else return $ GTR (head ps) (ps !! 1) (ps !! 2) (ps !! 3) (ps !! 4) f\n       _ -> error \"Model string could not be parsed.\"\n\ngammaShapeOpt :: Parser (Maybe Double)\ngammaShapeOpt = optional $ option auto\n  ( long \"gamma-shape\"\n    <> metavar \"DOUBLE\"\n    <> help \"Activate gamma rate heterogeneity and set gamma shape parameter (default: off)\" )\n\ngammaNCatOpt :: Parser (Maybe Int)\ngammaNCatOpt = optional $ option auto\n  ( long \"gamma-ncat\"\n    <> metavar \"INT\"\n    <> help \"Set the number of gamma rate categories (no default value)\" )\n\npopSizeOpt :: Parser Int\npopSizeOpt = option auto\n  ( short 'N'\n    <> metavar \"DOUBLE\"\n    <> value Def.popSize\n    <> showDefault\n    <> help \"Set the virtual population size\" )\n\nheterozygosityOpt :: Parser Double\nheterozygosityOpt = option auto\n  ( long \"heterozygosity\"\n    <> short 't'\n    <> metavar \"DOUBLE\"\n    <> value Def.heterozygosity\n    <> showDefault\n    <> help \"Set heterozygosity\" )\n\ntreeHeightOpt :: Parser Double\ntreeHeightOpt = option auto\n  ( long \"tree-height\"\n    <> short 'H'\n    <> metavar \"DOUBLE\"\n    <> value Def.treeHeight\n    <> showDefault\n    <> help \"Set tree height [average number of substitutions]\" )\n\ntreeTypeOpt :: Parser String\ntreeTypeOpt = strOption\n  ( long \"tree-type\"\n    <> metavar \"TYPE\"\n    <> value Def.treeType\n    <> showDefault\n    <> help \"Set tree type; ILS or Yule\")\n\ntreeYuleRateOpt :: Parser (Maybe Double)\ntreeYuleRateOpt = optional $ option auto\n  ( long \"tree-yule-rate\"\n  <> metavar \"DOUBLE\"\n  <> help \"Set the speciation rate of Yule tree (no default value)\")\n\nnSitesOpt :: Parser Int\nnSitesOpt = option auto\n  ( long \"nsites\"\n    <> short 'n'\n    <> metavar \"INT\"\n    <> value Def.nSites\n    <> showDefault\n    <> help \"Set number of sites to simulate\" )\n\nseedOpt :: Parser String\nseedOpt = strOption\n  ( long \"seed\"\n    <> short 's'\n    <> metavar \"INT\"\n    <> value \"random\"\n    <> showDefault\n    <> help \"Set seed for the random number generator\" )\n", "meta": {"hexsha": "0e833bd5290e337b640ee9c560d64b2e27f44a8c", "size": 7377, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ArgParse.hs", "max_stars_repo_name": "dschrempf/bmm-simulate", "max_stars_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-14T15:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T15:53:08.000Z", "max_issues_repo_path": "src/ArgParse.hs", "max_issues_repo_name": "pomo-dev/bmm-simulate", "max_issues_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "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/ArgParse.hs", "max_forks_repo_name": "pomo-dev/bmm-simulate", "max_forks_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "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": 32.3552631579, "max_line_length": 112, "alphanum_fraction": 0.6383353667, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21231062866679962}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Grenade.Layers.Internal.Pad (\n    pad\n  , crop\n  ) where\n\nimport qualified Data.Vector.Storable as U ( unsafeToForeignPtr0, unsafeFromForeignPtr0 )\n\nimport           Foreign ( mallocForeignPtrArray, withForeignPtr )\nimport           Foreign.Ptr ( Ptr )\n\nimport           Numeric.LinearAlgebra ( flatten, Matrix )\nimport qualified Numeric.LinearAlgebra.Devel as U\n\nimport           System.IO.Unsafe ( unsafePerformIO )\n\npad :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double\npad channels padLeft padTop padRight padBottom rows cols rows' cols' m\n = let outMatSize      = rows' * cols' * channels\n       vec             = flatten m\n   in unsafePerformIO $ do\n     outPtr        <- mallocForeignPtrArray outMatSize\n     let (inPtr, _) = U.unsafeToForeignPtr0 vec\n\n     withForeignPtr inPtr $ \\inPtr' ->\n       withForeignPtr outPtr $ \\outPtr' ->\n         pad_cpu inPtr' channels rows cols padLeft padTop padRight padBottom outPtr'\n\n     let matVec = U.unsafeFromForeignPtr0 outPtr outMatSize\n     return (U.matrixFromVector U.RowMajor (rows' * channels) cols' matVec)\n{-# INLINE pad #-}\n\nforeign import ccall unsafe\n    pad_cpu\n      :: Ptr Double -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr Double -> IO ()\n\ncrop :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double\ncrop channels padLeft padTop padRight padBottom rows cols _ _ m\n = let outMatSize      = rows * cols * channels\n       vec             = flatten m\n   in unsafePerformIO $ do\n     outPtr        <- mallocForeignPtrArray outMatSize\n     let (inPtr, _) = U.unsafeToForeignPtr0 vec\n\n     withForeignPtr inPtr $ \\inPtr' ->\n       withForeignPtr outPtr $ \\outPtr' ->\n         crop_cpu inPtr' channels rows cols padLeft padTop padRight padBottom outPtr'\n\n     let matVec = U.unsafeFromForeignPtr0 outPtr outMatSize\n     return (U.matrixFromVector U.RowMajor (rows * channels) cols matVec)\n\nforeign import ccall unsafe\n    crop_cpu\n      :: Ptr Double -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr Double -> IO ()\n", "meta": {"hexsha": "e6110988df12d5d515a6c210b0caf7916afc5e38", "size": 2130, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Internal/Pad.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1527, "max_stars_repo_stars_event_min_datetime": "2016-06-23T13:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T05:22:00.000Z", "max_issues_repo_path": "src/Grenade/Layers/Internal/Pad.hs", "max_issues_repo_name": "Alien-Inc/grenade", "max_issues_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2016-06-27T22:16:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-20T17:50:09.000Z", "max_forks_repo_path": "src/Grenade/Layers/Internal/Pad.hs", "max_forks_repo_name": "Alien-Inc/grenade", "max_forks_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2016-06-28T02:24:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:17:29.000Z", "avg_line_length": 38.7272727273, "max_line_length": 101, "alphanum_fraction": 0.6549295775, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.21197695174630618}}
{"text": "{-|\n  Safe immutable intermediate (functional) Matlab data structures.\n\n  This provides an alternative representation of Matlab data structures which can be marshalled to and from 'MXArray'.\n  An instance of 'Show' is provided which creates Matlab expressions.\n-}\nmodule Foreign.Matlab.Array.IMX (\n    IMXData(..),\n    IMXArray,\n    IMXArrayElem (imxConstr, imxArray),\n\n    -- * Interface with \"Foreign.Matlab.Array\"\n    imxData, iMXData,\n    imxFun, iMXFun,\n    withIMXData, takeIMXData,\n    withIMXDataList,\n\n    -- * Construction and access\n    imxSize,\n    listIMX, scalarIMX,\n    imxList, imxScalar,\n    listIMXStruct,\n    imxStructList\n  ) where\n\nimport           Control.Monad\nimport           Data.Array.IArray\nimport           Data.Complex\nimport           Data.List\nimport qualified Data.Map.Strict as DM\nimport           Foreign.Matlab.Util\nimport           Foreign.Matlab.Internal\nimport           Foreign.Matlab.Types\nimport           Foreign.Matlab.Array\n\ntype IMXArray a = Array MIndex a\n-- |The basic immutable (functional) representation of Matlab data structures, representing a generic 'MXArray'\ndata IMXData =\n    IMXNull\n  | IMXCell     (IMXArray IMXData)\n  | IMXStruct   [String] (Array (MIndex,Int) IMXData) -- ^ field name list and array mapping (index,field index) to values\n  | IMXLogical  (IMXArray MLogical)\n  | IMXChar     (IMXArray MChar)\n  | IMXDouble   (IMXArray MDouble)\n  | IMXSingle   (IMXArray MSingle)\n  | IMXInt8     (IMXArray MInt8)\n  | IMXUint8    (IMXArray MUint8)\n  | IMXInt16    (IMXArray MInt16)\n  | IMXUint16   (IMXArray MUint16)\n  | IMXInt32    (IMXArray MInt32)\n  | IMXUint32   (IMXArray MUint32)\n  | IMXInt64    (IMXArray MInt64)\n  | IMXUint64   (IMXArray MUint64)\n  | IMXComplexDouble    (IMXArray (MComplex MDouble))\n  | IMXComplexSingle    (IMXArray (MComplex MSingle))\n  | IMXObject   String IMXData -- ^ object class name and object data, currently always IMXStruct\n  deriving (Eq)\n\ntype IMXFun = [IMXData] -> Int -> IO [IMXData]\n\nfixMSize :: MSize -> [a] -> MSize\nfixMSize s l = maybe s (\\i -> replaceIndex s i (length l `div` negate (product s))) $ elemIndex (-1) s\n\n-- |Create an sized array for 'IMXData' from a sequential list of elements.  'MSize' may contain at most one -1 value, which will be inferred from the length of the list.\nlistIMXArray :: MSize -> [e] -> IMXArray e\nlistIMXArray s l = listArray (mSizeRange (fixMSize s l)) l\n\n-- |Create a scalar (array) for 'IMXData'\nscalarIMXArray :: e -> IMXArray e\nscalarIMXArray e = listIMXArray [] [e]\n\nclass IMXArrayElem a where\n  -- |Generic 'IMXData' 'IMXArray' constructor\n  imxConstr :: IMXArray a -> IMXData\n  -- |Generic 'IMXData' 'IMXArray' accessor\n  imxArray :: IMXData -> Maybe (IMXArray a)\ninstance IMXArrayElem IMXData  where { imxConstr = IMXCell    ; imxArray (IMXCell    a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MLogical where { imxConstr = IMXLogical ; imxArray (IMXLogical a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MChar    where { imxConstr = IMXChar    ; imxArray (IMXChar    a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MDouble  where { imxConstr = IMXDouble  ; imxArray (IMXDouble  a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MSingle  where { imxConstr = IMXSingle  ; imxArray (IMXSingle  a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MInt8    where { imxConstr = IMXInt8    ; imxArray (IMXInt8    a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MUint8   where { imxConstr = IMXUint8   ; imxArray (IMXUint8   a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MInt16   where { imxConstr = IMXInt16   ; imxArray (IMXInt16   a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MUint16  where { imxConstr = IMXUint16  ; imxArray (IMXUint16  a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MInt32   where { imxConstr = IMXInt32   ; imxArray (IMXInt32   a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MUint32  where { imxConstr = IMXUint32  ; imxArray (IMXUint32  a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MInt64   where { imxConstr = IMXInt64   ; imxArray (IMXInt64   a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem MUint64  where { imxConstr = IMXUint64  ; imxArray (IMXUint64  a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem (MComplex MDouble) where { imxConstr = IMXComplexDouble ; imxArray (IMXComplexDouble a) = Just a ; imxArray _ = Nothing }\ninstance IMXArrayElem (MComplex MSingle) where { imxConstr = IMXComplexSingle ; imxArray (IMXComplexSingle a) = Just a ; imxArray _ = Nothing }\n\n-- |Generic 'IMXData' list constructor.  Specified 'MSize' may contain at most one -1 value, which will be inferred from the length of the list.\nlistIMX :: IMXArrayElem a => MSize -> [a] -> IMXData\nlistIMX s = imxConstr . listIMXArray s\n-- |Generic 'IMXData' scalar constructor\nscalarIMX :: IMXArrayElem a => a -> IMXData\nscalarIMX = imxConstr . scalarIMXArray\n--emptyIMX :: IMXArrayElem a => a -> IMXData\n--emptyIMX a = listIMX [0] ([] `asTypeOf` [a])\n\n-- |Generic 'IMXData' array size accessor\nimxSize :: IMXData -> MSize\nimxSize IMXNull = [0]\nimxSize (IMXCell    a) = mRangeSize (bounds a)\nimxSize (IMXLogical a) = mRangeSize (bounds a)\nimxSize (IMXChar    a) = mRangeSize (bounds a)\nimxSize (IMXDouble  a) = mRangeSize (bounds a)\nimxSize (IMXSingle  a) = mRangeSize (bounds a)\nimxSize (IMXInt8    a) = mRangeSize (bounds a)\nimxSize (IMXUint8   a) = mRangeSize (bounds a)\nimxSize (IMXInt16   a) = mRangeSize (bounds a)\nimxSize (IMXUint16  a) = mRangeSize (bounds a)\nimxSize (IMXInt32   a) = mRangeSize (bounds a)\nimxSize (IMXUint32  a) = mRangeSize (bounds a)\nimxSize (IMXInt64   a) = mRangeSize (bounds a)\nimxSize (IMXUint64  a) = mRangeSize (bounds a)\nimxSize (IMXComplexDouble a) = mRangeSize (bounds a)\nimxSize (IMXComplexSingle a) = mRangeSize (bounds a)\nimxSize (IMXStruct _ a) = mRangeSize (r0,r1) where ((r0,_),(r1,_)) = bounds a\nimxSize (IMXObject _ d) = imxSize d\n\n-- |Generic 'IMXData' list accessor\nimxList :: IMXArrayElem a => IMXData -> Maybe [a]\nimxList = fmap elems . imxArray\n-- |Generic 'IMXData' scalar accessor\nimxScalar :: IMXArrayElem a => IMXData -> Maybe a\nimxScalar a = case imxList a of \n  Just [x] -> Just x\n  _ -> Nothing\n\n-- |Create a sized struct array from a sequential list of consecutive field values (@[i0f0,i0f1,...,i0fM,i1f0,i1f1,....,iNfM]@).\nlistIMXStruct :: [String] -> MSize -> [IMXData] -> IMXData\nlistIMXStruct f s l = IMXStruct f $ listArray r l where\n  n = length f\n  r = ((r0,0),(r1,pred n))\n  (r0,r1) = mSizeRange $ tail $ fixMSize (n:s) l\n\n-- |Access a struct as list of fields and list of consecutive field values\nimxStructList :: IMXData -> Maybe ([String], [IMXData])\nimxStructList (IMXStruct f v) = Just (f, elems v)\nimxStructList _ = Nothing\n\n-- |Create an immutable representation from an 'MXArray'\nimxData :: MXArray a -> IO IMXData\nimxData a = do\n  t <- mxArrayClass a\n  c <- if t /= MXClassNull then mxArrayIsComplex a else return undefined\n  imxc t c where\n  \n  imxc :: MXClass -> Bool -> IO IMXData\n  imxc MXClassNull _            = return IMXNull\n  imxc MXClassCell False        = IMXCell       =.< imxa (imxData . mCell)\n  imxc MXClassStruct False      = do\n    s <- mxArraySize a'\n    fv <- mxArrayGetAll a'\n    f <- if null fv then mStructFields a' else return (map fst (DM.toList $ _mStruct (head fv)))\n    listIMXStruct f s =.< mapM imxData (concatMap (map snd . DM.toList . _mStruct) fv)\n  imxc MXClassLogical False     = IMXLogical    =.< imxa return\n  imxc MXClassChar False        = IMXChar       =.< imxa return\n  imxc MXClassDouble False      = IMXDouble     =.< imxa return\n  imxc MXClassSingle False      = IMXSingle     =.< imxa return\n  imxc MXClassInt8 False        = IMXInt8       =.< imxa return\n  imxc MXClassUint8 False       = IMXUint8      =.< imxa return\n  imxc MXClassInt16 False       = IMXInt16      =.< imxa return\n  imxc MXClassUint16 False      = IMXUint16     =.< imxa return\n  imxc MXClassInt32 False       = IMXInt32      =.< imxa return\n  imxc MXClassUint32 False      = IMXUint32     =.< imxa return\n  imxc MXClassInt64 False       = IMXInt64      =.< imxa return\n  imxc MXClassUint64 False      = IMXUint64     =.< imxa return\n  imxc MXClassDouble True       = IMXComplexDouble      =.< imxa return\n  imxc MXClassSingle True       = IMXComplexSingle      =.< imxa return\n  imxc MXClassObject False      = do\n    Just c <- mObjectGetClass a'\n    IMXObject c =.< imxc MXClassStruct False\n  imxc t c = fail (\"imxData: unhandled mxArray type \" ++ show t ++ if c then \"(complex)\" else \"\")\n\n  imxa :: MXArrayComponent a => (a -> IO b) -> IO (IMXArray b)\n  imxa f = do\n    s <- mxArraySize a'\n    listIMXArray s =.< mapM f =<< mxArrayGetAll a'\n\n  a' = unsafeCastMXArray a\n\n-- |Create a new 'MXArray' from a functional representation.\niMXData :: IMXData -> IO MAnyArray\niMXData = imxd where\n  imxd :: IMXData -> IO MAnyArray\n  imxd IMXNull = return $ anyMXArray mNullArray\n  imxd (IMXCell a) = imxa a (MCell .=< iMXData)\n  imxd (IMXStruct f a) = do\n    let ((r0,_),(r1,_)) = bounds a\n    m <- createStruct (mRangeSize (r0,r1)) f\n    zipWithM_ (\\i -> mStructSetFields m (mOffset i) <=< mapM iMXData) [0..] (segment (length f) (elems a))\n    return $ anyMXArray m\n  imxd (IMXLogical a)   = imxa a return\n  imxd (IMXChar a)      = imxa a return\n  imxd (IMXDouble a)    = imxa a return\n  imxd (IMXSingle a)    = imxa a return\n  imxd (IMXInt8 a)      = imxa a return\n  imxd (IMXUint8 a)     = imxa a return\n  imxd (IMXInt16 a)     = imxa a return\n  imxd (IMXUint16 a)    = imxa a return\n  imxd (IMXInt32 a)     = imxa a return\n  imxd (IMXUint32 a)    = imxa a return\n  imxd (IMXInt64 a)     = imxa a return\n  imxd (IMXUint64 a)    = imxa a return\n  imxd (IMXComplexDouble a) = imxa a return\n  imxd (IMXComplexSingle a) = imxa a return\n  imxd (IMXObject c a) = do\n    m <- imxd a\n    mObjectSetClass (unsafeCastMXArray m) c\n    return m\n\n  imxa :: MXArrayComponent b => IMXArray a -> (a -> IO b) -> IO MAnyArray\n  imxa a f = do\n    m <- createMXArray (mRangeSize (bounds a))\n    mxArraySetAll m =<< mapM f (elems a)\n    return $ anyMXArray m\n\nwithIMXData :: IMXData -> (MAnyArray -> IO a) -> IO a\nwithIMXData d f = do\n  a <- iMXData d\n  r <- f a\n  freeMXArray a\n  return r\n\nwithIMXDataList :: [IMXData] -> ([MAnyArray] -> IO a) -> IO a\nwithIMXDataList = mapWith withIMXData\n\ntakeIMXData :: MXArray a -> IO IMXData\ntakeIMXData a = do\n  d <- imxData a\n  freeMXArray a\n  return d\n\nimxFun :: MFun -> IMXFun\nimxFun fun a no =\n  mapWith withIMXData a $ \\m ->\n  fun m no >>= mapM takeIMXData\n\niMXFun :: IMXFun -> MFun\niMXFun fun a no = do\n  ia <- mapM imxData a\n  fun ia no >>= mapM iMXData\n\n\nshowsApp :: String -> ShowS -> ShowS\nshowsApp f a s = f ++ '(' : a (')' : s)\n\n{-\nshowsReshape :: (MIndex,MIndex) -> ShowS -> ShowS\nshowsReshape (MSubs [],MSubs []) a s = a s\nshowsReshape (MSubs [],MSubs []) a s = a s\nshowsReshape r a s = \"reshape(\" ++ a (',' : shows (realMSize $ mRangeSize r) (')' : s))\n\nshowsIMXArrayDelimWith :: (Char,Char,Char) -> (a -> ShowS) -> IMXArray a -> ShowS\nshowsIMXArrayDelimWith d f a = showsReshape (bounds a) $ showsMListWith d f (elems a)\nshowsIMXArrayWith :: (a -> ShowS) -> IMXArray a -> ShowS\nshowsIMXArrayWith = showsIMXArrayDelimWith ('[',',',']')\nshowsIMXArray :: Show a => IMXArray a -> ShowS\nshowsIMXArray = showsIMXArrayWith shows\n-}\n\nshowsMList :: (Char,Char,Char) -> (a -> ShowS) -> [a] -> ShowS\nshowsMList (l,_,r) _ [] s = l : r : s\nshowsMList (l,d,r) f (x:xs) s = l : f x (shml xs) where\n  shml [] = r : s\n  shml (x:xs) = d : f x (shml xs)\n\nshowsReshape :: MSize -> (Char -> ShowS) -> ShowS\nshowsReshape [] f s = f ' ' s\nshowsReshape [_] f s = f ';' s\nshowsReshape [1,_] f s = f ',' s\nshowsReshape z f s = \"reshape(\" ++ f ' ' (',' : showsMList ('[',' ',']') shows (realMSize z) (')' : s))\n\nshowsIMXGenArray :: (Char,Char) -> (a -> ShowS) -> IMXArray a -> ShowS\nshowsIMXGenArray (l,r) f a = showsReshape (mRangeSize $ bounds a) $ \\d -> showsMList (l,d,r) f (elems a)\nshowsIMXArrayWith :: (a -> ShowS) -> IMXArray a -> ShowS\nshowsIMXArrayWith = showsIMXGenArray ('[',']')\nshowsIMXArray :: Show a => IMXArray a -> ShowS\nshowsIMXArray = showsIMXArrayWith shows\n\nshowsComplex :: (Show a, RealFloat a) => Complex a -> ShowS\nshowsComplex (x:+y) s = \"complex(\" ++ shows x (',' : shows y (')' : s))\n\nshowsMString :: String -> ShowS\nshowsMString s = showChar '\\'' . showString s . showChar '\\''\n\nshowsIMX :: IMXData -> ShowS\nshowsIMX IMXNull = showString \"[]\"\nshowsIMX (IMXCell a) = showsIMXGenArray ('{','}') shows a\nshowsIMX (IMXStruct f a) = showsReshape (mRangeSize (r0,r1)) $ \\d ->\n  showString \"struct\" . showsMList ('(',',',')') (shf d) (zip f v) where\n  shf d (f,v) s = showsMString f $ ',' : showsMList ('{',d,'}') showsIMX v s\n  v = transpose $ segment (length f) $ elems a\n  ((r0,_),(r1,_)) = bounds a\nshowsIMX (IMXLogical a) = showsApp \"logical\"  $ showsIMXArray a\nshowsIMX (IMXChar a)    = showsApp \"char\"     $ showsIMXArray a\nshowsIMX (IMXDouble a)  =                       showsIMXArray a\nshowsIMX (IMXSingle a)  = showsApp \"single\"   $ showsIMXArray a\nshowsIMX (IMXInt8 a)    = showsApp \"int8\"     $ showsIMXArray a\nshowsIMX (IMXUint8 a)   = showsApp \"uint8\"    $ showsIMXArray a\nshowsIMX (IMXInt16 a)   = showsApp \"int16\"    $ showsIMXArray a\nshowsIMX (IMXUint16 a)  = showsApp \"uint16\"   $ showsIMXArray a\nshowsIMX (IMXInt32 a)   = showsApp \"int32\"    $ showsIMXArray a\nshowsIMX (IMXUint32 a)  = showsApp \"uint32\"   $ showsIMXArray a\nshowsIMX (IMXInt64 a)   = showsApp \"int64\"    $ showsIMXArray a\nshowsIMX (IMXUint64 a)  = showsApp \"uint64\"   $ showsIMXArray a\nshowsIMX (IMXComplexDouble a)   = showsIMXArrayWith showsComplex a\nshowsIMX (IMXComplexSingle a)   = showsApp \"single\" $ showsIMXArrayWith showsComplex a\nshowsIMX (IMXObject c a) = showsApp \"class\" $ showsIMX a . showChar ',' . showsMString c\n\ninstance Show IMXData where\n  showsPrec _ = showsIMX\n", "meta": {"hexsha": "e89229283f9bd9daa0277d679cc2b26f40eb1ffb", "size": 13871, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Foreign/Matlab/Array/IMX.hs", "max_stars_repo_name": "CornellCAC/haskell-matlab", "max_stars_repo_head_hexsha": "21cdb98a2bcf23c90eb31026063f4c3a2cf5da15", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-02-10T07:58:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T12:13:16.000Z", "max_issues_repo_path": "Foreign/Matlab/Array/IMX.hs", "max_issues_repo_name": "CornellCAC/haskell-matlab", "max_issues_repo_head_hexsha": "21cdb98a2bcf23c90eb31026063f4c3a2cf5da15", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2015-01-20T02:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-28T19:48:32.000Z", "max_forks_repo_path": "Foreign/Matlab/Array/IMX.hs", "max_forks_repo_name": "CornellCAC/haskell-matlab", "max_forks_repo_head_hexsha": "21cdb98a2bcf23c90eb31026063f4c3a2cf5da15", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-02-10T07:58:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-26T22:30:15.000Z", "avg_line_length": 43.8955696203, "max_line_length": 170, "alphanum_fraction": 0.6699589071, "num_tokens": 4816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21037225816046312}}
{"text": "{-#LANGUAGE ForeignFunctionInterface#-}\n-- |This  module provides slow but functional means for exporting images from and to\n--  CArrays, which can easily be passed into foreign functions.\nmodule CV.Conversions (\n     -- Arrays of Double\n     copyCArrayToImage\n    ,copy8UCArrayToImage\n    ,copyImageToCArray\n     -- Arrays of Float\n    ,copyFCArrayToImage\n    ,copyImageToFCArray\n    -- * Complex arrays\n    ,copyComplexCArrayToImage\n    ,copyImageToComplexCArray\n    -- * Copying\n    ,copyImageToExistingCArray\n    -- * Acquiring images from pointers\n    ,unsafe8UC_RGBFromPtr\n    ,unsafe8UC_BGRFromPtr\n    ,unsafe8UC_MONOFromPtr\n    ,acquireImageSlowF'\n    ,acquireImageSlow'\n    ,acquireImageSlow8URGB'\n    ) where\n\nimport Data.Complex as C\n\nimport CV.Image\nimport Data.Word\n\nimport Data.Array.CArray\nimport Data.Array.IArray\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport System.IO.Unsafe\n\nunsafe8UC_RGBFromPtr :: (Int,Int) -> Ptr Word8 -> IO (Image RGB D8)\nunsafe8UC_RGBFromPtr (w,h) ptr = S `fmap`  creatingBareImage (acquireImageSlow8URGB' w h ptr)\n\nunsafe8UC_BGRFromPtr :: (Int,Int) -> Ptr Word8 -> IO (Image RGB D8)\nunsafe8UC_BGRFromPtr (w,h) ptr = S `fmap`  creatingBareImage (acquireImageSlow8UBGR' w h ptr)\n\nunsafe8UC_MONOFromPtr :: (Int,Int) -> Ptr Word8 -> IO (Image GrayScale D8)\nunsafe8UC_MONOFromPtr (w,h) ptr = S `fmap`  creatingBareImage (acquireImageSlow8U' w h ptr)\n\n-- |Copy the contents of a CArray into CV.Image type.\ncopy8UCArrayToImage :: CArray (Int,Int) Word8 -> Image GrayScale D8\ncopy8UCArrayToImage carr = S $ unsafePerformIO $\n                          creatingBareImage (withCArray carr (acquireImageSlow8U' w h))\n    where\n     ((sx,sy),(ex,ey)) = bounds carr\n     (w,h) = (fromIntegral $ ex-sx+1, fromIntegral $ ey-sy+1)\n--\n-- |Copy the contents of a CArray into CV.Image type.\ncopyCArrayToImage :: CArray (Int,Int) Double -> Image GrayScale D32\ncopyCArrayToImage carr = S $ unsafePerformIO $\n                          creatingBareImage (withCArray carr (acquireImageSlow' w h))\n    where\n     ((sx,sy),(ex,ey)) = bounds carr\n     (w,h) = (fromIntegral $ ex-sx+1, fromIntegral $ ey-sy+1)\n\n-- |Copy CArray of floats to image\ncopyFCArrayToImage :: CArray (Int,Int) Float -> Image GrayScale D32\ncopyFCArrayToImage carr = S $ unsafePerformIO $\n                          creatingBareImage (withCArray carr (acquireImageSlowF' w h))\n    where\n     ((sx,sy),(ex,ey)) = bounds carr\n     (w,h) = (fromIntegral $ ex-sx+1, fromIntegral $ ey-sy+1)\n\n-- |Copy D32 grayscale image to CArray\ncopyImageToFCArray :: Image GrayScale D32 -> CArray (Int,Int) Float\ncopyImageToFCArray (S img) = unsafePerformIO $\n         withBareImage img $ \\cimg ->\n          createCArray ((0,0),(w-1,h-1)) (exportImageSlowF' cimg) --({#call exportImageSlow#} cimg)\n    where\n     (w,h) = getSize img\n\n\n\n\n-- |Copy the real part of an array to image\ncopyComplexCArrayToImage :: CArray (Int,Int) (C.Complex Double) -> Image GrayScale D32\ncopyComplexCArrayToImage carr = S $ unsafePerformIO $\n                          creatingBareImage (withCArray carr (acquireImageSlowComplex' w h))\n    where\n     ((sx,sy),(ex,ey)) = bounds carr\n     (w,h) = (fromIntegral $ ex-sx+1, fromIntegral $ ey-sy+1)\n\n-- |Copy the contents of a CV.Image into a CArray.\ncopyImageToCArray :: Image GrayScale D32 -> CArray (Int,Int) Double\ncopyImageToCArray (S img) = unsafePerformIO $\n         withBareImage img $ \\cimg ->\n          createCArray ((0,0),(w-1,h-1)) (exportImageSlow' cimg) --({#call exportImageSlow#} cimg)\n    where\n     (w,h) = getSize img\n-- |Copy the contents of CV.Image into a pre-existing CArray.\n--\ncopyImageToExistingCArray (S img) arr =\n         withBareImage img $ \\cimg ->\n          withCArray arr $ \\carr -> (exportImageSlow' cimg carr) --({#call exportImageSlow#} cimg)\n    where\n     (w,h) = getSize img\n\n-- |Copy image as a real part of a complex CArray\ncopyImageToComplexCArray :: Image GrayScale D32 -> CArray (Int,Int) (C.Complex Double)\ncopyImageToComplexCArray (S img) = unsafePerformIO $\n         withBareImage img $ \\cimg ->\n          createCArray ((0,0),(w-1,h-1)) (exportImageSlowComplex' cimg) --({#call exportImageSlow#} cimg)\n    where\n     (w,h) = getSize img\n\nforeign import ccall safe \"CV/cvWrapLeo.h exportImageSlow\"\n  exportImageSlow' :: ((Ptr (BareImage)) -> ((Ptr Double) -> (IO ())))\n\nforeign import ccall safe \"CV/cvWrapLeo.h exportImageSlowF\"\n  exportImageSlowF' :: ((Ptr (BareImage)) -> ((Ptr Float) -> (IO ())))\n\nforeign import ccall safe \"CV/cvWrapLeo.h exportImageSlowComplex\"\n  exportImageSlowComplex' :: ((Ptr (BareImage)) -> ((Ptr (C.Complex Double)) -> (IO ())))\n\nforeign import ccall safe \"CV/cvWrapLeo.h acquireImageSlow\"\n  acquireImageSlow' :: (Int -> (Int -> ((Ptr Double) -> (IO (Ptr (BareImage))))))\n\nforeign import ccall safe \"CV/cvWrapLeo.h acquireImageSlowF\"\n  acquireImageSlowF' :: (Int -> (Int -> ((Ptr Float) -> (IO (Ptr (BareImage))))))\n\nforeign import ccall safe \"CV/cvWrapLeo.h acquireImageSlow8URGB\"\n  acquireImageSlow8URGB' :: (Int -> (Int -> ((Ptr Word8) -> (IO (Ptr (BareImage))))))\n\nforeign import ccall safe \"CV/cvWrapLeo.h acquireImageSlow8UBGR\"\n  acquireImageSlow8UBGR' :: (Int -> (Int -> ((Ptr Word8) -> (IO (Ptr (BareImage))))))\n\nforeign import ccall safe \"CV/cvWrapLeo.h acquireImageSlow8U\"\n  acquireImageSlow8U' :: (Int -> (Int -> ((Ptr Word8) -> (IO (Ptr (BareImage))))))\n\nforeign import ccall safe \"CV/cvWrapLeo.h acquireImageSlowComplex\"\n  acquireImageSlowComplex' :: (Int -> (Int -> ((Ptr (C.Complex Double)) -> (IO (Ptr (BareImage))))))\n\n", "meta": {"hexsha": "3843b84cc60d7c0830a36510151f05898597f62e", "size": 5506, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "CV/Conversions.hs", "max_stars_repo_name": "maaleske/CV", "max_stars_repo_head_hexsha": "91fb1b4258babf482bfdb5269d7b173a4bbdd545", "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": "CV/Conversions.hs", "max_issues_repo_name": "maaleske/CV", "max_issues_repo_head_hexsha": "91fb1b4258babf482bfdb5269d7b173a4bbdd545", "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": "CV/Conversions.hs", "max_forks_repo_name": "maaleske/CV", "max_forks_repo_head_hexsha": "91fb1b4258babf482bfdb5269d7b173a4bbdd545", "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": 39.3285714286, "max_line_length": 105, "alphanum_fraction": 0.6808935707, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2103722581604631}}
{"text": "{-# LANGUAGE DeriveDataTypeable    #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE TypeFamilies          #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Plots.Axis\n-- Copyright   :  (C) 2015 Christopher Chalmers\n-- License     :  BSD-style (see the file LICENSE)\n-- Maintainer  :  Christopher Chalmers\n-- Stability   :  experimental\n-- Portability :  non-portable\n--\n-- The 'Axis' is the main data type for \"plots\". It holds all the\n-- necessary infomation to be rendered into a 'Diagram'.\n--\n----------------------------------------------------------------------------\nmodule Plots.Axis\n  ( -- * Axis type\n    Axis\n  , axes\n  , axisPlots\n  , currentPlots\n  , finalPlots\n  , plotModifier\n  , axisSize\n  , colourBarRange\n\n    -- * Predefined axes\n  , r2Axis\n  , polarAxis\n\n    -- ** Base space\n  , BaseSpace\n\n    -- * Axis plots\n  , addPlot\n  , addPlotable\n  , addPlotable'\n\n    -- * Single axis\n  , SingleAxis\n\n    -- * Specific axes\n    -- ** x-axis\n  , xAxis\n  , xLabel\n  , xMin\n  , xMax\n\n    -- ** y-axis\n  , yAxis\n  , yLabel\n  , yMin\n  , yMax\n\n    -- ** r-axis\n  , rAxis\n  , rLabel\n  , rMax\n\n    -- ** theta-axis\n  , thetaAxis\n  , thetaLabel\n\n    -- ** z-axis\n  , zAxis\n  , zLabel\n  , zMin\n  , zMax\n  ) where\n\nimport           Control.Monad.State\nimport           Data.Complex\nimport           Data.Default\nimport           Data.Typeable\n\nimport           Diagrams.Coordinates.Polar\nimport           Diagrams.Prelude\nimport           Diagrams.TwoD.Text\n\nimport           Plots.Axis.ColourBar\nimport           Plots.Axis.Grid\nimport           Plots.Axis.Labels\nimport           Plots.Axis.Line\nimport           Plots.Axis.Scale\nimport           Plots.Axis.Title\nimport           Plots.Axis.Ticks\nimport           Plots.Legend\nimport           Plots.Style\nimport           Plots.Types\n\nimport           Linear\n\n------------------------------------------------------------------------\n-- Axis data type\n------------------------------------------------------------------------\n\n-- Single axis ---------------------------------------------------------\n\n-- | Render information for a single axis line.\ndata SingleAxis b v n = SingleAxis\n-- note the the v is only present for Style v n\n  { saLabel     :: AxisLabel b v n\n  , saLine      :: AxisLine v n\n  , saTickLabel :: TickLabels b v n\n  , saScaling   :: AxisScaling n\n  , saGridLines :: GridLines v n\n  , saTicks     :: Ticks v n\n  , saVisible   :: Bool\n  }\n\ntype instance V (SingleAxis b v n) = v\ntype instance N (SingleAxis b v n) = n\n\ninstance (TypeableFloat n, Renderable (Text n) b)\n    => Default (SingleAxis b V2 n) where\n  def = SingleAxis\n    { saLabel      = def\n    , saLine       = def\n    , saTickLabel  = def\n    , saGridLines  = def\n    , saTicks      = def\n    , saScaling    = def\n    , saVisible    = True\n    }\n\ninstance Functor f => HasTicks f (SingleAxis b v n) where\n  bothTicks = lens saTicks (\\sa ticks -> sa {saTicks = ticks})\n\ninstance Functor f => HasMajorTicks f (SingleAxis b v n) where\n  majorTicks = bothTicks . majorTicks\n\ninstance Functor f => HasMinorTicks f (SingleAxis b v n) where\n  minorTicks = bothTicks . minorTicks\n\ninstance Functor f => HasAxisLabel f (SingleAxis b v n) b where\n  axisLabel = lens saLabel (\\sa l -> sa {saLabel = l})\n\ninstance Functor f => HasTickLabels f (SingleAxis b v n) b where\n  tickLabel = lens saTickLabel (\\sa tl -> sa {saTickLabel = tl})\n\ninstance Functor f => HasAxisLine f (SingleAxis b v n) where\n  axisLine = lens saLine (\\sa l -> sa {saLine = l})\n\ninstance Functor f => HasGridLines f (SingleAxis b v n) where\n  gridLines = lens saGridLines (\\sa l -> sa {saGridLines = l})\n\ninstance Functor f => HasMajorGridLines f (SingleAxis b v n) where\n  majorGridLines = gridLines . majorGridLines\n\ninstance Functor f => HasMinorGridLines f (SingleAxis b v n) where\n  minorGridLines = gridLines . minorGridLines\n\ninstance Functor f => HasAxisScaling f (SingleAxis b v n) where\n  axisScaling = lens saScaling (\\sa s -> sa {saScaling = s})\n\ninstance HasVisibility (SingleAxis b v n) where\n  visible = lens saVisible (\\sa b -> sa {saVisible = b})\n\n-- singleAxisScale :: Lens' (SingleAxis b v n) AxisScale\n-- singleAxisScale = lens saScale (\\sa s -> sa {saScale = s})\n\n-- singleAxisBound :: Lens' (SingleAxis b v n) (Bound n)\n-- singleAxisBound = lens saBounds (\\sa b -> sa {saBounds = b})\n\n------------------------------------------------------------------------\n-- Axis type\n------------------------------------------------------------------------\n\n-- Base space ----------------------------------------------------------\n\n-- | This family is used so that we can say (Axis Polar) but use V2 for the\n--   underlying diagram.\ntype family BaseSpace (c :: * -> *) :: * -> *\n\ntype instance BaseSpace V2      = V2\ntype instance BaseSpace Complex = V2\ntype instance BaseSpace Polar   = V2\ntype instance BaseSpace V3      = V3\n\n-- Axis data type ------------------------------------------------------\n\n-- | Axis is the data type that holds all the necessary information to render\n--   a plot. Common 'LensLike's used for the axis (see haddock's\n--   instances for a more comprehensive list):\n--\n--   * 'axisStyle'    - customise the 'AxisStyle'\n--   * 'legend'       - customise the 'Legend'\n--   * 'colourBar'    - customise the 'ColourBar'\n--   * 'currentPlots' - current plots in the 'Axis'\n--   * 'finalPlots'   - changes to the plots just before rendering\n--   * 'axes'         - changes to each 'SingleAxis'\n--\n--          * 'xAxis' - the x-axis\n--          * 'yAxis' - the y-axis\n--          * 'zAxis' - the z-axis\n--\n--   The following 'LensLike's can be used on the on all the axes by\n--   applying it the to 'Axis' or can be used on a 'SingleAxis' by using\n--   it in combination with a specific axis (like 'xAxis').\n--\n--   * 'axisLabel'   - customise the 'MinorTicks'\n--   * 'tickLabel'   - customise the 'TickLabels'\n--   * 'minorTicks'  - customise the 'MinorTicks'\n--   * 'majorTicks'  - customise the 'MajorTicks'\n--   * 'gridLines'   - customise the 'GridLines'\n--   * 'axisLine'    - customise the 'AxisLine'\n--   * 'axisScaling' - customise the 'AxisScaling'\n--\n--   Plots are usually added to the axis using specific functions for\n--   those plots ('Plots.Types.Line.linePlot, 'Plots.Types.Bar.barPlot').\n--   These functions use 'addPlotable' to add the plot to the axis.\ndata Axis b c n = Axis\n  { _axisStyle   :: AxisStyle b (BaseSpace c) n\n  , _colourBar   :: ColourBar b n\n  , _colourBarR  :: (n,n)\n  , _legend      :: Legend b n\n  , _axisTitle   :: Title b (BaseSpace c) n\n  -- , _axisTitle      :: AxisTitle\n\n  , _axisPlots   :: [DynamicPlot b (BaseSpace c) n]\n  , _plotModifier :: Endo (StyledPlot b (BaseSpace c) n)\n\n  -- the v in each axis is only used for the style\n  , _axes        :: c (SingleAxis b (BaseSpace c) n)\n  } deriving Typeable\n\n-- | Lens onto the separate axes of an axis. Allows changing the\n--   coordinate system as long as the 'BaseSpace' is the same.\n--\n-- @\n-- 'axes' :: 'Lens'' ('Axis' b c n) (c ('SingleAxis' b v n))\n-- @\naxes :: (v ~ BaseSpace c, v ~ BaseSpace c')\n     => Lens (Axis b c  n)\n             (Axis b c' n)\n             (c  (SingleAxis b v n))\n             (c' (SingleAxis b v n))\naxes = lens _axes (\\(Axis a1 a2 a3 a4 a5 a6 a7 _) a8 -> Axis a1 a2 a3 a4 a5 a6 a7 a8)\n\n-- | The list of plots currently in the axis.\naxisPlots :: BaseSpace c ~ v => Lens' (Axis b c n) [DynamicPlot b v n]\naxisPlots = lens _axisPlots (\\a ps -> a {_axisPlots = ps})\n\n-- | Traversal over the current plots in the axis.\n--\n--   For example, to make all 'ScatterPlot's currently in the axis use a\n--   'connectingLine', you can write\n--\n-- @\n-- 'finalPlots' . 'connectingLine' .= 'True'\n-- @\ncurrentPlots :: BaseSpace c ~ v => Traversal' (Axis b c n) (DynamicPlot b v n)\ncurrentPlots = axisPlots . traversed\n\n-- | Setter over the final plot before the axis is rendered.\n--\n--   For example, to make all 'ScatterPlot's in the axis use a\n--   'connectingLine' (both currently in the axis and ones added later),\n--   you can add\n--\n-- @\n-- 'finalPlots' . 'connectingLine' .= 'True'\n-- @\n--\nfinalPlots :: BaseSpace c ~ v => Setter' (Axis b c n) (StyledPlot b v n)\nfinalPlots = sets $ \\f a -> a {_plotModifier = _plotModifier a <> Endo f}\n\n-- | Lens onto the modifier set by 'finalPlots'. This gets applied to\n--   all plots in the axis, just before they are rendered.\nplotModifier :: BaseSpace c ~ v => Lens' (Axis b c n) (Endo (StyledPlot b v n))\nplotModifier = lens _plotModifier (\\a f -> a {_plotModifier = f})\n\n-- Axis instances ------------------------------------------------------\n\ntype instance V (Axis b v n) = BaseSpace v\ntype instance N (Axis b v n) = n\n\ninstance (Applicative f, Traversable c) => HasTicks f (Axis b c n) where\n  bothTicks = axes . traverse . bothTicks\n\ninstance (Applicative f, Traversable c) => HasMajorTicks f (Axis b c n) where\n  majorTicks = axes . traverse . majorTicks\n\ninstance (Applicative f, Traversable c) => HasMinorTicks f (Axis b c n) where\n  minorTicks = axes . traverse . minorTicks\n\ninstance (Applicative f, Traversable c) => HasGridLines f (Axis b c n) where\n  gridLines = axes . traverse . gridLines\n\ninstance (Applicative f, Traversable c) => HasMajorGridLines f (Axis b c n) where\n  majorGridLines = axes . traverse . majorGridLines\n\ninstance (Applicative f, Traversable c) => HasMinorGridLines f (Axis b c n) where\n  minorGridLines = axes . traverse . minorGridLines\n\ninstance (Applicative f, Traversable c) => HasAxisLabel f (Axis b c n) b where\n  axisLabel = axes . traverse . axisLabel\n\ninstance (Applicative f, Traversable c) => HasTickLabels f (Axis b c n) b where\n  tickLabel = axes . traverse . tickLabel\n\ninstance (Applicative f, Traversable c) => HasAxisScaling f (Axis b c n) where\n  axisScaling = axes . traverse . axisScaling\n\ninstance Settable f => HasPlotOptions f (Axis b c n) b where\n  plotOptions = finalPlots . plotOptions\n\ninstance Settable f => HasPlotStyle f (Axis b c n) b where\n  plotStyle = finalPlots . plotStyle\n\ninstance HasLegend (Axis b c n) b where\n  legend = lens _legend (\\a l -> a {_legend = l})\n\ninstance HasTitle (Axis b c n) b where\n  title = lens _axisTitle (\\a t -> a {_axisTitle = t})\n\n-- | The size used for the rendered axis.\naxisSize :: (HasLinearMap c, Num n, Ord n) => Lens' (Axis b c n) (SizeSpec c n)\naxisSize = axes . column renderSize . iso mkSizeSpec getSpec -- column axisScaling . asSizeSpec -- iso mkSizeSpec getSpec\n\n-- | The range used for the colour bar limits. This is automatically set\n--   when using 'heatMap' or 'heatMap''\ncolourBarRange :: Lens' (Axis b v n) (n,n)\ncolourBarRange = lens _colourBarR (\\a r -> a {_colourBarR = r})\n\ninstance HasAxisStyle (Axis b v n) b where\n  axisStyle = lens _axisStyle (\\a sty -> a {_axisStyle = sty})\n\ninstance HasColourBar (Axis b v n) b where\n  colourBar = lens _colourBar (\\a cb -> a {_colourBar = cb})\n\n-- Axis functions ------------------------------------------------------\n\n-- $plotable\n-- The 'Plotable' class defines ways of converting the data type to a\n-- diagram for some axis. There are several variants for adding an axis\n-- with constraints @('InSpace' v n a, 'Plotable' a b)@:\n--\n-- @\n-- 'addPlotable'  ::           a -> 'PlotState' a b -> 'AxisState' b v n\n-- 'addPlotable''   ::           a ->                  'AxisState' b v n\n-- @\n--\n-- The last argument is a 'PlotState' so you can use @do@ notation to\n-- make adjustments to the plot. The @L@ suffix stands for \\\"legend\\\",\n-- it is equivalent of using 'addLegendEntry' in the 'PlotState'. Since\n-- legend entries are so common it has it's own suffix. The following\n-- are equivalent:\n--\n-- @\n-- myaxis = 'r2Axis' &~ do\n--   'addPlotable'' myplot $ do\n--     'addLegendEntry' \"my plot\"\n-- @\n--\n-- Most of the time you won't use these functions directly. However,\n-- other plotting functions follow this naming convention where instead\n-- of @a@, it takes the data needed to make the plot.\n\n-- | Add a 'Plotable' 'Plot' to an 'Axis'.\naddPlot\n  :: (InSpace (BaseSpace c) n p, MonadState (Axis b c n) m, Plotable p b)\n  => Plot p b -- ^ the plot\n  -> m ()     -- ^ add plot to the 'Axis'\naddPlot p = axisPlots <>= [DynamicPlot p]\n\n-- | Add something 'Plotable' to the 'Axis' with a stateful modification\n--   of the 'Plot'.\naddPlotable\n  :: (InSpace (BaseSpace c) n p, MonadState (Axis b c n) m, Plotable p b)\n  => p -- ^ the raw plot\n  -> State (Plot p b) () -- ^ changes to the plot\n  -> m () -- ^ add plot to the 'Axis'\naddPlotable p s = addPlot $ execState s (mkPlot p)\n\n-- | Simple version of 'AddPlotable' without any changes 'Plot'.\naddPlotable'\n  :: (InSpace (BaseSpace v) n p, MonadState (Axis b v n) m, Plotable p b)\n  => p    -- ^ the raw plot\n  -> m () -- ^ add plot to the 'Axis'\naddPlotable' p = addPlotable p (return ())\n\n------------------------------------------------------------------------\n-- Predefined axes\n------------------------------------------------------------------------\n\n-- | The default axis for plots in the 'V2' coordinate system.\nr2Axis\n  :: (TypeableFloat n,\n     Renderable (Text n) b,\n     Renderable (Path V2 n) b)\n  => Axis b V2 n\nr2Axis = Axis\n  { _axisStyle  = fadedColours\n  , _colourBar  = defColourBar\n  , _colourBarR = (0,1)\n  , _axisTitle  = def\n\n  , _legend       = def\n  , _axisPlots    = []\n  , _plotModifier = mempty\n\n  , _axes = pure def\n  }\n\n-- The x-axis ----------------------------------------------------------\n\n-- | Lens onto the x-axis of an 'Axis'.\nxAxis :: R1 c => Lens' (Axis b c n) (SingleAxis b (BaseSpace c) n)\nxAxis = axes . _x\n\n-- | The label for the x-axis. Shorthand for @'xAxis' . 'axisLabelText'@.\nxLabel :: R1 c => Lens' (Axis b c n) String\nxLabel = xAxis . axisLabelText\n\n-- | The minimum x value for the axis. If the value if 'Nothing' (the\n--   'Default'), the bounds will be infered by the plots in the axis.\nxMin :: R1 c => Lens' (Axis b c n) (Maybe n)\nxMin = xAxis . boundMin\n\n-- | The minimum x value for the axis. If the value if 'Nothing' (the\n--   'Default'), the bounds will be infered by the plots in the axis.\nxMax :: R1 c => Lens' (Axis b c n) (Maybe n)\nxMax = xAxis . boundMax\n\n-- The y-axis ----------------------------------------------------------\n\n-- | Lens onto the y-axis of an 'Axis'.\nyAxis :: R2 c => Lens' (Axis b c n) (SingleAxis b (BaseSpace c) n)\nyAxis = axes . _y\n\n-- | The label for the y-axis. Shorthand for @'yAxis' . 'axisLabelText'@.\nyLabel :: R2 c => Lens' (Axis b c n) String\nyLabel = yAxis . axisLabelText\n\n-- | The minimum y value for the axis. If the value if 'Nothing' (the\n--   'Default'), the bounds will be infered by the plots in the axis.\nyMin :: R2 c => Lens' (Axis b c n) (Maybe n)\nyMin = yAxis . boundMin\n\n-- | The minimum y value for the axis. If the value if 'Nothing' (the\n--   'Default'), the bounds will be infered by the plots in the axis.\nyMax :: R2 c => Lens' (Axis b c n) (Maybe n)\nyMax = yAxis . boundMax\n\n-- The z-axis ----------------------------------------------------------\n\n-- | Lens onto the z-axis of an 'Axis'.\nzAxis :: R3 c => Lens' (Axis b c n) (SingleAxis b (BaseSpace c) n)\nzAxis = axes . _z\n\n-- | The label for the z-axis. Shorthand for @'zAxis' . 'axisLabelText'@.\nzLabel :: R3 c => Lens' (Axis b c n) String\nzLabel = zAxis . axisLabelText\n\n-- | The minimum z value for the axis. If the value if 'Nothing' (the\n--   'Default'), the bounds will be infered by the plots in the axis.\nzMin :: R3 c => Lens' (Axis b c n) (Maybe n)\nzMin = zAxis . boundMin\n\n-- | The minimum z value for the axis. If the value if 'Nothing' (the\n--   'Default'), the bounds will be infered by the plots in the axis.\nzMax :: R3 c => Lens' (Axis b c n) (Maybe n)\nzMax = zAxis . boundMax\n\n-- The r-axis ----------------------------------------------------------\n\n-- | Lens onto the radial axis of an 'Axis'.\nrAxis :: Radial c => Lens' (Axis b c n) (SingleAxis b (BaseSpace c) n)\nrAxis = axes . _radial\n\n-- | The label for the radial axis. Shorthand for @'rAxis' . 'axisLabelText'@.\nrLabel :: Radial c => Lens' (Axis b c n) String\nrLabel = rAxis . axisLabelText\n\n-- | The minimum z value for the axis. If the value if 'Nothing' (the\n--   'Default'), the bounds will be infered by the plots in the axis.\n-- rMin :: R3 c => Lens' (Axis b c n) (Maybe n)\n-- rMin = zAxis . boundMin\n\n-- | The minimum radial value for the axis. If the value if 'Nothing'\n--   (the 'Default'), the bounds will be infered by the plots in the\n--   axis.\nrMax :: Radial c => Lens' (Axis b c n) (Maybe n)\nrMax = rAxis . boundMax\n\n-- The theta-axis ------------------------------------------------------\n\n-- | Lens onto the radial axis of an 'Axis'.\nthetaAxis :: Circle c => Lens' (Axis b c n) (SingleAxis b (BaseSpace c) n)\nthetaAxis = axes . el etheta\n\n-- | The label for the radial axis. Shorthand for @'rAxis' . 'axisLabelText'@.\nthetaLabel :: Circle c => Lens' (Axis b c n) String\nthetaLabel = thetaAxis . axisLabelText\n\n\n-- R3 Axis\n\n-- instance (TypeableFloat n, Enum n, Renderable (Text n) b, Renderable (Path V2 n) b)\n--     => Default (Axis b V3 n) where\n--   def = Axis\n--           { _axisTitle      = Nothing\n--           , _axisSize       = mkWidth 300\n--           , _axisPlots      = []\n--           , _axisLegend     = def\n--           , _axisTheme      = coolTheme\n--           , _axisLinearMap  = isometricProjection\n--           , _axisAxisBounds = Bounds $ pure def\n--           , _axisGridLines  = pure def\n--           , _axisLabels     = pure def\n--           , _axisScaling    = pure def\n--           , _axisTickLabels = pure def\n--           , _axisTicks      = pure def\n--           , _axisLines      = pure def\n--           }\n\n-- R3 Axis\n\npolarAxis\n  :: (TypeableFloat n,\n      Renderable (Text n) b,\n      Renderable (Path V2 n) b)\n  => Axis b Polar n\npolarAxis = Axis\n  { _axisStyle  = fadedColours\n  , _colourBar  = defColourBar\n  , _colourBarR = (0,1)\n  , _axisTitle  = def\n\n  , _legend       = def\n  , _axisPlots    = []\n  , _plotModifier = mempty\n\n  , _axes = pure def\n  }\n\n", "meta": {"hexsha": "d8730bde616893a1fdcf1877252e654cab40d2f3", "size": 18033, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Plots/Axis.hs", "max_stars_repo_name": "adamConnerSax/plots", "max_stars_repo_head_hexsha": "7e02bd98e8891d0673e3973a95a9b59db36b6f5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2015-05-28T14:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T05:11:43.000Z", "max_issues_repo_path": "src/Plots/Axis.hs", "max_issues_repo_name": "adamConnerSax/plots", "max_issues_repo_head_hexsha": "7e02bd98e8891d0673e3973a95a9b59db36b6f5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2015-08-22T16:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T00:23:05.000Z", "max_forks_repo_path": "src/Plots/Axis.hs", "max_forks_repo_name": "adamConnerSax/plots", "max_forks_repo_head_hexsha": "7e02bd98e8891d0673e3973a95a9b59db36b6f5b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-03-25T09:55:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T16:27:07.000Z", "avg_line_length": 33.2712177122, "max_line_length": 121, "alphanum_fraction": 0.5957965951, "num_tokens": 5115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21002921340285197}}
{"text": "module Widget.Total\n  ( Total()\n  , mkTotal\n  ) where\n\nimport Import\nimport File\nimport Format.SplitTime\nimport Format.Percentile\n\nimport Statistics.Distribution.Empirical\n\n\ndata Total = Total FileFormat (Zipper EmpiricalDistribution) (Zipper NominalDiffTime) Window\n\ninstance Widget Total where\n  update                 = updateTotal\n  handle                 = handleTotal\n  redraw                 = redrawTotal\n  window (Total _ _ _ w) = w\n\n\nmkTotal :: FileFormat -> [EmpiricalDistribution] -> Window -> Total\nmkTotal f p = Total f (listToZipper p) (listToZipper [0])\n\n\nupdateTotal :: NominalDiffTime -> Total -> Curses Total\nupdateTotal d (Total f c z w) = updateWindow w $ do\n  let nz = replace (curs z + d) z\n      nt = Total f c nz w\n      str = show $ splitTime (sum $ zipperToList nz)\n\n  (rows, columns) <- windowSize\n\n  moveCursor 1 (columns - 14)\n  drawString $\n    if null $ left z\n      then \"----\"\n      else if null $ right c\n             then show $ percentile (curs c) (sum $ zipperToList z)\n             else show $ percentile (curs $ prev c) (sum $ left z)\n\n\n  moveCursor 1 (columns - (fromIntegral $ length str))\n  insertString str\n\n  return nt\n\n\nhandleTotal :: TimerAction -> Total -> Curses Total\nhandleTotal Reset   (Total f c _ w) = return $ mkTotal f (zipperToList c) w\nhandleTotal Advance (Total f c z w) = return $ Total f (next c) (push 0 z) w\nhandleTotal Reverse (Total f c z w) =\n  return $\n    if null $ left z\n      then Total f (prev c) z w\n      else\n        let cz = curs z\n            z' = trunc $ prev z\n            nz = replace (curs z' + cz) z'\n        in Total f (prev c) nz w\nhandleTotal Skip    (Total f c z w) = return $ Total f (next c) (push 0 z) w\nhandleTotal _ t = return t\n\n\nredrawTotal :: Total -> Curses ()\nredrawTotal t@(Total f c z w) = updateWindow w $ do\n  (rows, columns) <- windowSize\n\n  erase\n\n  -- Top horizontal line\n  -- This is the only thing in row 0\n  moveCursor 0 0\n  drawLineH Nothing columns\n\n  -- Current total\n  -- Tag\n  moveCursor 1 (columns - 22)\n  drawString \"Total:\"\n\n  -- Percentile\n  moveCursor 1 (columns - 14)\n  insertString $\n    if null $ left z\n      then \"----\"\n      else if null $ right c\n             then show $ percentile (curs c) (sum $ zipperToList z)\n             else show $ percentile (curs $ prev c) (sum $ left z)\n\n  -- Current cumulative time over all splits\n  do\n     let str = show $ splitTime $ sum $ zipperToList z\n\n     moveCursor 1 (columns - (fromIntegral $ length str))\n     insertString str\n\n\n  -- The following are consistent internal to a run\n  let target = if null $ right c\n                 then curs c\n                 else last $ right c\n\n  -- Personal Best\n  -- Tag\n  moveCursor 2 (columns - 30)\n  drawString \"Personal Best:\"\n\n  do\n    let pb  = personalBest f\n        str = denoteZero $ splitTime pb\n        p   = percentile target pb\n\n    -- Percentile\n    moveCursor 2 (columns - 14)\n    insertString $ ignoreHigh p\n\n    -- Current personal best\n    moveCursor 2 (columns - (fromIntegral $ length str))\n    insertString str\n\n  -- Draw Sum of Bests\n  -- Tag\n  moveCursor 3 (columns - 29)\n  drawString \"Sum of Bests:\"\n\n  do\n    let sob = sumOfBests f\n        str = denoteZero $ splitTime $ sob\n        p   = percentile target sob\n\n    -- Percentile\n    moveCursor 3 (columns - 14)\n\n    if (sob > 0)\n      then insertString $ ignoreHigh p\n      else insertString \"----\"\n\n    -- Current sum of bests\n    moveCursor 3 (columns - (fromIntegral $ length str))\n    insertString str\n\n\n  -- Various vertical lines\n  moveCursor 0 (columns - 15)\n  drawGlyph glyphPlus\n\n  moveCursor 1 (columns - 15)\n  drawLineV Nothing 3\n\n  moveCursor 0 (columns - 10)\n  drawGlyph glyphPlus\n\n  moveCursor 1 (columns - 10)\n  drawLineV Nothing 3\n", "meta": {"hexsha": "38a3492b0d856407c13fe588fe2b9630e6e489bb", "size": 3726, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "timer/Widget/Total.hs", "max_stars_repo_name": "argiopetech/timer", "max_stars_repo_head_hexsha": "1962af91004cddb0e2409a5089164eb343e7eb2e", "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": "timer/Widget/Total.hs", "max_issues_repo_name": "argiopetech/timer", "max_issues_repo_head_hexsha": "1962af91004cddb0e2409a5089164eb343e7eb2e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-01-29T16:51:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-29T16:51:58.000Z", "max_forks_repo_path": "timer/Widget/Total.hs", "max_forks_repo_name": "argiopetech/timer", "max_forks_repo_head_hexsha": "1962af91004cddb0e2409a5089164eb343e7eb2e", "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": 23.8846153846, "max_line_length": 92, "alphanum_fraction": 0.6269457864, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20895467048751784}}
{"text": "{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Cargo(Cargo, Market,\n  randomCargo, randomMarket,\n  showCargo, showMarket,\n  fromMarket, fromCargo,\n  withdraw,\n  tradeScreen, takeScreen)\nwhere\n\nimport System.Random\nimport Text.Printf\nimport Data.List\nimport Control.Monad\nimport Control.Monad.State as State\n\nimport qualified Data.Edison.Assoc.StandardMap as M\nimport Graphics.Rendering.OpenGL as OpenGL\nimport Graphics.UI.SDL as SDL\nimport Graphics.Rendering.FTGL as FTGL\n\nimport Statistics\nimport TextScreen\nimport Space\nimport SDLUtils\n\ntype Cargo = M.FM String Int\ntype Market = M.FM String (Int, Int)\n\ncargonames = sort [\"Grain\", \"Fruit\", \"Gem stones\", \"Firearms\"]\n\nrandomCargo :: IO String\nrandomCargo = chooseIO cargonames\n\nshowCargo :: Cargo -> String\nshowCargo c | M.null c  = \"No cargo\\n\"\n            | otherwise = concatMap (\\(k, v) -> printf \"%-20s-%4d\\n\" k v) (M.toOrdSeq c) \n\nshowMarket :: Market -> String\nshowMarket m = title ++ infos\n  where title = printf \"%-16s%8s%8s\\n\" \"Good\" \"Quantity\" \"Price\"\n        infos = concatMap (\\(n, (q, p)) -> printf \"%-20s%10d%10d\\n\" n q p) (M.toOrdSeq m)\n\nnumCargoItems = length cargonames\n\nrandomMarket :: IO Market\nrandomMarket = do\n  let names = cargonames\n  prices <- replicateM numCargoItems $ randomRIO (5, 15)\n  quantities <- replicateM numCargoItems $ randomRIO (0, 30)\n  return $ M.fromSeq $ zip names (zip quantities prices)\n\nfitCargo :: Cargo -> [(String, Int)]\nfitCargo c = map (\\s -> (s, M.lookupWithDefault 0 s c)) cargonames\n\ncargoToMarket :: Cargo -> Market\ncargoToMarket cargo = \n  foldl' (\\acc x -> M.insert x (M.lookupWithDefault 0 x cargo, 0) acc) M.empty cargonames\n\nfromMarket :: Int -> String -> Market -> Market\nfromMarket q = toMarket (-q)\n\nfromCargo :: Int -> String -> Cargo -> Cargo\nfromCargo q = toCargo (-q)\n\ntoMarket :: Int -> String -> Market -> Market\ntoMarket q = M.adjust (\\(q', p) -> (q' + q, p))\n\ntoCargo :: Int -> String -> Cargo -> Cargo\ntoCargo q n = M.insertWith (+) n q\n\nshowMarketAndCargo :: Bool -> Market -> Cargo -> String\nshowMarketAndCargo t m c = title ++ infos\n  where title = if t\n                  then printf \"%-14s%9s%6s%6s\\n\" \"Good\" \"Quantity\" \"Price\" \"Cargo\"\n                  else printf \"%-17s%-12s%-9s\\n\" \"Good\" \"Captured\" \"Cargo\"\n        infos = if t\n                  then concatMap (\\((n, (q, p)), (_, q')) -> printf \"%-14s%9d%6d%6d\\n\" n q p q') (zip (M.toOrdSeq m) (fitCargo c))\n                  else concatMap (\\((n, (q, _)), (_, q')) -> printf \"%-17s%-12d%-9d\\n\" n q q') (zip (M.toOrdSeq m) (fitCargo c))\n\ntype TradeState = (Market, Cargo, Int, Int)\ntype TakeState = (Cargo, Cargo, Int, Int)\n\nbuy :: Int -> String -> StateT TradeState IO ()\nbuy q n = do\n  (market, cargo, cash, holdspace) <- State.get\n  let mval = M.lookupM n market\n  case mval of\n    Nothing      -> return ()\n    Just (q', p) -> do\n      let totalq = minimum [max 0 q', q, holdspace]\n      let totalp = totalq * p\n      if totalp > cash || totalq == 0\n        then return ()\n        else do\n          State.put (fromMarket totalq n market,\n               toCargo totalq n cargo,\n               subtract totalp cash,\n               holdspace - totalq)\n\nsell :: Int -> String -> StateT TradeState IO ()\nsell q n = do\n  (_, cargo, _, _) <- State.get\n  let mval = M.lookupM n cargo\n  case mval of\n    Nothing -> return ()\n    Just q' -> buy (negate (min q' q)) n\n\ntradeScreen :: String -> Font -> Font -> StateT TradeState IO ()\ntradeScreen = screenGeneric True\n\nwithdraw :: Int -> String -> StateT TradeState IO ()\nwithdraw q n = withStateT (\\(m, c, _, hold) -> (m, c, maxBound, hold)) (buy q n)\n\nscreenGeneric :: Bool -> String -> Font -> Font -> StateT TradeState IO ()\nscreenGeneric trade str f1 f2 = do\n  (market, _, _, _) <- State.get\n  let exitb = ((100, 100), (100, 30))\n      buybuttons  = map (\\i -> ((550, 440 - 50 * fromIntegral i), (100, 30))) [1..numCargoItems]\n      sellbuttons = map (\\i -> ((680, 440 - 50 * fromIntegral i), (100, 30))) [1..numCargoItems]\n      buyactions  = map (\\(n, (_, _)) -> buy  1 n >> return Nothing) (M.toOrdSeq market)\n      sellactions = map (\\(n, (_, _)) -> sell 1 n >> return Nothing) (M.toOrdSeq market)\n      allbuttons  = exitb : (buybuttons ++ sellbuttons)\n      allactions  = return (Just ()) : (buyactions ++ sellactions)\n      bttoaction  = zip allbuttons allactions\n  let handleInput = do\n        events <- liftIO $ pollAllSDLEvents\n        let mbutton = mouseClickInAny height [ButtonLeft] allbuttons events\n        case mbutton of\n          Nothing -> return Nothing\n          Just n  -> case lookup n bttoaction of\n                       Just act -> act\n                       Nothing  -> return Nothing\n  loopTextScreen (do (market', cargo, cash, holdspace) <- State.get\n                     liftIO $ makeTextScreen (10, 500) \n                               [(f1, Color4 1.0 1.0 1.0 1.0, str),\n                                (f2, Color4 1.0 1.0 0.0 1.0, showMarketAndCargo trade market' cargo),\n                                (f1, Color4 1.0 1.0 1.0 1.0, if trade then \"Cash: \" ++ show cash else \"\"),\n                                (f1, Color4 1.0 1.0 1.0 1.0, \"Hold space: \" ++ show holdspace)]\n                               (drawButton (Just (\"Exit\", f1)) exitb >>\n                                mapM_ (drawButton (Just (if trade then \"Buy\" else \"Take\", f1))) buybuttons >>\n                                mapM_ (drawButton (Just (if trade then \"Sell\" else \"Leave\", f1))) sellbuttons))\n                 handleInput\n\ntakeScreen :: String -> Font -> Font -> StateT TakeState IO ()\ntakeScreen str f1 f2 = do\n  (stuff, cargo, cash, hold) <- State.get\n  (_, cargo', _, hold') <- liftIO $ execStateT (screenGeneric False str f1 f2) (cargoToMarket stuff, cargo, cash, hold)\n  State.put (stuff, cargo', cash, hold')\n", "meta": {"hexsha": "6b3768a6afc5ac86ea298587c05ed7bb79227ede", "size": 5758, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Cargo.hs", "max_stars_repo_name": "anttisalonen/starrover2", "max_stars_repo_head_hexsha": "715f69d2c0ea3e213ee13b8b05f770de784c3c4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-01-17T15:29:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T07:10:37.000Z", "max_issues_repo_path": "src/Cargo.hs", "max_issues_repo_name": "anttisalonen/starrover2", "max_issues_repo_head_hexsha": "715f69d2c0ea3e213ee13b8b05f770de784c3c4b", "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": "src/Cargo.hs", "max_forks_repo_name": "anttisalonen/starrover2", "max_forks_repo_head_hexsha": "715f69d2c0ea3e213ee13b8b05f770de784c3c4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-12-11T18:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T22:41:36.000Z", "avg_line_length": 38.644295302, "max_line_length": 130, "alphanum_fraction": 0.6007294199, "num_tokens": 1693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.20889948824831894}}
{"text": "{-# LANGUAGE ViewPatterns #-}\n\nmodule Main where\n\nimport Codec.Image.DevIL\nimport Data.Array.Unboxed\nimport Math.Probably.MCMC\nimport Math.Probably.Sampler\nimport Math.Probably.RandIO\nimport Math.Probably.FoldingStats\nimport Control.Monad.State.Strict \nimport System.Cmd\nimport System.Environment\nimport Data.Array.IO\nimport System.IO\n\nimport Data.Array.Unboxed\nimport Data.Array.Base\nimport qualified Data.Vector.Unboxed as V\nimport qualified Data.StorableVector as SV\nimport qualified Data.StorableVector.Base as SVB\nimport Numeric.LinearAlgebra hiding (find)\nimport qualified Math.Probably.PDF as PDF\nimport Data.List\nimport Data.Maybe\nimport Control.Applicative\nimport Data.Ord\nimport System.Directory\n \nimport Data.IORef\nimport System.IO.Unsafe\n\nimport CVUtils\nimport Edge\nimport CVhelp\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Unsafe.Coerce\n\nbgImRef :: IORef Image\nbgImRef = unsafePerformIO $ newIORef undefined\n\nvisibleMat :: IORef BitImage\nvisibleMat = unsafePerformIO $ newIORef undefined\n\nnogoMat :: IORef BitImage\nnogoMat = unsafePerformIO $ newIORef undefined\n\ninNogoMat x y = unsafePerformIO $ do\n    nm <- readIORef nogoMat\n    return $ readBitImage nm x y \n     \n \ntriRef :: IORef Triangles\ntriRef = unsafePerformIO $ newIORef undefined\n\ngloTris = unsafePerformIO $ readIORef triRef\n\nsdv = 0.5\nsdrot = 0.4\nsddiv = 2\nsddivRot = 4\nsdlen = 0.1\nsdSideDisp = 0.3\n\nhiddenflat = 1\n\nnparticles = 1000\n\ngauss2i :: R -> R-> R-> R-> Sampler (R,R)\ngauss2i m1 sd1 m2 sd2 = do\n   u1 <- unitSample\n   u2 <- unitSample\n   let l = sqrt(-2*log(u1))\n       th = 2*pi*u2\n--   return (sqrt(-2*log(u1))*cos(2*pi*u2)*sd1+m1,\n--           sqrt(-2*log(u1))*sin(2*pi*u2)*sd2+m2)\n   return (l*cos(th)*sd1+m1,\n           l*sin(th)*sd2+m2)\n\nevolve :: Int -> Obj -> Sampler (Obj,Obj)\nevolve retries o@(Obj vlen side len x y rot) = do\n        (nvlen, nside) <- gauss2i vlen sdv 0 sdSideDisp\n--        nside <- gaussD 0 sdSideDisp\n        (nrot, nlen) <- gauss2i rot sdrot len sdlen\n--        nlen <- gaussD len sdlen\n        let no = Obj nvlen nside nlen\n                                 (x+nvlen*cos nrot+nside*cos(nrot-pi/2)) \n                                 (y+nvlen*sin nrot+nside*sin(nrot-pi/2)) nrot\n        if inNogoMat (round $ posx no) (round $ posy no) && retries > 0\n           then evolve (retries-1) o \n           else return $ (o,no)\n\ninvisible :: [((Int,Int),(Int,Int))]\n\ninvisible = [((362,621),(355,654)),\n             ((442,649),(443,674)),\n             ((866,626),(870,658)),\n             ((995,628),(999,657)),\n             ((1149,629),(1167,658)),\n             ((1003,71),(1010,36)),\n             ((422,71),(417,42)),\n             ((157,162),(127,158)),\n             ((1178,469),(1187,501))]\n\n--[ ((963,626), \n--               (999,663))]\n\nvisible :: Int -> Int -> Bool\nvisible x y  = not $ any (\\sqr -> within sqr  x  y) invisible\n\nmkVisibleMat :: IO ()\nmkVisibleMat = do\n    tris <- loadTriangles\n    writeIORef triRef tris    \n    let visIm = mkBitImage 1280 720 \n                 $ \\x -> \\y-> any (pointInTriangle (fromList [realToFrac x, \n                                                              realToFrac y])) \n                                  tris\n                              && visible x y\n    writeIORef visibleMat visIm\n    let nogoIm = mkBitImage 1280 720 \n                 $ \\x -> \\y-> any (\\sqr-> within sqr (realToFrac x) (realToFrac y)) nogo \n                              || (not $ any (pointInTriangle (fromList [realToFrac x, realToFrac y])) tris)\n    writeIORef nogoMat nogoIm\n    return ()\n\n\nobjCentreInvisible :: Obj -> Bool\nobjCentreInvisible (Obj _ _ _ cx cy _) = not $ visible (round cx) (round cy)\n\n\nnogo::  [Square]\nnogo = \n    [((1128,657.5),(1162,627.5)),\n     ((963.25,656),(997,626.5)),\n     ((836.5,653.75),(866.75,624.5)),\n     ((389.75,619.5),(359.75,648.75)),\n     ((162.75,309),(132,278.5)),\n     ((158.5,191.25),(127.25,160.75)),\n     ((422,72.25),(450.75,40.5)),\n     ((757.5,72),(728.5,41.75)),\n     ((1002.75,70.5),(974.25,39.75)),\n     ((1191,194),(1221,222.75)),\n     ((1185,435.25),(1213.5,463.5))]\n--  [ ((963,626), \n--     (997,663))]\n\nnogoPrior :: Obj -> R\nnogoPrior o = sum $ map f nogo\n          where  f sqr | within sqr (posx o) (posy o) = -1e100\n                       | otherwise = 0\n\n{-nogoObj :: Obj -> Bool\nnogoObj o = any (\\sqr-> within sqr (posx o) (posy o)) nogo \n              || (not $ any (pointInTriangle (fromList [posx o, \n                                                        posy o])) gloTris) -}\n\n\nprevprior :: Obj -> (Obj -> R)\nprevprior (Obj vlen side len x y rot) \n      (Obj nvlen nside nlen _ _ nrot) \n        =   PDF.gaussD vlen (sdv/sddiv) nvlen -- \"heavy tailed proposals\"\n          + PDF.gaussD rot (sdrot/sddivRot) nrot\n          + PDF.gaussD len (sdlen/sddiv) nlen\n          + PDF.gaussD 0 (sdSideDisp/sddiv) nside\n          + PDF.gaussD 5 0.5 nlen\n          + uniformLogPdf 3 7 nlen\n\n\ntrack :: StaticParams -> String -> Int -> Int -> Int -> Obj -> StateT Seed IO Obj\ntrack sp vidfnm startfrm nframes frameOffset obj0 = do\n  let outFnm = fileroot vidfnm ++ \".pos\"\n  h<- lift $ openFile outFnm WriteMode \n  lift $ withCString vidfnm open_video\n  res <-  go h (replicate nparticles obj0) [startfrm..startfrm+nframes-1] obj0\n  lift $ hClose h\n  lift $ close_video\n  return res\n   where\n    go _ objs [] o = return o\n    go h objs (i:is) _ = do\n           bgIm <- lift $ readIORef bgImRef\n           nogomat <- lift $ readIORef nogoMat\n--           lift $ putStrLn $\"~/cvutils/extract \"++vidfnm++\" \"++show i \n--           lift $ system $\"~/cvutils/extract \"++vidfnm++\" \"++show i \n--           frame <- lift $ readImage \"extract.png\"\n\n           lift advance\n           diffObjs <- sample $ mapM (evolve 10) objs\n           --lift $ print2  \"pixel1Red = \" (frame!(0,0,0))\n           vismat <- lift $ readIORef visibleMat\n           let wparticles = {-# SCC \"wpart\" #-} (dropLosers $ particleLike sp bgIm vismat nogomat diffObjs)\n           let anyInvisible = {-# SCC \"anyvis\" #-}any objCentreInvisible $ map fst wparticles\n           let npart = if anyInvisible then 5*nparticles else nparticles\n           let wparticles' = if anyInvisible then map (\\(x,w) -> (x,w/hiddenflat)) wparticles else wparticles\n\n           let smws = sumWeights wparticles'\n           let cummSmws = cummWeightedSamples wparticles'\n           lift $ print2 \"fr,npart=\" (i,npart)          \n           --lift $ print2 \"winners= \" (map snd wparticles')\n           --lift $ hFlush stdout\n           nextObjs <- {-# SCC \"resample\" #-} sample $ sequence \n                              $ replicate npart\n                              $ do u <- unitSample\n                                   return . fst . fromJust $ find ((>=u*smws) . snd) cummSmws\n           --lift $ print $ map snd $ take 10 $ reverse $ cummSmws\n\n           let mobj = {-# SCC \"mobj\" #-} \n                   runStat (pure Obj <*> before meanF vellen\n                                     <*> before meanF sideDisp\n                                     <*> before meanF objlen\n                                     <*> before meanF posx\n                                     <*> before meanF posy\n                                     <*> before meanF rot)\n                              nextObjs\n           --lift $ putStrLn $ show (i,mobj, snd $ last $  wparticles)\n           lift $ hPutStrLn h $ show (i,mobj, snd $ last $  wparticles)\n           lift $ hFlush h\n           when (i `rem` 50 == 0) $ {-# SCC \"upbg\" #-} do \n             lift $ updateBgIm mobj\n             when (i `rem` 100 == 0) $ {-# SCC \"outframe\" #-} do \n               lift $ system $\"~/cvutils/extract \"++vidfnm++\" \"++show i \n               frame <- lift $ readImage \"extract.png\"\n               bgIm2 <- lift $ readIORef bgImRef\n               lift $ writeImage (\"bgtrack\"++show (i+frameOffset)++\".png\") bgIm2\n               markedIm1 <- lift $ markEllipse sp (mobj) frame     \n               markedIm <- lift $ markObjsOnImage nextObjs markedIm1\n               lift $ writeImage (\"frame\"++show (i+frameOffset)++\".png\") markedIm\n           go h nextObjs is mobj\n           --return () -- $ mobj:rest\n\ncu2w8 :: CUChar -> Word8\ncu2w8 = unsafeCoerce\n\npixval :: Int -> Int -> CUChar -> Word8\npixval x y c = cu2w8 $ pixel_value (fromIntegral x) (fromIntegral (719-y)) c\n\nparticleLike :: StaticParams -> Image -> BitImage -> BitImage ->[(Obj,Obj)] -> [(Obj,R)]\nparticleLike sp@(SP noise len ecc) bgim vismat nogomat objprs = map pL objprs where\n  radiusi = 2* ceiling (len*ecc) + 2\n  objs = map snd objprs\n  xmin = minOn (posx) objs - radiusi \n  xmax = maxOn (posx) objs+radiusi\n  ymin = minOn (posy) objs-radiusi\n  ymax = maxOn posy objs+radiusi\n  xys = [(x,y) | x <- [xmin.. xmax], y <- [ymin..ymax]]\n  yrng = (ymax-ymin+1)\n--  cvec = fromList [20,25,30]\n  ifvis x y n = if readBitImage vismat x y then n else 0\n  ifInside, ifoutside :: UArray (Int,Int) R\n  ifInside = {-# SCC \"ifinside\" #-} listArray ((xmin,ymin),(xmax,ymax)) \n               [ifvis x y $ (gaussRnn noise 0.07 $ pixval x y 2) \n                           + (gaussRnn noise 0.09 $ pixval x y 1) \n                           + (gaussRnn noise 0.12 $ pixval x y 0)\n                       | (x,y) <- xys]\n  ifoutside = {-# SCC \"ifoutside\" #-} listArray ((xmin,ymin),(xmax,ymax)) \n              [ifvis x y $ (gaussW8nn noise (bgim!(y,x,0)) $ pixval x y 2)\n                           + (gaussW8nn noise (bgim!(y,x,1)) $ pixval x y 1) \n                           + (gaussW8nn noise (bgim!(y,x,2)) $ pixval x y 0)\n                       | (x,y) <- xys]\n \n  pL (old,o@(Obj  _ _ len cx cy rot)) = {-# SCC \"pL\" #-}\n    let lenecc=len*ecc\n        srot = lenecc*sin rot\n        crot = lenecc*cos rot\n        f1x = cx+crot\n        f1y = cy+srot\n        f2x = cx-crot\n        f2y = cy-srot\n--        f :: (R,R) -> R\n        f sm xy@(x, y)  \n--          | not $ readBitImage vismat x y  = 0\n          = {-# SCC \"f\" #-} if dist  f1x f1y   x  y  + dist  f2x f2y   x  y  < 2 * len \n                               then sm+ ifInside!xy\n                               else sm+ifoutside!xy\n--                               then sm + (V.unsafeIndex) ifInside  ((x-xmin)*yrng+(y-ymin))\n --                              else sm + (V.unsafeIndex) ifoutside ((x-xmin)*yrng+(y-ymin))\n--                               then (SVB.unsafeIndex) ifInside  \n--                               else (SVB.unsafeIndex) ifoutside ((x-xmin)*yrng+(y-ymin))\n\n    in if readBitImage nogomat (round $ cx) (round $ cy) \n          then (o,-1e100) \n          else (o, prevprior old o + {-# SCC \"fsum\" #-} (noise * foldl' f 0 xys))\n                   --x <- xs, \n                   --y <- ys]))\n\n\nupdateBgIm (Obj _ _ _ cx cy _) = do\n    im <- readIORef bgImRef\n    mutIm <- thaw im\n    ((loy,lox,_),(hiy,hix,_)) <- getBounds mutIm\n    forM_ [(y,x,c) | x<- [lox..hix], \n                     y<- [loy..hiy],\n                     c<- [0..2], \n                     dist cx cy x y > 30] $ \\ix@(y,x,c)-> do\n      now <- readArray mutIm ix\n      writeArray mutIm ix $ (now `div` 2)  + (pixval x y (rgb2bgr c) `div` 2)\n    newbg <- freeze (mutIm::MImage)\n    writeIORef bgImRef newbg\n\nrgb2bgr :: Int -> CUChar\nrgb2bgr 2 = 0\nrgb2bgr 0 = 2\nrgb2bgr 1 = 1\n\n\n\n{-testCV fvid = do\n     system $ \"~/cvutils/extract \"++fvid++\" 0\"\n     frame <- readImage \"extract.png\"\n     print2 \"via png \" $ frame!(100,100,0)     \n     withCString fvid open_video  \n     advance\n     print2 \"via c \" $ pixel_value 100 (719-100) 2\n     print2 \"via c \" $ pixval 100 100 2\n     close_video -}\n     --error \"foo\" \n\nmain = do\n     ilInit\n     bgnm : fvid : (read -> x) : (read -> y) : (read -> rot) : rest <- getArgs\n     --testCV fvid\n\n\n     bgIm <-readImage bgnm\n     writeIORef bgImRef bgIm\n--     marked <- markBg bgIm\n--     writeImage \"markbg.png\" marked\n     mkVisibleMat\n     print fvid    \n     vm <- readIORef visibleMat\n     writeVisMat \"vismat.png\" vm bgIm\n     let (frStart,nfr) = case rest of \n            [] -> (0,6000)\n            s:[] -> (read s, 6000)\n            s1:s2:_ -> (read s1,read s2)\n\n     --frame0 <-readImage \"extract.png\"\n     {-marked <- markObjsOnImage [Obj (x,y) 0, \n                                Obj (x+1,y) 0, \n                                Obj (x,y+1) 0, \n                                Obj (x+1,y+1) 0] frame0\n     writeImage \"marked.png\" marked -}\n     let --posterior = posteriorV bgIm frame0 (round x,round y)\n         --postAndV v = (posteriorV bgIm frame0 (round x,round y) $ fromList v, v)\n         sp = (SP 218 5 0.9)\n--         rot = negate (pi/7)\n         --initialsV = fromList [x,y,218, 6, rot, 0.9]\n         initObj =  (Obj 1 rot 6 x y rot) \n     --ellim <- markEllipse sp initObj frame0\n     --writeImage \"markell.png\" ellim\n     --print $ nogoPrior (Obj 0 rot 992 650 rot)\n     --print $ nogoPrior (Obj 0 rot 997 650 rot)\n     ----print $ visible 994 650\n     --print $ visible 1000 650\n\n     runRIO $ do\n--         iniampar <- sample $ initialAdaMet 500 1e-4 posterior initialsV\n--         AMPar v _ _ _ <- runAndDiscard 5000 (show . ampPar) iniampar $ adaMet False posterior\n--         lift $ print v\n--         track (v@> 2) (v @> 3) bgIm fvid 3 (v@>0,v@>1)\n         if \"%d\" `isInfixOf` fvid \n            then trackMany sp fvid initObj \n            else track sp fvid frStart nfr 0 $ initObj\n     \n     return () \n\nputS s  = lift . putStrLn $ s\n\ntrackMany sp fvid initObj = go 0 0 initObj where\n  go n frOff obj = do\n     let fnm = takeWhile (/='%') fvid ++ show n ++ \".avi\"\n     putS $ \"looking for \"++fnm\n     exists <- lift $ doesFileExist fnm\n     if exists then reallyGo n fnm frOff obj else putS \"all done\" >> return obj\n  reallyGo n fnm frOff obj0= do\n     lift $ system $ \"~/cvutils/extract \"++fnm++\" \"++show i ++\">tempout\"\n     lns <- lift $ lines `fmap` readFile \"tempout\"\n     let nframes = read $ tail $ dropWhile (/='=') $ head $ filter (\"total frames=\" `isPrefixOf`) lns\n     objNext <- track sp fnm 0 (nframes-2) frOff $ obj0\n     go (n+1) (frOff+nframes-2) objNext\n     \n\n-- initial on wl0: (956,641)\n\n--rm marked.png && track mixed.png ~/Dropbox/woodlice/wl0.avi '(956,641)' && eog marked.png\n--rm -f frame*.png && sudo cabal install --global && track mixed.png ~/Dropbox/woodlice/wl0.avi 956 641 '-0.448'\n\n\n--rm -f frame*.png && sudo cabal install --global && track mixed.png ~/Dropbox/woodlice/wl0.avi 1092 518 '-5.12'", "meta": {"hexsha": "1f80c8481d8aa8d6cd409b58cab0a91390266a53", "size": 14282, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Track.hs", "max_stars_repo_name": "glutamate/cvutils", "max_stars_repo_head_hexsha": "4211023dade7b755eceb2f16b127fdcd7ad16473", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:20:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:20:21.000Z", "max_issues_repo_path": "Track.hs", "max_issues_repo_name": "glutamate/cvutils", "max_issues_repo_head_hexsha": "4211023dade7b755eceb2f16b127fdcd7ad16473", "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": "Track.hs", "max_forks_repo_name": "glutamate/cvutils", "max_forks_repo_head_hexsha": "4211023dade7b755eceb2f16b127fdcd7ad16473", "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.5268542199, "max_line_length": 112, "alphanum_fraction": 0.5425010503, "num_tokens": 4522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.20888058443515464}}
{"text": "module Main\n  ( main\n  ) where\n\nimport           Control.Arrow\nimport           Control.Monad\nimport qualified Graphics.UI.GLFW    as GLFW\nimport           Lens.Micro.Platform ((%~), (&), (.~), (^.))\n\n--import           Numeric.LinearAlgebra\nimport           Application\nimport           Cmd\nimport           Initializable\nimport           Keyboard\nimport           Matrix\nimport           MyState\nimport           Primitives.Cube\nimport           Primitives.Square\nimport           Rotation\nimport           View\n\nnewtype Action = Action\n  { runAction :: MyState -> Update MyState\n  }\n\ntype Update a = State (Cmd Action) a\n\n-- Update\nblueGreen Blue  = Green\nblueGreen Green = Blue\n\nnoRun :: Action\nnoRun = Action return\n\nrun :: (MyState -> Update MyState) -> Action\nrun = Action\n\nrun1 :: (a -> MyState -> Update MyState) -> a -> Action\nrun1 f a = Action (f a)\n\nrun2 :: (a -> b -> MyState -> Update MyState) -> a -> b -> Action\nrun2 f a b = Action (f a b)\n\nshutdown :: MyState -> Update MyState\nshutdown state = do\n  doPrint \"Will shutdown\"\n  doShutdown\n  return state\n\nswapColor :: MyState -> Update MyState\nswapColor state = return $ state & color %~ blueGreen\n\naskTime :: Update ()\naskTime = getTime (run timeFail) (run1 gotTime)\n\ncameraMovement timeDiff = do\n  keyPress GLFW.Key'W (run $ moveCamera timeDiff forward) noRun\n  keyPress GLFW.Key'S (run $ moveCamera timeDiff (negate . forward)) noRun\n  keyPress GLFW.Key'A (run $ moveCamera timeDiff leftward) noRun\n  keyPress GLFW.Key'D (run $ moveCamera timeDiff (negate . leftward)) noRun\n  keyPress GLFW.Key'Space (run $ moveCamera timeDiff upward) noRun\n  keyPress GLFW.Key'C (run $ moveCamera timeDiff (negate . upward)) noRun\n\ncubeMovement timeDiff = do\n  keyPress GLFW.Key'Up (run $ moveSquare timeDiff yHat) noRun\n  keyPress GLFW.Key'Down (run $ moveSquare timeDiff (-yHat)) noRun\n  keyPress GLFW.Key'Right (run $ moveSquare timeDiff xHat) noRun\n  keyPress GLFW.Key'Left (run $ moveSquare timeDiff (-xHat)) noRun\n\nupdateSpacing t = ((sin (t / 2) + 1) * 5) + 2\n\ngotTime :: Double -> MyState -> Update MyState\ngotTime t state = do\n  askTime\n  let timeDiff = t - state ^. lastTime\n  cameraMovement timeDiff\n  cubeMovement timeDiff\n  return $ state & lastTime .~ t & spacing .~ updateSpacing t\n\ntimeFail :: MyState -> Update MyState\ntimeFail state = do\n  askTime\n  doPrint \"Time: failed\"\n  return state\n\nmoveSquare distance dir state =\n  return $ state & cubePos %~\n  (+ (dir * realToFrac (state ^. movementSpeed) * realToFrac distance))\n\nmoveCamera distance dirF state =\n  return $ state & camera . cameraPosition %~\n  (+ (dirF state * realToFrac (state ^. movementSpeed) * realToFrac distance))\n\nforward state = rotateV (negate zHat) $ mkXYRotation x y\n  where\n    (x, y) = state ^. camera . cameraRotation\n\nleftward state = negate $ cross (forward state) yHat\n\nupward state = yHat\n\nmouseMoved x y state\n  | abs x < 300 && abs y < 300 =\n    return $! state & camera . cameraRotation %~\n    (first (+ (negate x * 0.0001)) >>> second (+ (negate y * 0.0001)))\n  | otherwise = return state\n\nresize' :: Int -> Int -> MyState -> Update MyState\nresize' w h state =\n  return $ state & aspectRatio .~ fromIntegral w / fromIntegral h\n\nkeymap =\n  concat\n    [ [KeyPressed GLFW.Key'Escape (\\_ -> run shutdown)]\n    , [ KeyPressed\n          GLFW.Key'M\n          (\\_ -> run (\\state -> stopCaptureMouse >> return state))\n      ]\n    , KeyState <$> [GLFW.Key'Space] <*>\n      [GLFW.KeyState'Pressed, GLFW.KeyState'Repeating] <*>\n      [\\_ -> run swapColor]\n    ]\n\ninitialAction :: MyState -> Action\ninitialAction state =\n  Action $ \\_ -> do\n    askTime\n    return state\n\nsetup = do\n  square <- create\n  cube <- create\n  terrain' <- create\n  let state =\n        initialState & squares .~ [square] & cubes .~ [cube] & terrain .~\n        [terrain']\n  return $ initialAction state\n\ninitState = do\n  keyPresses keymap\n  resize $ run2 resize'\n  runIO setup\n  captureMouse $ run2 mouseMoved\n  return initialState\n\nmyApplication = Application runAction view\n\nmain :: IO ()\nmain = start DefaultConfig initState myApplication\n", "meta": {"hexsha": "69455b3b9d4fbde14c4693f7f826032fe68bd17c", "size": 4058, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "aelg/haskell-render", "max_stars_repo_head_hexsha": "c55fd2e3cfde1899b03910545b835935fef62759", "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": "app/Main.hs", "max_issues_repo_name": "aelg/haskell-render", "max_issues_repo_head_hexsha": "c55fd2e3cfde1899b03910545b835935fef62759", "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": "app/Main.hs", "max_forks_repo_name": "aelg/haskell-render", "max_forks_repo_head_hexsha": "c55fd2e3cfde1899b03910545b835935fef62759", "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": 27.0533333333, "max_line_length": 78, "alphanum_fraction": 0.6614095614, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20885328846094797}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport           Control.Monad.Primitive\nimport           Control.Monad\nimport           Foreign.C.Types\nimport           Foreign.Ptr\nimport           Unsafe.Coerce\nimport           Data.Complex\n\nimport qualified Data.Vector.Generic               as VG\nimport qualified Data.Vector.Generic.Mutable       as VGM\nimport qualified Data.Vector.Storable              as VS\nimport qualified Data.Vector.Storable.Mutable      as VSM\nimport qualified Data.Vector.Fusion.Bundle         as VFS\nimport qualified Data.Vector.Fusion.Stream.Monadic as VFSM\n\nimport           Foreign.Storable.Complex\nimport           Criterion.Main\n\nimport           SDR.FilterInternal\nimport           SDR.Util\nimport           SDR.CPUID\n\ntheBench :: IO ()\ntheBench = do\n    --Setup\n    let size       =  16384\n        numCoeffs  =  128\n        num        =  size - numCoeffs + 1\n        decimation =  4\n        interpolation = 3\n        numCoeffsDiv2  =  64\n\n        coeffsList :: [Float]\n        coeffsList = take numCoeffs [0 ..]\n        coeffs    :: VS.Vector Float\n        coeffs    =  VG.fromList $ take numCoeffs [0 ..]\n        coeffsSym    :: VS.Vector Float\n        coeffsSym    =  VG.fromList $ take numCoeffsDiv2 [0 ..]\n        inBuf     :: VS.Vector Float\n        inBuf     =  VG.fromList $ take size [0 ..]\n        inBufComplex :: VS.Vector (Complex Float)\n        inBufComplex =  VG.fromList $ take size $ do\n            i <- [0..]\n            return $ i :+ i\n        inBufRTLSDR  :: VS.Vector CUChar\n        inBufRTLSDR  =  VG.fromList $ take size [0 ..]\n        inBufBladeRF :: VS.Vector CShort\n        inBufBladeRF =  VG.fromList $ take size [0 ..]\n\n        numConv   = 16386\n        inBufConv :: VS.Vector CUChar\n        inBufConv = VG.fromList $ take size $ concat $ repeat [0 .. 255]\n\n        duplicate :: [a] -> [a]\n        duplicate = concatMap func\n            where func x = [x, x]\n\n        coeffs2 :: VS.Vector Float\n        coeffs2 =  VG.fromList $ duplicate $ take numCoeffs [0 ..]\n\n    outBuf        :: VS.MVector RealWorld Float <- VGM.new size\n    outBufComplex :: VS.MVector RealWorld (Complex Float) <- VGM.new size\n\n    info <- getCPUInfo\n\n    let hasFeatures :: [(CPUInfo -> Bool, a)] -> [a]\n        hasFeatures = map snd . filter (($ info) . fst)\n\n    resampler3 <- resampleCRR2   interpolation decimation coeffsList\n    resampler4 <- resampleCSSERR interpolation decimation coeffsList\n    resampler5 <- resampleCAVXRR interpolation decimation coeffsList\n\n    resampler3C <- resampleCRC    interpolation decimation coeffsList\n    resampler4C <- resampleCSSERC interpolation decimation coeffsList\n    resampler5C <- resampleCAVXRC interpolation decimation coeffsList\n\n    --Benchmarks\n    defaultMain [\n            bgroup \"filter\" [\n                bgroup \"real\" $ hasFeatures [\n                    (const True, bench \"highLevel\"   $ nfIO $ filterHighLevel          coeffs    num inBuf outBuf),\n                    (const True, bench \"imperative1\" $ nfIO $ filterImperative1        coeffs    num inBuf outBuf),\n                    (const True, bench \"imperative2\" $ nfIO $ filterImperative2        coeffs    num inBuf outBuf),\n                    (const True, bench \"c\"           $ nfIO $ filterCRR                coeffs    num inBuf outBuf),\n                    (hasSSE42,   bench \"cSSE\"        $ nfIO $ filterCSSERR             coeffs    num inBuf outBuf),\n                    (hasSSE42,   bench \"cSSESym\"     $ nfIO $ filterCSSESymmetricRR    coeffsSym num inBuf outBuf),\n                    (hasAVX,     bench \"cAVX\"        $ nfIO $ filterCAVXRR             coeffs    num inBuf outBuf),\n                    (hasAVX,     bench \"cAVXSym\"     $ nfIO $ filterCAVXSymmetricRR    coeffsSym num inBuf outBuf)\n                ],\n                bgroup \"complex\" $ hasFeatures [\n                    (const True, bench \"highLevel\"   $ nfIO $ filterHighLevel          coeffs    num inBufComplex outBufComplex),\n                    (const True, bench \"c\"           $ nfIO $ filterCRC                coeffs    num inBufComplex outBufComplex),\n                    (hasSSE42,   bench \"cSSE\"        $ nfIO $ filterCSSERC             coeffs2   num inBufComplex outBufComplex),\n                    (hasSSE42,   bench \"cSSE2\"       $ nfIO $ filterCSSERC2            coeffs    num inBufComplex outBufComplex),\n                    (hasSSE42,   bench \"cSSESym\"     $ nfIO $ filterCSSESymmetricRC    coeffsSym num inBufComplex outBufComplex),\n                    (hasAVX,     bench \"cAVX\"        $ nfIO $ filterCAVXRC             coeffs2   num inBufComplex outBufComplex),\n                    (hasAVX,     bench \"cAVX2\"       $ nfIO $ filterCAVXRC2            coeffs    num inBufComplex outBufComplex),\n                    (hasAVX,     bench \"cAVXSym\"     $ nfIO $ filterCAVXSymmetricRC    coeffsSym num inBufComplex outBufComplex)\n                ]\n            ],\n            bgroup \"decimate\" [\n                bgroup \"real\" $ hasFeatures [\n                    (const True, bench \"highLevel\"   $ nfIO $ decimateHighLevel        decimation coeffs    (num `quot` decimation) inBuf outBuf),\n                    (const True, bench \"c\"           $ nfIO $ decimateCRR              decimation coeffs    (num `quot` decimation) inBuf outBuf),\n                    (hasSSE42,   bench \"cSSE\"        $ nfIO $ decimateCSSERR           decimation coeffs    (num `quot` decimation) inBuf outBuf),\n                    (hasSSE42,   bench \"cSSESym\"     $ nfIO $ decimateCSSESymmetricRR  decimation coeffsSym (num `quot` decimation) inBuf outBuf),\n                    (hasAVX,     bench \"cAVX\"        $ nfIO $ decimateCAVXRR           decimation coeffs    (num `quot` decimation) inBuf outBuf),\n                    (hasAVX,     bench \"cAVXSym\"     $ nfIO $ decimateCAVXSymmetricRR  decimation coeffsSym (num `quot` decimation) inBuf outBuf)\n                ],\n                bgroup \"complex\" $ hasFeatures [\n                    (const True, bench \"highLevel\"   $ nfIO $ decimateHighLevel        decimation coeffs    (num `quot` decimation) inBufComplex outBufComplex),\n                    (const True, bench \"c\"           $ nfIO $ decimateCRC              decimation coeffs    (num `quot` decimation) inBufComplex outBufComplex),\n                    (hasSSE42,   bench \"cSSE\"        $ nfIO $ decimateCSSERC           decimation coeffs2   (num `quot` decimation) inBufComplex outBufComplex),\n                    (hasSSE42,   bench \"cSSE2\"       $ nfIO $ decimateCSSERC2          decimation coeffs    (num `quot` decimation) inBufComplex outBufComplex),\n                    (hasSSE42,   bench \"cSSESym\"     $ nfIO $ decimateCSSESymmetricRC  decimation coeffsSym (num `quot` decimation) inBufComplex outBufComplex),\n                    (hasAVX,     bench \"cAVX\"        $ nfIO $ decimateCAVXRC           decimation coeffs2   (num `quot` decimation) inBufComplex outBufComplex),\n                    (hasAVX,     bench \"cAVX2\"       $ nfIO $ decimateCAVXRC2          decimation coeffs    (num `quot` decimation) inBufComplex outBufComplex),\n                    (hasAVX,     bench \"cAVXSym\"     $ nfIO $ decimateCAVXSymmetricRC  decimation coeffsSym (num `quot` decimation) inBufComplex outBufComplex)\n                ]\n            ],\n            bgroup \"resample\" [\n                bgroup \"real\" $ hasFeatures [\n                    (const True, bench \"highLevel\"   $ nfIO $ resampleHighLevel        interpolation decimation coeffs 0 (num `quot` decimation) inBuf outBuf),\n                    (const True, bench \"c\"           $ nfIO $ resampleCRR              (num `quot` decimation) interpolation decimation 0 coeffs inBuf outBuf),\n                    (const True, bench \"c2\"          $ nfIO $ resampler3               (num `quot` decimation) 0 inBuf outBuf),\n                    (hasSSE42,   bench \"cSSE\"        $ nfIO $ resampler4               (num `quot` decimation) 0 inBuf outBuf),\n                    (hasAVX,     bench \"cAVX\"        $ nfIO $ resampler5               (num `quot` decimation) 0 inBuf outBuf)\n                ],\n                bgroup \"complex\" $ hasFeatures [\n                    (const True, bench \"highLevel\"   $ nfIO $ resampleHighLevel        interpolation decimation coeffs 0 (num `quot` decimation) inBufComplex outBufComplex),\n                    (const True, bench \"c\"           $ nfIO $ resampler3C               (num `quot` decimation) 0 inBufComplex outBufComplex),\n                    (const True, bench \"SSE\"         $ nfIO $ resampler4C               (num `quot` decimation) 0 inBufComplex outBufComplex),\n                    (const True, bench \"AVX\"         $ nfIO $ resampler5C               (num `quot` decimation) 0 inBufComplex outBufComplex)\n                ]\n            ],\n            bgroup \"scaling\" $ hasFeatures [\n                (const True, bench \"c\"               $ nfIO $ scaleC    0.3 inBuf outBuf),\n                (hasSSE42,   bench \"cSSE\"            $ nfIO $ scaleCSSE 0.3 inBuf outBuf),\n                (hasAVX,     bench \"cAVX\"            $ nfIO $ scaleCAVX 0.3 inBuf outBuf)\n            ],\n            bgroup \"conversion\" [\n                bgroup \"RTLSDR\" $ hasFeatures [\n                    (const True, bench \"h\"    $ nf (interleavedIQUnsigned256ToFloat :: VS.Vector CUChar -> VS.Vector (Complex Float)) inBufRTLSDR),\n                    (const True, bench \"c\"    $ nf interleavedIQUnsignedByteToFloat    inBufRTLSDR),\n                    (hasSSE42,   bench \"cSSE\" $ nf interleavedIQUnsignedByteToFloatSSE inBufRTLSDR),\n                    (hasAVX2,    bench \"cAVX\" $ nf interleavedIQUnsignedByteToFloatAVX inBufRTLSDR)\n                ],\n                bgroup \"BladeRF\" $ hasFeatures [\n                    (const True, bench \"h\"    $ nf (interleavedIQSigned2048ToFloat :: VS.Vector CShort -> VS.Vector (Complex Float))  inBufBladeRF),\n                    (const True, bench \"c\"    $ nf interleavedIQSignedWordToFloat    inBufBladeRF),\n                    (hasSSE42,   bench \"cSSE\" $ nf interleavedIQSignedWordToFloatSSE inBufBladeRF),\n                    (hasAVX2,    bench \"cAVX\" $ nf interleavedIQSignedWordToFloatAVX inBufBladeRF)\n                ]\n            ]\n        ]\n\nmain = theBench\n", "meta": {"hexsha": "eefb759a750021e9b9373b295c3dad9fa407ea95", "size": 10158, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/Benchmarks.hs", "max_stars_repo_name": "adamwalker/sdr", "max_stars_repo_head_hexsha": "c7d4d7dacb41039976e11df93adb10d3570cb8ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 94, "max_stars_repo_stars_event_min_datetime": "2015-05-10T02:13:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T16:32:22.000Z", "max_issues_repo_path": "benchmarks/Benchmarks.hs", "max_issues_repo_name": "peixian/sdr", "max_issues_repo_head_hexsha": "55bc865ea6c6df2d7e6e9fe6c4c3d02f76a5b2ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-05-05T19:20:46.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-02T04:19:15.000Z", "max_forks_repo_path": "benchmarks/Benchmarks.hs", "max_forks_repo_name": "adamwalker/sdr", "max_forks_repo_head_hexsha": "c7d4d7dacb41039976e11df93adb10d3570cb8ce", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-07-12T11:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T07:41:21.000Z", "avg_line_length": 63.8867924528, "max_line_length": 173, "alphanum_fraction": 0.5587714117, "num_tokens": 2649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.20883738738673852}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Models.Rover\n  (\n    Rover (..)\n  , getPolicyInput\n  , nnVars\n  , nnVarsNaive\n  ) where\n\nimport Models.RoverDomain\nimport Models.Location\nimport Models.State\n\nimport qualified Data.Map as Map\nimport Data.List (sortOn)\nimport Numeric.LinearAlgebra.HMatrix (Vector, fromList, (!))\n\nimport NN.NeuralNetwork\n\nimport System.IO.Unsafe\n\ndata Rover = Rover\n             {\n               _roverState :: State\n             , _roverNet   :: ((Network Double), NNVars)\n             , _roverUuid :: Int\n             }\n           | Traitor\n             {\n               _roverState :: State\n             , _roverNet :: ((Network Double), NNVars)\n             , _roverUuid :: Int\n             }\n             \n\nnnVars :: NNVars\nnnVars = Map.fromList [(\"numberInputs\", 12)\n                      ,(\"numberHidden\", 13)\n                      ,(\"numberOutputs\", 2)\n                      ,(\"timesToTrain\", 3)\n                      ,(\"learningRate\", 0.8)\n                      ,(\"sigmoidOrTanh\", 0)\n                      ,(\"randomLowerBound\", (-10))\n                      ,(\"randomUpperBound\", 10)\n                      ,(\"mutationRate\", 0.1)\n                      ,(\"gaussianStdDev\",1)\n                      ,(\"gaussianMean\",0)]\n\nnnVarsNaive :: NNVars\nnnVarsNaive = Map.fromList [(\"numberInputs\", 8)\n                           ,(\"numberHidden\", 13)\n                           ,(\"numberOutputs\", 2)\n                           ,(\"timesToTrain\", 3)\n                           ,(\"learningRate\", 0.8)\n                           ,(\"sigmoidOrTanh\", 0)\n                           ,(\"randomLowerBound\", (-10))\n                           ,(\"randomUpperBound\", 10)\n                           ,(\"mutationRate\", 0.1)\n                           ,(\"gaussianStdDev\",1)\n                           ,(\"gaussianMean\",0)]\n         \ninstance Actor Rover where\n  getState (Rover s _ _) = s\n  getState (Traitor s _ _) = s\n  setState (Rover _ n i) s = Rover s n i\n  setState (Traitor _ n i) s = Traitor s n i\n  getID (Rover _ _ i) = i\n  getID (Traitor _ _ i) = i\n  getMove = getNextMove\n  move r cmd = setState r (moveState (getState r) cmd)\n  resetActor (x,y) g r = let b = (fromIntegral x, fromIntegral y)\n                             (g', s) = getRandomState g b\n                         in (g', setState r s)\n  \n\ninstance Agent Rover where\n  setPolicy (Rover s (_,v) i) n = Rover s (n,v) i\n  setPolicy (Traitor s (_,v) i) n = Traitor s (n,v) i\n  getPolicy (Rover _ n _) = fst n\n  getPolicy (Traitor _ n _) = fst n\n  getFitness d r = let s = getGlobalScore d in if isLoyal r then s else (-1) * s\n  isLoyal (Rover _ _ _) = True\n  isLoyal (Traitor _ _ _) = False\n\ninstance Show Rover where\n  show (Rover _ _ i) = \"R\" ++ (show i)\n  show (Traitor _ _ i) = \"T\" ++ (show i)\n\ninstance Eq Rover where\n  (==) r1 r2 = getID r1 == getID r2\n  \ngetNextMove domain agent =\n  let cmd = toCmd $ get (getVars agent) (getPolicy agent) (getPolicyInput domain agent)\n      currentState = getState agent\n  in if inBounds domain (moveState currentState cmd) then cmd\n     else getBackupMove domain currentState cmd\n\ngetPolicyInput dom a = let as = getState a\n                           likeMe = if isLoyal a then isLoyal else not . isLoyal\n                           numInputs = getNumInputs a\n                           \n                           agentStates = map getState $ (getAgents dom)\n                           otherStates = map getState $ filter (not . likeMe) (getAgents dom)\n                           scoreStates = map getState (getScoring dom)\n                           actorStates = filter (/= as) agentStates\n\n                           quadActor = map (getQuad as) actorStates\n                           quadScore = map ((+) 4 . getQuad as) scoreStates\n                           quadOther = map ((+) 8 . getQuad as) otherStates\n\n                           actorSWithQuad = zip actorStates quadActor\n                           scoreSWithQuad = zip scoreStates quadScore\n                           otherSWithQuad = zip otherStates quadOther\n                           all = actorSWithQuad ++ scoreSWithQuad ++ otherSWithQuad\n                           \n                           allOverR = map (\\(a',q) -> (1.0 / (stateDistance as a'), q)) all\n                           blanks = zip (replicate numInputs 0.0) [1..numInputs]\n                           allSorted = sortOn snd (allOverR ++ blanks)\n                       in fromList $ take numInputs $ map fst $ compress allSorted\n\n-- given a list sorted by the second tuple value, if the second values are equal for\n-- consecutive elements, sum the fst value\ncompress :: (Num a, Eq b) => [(a, b)] -> [(a, b)]\ncompress [] = []\ncompress (x:[]) = [x]\ncompress (x:y:zs) = if snd x == snd y then compress $ (fst x + fst y, snd x):zs\n                    else x:(compress (y:zs))\n\ngetNumInputs :: Rover -> Int\ngetNumInputs r = round $ (getVars r) Map.! \"numberInputs\"\n\ngetVars (Rover _ (_,v) _) = v\ngetVars (Traitor _ (_,v) _) = v\n\n-- difference in locations, as vector, then get angle with atan2 y' x'.\n-- Rotate angle by x's orientation backwards, then compare to sectors\ngetBackupMove dom s (Move dx dy) =\n  if inBounds dom (moveState s (Move dx 0)) then Move dx 0\n  else if inBounds dom (moveState s (Move 0 dy)) then Move 0 dy\n       else Turn (pi / 2)\ngetBackupMove _ _ _ = Turn (pi / 2)\n\n-- Assuming tanh activation function, output will be between -1 and 1\n-- In that case, take values directly as x and y and normalize to unit vector\n-- Test: Don't normalize\ntoCmd :: Vector Double -> Cmd\ntoCmd vec = let (x,y) = (vec ! 0, vec ! 1)\n            in Move x y\n", "meta": {"hexsha": "e23426377fc1c7e2918f31497ca754826fbac808", "size": 5634, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Models/Rover.hs", "max_stars_repo_name": "eklinkhammer/rover-domain", "max_stars_repo_head_hexsha": "c1530883e477b1f38cb351a999bd424dbf308ab6", "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/Models/Rover.hs", "max_issues_repo_name": "eklinkhammer/rover-domain", "max_issues_repo_head_hexsha": "c1530883e477b1f38cb351a999bd424dbf308ab6", "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/Models/Rover.hs", "max_forks_repo_name": "eklinkhammer/rover-domain", "max_forks_repo_head_hexsha": "c1530883e477b1f38cb351a999bd424dbf308ab6", "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": 37.56, "max_line_length": 93, "alphanum_fraction": 0.5312389066, "num_tokens": 1450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.2081643008313568}}
{"text": "{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE KindSignatures        #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PolyKinds             #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE StandaloneDeriving    #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-|\nModule      : Grenade.Layers.Concat\nDescription : Concatenation layer\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n\nThis module provides the concatenation layer, which runs two chilld layers in parallel and combines their outputs.\n-}\nmodule Grenade.Recurrent.Layers.ConcatRecurrent (\n    ConcatRecurrent (..)\n  ) where\n\nimport           Data.Serialize\n\nimport           Data.Singletons\nimport           GHC.TypeLits\n\n#if MIN_VERSION_base(4,9,0)\nimport           Data.Kind                    (Type)\n#endif\n\nimport           Grenade.Core\nimport           Grenade.Recurrent.Core\n\nimport           Numeric.LinearAlgebra.Static (R, split, ( # ))\n\n-- | A Concatentating Layer.\n--\n-- This layer shares it's input state between two sublayers, and concatenates their output.\n--\n-- With Networks able to be Layers, this allows for very expressive composition of complex Networks.\n--\n-- The Concat layer has a few instances, which allow one to flexibly \"bash\" together the outputs.\n--\n-- Two 1D vectors, can go to a 2D shape with 2 rows if their lengths are identical.\n-- Any 2 1D vectors can also become a longer 1D Vector.\n--\n-- 3D images become 3D images with more channels. The sizes must be the same, one can use Pad\n-- and Crop layers to ensure this is the case.\ndata ConcatRecurrent :: Shape -> Type -> Shape -> Type -> Type where\n  ConcatRecLeft  :: !x -> !y -> ConcatRecurrent m (Recurrent x) n (FeedForward y)\n  ConcatRecRight :: !x -> !y -> ConcatRecurrent m (FeedForward x) n (Recurrent y)\n  ConcatRecBoth  :: !x -> !y -> ConcatRecurrent m (Recurrent x) n   (Recurrent y)\n\ninstance (Show x, Show y) => Show (ConcatRecurrent m (p x) n (q y)) where\n  show (ConcatRecLeft x y)  = \"ConcatRecLeft\\n\" ++ show x ++ \"\\n\" ++ show y\n  show (ConcatRecRight x y) = \"ConcatRecRight\\n\" ++ show x ++ \"\\n\" ++ show y\n  show (ConcatRecBoth x y)  = \"ConcatRecBoth\\n\" ++ show x ++ \"\\n\" ++ show y\n\ninstance (RecurrentUpdateLayer x, UpdateLayer y) => UpdateLayer (ConcatRecurrent m (Recurrent x) n (FeedForward y)) where\n  type Gradient (ConcatRecurrent m (Recurrent x) n (FeedForward y)) = (Gradient x, Gradient y)\n  runUpdate lr (ConcatRecLeft x y) (x', y')\n    = ConcatRecLeft (runUpdate lr x x') (runUpdate lr y y')\n\ninstance (RandomLayer x, RandomLayer y) => RandomLayer (ConcatRecurrent m (Recurrent x) n (FeedForward y)) where\n  createRandomWith m gen\n    = ConcatRecLeft <$> createRandomWith m gen <*> createRandomWith m gen\n\ninstance (UpdateLayer x, RecurrentUpdateLayer y) => UpdateLayer (ConcatRecurrent m (FeedForward x) n (Recurrent y)) where\n  type Gradient (ConcatRecurrent m (FeedForward x) n (Recurrent y)) = (Gradient x, Gradient y)\n  runUpdate lr (ConcatRecRight x y) (x', y')\n    = ConcatRecRight (runUpdate lr x x') (runUpdate lr y y')\n\ninstance (RandomLayer x, RandomLayer y) => RandomLayer (ConcatRecurrent m (FeedForward x) n (Recurrent y)) where\n  createRandomWith m gen\n    = ConcatRecRight <$> createRandomWith m gen <*> createRandomWith m gen\n\ninstance (RecurrentUpdateLayer x, RecurrentUpdateLayer y) => UpdateLayer (ConcatRecurrent m (Recurrent x) n (Recurrent y)) where\n  type Gradient (ConcatRecurrent m (Recurrent x) n (Recurrent y)) = (Gradient x, Gradient y)\n  runUpdate lr (ConcatRecBoth x y) (x', y')\n    = ConcatRecBoth (runUpdate lr x x') (runUpdate lr y y')\n\ninstance (RandomLayer x, RandomLayer y) => RandomLayer (ConcatRecurrent m (Recurrent x) n (Recurrent y)) where\n  createRandomWith m gen\n    = ConcatRecBoth <$> createRandomWith m gen <*> createRandomWith m gen\n\ninstance (RecurrentUpdateLayer x, UpdateLayer y) => RecurrentUpdateLayer (ConcatRecurrent m (Recurrent x) n (FeedForward y)) where\n  type RecurrentShape (ConcatRecurrent m (Recurrent x) n (FeedForward y)) = RecurrentShape x\n\ninstance (UpdateLayer x, RecurrentUpdateLayer y) => RecurrentUpdateLayer (ConcatRecurrent m (FeedForward x) n (Recurrent y)) where\n  type RecurrentShape (ConcatRecurrent m (FeedForward x) n (Recurrent y)) = RecurrentShape y\n\ninstance (RecurrentUpdateLayer x, RecurrentUpdateLayer y) => RecurrentUpdateLayer (ConcatRecurrent m (Recurrent x) n (Recurrent y)) where\n  type RecurrentShape (ConcatRecurrent m (Recurrent x) n (Recurrent y)) =  RecurrentInputs '[ Recurrent x, Recurrent y ]\n\ninstance ( SingI i\n         , Layer x i ('D1 m)\n         , RecurrentLayer y i ('D1 n)\n         , KnownNat o\n         , KnownNat m\n         , KnownNat n\n         , o ~ (m + n)\n         , n ~ (o - m)\n         , (m <=? o) ~ 'True\n         ) => RecurrentLayer (ConcatRecurrent ('D1 m) (FeedForward x) ('D1 n) (Recurrent y)) i ('D1 o) where\n  type RecTape (ConcatRecurrent ('D1 m) (FeedForward x) ('D1 n) (Recurrent y)) i ('D1 o) = (Tape x i ('D1 m), RecTape y i ('D1 n))\n\n  runRecurrentForwards (ConcatRecRight x y) s input =\n    let (xT, xOut :: S ('D1 m))       = runForwards x input\n        (yT, side, yOut :: S ('D1 n)) = runRecurrentForwards y s input\n    in case (xOut, yOut) of\n        (S1D xOut', S1D yOut') ->\n            ((xT, yT), side, S1D (xOut' # yOut'))\n\n  runRecurrentBackwards (ConcatRecRight x y) (xTape, yTape) s (S1D o) =\n    let (ox :: R m , oy :: R n) = split o\n        (x', xB :: S i)         = runBackwards x xTape (S1D ox)\n        (y', side, yB :: S i)   = runRecurrentBackwards y yTape s (S1D oy)\n    in  ((x', y'), side, xB + yB)\n\ninstance ( SingI i\n         , RecurrentLayer x i ('D1 m)\n         , Layer y i ('D1 n)\n         , KnownNat o\n         , KnownNat m\n         , KnownNat n\n         , o ~ (m + n)\n         , n ~ (o - m)\n         , (m <=? o) ~ 'True\n         ) => RecurrentLayer (ConcatRecurrent ('D1 m) (Recurrent x) ('D1 n) (FeedForward y)) i ('D1 o) where\n  type RecTape (ConcatRecurrent ('D1 m) (Recurrent x) ('D1 n) (FeedForward y)) i ('D1 o) = (RecTape x i ('D1 m), Tape y i ('D1 n))\n\n  runRecurrentForwards (ConcatRecLeft x y) s input =\n    let (xT, side, xOut :: S ('D1 m)) = runRecurrentForwards x s input\n        (yT, yOut :: S ('D1 n))       = runForwards y input\n    in case (xOut, yOut) of\n        (S1D xOut', S1D yOut') ->\n            ((xT, yT), side, S1D (xOut' # yOut'))\n\n  runRecurrentBackwards (ConcatRecLeft x y) (xTape, yTape) s (S1D o) =\n    let (ox :: R m , oy :: R n) = split o\n        (x', side, xB :: S i)   = runRecurrentBackwards x xTape s (S1D ox)\n        (y', yB :: S i)         = runBackwards y yTape (S1D oy)\n    in  ((x', y'), side, xB + yB)\n\ninstance ( SingI i\n         , RecurrentLayer x i ('D1 m)\n         , RecurrentLayer y i ('D1 n)\n         , Fractional (RecurrentShape x)\n         , Fractional (RecurrentShape y)\n         , KnownNat o\n         , KnownNat m\n         , KnownNat n\n         , o ~ (m + n)\n         , n ~ (o - m)\n         , (m <=? o) ~ 'True\n         ) => RecurrentLayer (ConcatRecurrent ('D1 m) (Recurrent x) ('D1 n) (Recurrent y)) i ('D1 o) where\n  type RecTape (ConcatRecurrent ('D1 m) (Recurrent x) ('D1 n) (Recurrent y)) i ('D1 o) = (RecTape x i ('D1 m), RecTape y i ('D1 n))\n\n  runRecurrentForwards (ConcatRecBoth x y) (sx :~@+> (sy :~@+> RINil)) input =\n    let (xT, s'x, xOut :: S ('D1 m)) = runRecurrentForwards x sx input\n        (yT, s'y, yOut :: S ('D1 n)) = runRecurrentForwards y sy input\n    in case (xOut, yOut) of\n        (S1D xOut', S1D yOut') ->\n            ((xT, yT), (s'x :~@+> (s'y :~@+> RINil)), S1D (xOut' # yOut'))\n\n  runRecurrentBackwards (ConcatRecBoth x y) (xTape, yTape) (sx :~@+> (sy :~@+> RINil)) (S1D o) =\n    let (ox :: R m , oy :: R n) = split o\n        (x', s'x, xB :: S i)    = runRecurrentBackwards x xTape sx (S1D ox)\n        (y', s'y, yB :: S i)    = runRecurrentBackwards y yTape sy (S1D oy)\n    in  ((x', y'), (s'x :~@+> (s'y :~@+> RINil)), xB + yB)\n\ninstance (Serialize a, Serialize b) => Serialize (ConcatRecurrent sa (FeedForward a) sb (Recurrent b)) where\n  put (ConcatRecRight a b) = put a *> put b\n  get = ConcatRecRight <$> get <*> get\n\ninstance (Serialize a, Serialize b) => Serialize (ConcatRecurrent sa (Recurrent a) sb (Recurrent b)) where\n  put (ConcatRecBoth a b) = put a *> put b\n  get = ConcatRecBoth <$> get <*> get\n\ninstance (Serialize a, Serialize b) => Serialize (ConcatRecurrent sa (Recurrent a) sb (FeedForward b)) where\n  put (ConcatRecLeft a b) = put a *> put b\n  get = ConcatRecLeft <$> get <*> get\n\n\n-------------------- GNum instances --------------------\n\ninstance (GNum x, GNum y) => GNum (ConcatRecurrent m (p x) n (q y)) where\n  n |* (ConcatRecLeft x y) = ConcatRecLeft (n |* x) (n |* y)\n  n |* (ConcatRecRight x y) = ConcatRecRight (n |* x) (n |* y)\n  n |* (ConcatRecBoth x y) = ConcatRecBoth (n |* x) (n |* y)\n  (ConcatRecLeft x1 y1) |+ (ConcatRecLeft x2 y2) = ConcatRecLeft (x1 |+ x2) (y1 |+ y2)\n  (ConcatRecRight x1 y1) |+ (ConcatRecRight x2 y2) = ConcatRecRight (x1 |+ x2) (y1 |+ y2)\n  (ConcatRecBoth x1 y1) |+ (ConcatRecBoth x2 y2) = ConcatRecBoth (x1 |+ x2) (y1 |+ y2)\n", "meta": {"hexsha": "1fc6e292c2219d3e7458fab78da69efc4afe6588", "size": 9321, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Recurrent/Layers/ConcatRecurrent.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Recurrent/Layers/ConcatRecurrent.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-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/Grenade/Recurrent/Layers/ConcatRecurrent.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 46.605, "max_line_length": 137, "alphanum_fraction": 0.6205342774, "num_tokens": 2981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20794889542627432}}
{"text": "{-# LANGUAGE CPP, DataKinds, GADTs, KindSignatures, RankNTypes,\n             StandaloneDeriving, TypeOperators #-}\n#if !MIN_VERSION_base(4,16,0)\n{-# LANGUAGE IncoherentInstances #-}\n#endif\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n-- | The second component of dual numbers, @Delta@, with its semantics.\n-- Neel Krishnaswami calls it \\\"sparse vector expressions\\\",\n-- and indeed even in the simplest case of an objective function\n-- defined on scalars only, the codomain of the function that computes\n-- gradients from such delta expressions is a set of vectors, because\n-- the gradient of an @R^n@ to @R@ function is an @R^n@ vector.\n--\n-- The \\'sparsity\\' is less obvious when the domain of the function consists\n-- of multiple vectors, matrices and tensors and when the expressions themselves\n-- contain vectors, matrices and tensors. However, a single tiny delta\n-- expression (e.g., a sum of two variables) may denote a vector of matrices.\n-- Even a delta expression containing a big matrix denotes something much\n-- bigger: a whole vector of such matrices and more.\n--\n-- The algebraic structure here is an extension of vector space.\n-- The crucial extra constructor of a variable is used both to represent\n-- sharing in order to avoid exponential blowup and to replace the one-hot\n-- access to parameters with something cheaper and more uniform.\n-- A lot of the remaining additional structure is for introducing\n-- and reducing dimensions (ranks).\n--\n-- This is an internal API now, superseded by \"HordeAd.Core.DualClass\"\n-- that permits other kinds of second component of dual numbers,\n-- e.g., the same as primal component, for fast computation\n-- of forward derivatives (because @derivativeFromDelta@ below,\n-- computing derivatives from delta-expressions, is slow once the expressions\n-- grow large enough to affect cache misses).\nmodule HordeAd.Internal.Delta\n  ( -- * Abstract syntax trees of the delta expressions\n    Delta0 (..), Delta1 (..), Delta2 (..), DeltaX (..), DeltaS (..)\n  , -- * Delta expression identifiers\n    DeltaId, toDeltaId, convertDeltaId\n  , -- * Evaluation of the delta expressions\n    DeltaBinding\n  , DeltaState (..)\n  , Domain0, Domain1, Domain2, DomainX, Domains\n  , gradientFromDelta, derivativeFromDelta, ppBindings\n  , bindInState0, bindInState1, bindInState2, bindInStateX\n  , isTensorDummy\n  , CodeOut(..)\n  ) where\n\nimport Prelude\n\nimport           Control.Exception (assert)\nimport           Control.Monad (unless, zipWithM_)\nimport           Control.Monad.ST.Strict (ST, runST)\nimport qualified Data.Array.Convert\nimport qualified Data.Array.Dynamic as OTB\nimport qualified Data.Array.DynamicS as OT\nimport qualified Data.Array.Internal\nimport qualified Data.Array.Internal.DynamicG\nimport qualified Data.Array.Internal.DynamicS\nimport qualified Data.Array.Shaped as OSB\nimport qualified Data.Array.ShapedS as OS\nimport           Data.Kind (Type)\nimport           Data.List (foldl')\nimport           Data.Proxy (Proxy)\nimport qualified Data.Strict.Vector as Data.Vector\nimport qualified Data.Strict.Vector.Autogen.Mutable as Data.Vector.Mutable\nimport qualified Data.Vector.Generic as V\nimport qualified Data.Vector.Generic.Mutable as VM\nimport qualified Data.Vector.Storable.Mutable\nimport           GHC.TypeLits (KnownNat, Nat, natVal, type (+))\nimport           Numeric.LinearAlgebra (Matrix, Numeric, Vector, (#>), (<.>))\nimport qualified Numeric.LinearAlgebra as HM\nimport           Text.Show.Pretty (ppShow)\n\nimport qualified HordeAd.Internal.MatrixOuter as MO\nimport           HordeAd.Internal.OrthotopeOrphanInstances (liftVS2, liftVT2)\n\n-- * Abstract syntax trees of the delta expressions\n\n-- | This is the grammar of delta-expressions at tensor rank 0, that is,\n-- at scalar level. The first few operations have analogues\n-- at the level of vectors, matrices and arbitrary tensors.\n--\n-- For each choice of the underlying scalar type @r@,\n-- we have several primitive differentiable types based on the scalar:\n-- the scalar type @r@ itself, @Vector r@, @Matrix r@ and tensors.\n-- Many operations span the ranks and so span the datatypes, which makes\n-- the datatypes mutually recursive.\n--\n-- The @Outline@ constructors represent primitive numeric function applications\n-- for which we delay computing and forgo inlining of the derivative.\ndata Delta0 r =\n    Zero0\n  | Scale0 r (Delta0 r)\n  | Add0 (Delta0 r) (Delta0 r)\n  | Var0 (DeltaId r)\n\n  | SumElements0 (Delta1 r) Int  -- ^ see Note [SumElements0]\n  | Index0 (Delta1 r) Int Int  -- ^ second integer is the length of the vector\n\n  | Dot0 (Vector r) (Delta1 r)  -- ^ Dot0 v vd == SumElements0 (Scale1 v vd) n\n\n  | FromX0 (DeltaX r)  -- ^ one of many conversions\n  | FromS0 (DeltaS '[] r)\n\n  | Outline0 CodeOut [r] [Delta0 r]\n  | Delay0 ~(Delta0 r)\n\nderiving instance (Show r, Numeric r) => Show (Delta0 r)\n\n-- | This is the grammar of delta-expressions at tensor rank 1, that is,\n-- at vector level.\ndata Delta1 r =\n    Zero1\n  | Scale1 (Vector r) (Delta1 r)\n  | Add1 (Delta1 r) (Delta1 r)\n  | Var1 (DeltaId (Vector r))\n\n  | Seq1 (Data.Vector.Vector (Delta0 r))  -- ^ \"unboxing\" conversion\n  | Konst1 (Delta0 r) Int  -- ^ length; needed only for forward derivative\n  | Append1 (Delta1 r) Int (Delta1 r)  -- ^ the length of the first argument\n  | Slice1 Int Int (Delta1 r) Int  -- ^ last integer is the length of argument\n  | SumRows1 (Delta2 r) Int  -- ^ the integer is the number of columns\n  | SumColumns1 (Delta2 r) Int  -- ^ the integer is the number of rows\n\n  | M_VD1 (Matrix r)\n          (Delta1 r)  -- ^ M_VD1 m vd == SumRows1 (M_MD2 m (AsRow2 vd))\n  | MD_V1 (Delta2 r)\n          (Vector r)  -- ^ MD_V1 md v == SumRows1 (MD_M2 md (asRow v))\n\n  | FromX1 (DeltaX r)\n  | forall len. KnownNat len\n    => FromS1 (DeltaS '[len] r)\n\n    -- unsorted and undocumented yet\n  | Reverse1 (Delta1 r)\n  | Flatten1 Int Int (Delta2 r)\n  | FlattenX1 OT.ShapeL (DeltaX r)\n  | forall sh. OS.Shape sh\n    => FlattenS1 (DeltaS sh r)\n\n  | Outline1 CodeOut [Vector r] [Delta1 r]\n  | Delay1 ~(Delta1 r)\n\nderiving instance (Show r, Numeric r) => Show (Delta1 r)\n\n-- | This is the grammar of delta-expressions at tensor rank 2, that is,\n-- at matrix level.\ndata Delta2 r =\n    Zero2\n  | Scale2 (Matrix r) (Delta2 r)\n  | Add2 (Delta2 r) (Delta2 r)\n  | Var2 (DeltaId (Matrix r))\n\n  | FromRows2 (Data.Vector.Vector (Delta1 r))  -- ^ \"unboxing\" conversion again\n  | FromColumns2 (Data.Vector.Vector (Delta1 r))\n  | Konst2 (Delta0 r) (Int, Int)  -- ^ size; needed only for forward derivative\n  | Transpose2 (Delta2 r)\n  | M_MD2 (Matrix r) (Delta2 r)  -- ^ matrix-(matrix-expression) multiplication\n  | MD_M2 (Delta2 r) (Matrix r)  -- ^ (matrix-expression)-matrix multiplication\n  | RowAppend2 (Delta2 r) Int (Delta2 r)  -- ^ row-length of first argument\n  | ColumnAppend2 (Delta2 r) Int (Delta2 r)  -- ^ col-length of first argument\n  | RowSlice2 Int Int (Delta2 r) Int  -- ^ last arg is row-length of the matrix\n  | ColumnSlice2 Int Int (Delta2 r) Int  -- ^ column-length of the matrix\n\n  | AsRow2 (Delta1 r)  -- ^ AsRow2 vd == FromRows2 (V.replicate n vd)\n  | AsColumn2 (Delta1 r)  -- ^ AsColumn2 vd == FromColumns2 (V.replicate n vd)\n\n  | FromX2 (DeltaX r)\n  | forall rows cols. (KnownNat rows, KnownNat cols)\n    => FromS2 (DeltaS '[rows, cols] r)\n\n    -- unsorted and undocumented yet\n  | Flipud2 (Delta2 r)\n  | Fliprl2 (Delta2 r)\n  | Reshape2 Int (Delta1 r)\n  | Conv2 (Matrix r) (Delta2 r)\n\n  | Outline2 CodeOut [Matrix r] [Delta2 r]\n  | Delay2 ~(Delta2 r)\n\nderiving instance (Show r, Numeric r) => Show (Delta2 r)\n\n-- | This is the grammar of delta-expressions at arbitrary tensor rank.\n--\n-- Warning: not tested enough nor benchmarked.\ndata DeltaX r =\n    ZeroX\n  | ScaleX (OT.Array r) (DeltaX r)\n  | AddX (DeltaX r) (DeltaX r)\n  | VarX (DeltaId (OT.Array r))\n\n  | KonstX (Delta0 r) OT.ShapeL  -- ^ size; needed only for forward derivative\n  | AppendX (DeltaX r) Int (DeltaX r)\n      -- ^ Append two arrays along the outermost dimension.\n      -- All dimensions, except the outermost, must be the same.\n      -- The integer argument is the outermost size of the first array.\n  | SliceX Int Int (DeltaX r) Int\n      -- ^ Extract a slice of an array along the outermost dimension.\n      -- The extracted slice must fall within the dimension.\n      -- The last argument is the outermost size of the argument array.\n  | IndexX (DeltaX r) Int Int\n      -- ^ The sub-tensors at the given index of the outermost dimension.\n      -- The second integer is the length of the dimension.\n  | RavelFromListX [DeltaX r]\n      -- ^ Create a tensor from a list treated as the outermost dimension.\n  | ReshapeX OT.ShapeL OT.ShapeL (DeltaX r)\n      -- ^ Change the shape of the tensor from the first to the second.\n\n  | From0X (Delta0 r)\n  | From1X (Delta1 r)\n  | From2X (Delta2 r) Int\n  | forall sh. OS.Shape sh\n    => FromSX (DeltaS sh r)\n\n  | OutlineX CodeOut [OT.Array r] [DeltaX r]\n  | DelayX ~(DeltaX r)\n\nderiving instance (Show r, Numeric r) => Show (DeltaX r)\n\n-- | This is the grammar of delta-expressions at arbitrary tensor rank,\n-- the fully typed Shaped version.\n--\n-- Warning: not tested enough nor benchmarked.\ndata DeltaS :: [Nat] -> Type -> Type where\n  ZeroS :: DeltaS sh r\n  ScaleS :: OS.Array sh r -> DeltaS sh r -> DeltaS sh r\n  AddS :: DeltaS sh r -> DeltaS sh r -> DeltaS sh r\n  VarS :: DeltaId (OS.Array sh r) -> DeltaS sh r\n\n  KonstS :: Delta0 r -> DeltaS sh r\n  AppendS :: (OS.Shape sh, KnownNat m, KnownNat n)\n          => DeltaS (m ': sh) r -> DeltaS (n ': sh) r\n          -> DeltaS ((m + n) ': sh) r\n    -- ^ Append two arrays along the outermost dimension.\n  SliceS :: (KnownNat i, KnownNat n, KnownNat k, OS.Shape rest)\n         => Proxy i -> Proxy n -> DeltaS (i + n + k ': rest) r\n         -> DeltaS (n ': rest) r\n    -- ^ Extract a slice of an array along the outermost dimension.\n  IndexS :: (KnownNat ix, KnownNat k, OS.Shape rest)\n         => DeltaS (ix + 1 + k ': rest) r -> Proxy ix -> DeltaS rest r\n    -- ^ The sub-tensors at the given index of the outermost dimension.\n  RavelFromListS :: (KnownNat k, OS.Shape rest)\n                 => [DeltaS rest r] -> DeltaS (k : rest) r\n    -- ^ Create a tensor from a list treated as the outermost dimension.\n  ReshapeS :: (OS.Shape sh, OS.Shape sh', OS.Size sh ~ OS.Size sh')\n           => DeltaS sh r -> DeltaS sh' r\n    -- ^ Change the shape of the tensor.\n\n  From0S :: Delta0 r -> DeltaS '[] r\n  From1S :: Delta1 r -> DeltaS '[n] r\n  From2S :: KnownNat cols\n         => Proxy cols -> Delta2 r -> DeltaS '[rows, cols] r\n  FromXS :: DeltaX r -> DeltaS sh r\n\n  OutlineS :: CodeOut -> [OS.Array sh r] -> [DeltaS sh r] -> DeltaS sh r\n  DelayS :: ~(DeltaS sh r) -> DeltaS sh r\n\ninstance Show (DeltaS sh r) where\n  show _ = \"a DeltaS delta expression\"\n\n\n-- * Delta expression identifiers\n\nnewtype DeltaId a = DeltaId Int\n  deriving Show\n\ntoDeltaId :: Int -> DeltaId a\ntoDeltaId = DeltaId\n\nconvertDeltaId :: DeltaId (OT.Array r) -> DeltaId (OS.Array sh r)\nconvertDeltaId (DeltaId i) = DeltaId i\n\n-- The key property is that it preserves the phantom type.\nsuccDeltaId :: DeltaId a -> DeltaId a\nsuccDeltaId (DeltaId i) = DeltaId (succ i)\n\n\n-- * Evaluation of the delta expressions\n\n-- | Binding at one of the ranks, with a given underlying scalar.\n--\n-- The 'DeltaId' components could be re-computed on the fly in 'buildFinMaps',\n-- but it costs more (they are boxed, so re-allocation is expensive)\n-- than storing them here at the time of binding creation and accessing\n-- in `buildFinMaps`.\ndata DeltaBinding r =\n    DeltaBinding0 (DeltaId r) (Delta0 r)\n  | DeltaBinding1 (DeltaId (Vector r)) (Delta1 r)\n  | DeltaBinding2 (DeltaId (Matrix r)) (Delta2 r)\n  | DeltaBindingX (DeltaId (OT.Array r)) (DeltaX r)\n\ndata DeltaState r = DeltaState\n  { deltaCounter0 :: DeltaId r\n  , deltaCounter1 :: DeltaId (Vector r)\n  , deltaCounter2 :: DeltaId (Matrix r)\n  , deltaCounterX :: DeltaId (OT.Array r)\n  , deltaBindings :: [DeltaBinding r]\n  }\n\n-- | Helper definitions to shorten type signatures. Note that these\n-- differ from their counterparts in all other modules, because the type\n-- argument here is the underlying scalar (e.g., @Double),\n-- while elsewhere it's the dual component of dual numbers from\n-- rank 0 (scalar) level (e.g., @Delta0 Double@).\n-- By chance, these definitions and definitions from other modules\n-- coincide in case of \"forward derivatives computed on the spot\"\n-- where @r@ is @Double@ and @Double@ is also the dual component.\n--\n-- More generally, @r@ in this module tends to refer to the underlying\n-- scalar type, while in all other modules it refers to the rank 0 dual\n-- component type.\ntype Domain0 r = Vector r\n\ntype Domain1 r = Data.Vector.Vector (Vector r)\n\ntype Domain2 r = Data.Vector.Vector (Matrix r)\n\ntype DomainX r = Data.Vector.Vector (OT.Array r)\n\ntype Domains r = (Domain0 r, Domain1 r, Domain2 r, DomainX r)\n\n-- | Delta expressions naturally denote forward derivatives,\n-- as encoded in function 'derivativeFromDelta'. However, we are more\n-- interested in computing gradients, which is what @gradientFromDelta@ does.\n-- The two functions are bound by the equation from Lemma 5 from the paper\n-- \"Provably correct, asymptotically efficient, higher-order reverse-mode\n-- automatic differentiation\":\n--\n-- > dt <.> derivativeFromDelta st d ds = gradientFromDelta st d dt <.> ds\n--\n-- where @\\<.\\>@ denotes generalized dot product (multiplying\n-- all tensors element-wise and summing the results),\n-- @st@ contains bindings of delta variables and @d@ is the top level\n-- delta expression from translation of the objective function @f@ to dual\n-- numbers, @ds@ belongs to the domain of @f@ and @dt@ to the codomain.\n-- We omitted for clarity the @dim0@, @dim1@, @dim2@ and @dimX@ arguments\n-- that are the lengths of vectors of the tensors in the domain of @f@.\n--\n-- Intuitively, @ds@ is a tiny perturbation of the arguments of @f@,\n-- for which we compute the derivative, that is, the induced change\n-- in the result of @f@. Similarly, @dt@ is a tiny perturbation of the\n-- result of @f@, for which we compute the gradient, that is, the change\n-- of arguments of @f@ sufficient to cause the perturbation.\n-- Note that the scaling factor @r@ in functions @eval*@ in @gradientFromDelta@\n-- locally plays the role of @dt@, just as the argument @parameters@\n-- in @eval*@ in @derivativeFromDelta@ corresponds to @ds@.\n--\n-- Let's first discuss in detail the semantics of delta-expressions\n-- in terms of forward derivatives, since it's more straightforward.\n-- Let @r@ be the type of underlying scalars. Let @f@ be a mathematical\n-- differentiable function that takes a collection of type @C@\n-- of arguments and produces a single result of type @r@.\n-- Let a dual number counterpart of @f@ applied to a collection\n-- of parameters @P@ of type @C@ be represented as a Haskell value @b@.\n-- Let @d :: Delta0 r@ be the closed delta expression that is the second\n-- component of @b@, let @ds@ belong to @C@. The semantics of @d@ is a linear\n-- function from @C@ to @r@ that is the derivative of @f@ at point @P@\n-- with respect to the perturbation @ds@. The mathematical formula\n-- for the derivative follows straightforwardly the syntactic form\n-- of the delta expression @d@ (see 'derivativeFromDelta').\n--\n-- Let's now describe the semantics of closed delta expression @d@\n-- as the gradient of @f@ at point @P@ with respect to a @dt@ that belongs\n-- to @r@. Here the semantics of @d@ is a collection of four finite maps\n-- (vectors) @v0@, @v1@, @v2@, @vX@, corresponding to @C@,\n-- each map @vi@ taking indexes of type @DeltaId ai@ to values of type @ai@,\n-- where @a0@ is @r@, @a1@ is @Vector r@, @a2@ is @Matrix r@\n-- and @aX@ is the type of tensors of @r@.\n-- The value of @vi@ at index @DeltaId k@ is the partial derivative\n-- of function @f@ at @P@ with respect to its parameter of type @ai@.\n-- The position of the @ai@ parameter is represented by @DeltaId k@\n-- (in other words, the partial derivative is with respect to a variable\n-- quantity tagged with @DeltaId k@) and its value comes from @dt@.\n--\n-- The semantics of a delta expression that is not closed but contains\n-- occurrences of variables that do not correspond to parameters of @f@ is only\n-- defined in the context of four vectors that contain values associated\n-- to its free variables or, alternatively, of bindings from which the values\n-- can be computed, or of a mixture of both. This semantics does not change\n-- if a bound expression is substituted for a variable instead of being used\n-- to compute a value. (Note however that a computed value can't be\n-- substituted for all occurrences of the variable in an expression,\n-- because the \"computing backwards\" trick, needed to get gradients\n-- from derivative expressions, computes a value for each occurrence\n-- of a variable separately and sums over all occurrences instead\n-- of substituting a single value into each occurrence.)\n--\n-- Function @gradientFromDelta@ computes the four vectors described above.\n-- Requested lengths of the vectors are given in the first few arguments.\n-- The delta state contains a list of mutually-referencing delta bindings\n-- that are to be evaluated, in the given order, starting with the top-level\n-- binding of a scalar type provided in the next argument and with respect\n-- to perturbation @dt@ (usually set to @1@) in the last argument.\ngradientFromDelta :: (Eq r, Numeric r, Num (Vector r))\n                  => (CodeOut -> [r] -> [Delta0 r] -> Delta0 r)\n                  -> (CodeOut -> [Vector r] -> [Delta1 r] -> Delta1 r)\n                  -> (CodeOut -> [Matrix r] -> [Delta2 r] -> Delta2 r)\n                  -> (CodeOut -> [OT.Array r] -> [DeltaX r] -> DeltaX r)\n                  -> (forall sh. OS.Shape sh\n                      => CodeOut -> [OS.Array sh r] -> [DeltaS sh r]\n                      -> DeltaS sh r)\n                  -> Int -> Int -> Int -> Int -> DeltaState r -> Delta0 r -> r\n                  -> Domains r\ngradientFromDelta inlineDerivative0 inlineDerivative1 inlineDerivative2\n                  inlineDerivativeX inlineDerivativeS\n                  dim0 dim1 dim2 dimX st deltaTopLevel dt =\n  -- This is morally @V.create@ and so totally safe,\n  -- but we can't just call @V.create@ thrice, because it would run\n  -- the @ST@ action thrice, so we inline and extend @V.create@ here.\n  runST $ do\n    (finMap0, finMap1, finMap2, finMapX) <-\n      buildFinMaps inlineDerivative0 inlineDerivative1 inlineDerivative2\n                   inlineDerivativeX inlineDerivativeS\n                   st deltaTopLevel dt\n    v0 <- V.unsafeFreeze $ VM.take dim0 finMap0\n    v1 <- V.unsafeFreeze $ VM.take dim1 finMap1\n    v2 <- V.unsafeFreeze $ VM.take dim2 finMap2\n    vX <- V.unsafeFreeze $ VM.take dimX finMapX\n    -- Convert to normal matrices, but only the portion of vector\n    -- that is not discarded.\n    return (v0, v1, V.map MO.convertMatrixOuterOrNull v2, vX)\n\n-- | Create vectors (representing finite maps) that hold delta-variable\n-- values. They are initialized with dummy values so that it's cheap to check\n-- if any update has already been performed to a cell (allocating big matrices\n-- filled with zeros is too costly, especially if never used in an iteration,\n-- and adding to such matrices and especially using them as scaling factors\n-- is wasteful). The vectors are longer than those representing objective\n-- function parameters (e.g., @deltaCounter0@ vs @dim0@), because variables\n-- represent not only parameters, but also the bindings that prevent blowup\n-- via delta-expression duplication.\ninitializeFinMaps :: forall s r. Numeric r\n                  => DeltaState r\n                  -> ST s ( Data.Vector.Storable.Mutable.MVector s r\n                          , Data.Vector.Mutable.MVector s (Vector r)\n                          , Data.Vector.Mutable.MVector s (MO.MatrixOuter r)\n                          , Data.Vector.Mutable.MVector s (OT.Array r) )\ninitializeFinMaps st = do\n  let DeltaId counter0 = deltaCounter0 st\n      DeltaId counter1 = deltaCounter1 st\n      DeltaId counter2 = deltaCounter2 st\n      DeltaId counterX = deltaCounterX st\n  finMap0 <- VM.replicate counter0 0  -- correct value\n  finMap1 <- VM.replicate counter1 (V.empty :: Vector r)  -- dummy value\n  finMap2 <- VM.replicate counter2 MO.emptyMatrixOuter  -- dummy value\n  finMapX <- VM.replicate counterX dummyTensor\n  return (finMap0, finMap1, finMap2, finMapX)\n\nbuildFinMaps :: forall s r. (Eq r, Numeric r, Num (Vector r))\n             => (CodeOut -> [r] -> [Delta0 r] -> Delta0 r)\n             -> (CodeOut -> [Vector r] -> [Delta1 r] -> Delta1 r)\n             -> (CodeOut -> [Matrix r] -> [Delta2 r] -> Delta2 r)\n             -> (CodeOut -> [OT.Array r] -> [DeltaX r] -> DeltaX r)\n             -> (forall sh. OS.Shape sh\n                 => CodeOut -> [OS.Array sh r] -> [DeltaS sh r]\n                 -> DeltaS sh r)\n             -> DeltaState r -> Delta0 r -> r\n             -> ST s ( Data.Vector.Storable.Mutable.MVector s r\n                     , Data.Vector.Mutable.MVector s (Vector r)\n                     , Data.Vector.Mutable.MVector s (MO.MatrixOuter r)\n                     , Data.Vector.Mutable.MVector s (OT.Array r) )\nbuildFinMaps inlineDerivative0 inlineDerivative1 inlineDerivative2\n             inlineDerivativeX inlineDerivativeS\n             st deltaTopLevel dt = do\n  (finMap0, finMap1, finMap2, finMapX) <- initializeFinMaps st\n  let addToVector :: Vector r -> Vector r -> Vector r\n      addToVector r = \\v -> if V.null v then r else v + r\n      addToMatrix :: MO.MatrixOuter r -> MO.MatrixOuter r -> MO.MatrixOuter r\n      addToMatrix r = \\v -> if MO.nullMatrixOuter v then r else MO.plus v r\n      addToArray :: OT.Array r -> OT.Array r -> OT.Array r\n      addToArray r = \\v -> if isTensorDummy v then r else liftVT2 (+) v r\n      addToArrayS :: OS.Shape sh => OS.Array sh r -> OT.Array r -> OT.Array r\n      addToArrayS r = \\v -> let rs = Data.Array.Convert.convert r\n                            in if isTensorDummy v\n                               then rs\n                               else liftVT2 (+) v rs\n      eval0 :: r -> Delta0 r -> ST s ()\n      eval0 !r = \\case\n        Zero0 -> return ()\n        Scale0 k d -> eval0 (k * r) d\n        Add0 d e -> eval0 r d >> eval0 r e\n        Var0 (DeltaId i) -> VM.modify finMap0 (+ r) i\n\n        SumElements0 vd n -> eval1 (HM.konst r n) vd\n        Index0 (Var1 (DeltaId i)) ix k -> do\n          let f v = if V.null v\n                    then HM.konst 0 k V.// [(ix, r)]\n                    else v V.// [(ix, v V.! ix + r)]\n          VM.modify finMap1 f i\n            -- this would be an asymptotic optimization compared to\n            -- the general case below, if not for the non-mutable update,\n            -- which involves copying the whole vector, so it's just\n            -- several times faster (same allocation, but not adding vectors)\n        Index0 d ix k -> eval1 (HM.konst 0 k V.// [(ix, r)]) d\n\n        Dot0 v vd -> eval1 (HM.scale r v) vd\n\n        FromX0 d -> evalX (OT.scalar r) d\n        FromS0 d -> evalS (OS.scalar r) d\n\n        Outline0 codeOut primalArgs dualArgs ->\n          eval0 r $ inlineDerivative0 codeOut primalArgs dualArgs\n        Delay0 d -> eval0 r d\n      eval1 :: Vector r -> Delta1 r -> ST s ()\n      eval1 !r = \\case\n        Zero1 -> return ()\n        Scale1 k d -> eval1 (k * r) d\n        Add1 d e -> eval1 r d >> eval1 r e\n        Var1 (DeltaId i) -> VM.modify finMap1 (addToVector r) i\n\n        Seq1 lsd -> V.imapM_ (\\i d -> eval0 (r V.! i) d) lsd\n        Konst1 d _n -> V.mapM_ (`eval0` d) r\n        Append1 d k e -> eval1 (V.take k r) d >> eval1 (V.drop k r) e\n        Slice1 i n d len ->\n          eval1 (HM.konst 0 i V.++ r V.++ HM.konst 0 (len - i - n)) d\n        SumRows1 dm cols -> eval2 (MO.asColumn r cols) dm\n        SumColumns1 dm rows -> eval2 (MO.asRow r rows) dm\n\n        M_VD1 m dRow ->\n          mapM_ (`eval1` dRow)\n                (MO.toRows (MO.MatrixOuter (Just m) (Just r) Nothing))\n        MD_V1 md row -> eval2 (MO.MatrixOuter Nothing (Just r) (Just row)) md\n\n        FromX1 d -> evalX (OT.fromVector [V.length r] r) d\n        FromS1 d -> evalS (OS.fromVector r) d\n\n        Reverse1 d -> eval1 (V.reverse r) d\n        Flatten1 rows cols d ->\n          eval2 (MO.MatrixOuter (Just $ rows HM.>< cols $ V.toList r)\n                                Nothing Nothing)\n                d\n        FlattenX1 sh d -> evalX (OT.fromVector sh r) d\n        FlattenS1 d -> evalS (OS.fromVector r) d\n\n        Outline1 codeOut primalArgs dualArgs ->\n          eval1 r $ inlineDerivative1 codeOut primalArgs dualArgs\n        Delay1 d -> eval1 r d\n      eval2 :: MO.MatrixOuter r -> Delta2 r -> ST s ()\n      eval2 !r = \\case\n        Zero2 -> return ()\n        Scale2 k d -> eval2 (MO.multiplyWithOuter k r) d\n        Add2 d e -> eval2 r d >> eval2 r e\n        Var2 (DeltaId i) -> VM.modify finMap2 (addToMatrix r) i\n\n        FromRows2 lvd -> zipWithM_ eval1 (MO.toRows r) (V.toList lvd)\n        FromColumns2 lvd -> zipWithM_ eval1 (MO.toColumns r) (V.toList lvd)\n        Konst2 d _sz -> mapM_ (V.mapM_ (`eval0` d)) $ MO.toRows r\n        Transpose2 md -> eval2 (MO.transpose r) md  -- TODO: test!\n        M_MD2 m md ->\n          let mo = MO.MatrixOuter (Just $ HM.tr' m) Nothing Nothing\n          in eval2 (MO.matMul mo r) md\n        MD_M2 md m ->\n          let mo = MO.MatrixOuter (Just $ HM.tr' m) Nothing Nothing\n          in eval2 (MO.matMul r mo) md\n        RowAppend2 d k e -> eval2 (MO.takeRows k r) d\n                            >> eval2 (MO.dropRows k r) e\n        ColumnAppend2 d k e -> eval2 (MO.takeColumns k r) d\n                               >> eval2 (MO.dropColumns k r) e\n        RowSlice2 i n d rows ->\n          assert (MO.rows r == n) $\n          let cols = MO.cols r\n          in eval2 (MO.konst 0 i cols\n                    `MO.rowAppend` r\n                    `MO.rowAppend` MO.konst 0 (rows - i - n) cols)\n                   d\n        ColumnSlice2 i n d cols ->\n          assert (MO.cols r == n) $\n          let rows = MO.rows r\n          in eval2 (MO.konst 0 rows i\n                    `MO.columnAppend` r\n                    `MO.columnAppend` MO.konst 0 rows (cols - i - n))\n                   d\n\n        AsRow2 dRow -> mapM_ (`eval1` dRow) (MO.toRows r)\n        AsColumn2 dCol -> mapM_ (`eval1` dCol) (MO.toColumns r)\n\n        FromX2 d -> evalX (OT.fromVector [MO.rows r, MO.cols r]\n                                         (V.concat $ MO.toRows r)) d\n        FromS2 d -> evalS (OS.fromVector $ V.concat $ MO.toRows r) d\n\n        Flipud2 d -> eval2 (MO.flipud r) d\n        Fliprl2 d -> eval2 (MO.fliprl r) d\n        Reshape2 _cols d -> eval1 (V.concat $ MO.toRows r) d\n        Conv2 m md ->\n          let mor = MO.convertMatrixOuter r\n              convolved = HM.corr2 m mor\n              moc = MO.MatrixOuter (Just convolved) Nothing Nothing\n          in eval2 moc md\n\n        Outline2 codeOut primalArgs dualArgs ->\n          eval2 r $ inlineDerivative2 codeOut primalArgs dualArgs\n        Delay2 d -> eval2 r d\n      evalX :: OT.Array r -> DeltaX r -> ST s ()\n      evalX !r = \\case\n        ZeroX -> return ()\n        ScaleX k d -> evalX (liftVT2 (*) k r) d\n        AddX d e -> evalX r d >> evalX r e\n        VarX (DeltaId i) -> VM.modify finMapX (addToArray r) i\n\n        KonstX d _sz -> mapM_ (`eval0` d) $ OT.toList r\n        AppendX d k e -> case OT.shapeL r of\n          n : _ -> evalX (OT.slice [(0, k)] r) d\n                   >> evalX (OT.slice [(k, n - k)] r) e\n          [] -> error \"evalX: appending a 0-dimensional tensor\"\n        SliceX i n d len -> case OT.shapeL r of\n          n' : rest ->\n            assert (n' == n) $\n            evalX (OT.concatOuter [ OT.constant (i : rest) 0\n                                  , r\n                                  , OT.constant (len - i - n : rest) 0 ])\n                  d\n          [] -> error \"evalX: slicing a 0-dimensional tensor\"\n        IndexX d ix len ->\n          let rest = OT.shapeL r\n          in evalX (OT.concatOuter [ OT.constant (ix : rest) 0\n                                   , OT.reshape (1 : rest) r\n                                   , OT.constant (len - ix - 1 : rest) 0 ])\n                   d  -- TODO: optimize for Var case\n        RavelFromListX ld -> do\n          let lr = OTB.toList $ OT.unravel r\n          mapM_ (uncurry evalX) (zip lr ld)\n        ReshapeX sh _sh' d -> evalX (OT.reshape sh r) d\n\n        From0X d -> eval0 (OT.unScalar r) d\n        From1X d -> eval1 (OT.toVector r) d\n        From2X d cols ->\n          eval2 (MO.MatrixOuter (Just $ HM.reshape cols $ OT.toVector r)\n                                Nothing Nothing)\n                d\n        FromSX d -> evalS (Data.Array.Convert.convert r) d\n\n        OutlineX codeOut primalArgs dualArgs ->\n          evalX r $ inlineDerivativeX codeOut primalArgs dualArgs\n        DelayX d -> evalX r d\n      evalS :: OS.Shape sh\n            => OS.Array sh r -> DeltaS sh r -> ST s ()\n      evalS !r = \\case\n        ZeroS -> return ()\n        ScaleS k d -> evalS (liftVS2 (*) k r) d\n        AddS d e -> evalS r d >> evalS r e\n        VarS (DeltaId i) -> VM.modify finMapX (addToArrayS r) i\n\n        KonstS d -> mapM_ (`eval0` d) $ OS.toList r\n        AppendS (d :: DeltaS (k ': rest) r) (e :: DeltaS (l ': rest) r) ->\n          evalS (OS.slice @'[ '(0, k) ] r) d\n          >> evalS (OS.slice @'[ '(k, l) ] r) e\n        SliceS (_ :: Proxy i) _ (d :: DeltaS (i_plus_n_plus_k ': rest) r) ->\n          evalS (OS.constant @(i ': rest) 0\n                 `OS.append` r\n                 `OS.append` OS.constant 0)\n                d\n        IndexS (d :: DeltaS (ix_plus_1_plus_k ': rest) r) (_ :: Proxy ix) ->\n          evalS (OS.constant @(ix ': rest) 0\n                 `OS.append` OS.reshape r\n                 `OS.append` OS.constant 0)\n                d  -- TODO: optimize for Var case\n        RavelFromListS ld -> do\n          let lr = OSB.toList $ OS.unravel r\n          mapM_ (uncurry evalS) (zip lr ld)\n        ReshapeS d -> evalS (OS.reshape r) d\n\n        From0S d -> eval0 (OS.unScalar r) d\n        From1S d -> eval1 (OS.toVector r) d\n        From2S proxyCols d ->\n          eval2 (MO.MatrixOuter\n                   (Just $ HM.reshape (fromInteger $ natVal proxyCols)\n                         $ OS.toVector r)\n                   Nothing Nothing)\n                d\n        FromXS d -> evalX (Data.Array.Convert.convert r) d\n\n        OutlineS codeOut primalArgs dualArgs ->\n          evalS r $ inlineDerivativeS codeOut primalArgs dualArgs\n        DelayS d -> evalS r d\n\n  eval0 dt deltaTopLevel\n\n  let evalUnlessZero :: DeltaBinding r -> ST s ()\n      evalUnlessZero (DeltaBinding0 (DeltaId i) d) = do\n        r <- finMap0 `VM.read` i\n        unless (r == 0) $  -- we init with exactly 0.0 so the comparison works\n          eval0 r d\n      evalUnlessZero (DeltaBinding1 (DeltaId i) d) = do\n        r <- finMap1 `VM.read` i\n        unless (V.null r) $\n          eval1 r d\n      evalUnlessZero (DeltaBinding2 (DeltaId i) d) = do\n        r <- finMap2 `VM.read` i\n        unless (MO.nullMatrixOuter r) $\n          eval2 r d\n      evalUnlessZero (DeltaBindingX (DeltaId i) d) = do\n        r <- finMapX `VM.read` i\n        unless (isTensorDummy r) $\n          evalX r d\n  mapM_ evalUnlessZero (deltaBindings st)\n  return (finMap0, finMap1, finMap2, finMapX)\n\n-- | Forward derivative computation via forward-evaluation of delta-expressions\n-- (which is surprisingly competitive to the direct forward method,\n-- until the allocation of deltas gets large enough to affect cache hits).\n-- This is the directional derivative, calculated for the point,\n-- at which the delta expression was computed (which is the point\n-- represented by the parameters of the objective function and used\n-- to compute it's dual number result) and along the direction vector(s)\n-- given in the last parameter called @ds@.\nderivativeFromDelta\n  :: forall r. (Numeric r, Num (Vector r))\n  => (CodeOut -> [r] -> [Delta0 r] -> Delta0 r)\n  -> (CodeOut -> [Vector r] -> [Delta1 r] -> Delta1 r)\n  -> (CodeOut -> [Matrix r] -> [Delta2 r] -> Delta2 r)\n  -> (CodeOut -> [OT.Array r] -> [DeltaX r] -> DeltaX r)\n  -> (forall sh. OS.Shape sh\n      => CodeOut -> [OS.Array sh r] -> [DeltaS sh r]\n      -> DeltaS sh r)\n  -> DeltaState r -> Delta0 r -> Domains r -> r\nderivativeFromDelta inlineDerivative0 inlineDerivative1 inlineDerivative2\n                    inlineDerivativeX inlineDerivativeS\n                    st deltaTopLevel\n                    _ds@(params0Init, params1Init, params2Init, paramsXInit) =\n  let eval0 :: Domains r -> Delta0 r -> r\n      eval0 parameters@(params0, _, _, _) = \\case\n        Zero0 -> 0\n        Scale0 k d -> k * eval0 parameters d\n        Add0 d e -> eval0 parameters d + eval0 parameters e\n        Var0 (DeltaId i) -> params0 V.! i\n\n        SumElements0 vd _n -> HM.sumElements $ eval1 parameters vd\n        Index0 d ix _k -> eval1 parameters d V.! ix\n\n        Dot0 vr vd -> vr <.> eval1 parameters vd\n\n        FromX0 d -> OT.unScalar $ evalX parameters d\n        FromS0 d -> OS.unScalar $ evalS parameters d\n\n        Outline0 codeOut primalArgs dualArgs ->\n          eval0 parameters $ inlineDerivative0 codeOut primalArgs dualArgs\n        Delay0 d -> eval0 parameters d\n      eval1 :: Domains r -> Delta1 r -> Vector r\n      eval1 parameters@(_, params1, _, _) = \\case\n        Zero1 -> 0\n        Scale1 k d -> k * eval1 parameters d\n        Add1 d e -> eval1 parameters d + eval1 parameters e\n        Var1 (DeltaId i) -> params1 V.! i\n\n        Seq1 lsd -> V.convert $ V.map (eval0 parameters) lsd\n        Konst1 d n -> HM.konst (eval0 parameters d) n\n        Append1 d _k e -> eval1 parameters d V.++ eval1 parameters e\n        Slice1 i n d _len -> V.slice i n $ eval1 parameters d\n        SumRows1 dm _cols ->\n          V.fromList $ map HM.sumElements $ HM.toRows $ eval2 parameters dm\n        SumColumns1 dm _rows ->\n          V.fromList $ map HM.sumElements $ HM.toColumns $ eval2 parameters dm\n\n        M_VD1 m dRow -> m #> eval1 parameters dRow\n        MD_V1 md row -> eval2 parameters md #> row\n\n        FromX1 d -> OT.toVector $ evalX parameters d\n        FromS1 d -> OS.toVector $ evalS parameters d\n\n        Reverse1 d -> V.reverse $ eval1 parameters d\n        Flatten1 _rows _cols d -> HM.flatten $ eval2 parameters d\n        FlattenX1 _sh d -> OT.toVector $ evalX parameters d\n        FlattenS1 d -> OS.toVector $ evalS parameters d\n\n        Outline1 codeOut primalArgs dualArgs ->\n          eval1 parameters $ inlineDerivative1 codeOut primalArgs dualArgs\n        Delay1 d -> eval1 parameters d\n      eval2 :: Domains r -> Delta2 r -> Matrix r\n      eval2 parameters@( _, _, params2, _) = \\case\n        Zero2 -> 0\n        Scale2 k d -> k * eval2 parameters d\n        Add2 d e -> eval2 parameters d + eval2 parameters e\n        Var2 (DeltaId i) -> params2 V.! i\n\n        FromRows2 lvd ->\n          HM.fromRows $ map (eval1 parameters) $ V.toList lvd\n        FromColumns2 lvd ->\n          HM.fromColumns $ map (eval1 parameters) $ V.toList lvd\n        Konst2 d sz -> HM.konst (eval0 parameters d) sz\n        Transpose2 md -> HM.tr' $ eval2 parameters md\n        M_MD2 m md -> m HM.<> eval2 parameters md\n        MD_M2 md m -> eval2 parameters md HM.<> m\n        RowAppend2 d _k e -> eval2 parameters d HM.=== eval2 parameters e\n        ColumnAppend2 d _k e -> eval2 parameters d HM.||| eval2 parameters e\n        RowSlice2 i n d _rows ->\n          HM.takeRows n $ HM.dropRows i $ eval2 parameters d\n        ColumnSlice2 i n d _cols ->\n          HM.takeColumns n $ HM.dropColumns i $ eval2 parameters d\n\n        AsRow2 dRow -> HM.asRow $ eval1 parameters dRow  -- TODO: risky\n        AsColumn2 dCol -> HM.asColumn $ eval1 parameters dCol  -- TODO: risky\n\n        FromX2 d ->\n          let t = evalX parameters d\n          in case OT.shapeL t of\n            [_rows, cols] -> HM.reshape cols $ OT.toVector t\n            _ -> error \"eval2: wrong tensor dimensions\"\n        FromS2 d ->\n          let t = evalS parameters d\n          in case OS.shapeL t of\n            [_rows, cols] -> HM.reshape cols $ OS.toVector t\n            _ -> error \"eval2: wrong tensor dimensions\"\n\n        Flipud2 d -> HM.flipud $ eval2 parameters d\n        Fliprl2 d -> HM.fliprl $ eval2 parameters d\n        Reshape2 cols d -> HM.reshape cols $ eval1 parameters d\n        Conv2 m md -> HM.conv2 m $ eval2 parameters md\n\n        Outline2 codeOut primalArgs dualArgs ->\n          eval2 parameters $ inlineDerivative2 codeOut primalArgs dualArgs\n        Delay2 d -> eval2 parameters d\n      evalX :: Domains r -> DeltaX r -> OT.Array r\n      evalX parameters@( _, _, _, paramsX) = \\case\n        ZeroX -> 0\n        ScaleX k d -> k * evalX parameters d\n        AddX d e -> evalX parameters d + evalX parameters e\n        VarX (DeltaId i) -> paramsX V.! i\n\n        KonstX d sz -> OT.constant sz $ eval0 parameters d\n        AppendX d _k e -> evalX parameters d `OT.append` evalX parameters e\n        SliceX i n d _len -> OT.slice [(i, n)] $ evalX parameters d\n        IndexX d ix _len -> OT.index (evalX parameters d) ix\n        RavelFromListX ld ->\n          let la = map (evalX parameters) ld\n              sh = case la of\n                a : _ -> length la : OT.shapeL a\n                [] -> []\n          in OT.ravel $ OTB.fromList sh la\n        ReshapeX _sh sh' d -> OT.reshape sh' $ evalX parameters d\n\n        From0X d -> OT.scalar $ eval0 parameters d\n        From1X d -> let v = eval1 parameters d\n                    in OT.fromVector [V.length v] v\n        From2X d cols -> let l = eval2 parameters d\n                         in OT.fromVector [HM.rows l, cols] $ HM.flatten l\n        FromSX d -> Data.Array.Convert.convert $ evalS parameters d\n\n        OutlineX codeOut primalArgs dualArgs ->\n          evalX parameters $ inlineDerivativeX codeOut primalArgs dualArgs\n        DelayX d -> evalX parameters d\n      evalS :: OS.Shape sh => Domains r -> DeltaS sh r -> OS.Array sh r\n      evalS parameters@( _, _, _, paramsX) = \\case\n        ZeroS -> 0\n        ScaleS k d -> k * evalS parameters d\n        AddS d e -> evalS parameters d + evalS parameters e\n        VarS (DeltaId i) -> Data.Array.Convert.convert $ paramsX V.! i\n\n        KonstS d -> OS.constant $ eval0 parameters d\n        AppendS d e -> evalS parameters d `OS.append` evalS parameters e\n        SliceS (_ :: Proxy i) (_ :: Proxy n) d ->\n          OS.slice @'[ '(i, n) ] $ evalS parameters d\n        IndexS d proxyIx ->\n          OS.index (evalS parameters d) (fromInteger $ natVal proxyIx)\n        RavelFromListS ld ->\n          let la = map (evalS parameters) ld\n          in OS.ravel $ OSB.fromList la\n        ReshapeS d -> OS.reshape $ evalS parameters d\n\n        From0S d -> OS.scalar $ eval0 parameters d\n        From1S d -> OS.fromVector $ eval1 parameters d\n        From2S _ d -> OS.fromVector $ HM.flatten $ eval2 parameters d\n        FromXS d -> Data.Array.Convert.convert $ evalX parameters d\n\n        OutlineS codeOut primalArgs dualArgs ->\n          evalS parameters $ inlineDerivativeS codeOut primalArgs dualArgs\n        DelayS d -> evalS parameters d\n      evalUnlessZero :: Domains r -> DeltaBinding r -> Domains r\n      evalUnlessZero parameters@(!params0, !params1, !params2, !paramsX) = \\case\n        DeltaBinding0 (DeltaId i) d ->\n          let v = eval0 parameters d\n          in (params0 V.// [(i, v)], params1, params2, paramsX)\n        DeltaBinding1 (DeltaId i) d ->\n          let v = eval1 parameters d\n          in (params0, params1 V.// [(i, v)], params2, paramsX)\n        DeltaBinding2 (DeltaId i) d ->\n          let v = eval2 parameters d\n          in (params0, params1, params2 V.// [(i, v)], paramsX)\n        DeltaBindingX (DeltaId i) d ->\n          let v = evalX parameters d\n          in (params0, params1, params2, paramsX V.// [(i, v)])\n      parameters1 = runST $ do\n        (finMap0, finMap1, outerFinMap2, finMapX) <- initializeFinMaps st\n        -- We use normal hmatrix matrices rather than the sparse replacement.\n        finMap2 <- VM.replicate (VM.length outerFinMap2) (HM.fromRows [])\n        -- TODO: the following coredumps without the @VM.take@; it's a shame\n        -- there's no copying of a smaller vector into a larger one in the API.\n        -- Perhaps use https://hackage.haskell.org/package/base-4.16.0.0/docs/Foreign-Marshal-Array.html#v:copyArray?\n        V.unsafeCopy (VM.take (V.length params0Init) finMap0) params0Init\n        V.unsafeCopy (VM.take (V.length params1Init) finMap1) params1Init\n        V.unsafeCopy (VM.take (V.length params2Init) finMap2) params2Init\n        V.unsafeCopy (VM.take (V.length paramsXInit) finMapX) paramsXInit\n        v0 <- V.unsafeFreeze finMap0\n        v1 <- V.unsafeFreeze finMap1\n        v2 <- V.unsafeFreeze finMap2\n        vX <- V.unsafeFreeze finMapX\n        return (v0, v1, v2, vX)\n      parametersB = foldl' evalUnlessZero parameters1\n                           (reverse $ deltaBindings st)\n  in eval0 parametersB deltaTopLevel\n\n-- | This is yet another semantics of delta-expressions and their\n-- bindings --- by pretty-printing as texts.\nppBindings :: (Show r, Numeric r) => Bool -> DeltaState r -> Delta0 r -> String\nppBindings reversed st deltaTopLevel =\n  let pp = if reversed\n           then foldl' (\\ !l b -> l ++ ppBinding \"where\" b)\n                       [\"COMPUTE \" ++ ppShow deltaTopLevel ++ \"\\n\"]\n           else foldl' (\\ !l b -> ppBinding \"let\" b ++ l)\n                       [\"in \" ++ ppShow deltaTopLevel ++ \"\\n\"]\n  in concat $ pp $ deltaBindings st\n\nppBinding :: (Show r, Numeric r) => String -> DeltaBinding r -> [String]\nppBinding prefix = \\case\n  DeltaBinding0 (DeltaId i) d ->\n    [prefix ++ \"0 DeltaId_\", show i, \" = \", ppShow d, \"\\n\"]\n  DeltaBinding1 (DeltaId i) d ->\n    [prefix ++ \"1 DeltaId_\", show i, \" = \", ppShow d, \"\\n\"]\n  DeltaBinding2 (DeltaId i) d ->\n    [prefix ++ \"2 DeltaId_\", show i, \" = \", ppShow d, \"\\n\"]\n  DeltaBindingX (DeltaId i) d ->\n    [prefix ++ \"X DeltaId_\", show i, \" = \", ppShow d, \"\\n\"]\n\nbindInState0 :: Delta0 r -> DeltaState r -> (DeltaState r, DeltaId r)\n{-# INLINE bindInState0 #-}\nbindInState0 u' st =\n  let dId = deltaCounter0 st\n      !binding = DeltaBinding0 dId u'\n  in ( st { deltaCounter0 = succDeltaId dId\n          , deltaBindings = binding : deltaBindings st\n          }\n     , dId )\n\nbindInState1 :: Delta1 r -> DeltaState r -> (DeltaState r, DeltaId (Vector r))\n{-# INLINE bindInState1 #-}\nbindInState1 u' st =\n  let dId = deltaCounter1 st\n      !binding = DeltaBinding1 dId u'\n  in ( st { deltaCounter1 = succDeltaId dId\n          , deltaBindings = binding : deltaBindings st\n          }\n     , dId )\n\nbindInState2 :: Delta2 r -> DeltaState r -> (DeltaState r, DeltaId (Matrix r))\n{-# INLINE bindInState2 #-}\nbindInState2 u' st =\n  let dId = deltaCounter2 st\n      !binding = DeltaBinding2 dId u'\n  in ( st { deltaCounter2 = succDeltaId dId\n          , deltaBindings = binding : deltaBindings st\n          }\n     , dId )\n\nbindInStateX :: DeltaX r -> DeltaState r -> (DeltaState r, DeltaId (OT.Array r))\n{-# INLINE bindInStateX #-}\nbindInStateX u' st =\n  let dId = deltaCounterX st\n      !binding = DeltaBindingX dId u'\n  in ( st { deltaCounterX = succDeltaId dId\n          , deltaBindings = binding : deltaBindings st\n          }\n     , dId )\n\n{- Note [SumElements0]\n~~~~~~~~~~~~~~~~~~~~~~\n\nThe second argument of SumElements0 is the length of the vector\nto be summed. Given that we sum a delta-expression representing\na vector, we can't call Vector.length on it, so the length needs\nto be recorded in the constructor. Alternatively, it could be\nrecorded in the Delta1 argument to SumElements0. This is what\nshaped tensors do at the type level, so for DeltaS the argument\nwould not be needed.\n\nSum of vector elements can be implemented using a delta-expression\nprimitive SumElements0 as well as without this primitive, referring\nonly to the primitive Index0:\n\nhttps://github.com/Mikolaj/horde-ad/blob/d069a45773ed849913b5ebd0345153072f304fd9/src/HordeAd/Core/DualNumber.hs#L125-L143\n\nwhich is confirmed by tests to be equivalent in three different\nimplementations:\n\nhttps://github.com/Mikolaj/horde-ad/blob/d069a45773ed849913b5ebd0345153072f304fd9/test/TestSingleGradient.hs#L116-L128\n\nand proved to be prohibitively slow in the two implementations\nthat don't use the SumElements0 primitive in benchmarks (despite\nan ingenious optimization of the common case of Index0 applied to a variable):\n\nhttps://github.com/Mikolaj/horde-ad/blob/d069a45773ed849913b5ebd0345153072f304fd9/bench/BenchProdTools.hs#L178-L193\n-}\n\ndummyTensor :: Numeric r => OT.Array r\ndummyTensor =  -- an inconsistent tensor array\n  Data.Array.Internal.DynamicS.A\n  $ Data.Array.Internal.DynamicG.A []\n  $ Data.Array.Internal.T [] (-1) V.empty\n\nisTensorDummy :: OT.Array r -> Bool\nisTensorDummy (Data.Array.Internal.DynamicS.A\n                 (Data.Array.Internal.DynamicG.A _\n                    (Data.Array.Internal.T _ (-1) _))) = True\nisTensorDummy _ = False\n\ndata CodeOut =\n    PlusOut | MinusOut | TimesOut | NegateOut | AbsOut | SignumOut\n  | DivideOut | RecipOut\n  | ExpOut | LogOut | SqrtOut | PowerOut | LogBaseOut\n  | SinOut | CosOut | TanOut | AsinOut | AcosOut | AtanOut\n  | SinhOut | CoshOut | TanhOut | AsinhOut | AcoshOut | AtanhOut\n  | Atan2Out\n  deriving Show\n", "meta": {"hexsha": "4151c8489d080719a6bee7ff5a379559b5fdd094", "size": 45200, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Internal/Delta.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/Internal/Delta.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/Internal/Delta.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": 44.5759368836, "max_line_length": 122, "alphanum_fraction": 0.6302433628, "num_tokens": 12518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.3040416875789103, "lm_q1q2_score": 0.20753087010776197}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE BangPatterns #-}\nmodule SDLib where\n\nimport qualified SDL\nimport qualified Graphics.Rendering.OpenGL.GL as GL\nimport           Graphics.Rendering.OpenGL.GL (($=))\nimport           Control.Monad\nimport qualified Numeric.LinearAlgebra as L\nimport           Numeric.LinearAlgebra.Data (flatten)\nimport qualified Numeric.LinearAlgebra.Data as LD\nimport           Control.Lens      hiding (indices)\nimport           Debug.Trace\nimport           Control.Arrow\nimport qualified Data.Vector as V\nimport Data.Vector.Strategies\nimport Control.Concurrent (forkOS, killThread)\nimport Control.Concurrent.MVar\n\n\nimport           Utils (step, projectionMatrix,normalize,clampSpeed,norm)\n\nimport           OBJReader\nimport           Data.Shaders (loadShaders)\n\nimport           Data.Mesh    ( loadTexture\n                              , createMesh\n                              , flatQuad\n                              , quaternion)\nimport           Data.GameObject\nimport           Physics.Collision\nimport           Data.Scene\nimport           Data.PhysicsData (acc,speed)\nimport           Data.SkyBox\nimport           Physics.Mechanics\nimport           Tasks.Swarm\nimport           EventHandler\nimport           Utils.Quaternions\n\nframeTime = round $ 1000/60\n\n\n-- drawThread ::\n\ndebugPrint (GL.DebugMessage _ GL.DebugTypeError _ _ err) = putStrLn err\ndebugPrint _ = return ()\n\nsetup = do\n  SDL.swapInterval $= SDL.SynchronizedUpdates\n  GL.depthFunc $= Just GL.Less\n  -- GL.cullFace $= Just GL.Front\n  -- GL.debugMessageCallback $= Just debugPrint\n  -- GL.debugOutput $= GL.Enabled\n\n\ndrawThread mv window = forkOS $ do\n  context <- SDL.glCreateContext window\n  setup\n  let uniforms = [\"camera\",\"proj\",\"pos\",\"rot\",\"texSampler\",\"normSampler\"] :: [String]\n  shad <- loadShaders \"shaders/vert.glsl\" \"shaders/frag.glsl\" uniforms\n  shadNoTex <- loadShaders \"shaders/vert.glsl\" \"shaders/frag_no_text.glsl\" uniforms\n  ultraMesh <- readOBJ \"media/sphere.obj\"\n  ultraVeh  <- readOBJ \"media/cube.obj\"\n  vehPrim   <- readBoxFromObj \"media/cube.obj\"\n  let miniVeh = ultraMesh\n  meh       <- createMesh ultraVeh shadNoTex Nothing Nothing\n  veh       <- createMesh ultraMesh shadNoTex Nothing Nothing\n  -- crvMesh   <- createMesh curveVertices shadNoTex Nothing\n  tex       <- loadTexture \"media/bricks_dif.png\"\n  normalTex <- loadTexture \"media/bricks_norm.png\"\n  sbox      <- loadSkyBox\n  qd        <- flatQuad shad tex normalTex\n  let quads =\n        V.fromList .\n        map (\\(x,z) -> GameObject qd [x, -2.5, z] Nothing [] (Plane [0,1,0] (-2.5))) $\n        [(x,z) | x <- [-30,-26..30], z <- [-30,-26..30]]\n      camPos = [ 0, 10,20]\n      vehOb pos = initializePhysics (1/10) $\n        GameObject meh pos Nothing [] vehPrim\n      sphOb pos = initializePhysics (1/10) .\n                  GameObject veh pos Nothing [] $\n                  Sphere 1 (LD.ident 4)\n      dim = 1\n      sep = 3\n      vehs = -- V.fromList [vehOb [0.5,1,-5]]\n        -- V.fromList []\n                    -- initializePhysics (1/10) .\n                    -- GameObject veh [0.5,1,-5] Nothing [] $\n                    -- Sphere 1 (LD.ident 4)]\n        V.fromList [sphOb [0,2,sep*z] | z <- [0..dim]]\n      mehOb =\n        -- initializePhysics (1/100) .\n        --             GameObject veh [0, 0, 10] Nothing [] $\n        --             Sphere 1 (LD.ident 4)\n        initializePhysics (1/10) $\n        GameObject meh [0,0,10] Nothing [] vehPrim\n      -- curve = GameObject crvMesh [0,0,0] Nothing []\n      scene = Scene camPos (Objects mehOb vehs quads) (flatten . L.tr $ projectionMatrix) (Just sbox)\n  putMVar mv scene\n  drawLoop\n  where drawLoop = takeMVar mv >>= draw window >> drawLoop\n\nmainLoop :: MVar Scene -> SDL.Window -> Scene -> IO ()\nmainLoop mv window scene = do\n  begTime <- SDL.ticks\n  events <- SDL.pollEvents\n  kState <- SDL.getKeyboardState\n  let qpressed   = any handleQuit events\n      -- newTime    = time + (0.1*step)\n      -- newTime2   = if newTime > 1 then 0 else newTime\n      handleKeys = foldr ((.).keyHandler) id $ filter kState keys\n      loc        = scene^.objects.player.location\n      -- updateNPCS = applyLinear\n      --            . over (physics._Just.speed) (clamp 20)\n      --            . addGravityForce loc\n      !newScene  = -- set objects.player.location) (countPosition newTime2)\n                 adjustCamera .\n                 over objects resolveObjectCollisions .\n                 traverseObjects (floorReaction . applyForce . friction) .\n                 traverseObjects gravityF $\n                 -- . over (objects.npc) (computeForces updateNPCS)\n                 handleKeys scene\n  -- print $ newScene^.campos\n  endTime <- SDL.ticks\n  when ((endTime - begTime) < frameTime)\n    $ SDL.delay (frameTime - (endTime - begTime))\n  print $ endTime - begTime\n  print $ scene^.objects.player\n  let cp = prepareCPrim $ scene^.objects.player\n      p  = V.toList $ _cpoints cp\n      d  = [norm (a- b) | a <- p, b <- p]\n  print $ p\n  print d\n  putMVar mv newScene\n  unless qpressed $ mainLoop mv window newScene\n\nsdlMain :: IO ()\nsdlMain = do\n  SDL.initializeAll\n  window <- SDL.createWindow \"yolo\" SDL.defaultWindow {\n      SDL.windowOpenGL = Just SDL.defaultOpenGL\n    , SDL.windowInitialSize = SDL.V2 1366 768 }\n  mv <- newEmptyMVar\n  dthr <- drawThread mv window\n  scene <- takeMVar mv\n  mainLoop mv window scene\n  killThread dthr\n  GL.finish\n  -- SDL.glDeleteContext context\n  SDL.quit\n", "meta": {"hexsha": "a0b21663887e05931d2a3866170f4c9854d1d177", "size": 5524, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SDLib.hs", "max_stars_repo_name": "Antystenes/CPG", "max_stars_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "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/SDLib.hs", "max_issues_repo_name": "Antystenes/CPG", "max_issues_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "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/SDLib.hs", "max_forks_repo_name": "Antystenes/CPG", "max_forks_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "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.8701298701, "max_line_length": 101, "alphanum_fraction": 0.6164011586, "num_tokens": 1453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.20712816634825396}}
{"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE BangPatterns          #-}\n-- |\n-- Module     : Data.Matrix.Generic.Mutable\n-- Copyright  : Copyright (c) 2012 Aleksey Khudyakov <alexey.skladnoy@gmail.com>\n-- License    : BSD3\n-- Maintainer : Aleksey Khudyakov <alexey.skladnoy@gmail.com>\n-- Stability  : experimental\n--\n-- Interface for generic mutable matrices. For matrix transposition\n-- and conjugate transposition newtype wrappers are used.\nmodule Data.Matrix.Generic.Mutable (\n    -- * Type class\n    IsMMatrix(..)\n    -- * Accesors\n  , rows\n  , cols\n  , shape\n    -- * Reading and writing\n  , read\n  , write\n  , unsafeRead\n  , unsafeWrite\n  , cloneShape\n  , clone\n    -- * Newtype wrappers\n  , TransposedM(..)\n  , ConjugatedM(..)\n  ) where\n\nimport Control.Monad.Primitive\nimport Data.Complex             (Complex,conjugate)\nimport Prelude hiding (read)\n\n----------------------------------------------------------------\n-- Type class\n----------------------------------------------------------------\n\n-- | Type class of mutable matrices. Since there's many way to lay\n--   matrix in memory there isn't many operation which work for all of\n--   them.\n--\n--   Indexing uses following form: @(row,column)@\nclass IsMMatrix mat a where\n  -- | Number of rows.\n  basicRows :: mat s a -> Int\n  -- | Number of columns.\n  basicCols :: mat s a -> Int\n  -- | Whether index could be mutated. E.g. not every element of\n  --   banded matrix could be written to. Function need not to check\n  --   that indices are inside of the matrix and free to return anything if\n  --   they are outside.\n  basicIsIndexMutable :: mat s a -> (Int,Int) -> Bool\n  -- | Retrive element at given index. It should alway succed if row\n  --   and column numbers are in range.\n  basicUnsafeRead :: PrimMonad m => mat (PrimState m) a -> (Int,Int) -> m a\n  -- | Write element at given index.\n  basicUnsafeWrite :: PrimMonad m => mat (PrimState m) a -> (Int,Int) -> a -> m ()\n  -- | Create matrix with same dimensions. Elements' values are undefined\n  --\n  --   Unlike vector which have only length there are many kinds of\n  --   matrices. it's not possible to write such function from simpler ones.\n  basicCloneShape :: PrimMonad m => mat (PrimState m) a -> m (mat (PrimState m) a)\n  -- | Create copy of matrix.\n  basicClone :: PrimMonad m => mat (PrimState m) a -> m (mat (PrimState m) a)\n\n\n----------------------------------------------------------------\n-- Accesors\n----------------------------------------------------------------\n\n-- | Number of rows.\nrows :: IsMMatrix mat a => mat s a -> Int\n{-# INLINE rows #-}\nrows = basicRows\n\n-- | Number of columns.\ncols :: IsMMatrix mat a => mat s a -> Int\n{-# INLINE cols #-}\ncols = basicCols\n\n-- | Shape of the matrix.\nshape :: IsMMatrix mat a => mat s a -> (Int,Int)\n{-# INLINE shape #-}\nshape m = (rows m, cols m)\n\n-- | Whether index could be mutated. E.g. not every element of banded\n--   matrix could be written to. Function need not to check that\n--   indices are inside of the matrix and free to return anything if\n--   they are outside\nisIndexMutable :: IsMMatrix mat a => mat s a -> (Int, Int) -> Bool\n{-# INLINE isIndexMutable #-}\nisIndexMutable = basicIsIndexMutable\n\n\n\n----------------------------------------------------------------\n-- Read/write\n----------------------------------------------------------------\n\n-- | Read matrix element at given index. It should alway succed if row\n--   and column numbers are in range.\nread :: (PrimMonad m, IsMMatrix mat a) => mat (PrimState m) a -> (Int,Int) -> m a\n{-# INLINE read #-}\nread m i@(!r,!c)\n  | r < 0 || r >= rows m = error \"Numeric.BLAS.Matrix.Mutable.read: row out of bounds\"\n  | c < 0 || r >= cols m = error \"Numeric.BLAS.Matrix.Mutable.read: column out of bounds\"\n  | otherwise            = unsafeRead m i\n\n\n-- | Write element to matrix at given index. It could be impossible to\n--   change values of some elements.\nwrite :: (PrimMonad m, IsMMatrix mat a) => mat (PrimState m) a -> (Int,Int) -> a -> m ()\n{-# INLINE write #-}\nwrite m i@(!r,!c)\n  | r < 0 || r >= rows m = error \"Numeric.BLAS.Matrix.Mutable.write: row out of bounds\"\n  | c < 0 || r >= cols m = error \"Numeric.BLAS.Matrix.Mutable.write: column out of bounds\"\n  | isIndexMutable m i   = basicUnsafeWrite m i\n  | otherwise            = error \"Numeric.BLAS.Matrix.Mutable.write: index is not mutable\"\n\n-- | Read element from matrix without range checking\nunsafeRead :: (PrimMonad m, IsMMatrix mat a) => mat (PrimState m) a -> (Int, Int) -> m a\n{-# INLINE unsafeRead #-}\nunsafeRead = basicUnsafeRead\n\n-- | Write element to matrix without range checking.\nunsafeWrite :: (PrimMonad m, IsMMatrix mat a) => mat (PrimState m) a -> (Int, Int) -> a -> m ()\n{-# INLINE unsafeWrite #-}\nunsafeWrite = basicUnsafeWrite\n\n-- | Create matrix with same dimensions. Elements' values are undefined\n--\n--   Unlike vector which have only length there are many kinds of\n--   matrices. it's not possible to write such function from simpler ones.\ncloneShape :: (PrimMonad m, IsMMatrix mat a) => mat (PrimState m) a -> m (mat (PrimState m) a)\n{-# INLINE cloneShape #-}\ncloneShape = basicCloneShape\n\n-- | Create copy of matrix.\nclone :: (PrimMonad m, IsMMatrix mat a) => mat (PrimState m) a -> m (mat (PrimState m) a)\n{-# INLINE clone #-}\nclone = basicClone\n\n\n\n----------------------------------------------------------------\n-- Newtypes\n----------------------------------------------------------------\n\n-- | Transposed matrix\nnewtype TransposedM mat s a = TransposedM { unTranspose :: mat s a }\n\ninstance IsMMatrix mat a => IsMMatrix (TransposedM mat) a where\n  basicRows (TransposedM m) = cols m\n  {-# INLINE basicRows #-}\n  basicCols (TransposedM m) = rows m\n  {-# INLINE basicCols #-}\n  basicIsIndexMutable (TransposedM m) (i,j)   = isIndexMutable m (j,i)\n  {-# INLINE basicIsIndexMutable #-}\n  basicUnsafeRead     (TransposedM m) (i,j)   = unsafeRead     m (j,i)\n  {-# INLINE basicUnsafeRead #-}\n  basicUnsafeWrite    (TransposedM m) (i,j) x = unsafeWrite    m (j,i) x\n  {-# INLINE basicUnsafeWrite #-}\n  basicCloneShape     (TransposedM m) = do { r <- basicCloneShape m; return $ TransposedM r }\n  {-# INLINE basicCloneShape #-}\n  basicClone          (TransposedM m) = do { r <- basicCloneShape m; return $ TransposedM r }\n  {-# INLINE basicClone #-}\n\n-- | Conjugate-transposed matrix\nnewtype ConjugatedM mat s a = ConjugatedM { unConjugate :: mat s a }\n\ninstance (IsMMatrix mat (Complex a), RealFloat a) => IsMMatrix (ConjugatedM mat) (Complex a) where\n  basicRows (ConjugatedM m) = basicCols m\n  {-# INLINE basicRows #-}\n  basicCols (ConjugatedM m) = rows m\n  {-# INLINE basicCols #-}\n  basicIsIndexMutable (ConjugatedM m) (i,j)   = isIndexMutable m (j,i)\n  {-# INLINE basicIsIndexMutable #-}\n  basicUnsafeRead (ConjugatedM m) (i,j)\n    | j >= i    = unsafeRead m (j,i)\n    | otherwise = do { x <- unsafeRead m (j,i); return $! conjugate x }\n  {-# INLINE basicUnsafeRead #-}\n  basicUnsafeWrite (ConjugatedM m) (i,j) x\n    | j >= i    = unsafeWrite m (j,i) x\n    | otherwise = unsafeWrite m (j,i) $! conjugate x\n  {-# INLINE basicUnsafeWrite #-}\n  basicCloneShape     (ConjugatedM m) = do { r <- basicCloneShape m; return $ ConjugatedM r }\n  {-# INLINE basicCloneShape #-}\n  basicClone          (ConjugatedM m) = do { r <- basicCloneShape m; return $ ConjugatedM r }\n  {-# INLINE basicClone #-}\n", "meta": {"hexsha": "460f838bec6d5a5d721852ad9e1ab69910ecbc4d", "size": 7396, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Matrix/Generic/Mutable.hs", "max_stars_repo_name": "Shimuuar/blas-lapack", "max_stars_repo_head_hexsha": "1b1bd3d1a61c4068a295a92ca369bb807f5868fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-31T04:52:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T04:52:43.000Z", "max_issues_repo_path": "Data/Matrix/Generic/Mutable.hs", "max_issues_repo_name": "Shimuuar/blas-lapack", "max_issues_repo_head_hexsha": "1b1bd3d1a61c4068a295a92ca369bb807f5868fb", "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": "Data/Matrix/Generic/Mutable.hs", "max_forks_repo_name": "Shimuuar/blas-lapack", "max_forks_repo_head_hexsha": "1b1bd3d1a61c4068a295a92ca369bb807f5868fb", "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": 38.3212435233, "max_line_length": 98, "alphanum_fraction": 0.6142509465, "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2049247125387315}}
{"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    \u2102\n  , \u211d\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 \u211d = Float\ntype \u2102 = Complex \u211d\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 -> \u2102))\n        -- ^ Regulariser for the S matrix. If it is @'Just' f@,\n        -- then @\u03bb = f i@ where @i@ is the currect iteration is used to\n        -- regularise the matrix S according to @S <- S + \u03bb1@.\n    , _sRConfigRate :: !(Int -> \u2102)\n        -- ^ Learning rate as a function of the iteration.\n    , _sRConfigCg :: !(CGConfig \u211d)\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}}
{"text": "module OidTableSVG where\n\nimport Data.Word\nimport qualified Data.ByteString.Lazy as LB\nimport Control.Monad hiding (forM_)\nimport Data.Foldable (forM_)\nimport Text.Printf\nimport Control.Arrow ((***))\nimport Data.String\nimport Data.Complex\n\nimport qualified Text.Blaze.Svg11 as S\nimport qualified Text.Blaze.Svg11.Attributes as A\nimport Text.Blaze.Svg11 ((!))\nimport Text.Blaze.Svg.Renderer.Utf8\n\nimport OidCode\nimport KnownCodes\nimport Types\nimport Utils\n\ntype Point = Complex Double\n\noidTableSvg :: Conf -> Bool -> String -> [(String, Word16)] -> LB.ByteString\noidTableSvg conf usePNG title entries\n    | entriesPerPage < 1 = error \"OID codes too large to fit on a single page\"\n    | otherwise = renderSvg $\n        S.docTypeSvg  ! A.version (S.toValue \"1.1\")\n                      ! A.width  (S.toValue (printf \"%fmm\" (a4w/mm) :: String))\n                      ! A.height (S.toValue (printf \"%fmm\" (a4h/mm) :: String))\n                      ! A.viewbox (S.toValue (printf \"0 0 %f %f\" a4w a4h :: String))\n                      ! A.fontFamily (S.toValue \"sans-serif\")\n                      $ do\n    let patid d c | d == show c = d\n                  | otherwise   = printf \"%s-%d\" d c\n\n    -- Create patterns for the codes\n    S.defs $ forM_ entries $ \\(d,c) ->\n        case code2RawCode c of\n            Nothing -> return ()\n            Just rc -> oidSVGPattern conf usePNG (patid d c) rc\n\n    -- For SVG, we put all on one page (and exceed the page if it is too big)\n    let chunks = [entries]\n    let totalPages = length chunks\n\n    forM_ (zip [1::Int ..] chunks) $ \\(pageNum, thisPage) -> do\n            S.text_ ! A.x (S.toValue (a4w / 2))\n                    ! A.y (S.toValue (padTop + titleHeight))\n                    ! A.textAnchor (S.toValue \"middle\")\n                    ! A.stroke (S.toValue \"black\")\n                    ! A.fontSize (S.toValue (printf \"%f\" (12*pt) :: String))\n                    $ fromString title\n\n            S.text_ ! A.x (S.toValue padLeft)\n                    ! A.y (S.toValue (a4h - padBot))\n                    ! A.textAnchor (S.toValue \"left\")\n                    ! A.stroke (S.toValue \"black\")\n                    ! A.fontSize (S.toValue (printf \"%f\" (8*pt) :: String))\n                    $ fromString $ \"Created by tttool-\" ++ tttoolVersion\n\n\n            forM_ (zip thisPage positions) $ \\((d,c), x :+ y) -> do\n                S.rect ! A.width (S.toValue imageWidth)\n                       ! A.height (S.toValue imageHeight)\n                       ! A.x (S.toValue x)\n                       ! A.y (S.toValue y)\n                       ! A.fill (S.toValue $ \"url(#\"++patid d c++\")\")\n\n                S.text_ ! A.x (S.toValue x)\n                        ! A.y (S.toValue (y + imageHeight + subtitleSep + subtitleHeight))\n                        ! A.textAnchor (S.toValue \"left\")\n                        ! A.stroke (S.toValue \"black\")\n                        ! A.fontSize (S.toValue (printf \"%f\" (8*pt) :: String))\n                        $ fromString d\n  where\n    -- Configure-dependent dimensions (all in pt)\n    (imageWidth,imageHeight) = (*mm) *** (*mm) $ fromIntegral *** fromIntegral $cCodeDim conf\n\n    -- Static dimensions (all in pt)\n\n    -- Page paddings\n    padTop, padLeft, padBot, padRight :: Double\n    padTop   = 1*cm\n    padBot   = 1*cm\n    padLeft  = 2*cm\n    padRight = 2*cm\n\n    titleHeight  = 1*cm\n    titleSep     = 0.5*cm\n    footerHeight = 0.5*cm\n    footerSep    = 0.5*cm\n\n    imageSepH = 0.4*cm\n    imageSepV = 0.2*cm\n\n    subtitleHeight = 0.4*cm\n    subtitleSep    = 0.2*cm\n\n    -- Derived dimensions (all in pt)\n    {-\n    titleRect = Rectangle\n        (padLeft          :+ (a4h - padTop - titleHeight))\n        ((a4w - padRight) :+ (a4h - padTop))\n    titleFont = Font (PDFFont Helvetica 12) black black\n\n    footerRect = Rectangle\n        (padLeft          :+ padBot)\n        ((a4w - padRight) :+ (padBot + footerHeight))\n    footerFont = Font (PDFFont Helvetica 8) black black\n\n    bodyFont = Font (PDFFont Helvetica 8) black black\n    -}\n\n    bodyWidth  = a4w - padLeft - padRight\n    bodyHeight = a4h - padTop - titleHeight - titleSep - footerSep - footerHeight - padBot\n\n\n    positions = map (+(padLeft :+ (padTop + titleHeight + titleSep))) $\n        calcPositions bodyWidth  bodyHeight\n                      imageWidth (imageHeight + subtitleSep + subtitleHeight)\n                      imageSepH  imageSepV\n    entriesPerPage = length positions\n\n\n    -- Derived dimensions (all in pixels)\n    imageWidthPx = floor (imageWidth * px)\n    imageHeightPx = floor (imageHeight * px)\n\n    -- config-dependent conversion factors\n    px :: Double\n    px = fromIntegral (cDPI conf) / 72\n\n\n    {-\n    -- Makes sure the given point is at a coordinate that is a multiple\n    -- of an pixel\n    align :: Point -> Point\n    align pos = alignToPx (realPart pos) :+ (a4h - alignToPx (a4h - imagPart pos))\n\n    -- Makes sure the given distance is an interal mulitple of a pixel\n    alignToPx :: Double -> Double\n    alignToPx x = fromIntegral (floor (x * px)) / px\n    -}\n\ncalcPositions\n    :: Double -- ^ total width\n    -> Double -- ^ total height\n    -> Double -- ^ entry width\n    -> Double -- ^ entry height\n    -> Double -- ^ pad width\n    -> Double -- ^ pad height\n    -> [Point]\ncalcPositions tw th ew eh pw ph = [ x :+ ({-(th - -} y) | y <- ys , x <- xs]\n  where\n    xs = [0,ew+pw..tw-ew]\n    ys = [0,eh+ph..th-eh]\n\npt :: Double\npt = 48/2.83465\n\n-- Conversation factor\ncm :: Double\ncm = 10 * mm\n\nmm :: Double\nmm = 2.83465 * pt\n\n-- A4 dimensions\na4w, a4h :: Double\na4w = 595 * pt\na4h = 842 * pt\n", "meta": {"hexsha": "0c363dfe02fa434b118682d37fd3d005e1eae343", "size": 5556, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/OidTableSVG.hs", "max_stars_repo_name": "dalijolijo/tip-toi-reveng", "max_stars_repo_head_hexsha": "d048dbeb1a78eae86d8f7eb58b519ade10281b11", "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": "src/OidTableSVG.hs", "max_issues_repo_name": "dalijolijo/tip-toi-reveng", "max_issues_repo_head_hexsha": "d048dbeb1a78eae86d8f7eb58b519ade10281b11", "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": "src/OidTableSVG.hs", "max_forks_repo_name": "dalijolijo/tip-toi-reveng", "max_forks_repo_head_hexsha": "d048dbeb1a78eae86d8f7eb58b519ade10281b11", "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": 32.1156069364, "max_line_length": 93, "alphanum_fraction": 0.555975522, "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.20244453060103684}}
{"text": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE DefaultSignatures #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FunctionalDependencies #-}\n\n{-# LANGUAGE AllowAmbiguousTypes #-}\n\nmodule Expr where\n\nimport           Data.Void\nimport           Data.Tagged\nimport           Data.Proxy\nimport           Data.Constraint (Constraint)\n\nimport           Data.Bifunctor\n\nimport           GHC.Generics\nimport           Language.Haskell.TH (Name)\n\nimport           Data.Complex\n\nimport           GHC.Types\n\ndata Tagged2 (h :: k) (t :: *) (a :: *) = Tagged2 { unTagged2 :: a }\n\n-- Idea: Represent a pattern match of a particular type as\n--    KnownSymbol name => Proxy name -> MatchType name\n-- with 'MatchType' being a type family that gives the type of the match\n-- associated to matching on the constructor named 'name'. Maybe these\n-- could be stored in a heterogenous list.\n\n-- | Idea: Deep embedding for a pattern match (possibly using a non-regular\n-- type?). Convert types to a \"canonical form\" to use this (like 'Either's\n-- and '(,)'s)\n\n-- TODO: Should we have a phantom type argument with the original type to preserve (possibly) more type safety?\n\n-- TODO: Should this just be a function type? Maybe it could be a function\n-- from s -> t, where is a nested pair type, and we use projection\n-- combinators to extract the values inside the function.\ndata ProdMatch s t where\n  ProdMatch ::\n    (GPURep k1 a, GPURep k2 b)\n       => (GPUExp (GetType a) -> ProdMatch b r) -> ProdMatch (Tagged2 (TypeHead t) t (a, b)) r\n\n  OneProdMatch :: (GPURep k a) => (GPUExp (GetType a) -> GPUExp r) -> ProdMatch a r\n  NullaryMatch :: GPURep k r => GPUExp r -> ProdMatch a r\n\ndata SumMatch s t where\n  SumMatch ::\n    (GPURep k1 a, GPURep k2 b, GPURepTy b ~ b)\n        => ProdMatch a r -> SumMatch b r -> SumMatch (Tagged2 (TypeHead t) t (Either a b)) r\n\n  EmptyMatch :: SumMatch Void r\n\n  OneSumMatch :: (GPURep k1 a, GPURep k2 b, GPURepTy a ~ a) => ProdMatch a b -> SumMatch a b\n\n\ntype family TagMatches t x :: Constraint where\n  -- TagMatches t (Tagged2 h t x) = ()\n  TagMatches t (Tagged2 h t x) = TypeHead t ~ h\n\ndata SafeSumMatch origType s t where\n  SafeSumMatch :: TagMatches origType s => Proxy (TypeHead s) -> SumMatch s t -> SafeSumMatch origType s t\n\n  SafeEmptyMatch :: SafeSumMatch origType Void r\n  SafeOneMatch :: (GPURep k1 a, GPURep k2 b, GPURepTy a ~ a) => ProdMatch a b -> SafeSumMatch origType a b\n\n\ntype family TagWith t x where\n  TagWith t (Tagged2 h t' x) = Tagged2 (TypeHead t) t x\n  TagWith t x                = Tagged2 (TypeHead t) t x\n\ntype family GetType x where\n  GetType (Tagged2 h t x) = t\n  GetType t            = t\n\ntype family Untag x where\n  Untag (Tagged2 h t x) = x\n  Untag x            = x\n\n-- Done (case ... of A -> x; B -> y)  ==>  (case ... of A -> Done x; B -> Done y)\ndata Iter a b\n  = Step b\n  | Done a\n  deriving (Functor, Generic)\n\ndata GPUExp t where\n  CaseExp :: (GPURep k t) => GPUExp t -> SafeSumMatch t (GPURepTy t) r -> GPUExp r\n\n  FalseExp :: GPUExp Bool\n  TrueExp :: GPUExp Bool\n\n  Repped :: GPURep k a => GPURepTy a -> GPUExp a\n\n  Lam :: GPURep k a => Name -> GPUExp b -> GPUExp (a -> b)\n  Var :: Proxy a -> Name -> GPUExp a -- Constructed internally\n\n  -- Lam :: GPURep a =>  -> GPUExp (a -> b)\n\n  Apply :: GPUExp (a -> b) -> GPUExp a -> GPUExp b\n\n  Lit :: Num a => a -> GPUExp a\n\n  Add :: Num a => GPUExp a -> GPUExp a -> GPUExp a\n  Sub :: Num a => GPUExp a -> GPUExp a -> GPUExp a\n  Mul :: Num a => GPUExp a -> GPUExp a -> GPUExp a\n\n  Twice :: GPUExp (a -> a) -> GPUExp a -> GPUExp a\n\n  FromEnum :: Enum a => GPUExp a -> GPUExp Int\n  FromIntegral :: (Integral a, Num b) => GPUExp a -> GPUExp b\n\n  Sqrt :: Floating a => GPUExp a -> GPUExp a\n\n  Equal :: Eq a => GPUExp a -> GPUExp a -> GPUExp Bool\n  Lte :: Ord a => GPUExp a -> GPUExp a -> GPUExp Bool\n  Gt :: Ord a => GPUExp a -> GPUExp a -> GPUExp Bool\n\n  Not :: GPUExp Bool -> GPUExp Bool\n\n  LeftExp :: GPUExp a -> GPUExp (Either a b)\n  RightExp :: GPUExp b -> GPUExp (Either a b)\n\n  PairExp :: GPUExp a -> GPUExp b -> GPUExp (a, b)\n\n  StepExp :: GPUExp b -> GPUExp (Iter a b)\n  DoneExp :: GPUExp a -> GPUExp (Iter a b)\n\n  IfThenElse :: GPUExp Bool -> GPUExp a -> GPUExp a -> GPUExp a\n\n  TailRec :: (GPURep k1 a, GPURep k2 b) => (GPUExp b -> GPUExp (Iter a b)) -> GPUExp (b -> a)\n\n  Construct :: a -> GPUExp a\n  ConstructAp :: (GPURep k a) => GPUExp (a -> b) -> GPUExp a -> GPUExp b\n\nclass GPURep k t where\n    -- Should we wrap these types in a 'Tagged t' in order to preserve more\n    -- type safety?\n  type GPURepTy t\n  type GPURepTy t = TagWith t (GPURepTy (Rep t Void))\n\n  -- | This should be unapplied type (without type arguments)\n  type TypeHead t :: k\n  -- type TypeHead t = t\n\n  rep :: t -> GPUExp t\n  rep = Repped . rep'\n\n  rep' :: t -> GPURepTy t\n\n  default rep' :: (Generic t, GenericRep (Rep t Void), GPURepTy t ~ Tagged2 (TypeHead t) t (GenericRepTy (Rep t Void)))\n    => t -> GPURepTy t\n  rep' = Tagged2 . genericRep' . (from :: t -> Rep t Void)\n\n\n  unrep' :: GPURepTy t -> t\n\n  default unrep' :: (Generic t, GenericRep (Rep t Void), GPURepTy t ~ Tagged2 (TypeHead t) t (GenericRepTy (Rep t Void)))\n    => GPURepTy t -> t\n  unrep' = (to :: Rep t Void -> t) . genericUnrep' . unTagged2\n\n  repGetType :: t -> GPUExp (GetType t)\n\n  default repGetType :: GetType t ~ t => t -> GPUExp (GetType t)\n  repGetType = rep\n\ninstance (GPURep k t, h ~ TypeHead t, GPURepTy t ~ Tagged2 h t x) => GPURep k (Tagged2 (h :: k) t x) where\n  type GPURepTy (Tagged2 h t x) = Tagged2 h t x\n  type TypeHead (Tagged2 h t x) = h -- This instance is special\n\n  rep' :: Tagged2 h t x -> GPURepTy (Tagged2 h t x)\n  rep' = id\n\n  unrep' :: GPURepTy (Tagged2 h t x) -> Tagged2 h t x\n  unrep' = id\n\n  repGetType :: Tagged2 h t x -> GPUExp (GetType (Tagged2 h t x))\n  repGetType = rep . unrep'\n\ninstance GPURep * Int where\n  type GPURepTy Int = Int\n  type TypeHead Int = Int\n  rep = Lit\n  rep' = id\n  unrep' = id\ninstance GPURep * Integer where\n  type GPURepTy Integer = Integer\n  type TypeHead Integer = Integer\n  rep = Lit\n  rep' = id\n  unrep' = id\ninstance GPURep * Float where\n  type GPURepTy Float = Float\n  type TypeHead Float = Float\n  rep = Lit\n  rep' = id\n  unrep' = id\ninstance GPURep * Double where\n  type GPURepTy Double = Double\n  type TypeHead Double = Double\n  rep = Lit\n  rep' = id\n  unrep' = id\n\ninstance GPURep * Bool where\n  type GPURepTy Bool = Bool\n  type TypeHead Bool = Bool\n  rep False = FalseExp\n  rep True  = TrueExp\n  rep' = id\n  unrep' = id\n\n\ninstance GPURep * a => GPURep (* -> *) (Complex a) where\n  type TypeHead (Complex a) = Complex\n\ninstance GPURep * a => GPURep (* -> *) (Maybe a) where\n  type TypeHead (Maybe a) = Maybe\n\n\ninstance (GPURep * a, GPURep * b) => GPURep (* -> * -> *) (Either a b) where\n  type GPURepTy (Either a b) = Tagged2 (Either) (Either a b) (Either (GPURepTy a) (GPURepTy b))\n  type TypeHead (Either a b) = Either\n\n  rep (Left x) = LeftExp (rep x)\n  rep (Right y) = RightExp (rep y)\n\n  rep' (Left x) = Tagged2 . Left $ rep' x\n  rep' (Right y) = Tagged2 . Right $ rep' y\n\n  unrep' (Tagged2 (Left x)) = Left $ unrep' x\n  unrep' (Tagged2 (Right y)) = Right $ unrep' y\n\ninstance (GPURep * a, GPURep * b) => GPURep (* -> * -> *) (a, b) where\n  type GPURepTy (a, b) = Tagged2 (,) (a, b) (GPURepTy a, GPURepTy b)\n  type TypeHead (a, b) = (,)\n\n  rep (x, y) = PairExp (rep x) (rep y)\n  rep' (x, y) = Tagged2 (rep' x, rep' y)\n  unrep' (Tagged2 (x, y)) = (unrep' x, unrep' y)\n\ninstance (GPURep * a, GPURep * b, GPURep * c) => GPURep (* -> * -> * -> *) (a, b, c) where\n  type TypeHead (a, b, c) = (,,)\ninstance (GPURep * a, GPURep * b, GPURep * c, GPURep * d) =>\n    GPURep (* -> * -> * -> * -> *) (a, b, c, d) where\n  type TypeHead (a, b, c, d) = (,,,)\n\n-- XXX: Should this instance exist?\ninstance (GPURep * a, GPURep * b) => GPURep (* -> * -> *) (Iter a b) where\n  type TypeHead (Iter a b) = Iter\n\n\n-- Generics instances\n-- i (c :: Meta) (f :: k -> *) (p :: k)\ninstance GPURep * (f p) => GPURep (* -> Meta -> (k -> *) -> k -> *) (M1 i c f p) where\n  type GPURepTy (M1 i c f p) = GPURepTy (f p)\n  type TypeHead (M1 i c f p) = M1\n\n  rep = Repped . rep'\n  rep' (M1 x) = rep' x\n  unrep' = M1 . unrep'\n\ninstance (GPURep k (p x), GPURep k (q x)) => GPURep ((k -> *) -> (k -> *) -> k -> *) ((p :+: q) x) where\n  type GPURepTy ((p :+: q) x) = Tagged2 (:+:) (Either (p x) (q x)) (Either (GPURepTy (p x)) (GPURepTy (q x)))\n  type TypeHead ((p :+: q) x) = (:+:)\n\n  rep = Repped . rep'\n\n  rep' (L1 x) = Tagged2 $ Left (rep' x)\n  rep' (R1 y) = Tagged2 $ Right (rep' y)\n\n  unrep' (Tagged2 (Left x)) = L1 (unrep' x)\n  unrep' (Tagged2 (Right y)) = R1 (unrep' y)\n\ninstance (GPURep k (p x), GPURep k (q x)) => GPURep ((k -> *) -> (k -> *) -> k -> *) ((p :*: q) x) where\n  type GPURepTy ((p :*: q) x) = Tagged2 (:*:) (p x, q x) (GPURepTy (p x), GPURepTy (q x))\n  type TypeHead ((p :*: q) x) = (:*:)\n\n  rep' (x :*: y) = Tagged2 (rep' x, rep' y)\n  unrep' (Tagged2 (x, y)) = (unrep' x :*: unrep' y)\n\ninstance GPURep * c => GPURep (* -> * -> k -> *) (K1 i c p) where\n  type GPURepTy (K1 i c p) = GPURepTy c\n  type TypeHead (K1 i c p) = K1\n\n  rep = Repped . rep'\n\n  rep' (K1 x) = rep' x\n  unrep' = K1 . unrep'\n\ninstance GPURep (k -> *) (U1 p) where\n  type GPURepTy (U1 p) = ()\n  type TypeHead (U1 p) = U1\n\n  rep' U1 = ()\n  unrep' () = U1\n\n\nclass GenericRep repr where\n    type GenericRepTy repr\n\n    genericRep' :: repr -> GenericRepTy repr\n    genericUnrep' :: GenericRepTy repr -> repr\n\ninstance forall k p q. (GPURep k (p Void), GPURep k (q Void)) =>\n  GenericRep ((p :+: q) Void) where\n\n    type GenericRepTy ((p :+: q) Void) = Either (GPURepTy (p Void)) (GPURepTy (q Void))\n\n    genericRep' = bimap rep' rep' . toCanonical\n    genericUnrep' = fromCanonical . bimap unrep' unrep'\n\ninstance (GPURep k (p Void), GPURep k (q Void)) =>\n  GenericRep ((p :*: q) Void) where\n\n    type GenericRepTy ((p :*: q) Void) = (GPURepTy (p Void), GPURepTy (q Void))\n\n    genericRep' = bimap rep' rep' . toCanonical\n    genericUnrep' = fromCanonical . bimap unrep' unrep'\n\ninstance (GenericRep (f Void)) =>\n  GenericRep (M1 i c f Void) where\n    type GenericRepTy (M1 i c f Void) = GenericRepTy (f Void)\n\n    genericRep' = genericRep' . unM1\n    genericUnrep' = M1 . genericUnrep'\n\nthe :: a -> a\nthe = id\n\nthe_repr :: GPUExp a -> GPUExp a\nthe_repr = id\n\ntype family LiftedFn t where\n  LiftedFn (a -> b) = GPUExp a -> LiftedFn b\n  LiftedFn b = GPUExp b\n\nconstruct :: (Construct t)\n  => t -> LiftedFn t\nconstruct = construct' . Construct\n\nclass Construct t where\n    construct' :: GPUExp t -> LiftedFn t\n\ninstance (GPURep k a, Construct b) => Construct (a -> b) where\n    construct' :: GPUExp (a -> b) -> GPUExp a -> LiftedFn b\n    construct' c = construct' . ConstructAp c\n\ninstance {-# INCOHERENT #-} (LiftedFn b ~ GPUExp b) => Construct b where\n    construct' :: GPUExp b -> GPUExp b\n    construct' = id\n\n-- Should this just produce an error?\nsumMatchAbs :: GPURep k s => SafeSumMatch s (GPURepTy s) t -> s -> t\nsumMatchAbs (SafeSumMatch Proxy s) = go s\n  where\n    go :: GPURep k s => SumMatch (GPURepTy s) t -> s -> t\n    go (SumMatch p q) =\n      \\x0 ->\n        let Tagged2 x = rep' x0\n        in\n        case x of\n          Left  a -> prodMatchAbs p a\n          Right b -> go q b\n    go EmptyMatch = \\_ -> error \"Non-exhaustive match\"\n    go (OneSumMatch f) = prodMatchAbs f . unrep' . rep' -- TODO: Is this reasonable?\n\nprodMatchAbs :: GPURep k s => ProdMatch s t -> s -> t\nprodMatchAbs (ProdMatch f) =\n  \\(Tagged2 pair) ->\n    case pair of\n      (x, y) -> prodMatchAbs (f (repGetType x)) y\n\nprodMatchAbs (OneProdMatch f) = \\x -> gpuAbs (f (repGetType x))\nprodMatchAbs (NullaryMatch x) = \\_ -> gpuAbs x\n\ngpuAbs :: GPUExp t -> t\ngpuAbs (CaseExp x f) = sumMatchAbs f (gpuAbs x)\ngpuAbs FalseExp = False\ngpuAbs TrueExp  = True\ngpuAbs (Repped x) = unrep' x\n-- gpuAbs (Lam f) = gpuAbs . f . rep\n-- gpuAbs (Apply f x) = gpuAbs f (gpuAbs x)\ngpuAbs (Lit x)  = x\ngpuAbs (Add x y) = gpuAbs x + gpuAbs y\ngpuAbs (Sub x y) = gpuAbs x - gpuAbs y\ngpuAbs (Mul x y) = gpuAbs x * gpuAbs y\ngpuAbs (FromEnum x) = fromEnum (gpuAbs x)\ngpuAbs (FromIntegral x) = fromIntegral (gpuAbs x)\ngpuAbs (Sqrt x) = sqrt (gpuAbs x)\ngpuAbs (Equal x y) = gpuAbs x == gpuAbs y\ngpuAbs (Lte x y) = gpuAbs x <= gpuAbs y\ngpuAbs (Gt x y) = gpuAbs x > gpuAbs y\ngpuAbs (Not x) = not (gpuAbs x)\ngpuAbs (LeftExp x) = Left (gpuAbs x)\ngpuAbs (RightExp y) = Right (gpuAbs y)\ngpuAbs (PairExp x y) = (gpuAbs x, gpuAbs y)\ngpuAbs (StepExp x) = Step $ gpuAbs x\ngpuAbs (DoneExp y) = Done $ gpuAbs y\ngpuAbs (TailRec f) = \\x ->\n  case gpuAbs (f (rep x)) of\n    Step x' -> gpuAbs (TailRec f) x'\n    Done r  -> r\ngpuAbs (IfThenElse cond t f)\n  | gpuAbs cond = gpuAbs t\n  | otherwise = gpuAbs f\ngpuAbs (Construct x) = x\ngpuAbs (ConstructAp f x) = gpuAbs f (gpuAbs x)\n\n\nclass Canonical t where\n  type GenericOp t :: (* -> *) -> (* -> *) -> * -> *\n\n  toCanonical :: GenericOp t p q x -> t (p x) (q x)\n  fromCanonical :: t (p x) (q x) -> GenericOp t p q x\n\ninstance Canonical Either where\n  type GenericOp Either = (:+:)\n\n  toCanonical (L1 x) = Left x\n  toCanonical (R1 y) = Right y\n\n  fromCanonical (Left x) = L1 x\n  fromCanonical (Right y) = R1 y\n\ninstance Canonical (,) where\n  type GenericOp (,) = (:*:)\n\n  toCanonical (x :*: y) = (x, y)\n  fromCanonical (x, y) = x :*: y\n\n\n", "meta": {"hexsha": "4d68a1aa57eb80c3ce55ef670c5a816bd7efab0a", "size": 13488, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Deep/Expr-kinds.hs", "max_stars_repo_name": "roboguy13/gpu-embed", "max_stars_repo_head_hexsha": "e04cddfcd972dc8087e2621137a1619021eab0eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-27T03:47:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-27T03:47:16.000Z", "max_issues_repo_path": "src/Deep/Expr-kinds.hs", "max_issues_repo_name": "roboguy13/gpu-embed", "max_issues_repo_head_hexsha": "e04cddfcd972dc8087e2621137a1619021eab0eb", "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/Deep/Expr-kinds.hs", "max_forks_repo_name": "roboguy13/gpu-embed", "max_forks_repo_head_hexsha": "e04cddfcd972dc8087e2621137a1619021eab0eb", "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": 30.4469525959, "max_line_length": 121, "alphanum_fraction": 0.6084667853, "num_tokens": 4591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.20192150024102862}}
{"text": "import Test.Tasty\nimport Test.Tasty.HUnit\n\nimport Control.Lens\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport Data.Default\nimport Data.Function\nimport Data.List\nimport Data.Ord\nimport Data.Maybe\n\nimport Linear\n\nimport Linear.Vector\nimport qualified Numeric.LinearAlgebra.HMatrix as HM\nimport qualified FrameGrabber\nimport StartFiducial as SF\nimport StartFiducialDebug\nimport TileMatcher\nimport TrackTracker as TT\nimport qualified TileMatcherDebug\nimport qualified Loop\nimport qualified Track\nimport Transform\nimport qualified OpenCV as CV\nimport TrackDebug\nimport OpenCV.Core.Types.Mat\nimport OpenCV.VideoIO.Types\nimport qualified Data.Vector as V\n\nimport Image\nimport qualified Video\nimport MaskDebug\nimport qualified SegmentPositionerTests\nimport FrameWriter\n\nimport Text.Printf\n\nimport System.IO.Unsafe ( unsafePerformIO )\n\nmain :: IO ()\nmain = defaultMain unitTests\n\nunitTests = testGroup \"Unit tests\"\n  [ Video.tests\n  , SegmentPositionerTests.tests\n  , startFiducialTests\n  , tileMatcherTests\n  , trackDebugTests\n  , loopTests\n  , trackTests\n  , trackTrackingTests\n  ]\n\nstartFiducialTests :: TestTree\nstartFiducialTests = testGroup \"Start fiducial tests\"\n  [ testCase \"Start fiducial position\" testStartFiducialPosition\n  , testCase \"Start fiducial transform\" testStartFiducialTransform\n  , testCase \"Start fiducial consistency\" testStartFiducialConsistency\n  , testStartFiducialIsRectangle\n  ]\n\ntestStartFiducialPosition :: Assertion\ntestStartFiducialPosition = do\n  points@(V2 center tip) <- fromJust <$> SF.findCenter idleNoCars\n  renderImage \"/tmp/drawCenter.png\" $ drawArrow idleNoCars points\n\n  (round <$> center) @?= V2 485 151\n  (round <$> tip) @?= V2 383 430\n\ntestStartFiducialTransform :: Assertion\ntestStartFiducialTransform = do\n  points <- fromJust <$> SF.findCenter idleNoCars\n  roundTransform (transformFromVector points) @?= Track.transform idleNoCarsStart\n\nvideo :: FilePath\nvideo = \"test/video/idle-no-cars-0-3-frames.mp4\"\n\ntestStartFiducialConsistency :: Assertion\ntestStartFiducialConsistency = do\n  (frames :: [FrameGrabber.TestMat]) <- FrameGrabber.getFrames video\n  (points :: [Maybe (V2 (V2 Double))]) <- mapM SF.findCenter frames\n\n  let (debugs :: [SF.FrameMat]) = zipWith drawArrow frames (map fromJust points)\n\n  let renderFrame n = renderImage (\"/tmp/testStartFiducial_\" ++ show n ++ \".png\")\n  zipWithM_ renderFrame [0..] debugs\n\n  let centers = fmap (^._x) (catMaybes points)\n  let mean = sumV centers ^/ 3\n  let deltas = fmap (mean ^-^) centers\n  (< V2 1.0 1.0) <$> deltas @?= replicate 3 True\n\ntestStartFiducialIsRectangle :: TestTree\ntestStartFiducialIsRectangle = testGroup \"isRectangle\"\n  [ testCase \"perfect\" $ isIt True [V2 5 0, V2 5 10, V2 0 10, V2 0 0]\n  , testCase \"close\" $ isIt True [V2 4 0, V2 5 10, V2 0 13, V2 0 0]\n  , testCase \"way off\" $ isIt False [V2 2 0, V2 5 10, V2 0 12, V2 0 0]\n  ]\n  where isIt b = (@?= b) . SF.isRectangle . V.fromList\n\ntileMatcherTests :: TestTree\ntileMatcherTests = testGroup \"Tile matcher tests\"\n  [ testCase \"Straight is a straight\" tileMatcherStraight\n  , testCase \"Left is a left\" tileMatcherLeft\n  , testCase \"Find track\" tileMatcherFindTrack\n  ]\n\n\ntileMatcherStraight :: Assertion\ntileMatcherStraight = do\n  let straight = idleNoCarsTrack Loop.!! 1\n  renderImage \"/tmp/tileMatcherStraight.png\" $ TileMatcherDebug.drawTileMasks idleNoCars straight\n\ntileMatcherLeft :: Assertion\ntileMatcherLeft = do\n  let left = idleNoCarsTrack Loop.!! 2\n  renderImage \"/tmp/tileMatcherLeft.png\" $ TileMatcherDebug.drawTileMasks idleNoCars left\n\ntileMatcherFindTrack :: Assertion\ntileMatcherFindTrack = do\n  let foundTrack = TileMatcher.findTrack idleNoCars idleNoCarsStart\n  renderImage \"/tmp/tileMatcherTrackMask.png\" $ drawTrackMask idleNoCars foundTrack\n  foundTrack @?= idleNoCarsTrack\n\ntrackDebugTests :: TestTree\ntrackDebugTests = testGroup \"TrackDebug tests\"\n  [ testCase \"drawTrack\" trackDebugArrows\n  , testCase \"outline\" trackDebugOutline\n  , testCase \"Draw track mask\" trackDrawTrackMask\n  ]\n\ntrackDebugArrows :: Assertion\ntrackDebugArrows = renderImage \"/tmp/trackArrows.png\" $ drawTrackArrows idleNoCars idleNoCarsTrack\n\ntrackDebugOutline :: Assertion\ntrackDebugOutline = renderImage \"/tmp/trackOutline.png\" $ drawTrackOutline idleNoCars idleNoCarsTrack\n\ntrackDrawTrackMask :: Assertion\ntrackDrawTrackMask =  renderImage \"/tmp/trackMask.png\" $ drawTrackMask idleNoCars idleNoCarsTrack\n\nloopTests :: TestTree\nloopTests = testGroup \"Loop tests\"\n  [ testCase \"mkLoop single\" mkLoopSingleTest\n  , testCase \"mkLoop multiple\" mkLoopMultipleTest\n  , testCase \"mkLoop multiple second\" mkLoopMultipleSecondTest\n  , testCase \"mkLoop multiple last\" mkLoopMultipleLastTest\n  , testCase \"loop unfold\" loopUnfold\n  , testCase \"loop unfold from middle\" loopUnfoldMiddle\n  ]\n\nmkLoopSingleTest :: Assertion\nmkLoopSingleTest = let\n  loop = Loop.mkLoop [1]\n  Loop.Loop end (Loop.Start one) next = loop\n  in one @?= 1\n\nmkLoopMultipleTest :: Assertion\nmkLoopMultipleTest = let\n  loop = Loop.mkLoop [1,2,3]\n  Loop.Loop end (Loop.Start one) next = loop\n  Loop.Loop _ (Loop.Node two) _ = next\n  Loop.Loop _ (Loop.Node three) _ = end\n  in [one, two, three] @?= [1,2,3]\n\nmkLoopMultipleSecondTest :: Assertion\nmkLoopMultipleSecondTest = let\n  loop = Loop.mkLoop [1,2,3]\n  Loop.Loop _ _ (Loop.Loop left x right) = loop\n  Loop.Loop _ (Loop.Start one) _ = left\n  Loop.Node two = x\n  Loop.Loop _ (Loop.Node three) _ = right\n  in [one, two, three] @?= [1,2,3]\n\nmkLoopMultipleLastTest :: Assertion\nmkLoopMultipleLastTest = let\n  loop = Loop.mkLoop [1,2,3]\n  Loop.Loop (Loop.Loop left x right) _ _ = loop\n  Loop.Loop _ (Loop.Node two) _ = left\n  Loop.Node three = x\n  Loop.Loop _ (Loop.Start one) _ = right\n  in [two, three, one] @?= [2,3, 1]\n\nloopUnfold :: Assertion\nloopUnfold = let\n  list = [1, 2]\n  loop = Loop.mkLoop list\n  in Loop.unfold loop @?= list\n\nloopUnfoldMiddle :: Assertion\nloopUnfoldMiddle = let\n  list = [1..6]\n  loop = Loop.mkLoop list\n  Loop.Loop _ _ second = loop\n  in Loop.unfold second @?= list\n\ntrackTests :: TestTree\ntrackTests = testGroup \"Track tests\"\n  [testCase \"parseTrack\" parseTestTrack\n  , testCase \"parseBadTrack\" parseBadTrack\n  , testCase \"start\" trackStart\n  , testCase \"nextSegment\" trackNextSegment\n  , testCase \"parse to length\" trackLength\n  , testCase \"scanl\" trackScanl\n  , testCase \"shows\" trackShow\n  , testCase \"moves\" trackMoves\n  , testCase \"loops\" trackLoops\n  , testCase \"transform\" trackTransform\n  ]\n\ntestTrack = fromJust $ Track.parseTrack Track.start \"srrsrr\"\n\nparseTestTrack :: Assertion\nparseTestTrack = let\n  tiles = Track.tile <$> testTrack\n  in tiles @?= Loop.mkLoop [Track.Straight, Track.Right, Track.Right, Track.Straight, Track.Right, Track.Right]\n\nparseBadTrack :: Assertion\nparseBadTrack = Track.parseTrack Track.start \"fail\" @?= Nothing\n\ntrackNextSegment :: Assertion\ntrackNextSegment = let\n  (Track.Segment tile p t) = Track.nextSegment Track.start Track.Right\n  in do\n    tile @?= Track.Right\n    p @?= V2 Track.trackLength 0\n    getMat t @?= V2 Track.trackUnitVector (V2 0 1)\n\ntrackScanl :: Assertion\ntrackScanl = let\n  [x, y, z] = scanl Track.nextSegment Track.start [Track.Right, Track.Right]\n  (Track.Segment x_tile x_p x_t) = x\n  (Track.Segment y_tile y_p y_t) = y\n  (Track.Segment z_tile z_p z_t) = z\n  in do\n    x_tile @?= Track.Straight\n    x_p @?= zero\n    getMat x_t @?= V2 Track.trackUnitVector (V2 0 1)\n\n    y_tile @?= Track.Right\n    y_p @?= V2 Track.trackLength 0\n    getMat y_t @?= V2 Track.trackUnitVector (V2 0 1)\n\n    z_tile @?= Track.Right\n    z_p @?= V2 (Track.trackLength + Track.cornerWidth) Track.cornerWidth\n    getMat z_t @?= V2 (V2 0 1) (V2 (-1) 0)\n\ntrackStart :: Assertion\ntrackStart = let\n  Loop.Loop _ (Loop.Start start) _  = testTrack\n  Track.Segment startTile _ _ = start\n  in startTile @?= Track.Straight\n\ntrackLength :: Assertion\ntrackLength = Loop.length testTrack  @?= 6\n\ntrackShow :: Assertion\ntrackShow = let string = concatMap (show . Track.tile) . Loop.unfold $ testTrack\n            in string @?= \"srrsrr\"\n\ntrackMoves :: Assertion\ntrackMoves = let\n  lengthNub = length . nubBy ((==) `on` Track.position) . Loop.unfold\n  in lengthNub testTrack @?= Loop.length testTrack\n\ntrackLoops :: Assertion\ntrackLoops = let\n  Loop.Loop _ (Loop.Node end) _ = Loop.prev testTrack\n  Track.Segment tile p t = end\n  in show (Track.nextSegment end Track.Straight) @?= show Track.start\n\ntrackTransform :: Assertion\ntrackTransform = do\n  transformFromAngle eye 0 @?= mkTransform (V2 (V2 1 0) (V2 0 1))\n  (round <$>) <$> getMat (transformFromAngle eye (pi / 2) ) @?= V2 (V2 0 1) (V2 (-1) 0)\n  (round <$>) <$> getMat (transformFromAngle eye pi ) @?= V2 (V2 (-1) 0) (V2 0 (-1))\n  (round <$>) <$> getMat (transformFromAngle eye (3* (pi/2)) ) @?= V2 (V2 0 (-1)) (V2 1 0)\n\n  Transform.angleFromTransform (mkTransform (V2 (V2 1 0) (V2 0 1))) @?= 0\n  Transform.angleFromTransform (mkTransform (V2 (V2 0 1) (V2 (-1) 0))) @?= (pi/2)\n  Transform.angleFromTransform (transformFromAngle eye 0) @?= 0\n  Transform.angleFromTransform (transformFromAngle eye (pi/2)) @?= (pi/2)\n  Transform.angleFromTransform (transformFromAngle eye 2) @?= 2\n\ntrackTrackingTests :: TestTree\ntrackTrackingTests = testGroup \"Track tracking\"\n  [ testCase \"track\" trackTrackingTrack\n  , testCase \"rotated\" trackTracking\n  -- , testCase \"pertubations\" trackTrackingPertubations\n  ]\n\ntrackTrackingTrack :: Assertion\ntrackTrackingTrack = do\n  track <- fromJust <$> TT.track idleNoCars\n  renderImage \"/tmp/trackTrackerOutline.png\" $ drawTrackOutline idleNoCars track\n\ntrackTracking :: Assertion\ntrackTracking = do\n  (frames :: [FrameGrabber.TestMat]) <- FrameGrabber.getFrames \"test/video/idle-no-cars-0-3-frames.mp4\"\n  outlines <- mapM maybeOutline frames\n  FrameWriter.writeFrames \"/tmp/trackTracking.mov\" outlines\n\ntrackTrackingPertubations :: Assertion\ntrackTrackingPertubations = do\n  (frames :: [FrameGrabber.TestMat]) <- FrameGrabber.getFrames \"test/video/track/pertubations.mov\"\n  outlines <- mapM maybeOutline frames\n  FrameWriter.writeFrames \"/tmp/trackTrackingPertubations.mov\" outlines\n\nmaybeOutline :: FrameGrabber.TestMat -> IO FrameGrabber.TestMat\nmaybeOutline frame = do\n  maybeTrack <- TT.track frame\n  case maybeTrack of\n    Nothing -> return frame\n    Just track -> return $ drawTrackOutline frame track\n", "meta": {"hexsha": "28a96428f28696fa07bb16cb326473bbb234e502", "size": 10233, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Spec.hs", "max_stars_repo_name": "dukedave/pitchskell", "max_stars_repo_head_hexsha": "5ab10825bb10ddcac4a8364659d87b7a45652a58", "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": "test/Spec.hs", "max_issues_repo_name": "dukedave/pitchskell", "max_issues_repo_head_hexsha": "5ab10825bb10ddcac4a8364659d87b7a45652a58", "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": "test/Spec.hs", "max_forks_repo_name": "dukedave/pitchskell", "max_forks_repo_head_hexsha": "5ab10825bb10ddcac4a8364659d87b7a45652a58", "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": 32.2807570978, "max_line_length": 111, "alphanum_fraction": 0.7386885566, "num_tokens": 3050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20102337632245953}}
{"text": "{-# LANGUAGE ViewPatterns, MagicHash, BangPatterns #-}\n\nmodule CVUtils where\n\nimport Codec.Image.DevIL\nimport Data.Array.Unboxed\nimport Math.Probably.MCMC\nimport Math.Probably.Sampler\nimport Math.Probably.FoldingStats\nimport Control.Monad.State.Strict \nimport System.Cmd\nimport System.Environment\nimport Data.Array.IO\nimport System.IO\n\nimport Data.Array.Unboxed\nimport Numeric.LinearAlgebra hiding (find)\nimport qualified Math.Probably.PDF as PDF\nimport Data.List\nimport Data.Maybe\nimport Control.Applicative\nimport Data.Ord\n\nimport Data.IORef\nimport System.IO.Unsafe\nimport Data.BitArray \n\nimport GHC.Exts\nimport GHC.Word \n\ntype R = Double\n\ntype Pos = (R,R)\ntype Image = UArray (Int, Int, Int) Word8\ntype MImage = IOUArray (Int, Int, Int) Word8\ndata BitImage = BitImage Int BitArray\n\nmkBitImage :: Int -> Int -> (Int -> Int -> Bool) -> BitImage\nmkBitImage hix hiy f = BitImage hiy $ bitArray (0,(hix)*(hiy)-1) [ (x*hiy+y, f x y) | x<- [0..hix-1], y<- [0..hiy-1]]\n\nreadBitImage :: BitImage -> Int -> Int -> Bool\nreadBitImage (BitImage hiy im) x y = unsafeLookupBit im (x*hiy+y)\n\n{-track1 :: Image -> [Obj] -> Image -> Sampler Obj\ntrack1 bgIm objs im = \n   samplingImportanceResampling $ particleLike bgIm im objs -}\n\n\ntype Square = (Pos,Pos)\n\nwithin ((lox,loy), (hix,hiy)) ox oy\n       =    ox > min lox hix\n         && ox < max lox hix\n         && oy > min loy hiy\n         && oy < max loy hiy\n\n\ndata Obj = \n  Obj {vellen :: !R,\n       sideDisp :: !R,\n       objlen:: !R,\n       posx :: !R, \n       posy :: !R,       \n       rot :: !R  } deriving Show\n\nfileroot = reverse . takeWhile (/='/') . reverse . takeWhile (/='.')\n\n         \nprint2 x y = putStrLn $ x ++show y\n\nsmallest ws = foldl1' (min) $ map snd ws\nlargest ws = map snd $ sortBy (comparing snd) ws\nsumWeights ws = sum $ map ( (subtr (smallest ws)) . snd) ws\ncummWeightedSamples ws= \n   let least = smallest ws\n   in scanl (\\(_,csum) (x,w) -> (x,csum+ (w-least))) (fst $ head ws ,0) ws\n\ndropLosers ws = \n  let topW = foldl1' (max) $ map snd ws\n      p (x,w) = w>topW-100\n  in sortBy (comparing snd) $ filter p ws\n\nsubtr x y = y - x\n\n\nmaxOn f xs = ceiling $ foldl1' max $ map f xs\nminOn f xs = floor $ foldl1' min $ map f xs\n \ndata StaticParams = SP {noise :: !R,\n                        wlength :: !R,\n                        eccentric :: !R } deriving Show\n\n\n\ndist :: R -> R -> Int ->Int -> R \ndist  !cx !cy !x !y  = let !dx = cx-(unround x+0.5)\n                           !dy = cy-(unround y+0.5)\n                       in sqrt(dx*dx + dy*dy)\n\ndist' :: R -> R -> Int ->Int -> R \ndist' (D# cx) (D# cy) (I# x) (I# y)  \n       = let !dx = cx -## (int2Double# x+##half)\n             !dy = cy -## (int2Double# y+##half)\n             !(D# half) = 0.5\n         in  D# (sqrtDouble# (dx*##dx +## dy*##dy))\n  \ngaussW8 :: R -> Word8 -> Word8 -> R\ngaussW8 tau muw8 = lpdf . word8ToR  \n   where lpdf x = log (sqrt (tau/2.0*pi)) + (0.0-((x-mu)*(x-mu)*tau))\n         mu = word8ToR  muw8\ngaussR :: R-> R -> Word8 -> R\ngaussR tau mu = lpdf . word8ToR  \n   where lpdf :: R -> R\n         lpdf x = log (sqrt (tau/2.0*pi)) + (0.0-((x-mu)*(x-mu)*tau))\n\n--no-noise versions\ngaussW8nn :: R -> Word8 -> Word8 -> R\ngaussW8nn tau muw8 = lpdf . word8ToR  \n   where lpdf x = let y = x - mu in negate $ y*y\n         mu = word8ToR  muw8\ngaussRnn :: R-> R -> Word8 -> R\ngaussRnn tau mu = lpdf . word8ToR  \n   where lpdf :: R -> R\n         lpdf x = let y = x - mu in negate $ y*y\n\n\nword8ToR :: Word8 -> R\n--word8ToR (W8# whash) = (/256) $ F# $ int2Float# $ word2Int# whash\nword8ToR (W8# whash) = (/256) $ D# $ int2Double# $ word2Int# whash\nrealToW8 :: R -> Word8\nrealToW8 =  round . (*256) \n\n\nunround :: Int -> R\n--word8ToR (W8# whash) = (/256) $ F# $ int2Float# $ word2Int# whash\nunround (I# whash) = D# $ int2Double# whash\n\nmarkObjsOnImage :: [Obj] -> Image -> IO (Image)\nmarkObjsOnImage objs im = do\n    mutIm <- thaw im\n    forM_ objs $ \\(Obj _ _ _ cx cy _) -> do\n          writeArray mutIm (round cy, round cx, 2) 255\n          writeArray mutIm (round cy, round cx, 0) 0\n          writeArray mutIm (round cy, round cx, 1) 0\n\n    freeze (mutIm::MImage)\n    \n--updateBgIm :: Image -> \n\n\n\n\n         \nmkRed arr cx cy = do \n          writeArray arr ( cy,\n                             cx, 0) 255\n--          writeArray arr ( cy,\n--                             cx, 1) 0\n--          writeArray arr ( cy,\n--                             cx, 2) 0\n\n\nmarkEllipse :: StaticParams -> Obj -> Image -> IO (Image)\nmarkEllipse sp@(SP noise _ ecc) (Obj _ _ len px py rot) im = do\n    mutIm <- thaw im\n    \n    let cx = round px\n    let cy = round py\n        f1x = px+(len*ecc)*cos rot\n        f1y = py+(len*ecc)*sin rot\n        f2x = px-(len*ecc)*cos rot\n        f2y = py-(len*ecc)*sin rot\n    let f x y = do -- print2 \"f at\" (x,y,dist (f1x,f1y) (x, y) + dist (f2x,f2y) (x, y) )\n                   when (dist  f1x f1y   x  y  + dist  f2x f2y   x  y  < 2 * len) $ do\n                      --print2 \"red at \" (x,y) \n                      mkRed mutIm x y\n                      return ()\n    sequence_ [ f x y  | \n                   x <- [ (cx::Int) -50.. cx +50],\n                   y <- [ cy -50.. cy +50]]\n    freeze (mutIm::MImage)\n\n\n\nuniformLogPdf :: R -> R-> R-> R\nuniformLogPdf from to = \\x-> if x>=from && x <=to\n                               then log $ realToFrac $ 1/(to-from )\n                               else -1e20\n\n\n\n", "meta": {"hexsha": "f64dc7f43b573366752adabd68caad2250afd4de", "size": 5345, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "CVUtils.hs", "max_stars_repo_name": "glutamate/cvutils", "max_stars_repo_head_hexsha": "4211023dade7b755eceb2f16b127fdcd7ad16473", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:20:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:20:21.000Z", "max_issues_repo_path": "CVUtils.hs", "max_issues_repo_name": "glutamate/cvutils", "max_issues_repo_head_hexsha": "4211023dade7b755eceb2f16b127fdcd7ad16473", "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": "CVUtils.hs", "max_forks_repo_name": "glutamate/cvutils", "max_forks_repo_head_hexsha": "4211023dade7b755eceb2f16b127fdcd7ad16473", "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": 27.8385416667, "max_line_length": 117, "alphanum_fraction": 0.5434985968, "num_tokens": 1822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.2003305003697723}}
