File size: 208,486 Bytes
5697766
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{"text": "{-# OPTIONS_GHC  -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}\n{-# LANGUAGE FlexibleInstances, DeriveFunctor, MultiParamTypeClasses, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}\n\n\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n-- | \n-- | Module : First attempt at approximate mean\n-- | Creator: Xiao Ling\n-- | Created: 11/29/2015\n-- | see    : https://github.com/snoyberg/conduit\n--            https://gist.github.com/thoughtpolice/3704890\n--            http://blog.ezyang.com/2012/01/problem-set-the-codensity-transformation/\n--            http://www.janis-voigtlaender.eu/papers/AsymptoticImprovementOfComputationsOverFreeMonads.pdf\n--            https://gist.github.com/supki/3776752\n-- |\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n\nmodule Play1129 where\n\n\nimport System.Random\n\nimport Data.List\nimport Data.Random\nimport Data.Conduit\nimport qualified Data.Conduit.List as Cl\n\nimport Control.Monad.Identity\nimport Control.Monad.State\n\nimport qualified Test.QuickCheck as T\n\nimport Core\nimport Statistics\n\n\n\n\n{-----------------------------------------------------------------------------\n   1. make some examples\n   2. make \n   3. see if cassava can be put into a conduit\n   4. output Row type\n   \n   see : http://stackoverflow.com/questions/2376981/haskell-types-frustrating-a-simple-average-function\n------------------------------------------------------------------------------}\n\n{-----------------------------------------------------------------------------\n    II. Approximate Median try ii\n    TODO: figure out uniform sampling without knowing length of stream \n------------------------------------------------------------------------------}\n\n-- * TODO: make this into an array since we'll be doing (!!) which is O(n) in list\n-- * A reservoir is a list, its max allowed size, and its current size\n\n-- * this deign is really bad, cannot gaurantee that currentSize is upToDate with length [a]\n-- * dependent types would be good, or we can jsut get rid of current size\n-- * or hide it in Core\ndata Reservoir a = R { run :: [a], size :: Int, currentSize :: Int }\n  deriving (Show,Functor,Eq)\n\n\ninstance Num a => T.Arbitrary (Reservoir a) where\n\n  -- * by construction, an arbitrary reservoir is always 1 item away from full\n  arbitrary = do\n    s <- T.arbitrary :: T.Gen (T.Positive Int)\n    let s' = T.getPositive s\n    let n = s' - 1 :: Int\n    return $ R (replicate n 0) s' n\n\n  shrink (R xs s n) = (\\s' -> let n = max 0 (s' - 1) in (R (replicate n 0) s' n)) <$> T.shrink s\n\n\n\n-- * constructor an empty resoivor of max size `s`\nreservoir :: Int -> Reservoir a\nreservoir s = R [] s 0\n\n-- * check if reservoir is full\nfull :: Reservoir a -> Bool\nfull (R xs s n) = n >= s\n\n-- * insert item, note the order\n(>+) :: Reservoir a -> a -> Reservoir a\n(>+) t@(R xs s n) x | full t     = t\n                    | otherwise  = R (x:xs) s $ succ n\n\n-- * remove the `i`th item from `r`\n-- * if i > size then no item removed\n(>-) :: Reservoir a -> Int -> Reservoir a\nr@(R xs s n) >- i | i > n     = r\n                  | otherwise = undefined      -- * really need to use array here\n\n\n-- * sample an item `x` from the stream with uniform probability place in reservoir\n-- * keep a conter `c` of elements seen\nsampl :: Counter -> Sink a (StateT (Reservoir a) RVar) [a]\nsampl i = do\n  ma <- await\n  case ma of \n    Nothing -> lift get >>= \\r -> return $ run r\n    Just a  -> do\n      lift $ store i a\n      sampl $ succ i\n\n\nstore :: Counter -> a -> StateT (Reservoir a) RVar ()\nstore i a = do\n  r <- get\n  case full r of\n    False -> put $ r >+ a\n    _     -> return ()\n      where p = (read . show $ size r :: Float)/i\n\n\n\n-- * test m/2 - e*m < rank(y) < m/2 + e*m\n\n\n\n-- * quickCheck Resoivor\n\n-- * full resoivor is full\nprop_fullReso :: Reservoir Int -> T.Property\nprop_fullReso r = (T.==>) (size r > 0) $ full (r>+1) == True\n\n\n---- * inserting into non-full resoivor resutls in additional element\nprop_insertNotFull :: Reservoir Int -> T.Property\nprop_insertNotFull r = (T.==>) (size r > 0) $ currentSize (r>+1) == currentSize r + 1\n\n\n-- * inserting into full resoivor leaves it unchanged\nprop_insertFull :: Reservoir Int -> T.Property\nprop_insertFull r = (T.==>) (size r > 0) $ currentSize (r'>+1) == currentSize r'\n  where r' = r >+ 1\n\n\ntestReservoir :: IO ()\ntestReservoir = do\n  T.quickCheck $ prop_fullReso\n  T.quickCheck $ prop_insertFull\n  T.quickCheck $ prop_insertNotFull\n\n\n{-----------------------------------------------------------------------------\n    II. Approximate Median Naive\n------------------------------------------------------------------------------}\n\n-- * setting problem: can you make this streaming? assuming you know m?\n-- * can you do running uniform distribution?\n\n-- * Find approximate eps e-median of list `xs` \n-- * Setting: list given before hand for some parameter t\n-- * Use : runRVar (naive xs e d) StdRandom\nmedianNaive :: (Floating a, Ord a) => [a] -> Eps -> Delta -> RVar a\nmedianNaive xs e d | m <= t    = return $ median xs\n             | otherwise = fmap median $ sampl' xs m t\n              where\n                m = length xs\n                t = round $ 7/(e^2) * log (2/d)\n\n-- * use vector here due to (!!) \n-- * sample `t` items from the list `[0..m-1]` *with replacement*\n-- * Use : runRVar (sample m t) StdRandom\nsampl' :: [a] -> Int -> Int -> RVar [a]\nsampl' xs m t | m < 0 || t < 0   = return []\n          | otherwise        = (\\is -> [ xs !! i | i <- is]) <$> mis\n            where mis = fmap sort . replicateM t $ uniform 0 (m-1) \n\n{-----------------------------------------------------------------------------\n    III. Frequency Moments\n------------------------------------------------------------------------------}\n\n\n\n\n\n\n{-----------------------------------------------------------------------------\n    I. Approximate Counting\n------------------------------------------------------------------------------}\n\n\n-- * Run on stream inputs `xs` for t independent trials for `t = 1/eps`, \n-- * and `m` times in parralell, for `m = 1/(e^2 * d)`\n-- * and take the median\nmorris :: Eps -> Delta -> [a] -> RVar Counter\nmorris e d xs = fmap rmedian . (fmap . fmap) rmean        -- * take median of the means\n              $ Cl.sourceList xs $$ count                 -- * stream to counter\n              $ replicate m $ replicate t 0               -- * make m counters of length t\n              where\n                t  = round $ 1/(e^2*d)\n                m  = round $ 1/d\n\n\n\n-- * Given an m-long list `xs` of lists (each of which is t-lengthed) of counters,\n-- * consume the stream and output result\ncount :: [[Counter]] -> Sink a RVar [[Counter]]\ncount xxs = (fmap . fmap . fmap) (\\x -> 2^(round x) - 1) \n            $ Cl.foldM (\\xs _ -> incrs xs) xxs\n\n-- * given a list of list of counter `xs` of length `n`, \n-- * toss a coin and count\nincrs :: [[Counter]] -> RVar [[Counter]]\nincrs = sequence . fmap incr where\n  incr xs = do\n    hs <- sequence $ (\\x -> toss . coin $ 0.5^(round x)) <$> xs \n    return $ pincr <$> zip hs xs  \n      where pincr (h,x) = if isHead h then (seq () succ x) else seq () x\n\n\n\n-- * Naive solution * -- \n\n\n-- * Run Morris alpha on stream inputs `xs`\nmorrisA :: [a] -> IO Counter\nmorrisA xs = flip runRVar StdRandom $ Cl.sourceList xs $$ alpha\n\n-- * Run Morris beta on stream inputs `xs` for `t` independent trials and average\nmorrisB :: Int -> [a] -> IO Counter\nmorrisB t =  fmap rmean . replicateM t . morrisA\n\n-- * Naive morris algorithm\n-- * Run on stream inputs `xs` for t independent trials for `t = 1/eps`, \n-- * and `m` times in parralell, for `m = 1/(e^2 * d)`\n-- * and take the median\n-- * Problem : `replicateM n` is O(n) time\nmorris' :: Eps -> Delta -> [a] -> IO Counter\nmorris' e d = fmap rmedian . replicateM m . morrisB t \n  where (t,m) = (round $ 1/(e^2*d), round $ 1/d)\n\n\n-- * A step in morris Algorithm alpha\nalpha :: Sink a RVar Counter\nalpha = (\\x -> 2^(round x) - 1) <$> Cl.foldM (\\x _ -> incr x) 0\n\n\n-- * Increment a counter `x` with probability 1/2^x\nincr :: Counter -> RVar Counter\nincr x = do\n  h <- toss . coin $ 0.5^(round x)\n  return $ if isHead h then (seq () succ x) else seq () x\n\n\nrmean, rmedian :: (Floating a, Ord a, RealFrac a) => [a] -> Float\nrmean   = fromIntegral . round . mean\nrmedian = fromIntegral . round . median\n\n\n---- * Increment a counter `x` with probability 1/2^x\n--incr' :: Counter -> RVar Counter\n--incr' x = do\n--  h <- (\\q -> q <= (0.5^(round x) :: Prob)) <$> uniform 0 1\n--  return $ if h then (seq () succ x) else seq () x\n\n\n-- * Test Morris\ntMorris :: IO ()\ntMorris = undefined\n\n\n\n\n{-----------------------------------------------------------------------------\n   X. Finger Exercises\n\n   type Source    m a = ConduitM () a   m ()   -- no meaningful input or return value\n   type Conduit a m b = ConduitM a  b   m ()   -- no meaningful return value\n   type Sink    a m b = ConduitM a Void m b    -- no meaningful output value\n------------------------------------------------------------------------------}\n\n-- * generator\ngenRs :: Monad m => Source m Int\ngenRs = Cl.sourceList rs\n\n-- * conduits\ncond :: Monad m => Conduit Int m String\ncond = Cl.map show\n\nadd1 :: Monad m => Conduit Int m Int\nadd1 = Cl.map (+1)\n\nadd2 :: Monad m => Conduit Int m Int\nadd2 = do\n   mx <- await\n   case mx of\n      Nothing -> return ()   \n      Just x  -> (yield $ x + 2) >> add2\n\n-- * sinks\nsink1 :: Sink Int IO ()\nsink1 = Cl.mapM_ $ putStrLn . show\n\nsink2 :: Sink String IO ()\nsink2 = Cl.mapM_ putStrLn\n\n-- * accumlate the values in a list\nsink3 :: Monad m => [Int] -> Sink Int m [Int]\nsink3 xs = do \n   mx <- await\n   case mx of\n      Nothing -> return xs\n      Just x  -> sink3 $ xs ++ [x]\n\n-- * accuulate values in a list and increment by 3\nadd3 :: (Num a, Monad m) => Sink Int m [Int]\nadd3 = Cl.fold (\\xs x -> xs ++ [x+3]) []\n\n-- * some trivial pipes \npp0, pp1, pp2 :: IO ()\npp0 = genRs $$ sink1\npp1 = genRs $$ add1 $= cond $= sink2\npp2 = genRs $$ add2 $= cond $= sink2\n\n\n-- * map and fold\npp2' :: Identity [Int]\npp2' = genRs $$ add2 $= sink3 []\n\n-- * fold a list\npp3 :: Identity [Int]\npp3 = genRs $$ add3\n\n-- * counts everything\nbrute :: [a] -> Counter\nbrute xs = runIdentity $ Cl.sourceList xs $$ Cl.fold (\\n _ -> succ n) 0 \n\n-- * filter a list\npp4 :: Int -> Identity [Int]\npp4 n = genRs $= Cl.filter (>n) $$ Cl.fold (flip $ (++) . pure) []\n\n-- * map list\npp5 :: Identity [Int]\npp5 = genRs $= Cl.map (+5) $$ sink3 []\n\n-- * test property\ntpp2, tpp3, tpp5 :: Bool\ntpp2 = runIdentity pp2' == fmap (+2) rs\ntpp3 = runIdentity pp3  == fmap (+3) rs\ntpp5 = runIdentity pp5  == fmap (+5) rs\n\n-- * test uniformness of list, observe it's relatively uniform\ntpp4 :: [Int]\ntpp4 = length . runIdentity . pp4 <$> [1..10]\n\n\n\n{-----------------------------------------------------------------------------\n    X. Test Data\n------------------------------------------------------------------------------}\n\n\n-- * random string of choice\nrs :: (Enum a, Num a) => [a]\nrs = [1..1000]\n\n{-----------------------------------------------------------------------------\n  Depricated\n------------------------------------------------------------------------------}\n\n\n--morrisA' :: Sink a RVar Counter\n--morrisA' = Cl.foldM (\\x _ -> incr x) 0\n\n--incr :: MonadRandom m => Counter -> m Counter\n--incr x = do\n--  h <- toss . coin $ 0.5^x\n--  return $ if isHead h then (seq () succ x) else seq () x\n\n\n--morrisB :: Conduit a (StateT Counter RVar) a\n--morrisB = do\n--  mi <- await\n--  case mi of\n--    Nothing -> return ()\n--    Just i  -> do\n--      yield i\n--      x <- lift get\n--      h <- lift . lift . toss . coin $ 0.5^x\n--      let x' = if isHead h then succ x else x\n--      lift . put $ seq () x'\n--      morrisB\n\n--cap :: Monad m => Sink a m ()\n--cap = do\n--  mi <- await\n--  case mi of\n--    Nothing -> return ()\n--    _       -> cap\n\n\n--morrisBs = flip runStateT 0 $ Cl.sourceList [1..10000] $= morrisB $= morrisB $$ cap\n\n\n\n\n-- * Morris Algorithm Beta, repeat step in morris alpha `t` times\n--morrisB :: Trials -> Sink a RVar [Counter]\n--morrisB t = replicateM t morrisA\n\n--tmorrisB' :: Trials -> [a] -> IO [Counter]\n--tmorrisB' t xs = (fmap . fmap) toN . flip runRVar StdRandom $ Cl.sourceList xs $$ morrisB t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ebdf7b2aa3912e29f971fbb1defc933c707e7d33", "size": 12496, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "depricated/Play1129.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": "depricated/Play1129.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": "depricated/Play1129.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.5413711584, "max_line_length": 134, "alphanum_fraction": 0.5207266325, "num_tokens": 3473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.07369626563712978, "lm_q1q2_score": 0.03656026263762985}}
{"text": "module Numeric.Sundials\n  ( -- * The solving function\n    solve\n    -- * Problem specification\n  , OdeRhsCType\n  , OdeRhs(..)\n  , odeRhsPure\n  , OdeJacobianCType\n  , OdeJacobian(..)\n  , UserData\n  , JacobianRepr(..)\n  , SparsePattern(..)\n  , OdeProblem(..)\n    -- * Events\n  , EventHandler\n  , EventHandlerResult(..)\n  , EventConditionCType\n  , EventConditions(..)\n  , eventConditionsPure\n  , CrossingDirection(..)\n  , TimeEventSpec(..)\n    -- * Solution\n  , SundialsDiagnostics(..)\n  , ErrorDiagnostics(..)\n  , SundialsSolution(..)\n    -- * Solving options\n  , ODEOpts(..)\n  , OdeMethod(..)\n  , ARK.ARKMethod(..)\n  , CV.CVMethod(..)\n  , allOdeMethods\n  , IsMethod(..)\n  , MethodType(..)\n  , Tolerances(..)\n    -- * Low-level types from sundials\n  , SunVector(..)\n  , SunMatrix(..)\n  , SunIndexType\n  , SunRealType\n    -- * Offsets\n    -- ** NVector\n  , nvectorContentOffset\n    -- ** NVector_SERIAL\n  , nvectorContentSerialLengthOffset\n  , nvectorContentSerialDataOffset\n    -- ** SUNMatrix\n  , sunmatrixContentOffset\n    -- ** SUNMatrix_DENSE\n  , sunmatrixContentDenseDataOffset\n    -- ** SUNMatrix_SPARSE\n  , sunmatrixContentSparseIndexvalsOffset\n  , sunmatrixContentSparseIndexptrsOffset\n  , sunmatrixContentSparseDataOffset\n  , sunmatrixContentSparseNnzOffset\n  ) where\n\nimport Numeric.Sundials.Common\nimport Numeric.Sundials.Foreign\nimport qualified Numeric.Sundials.CVode as CV\nimport qualified Numeric.Sundials.ARKode as ARK\nimport Katip\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.Storable (peek, poke)\nimport Numeric.Sundials.Foreign as T\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Storable as VS\nimport Data.Maybe\nimport Data.Int\nimport Numeric.LinearAlgebra.HMatrix as H hiding (Vector)\nimport GHC.Prim\nimport GHC.Generics\nimport Control.Monad.IO.Class\nimport Control.Monad.Cont\nimport Control.Exception\n\n-- | A supported ODE solving method, either by CVode or ARKode\ndata OdeMethod\n  = CVMethod CV.CVMethod\n  | ARKMethod ARK.ARKMethod\n  deriving (Eq, Ord, Show, Read, Generic)\n\n-- | List of all supported ODE methods\nallOdeMethods :: [OdeMethod]\nallOdeMethods =\n  (CVMethod <$> [minBound .. maxBound]) ++\n  (ARKMethod <$> [minBound .. maxBound])\n\ninstance IsMethod OdeMethod where\n  methodToInt = \\case\n    ARKMethod m -> methodToInt m\n    CVMethod m -> methodToInt m\n  methodType = \\case\n    ARKMethod m -> methodType m\n    CVMethod m -> methodType m\n\ndata ODEOpts = ODEOpts {\n    maxNumSteps :: Int32\n  , minStep     :: Double\n  , fixedStep   :: Double\n      -- ^ If this is greater than 0.0, then a fixed-size step is used.\n      --\n      -- This is only recommended for testing/debugging, not for production\n      -- use.\n      --\n      -- Also, this only has effect for ARKode; using this with CVode will\n      -- trigger an error.\n  , maxFail     :: Int32\n  , odeMethod   :: OdeMethod\n  , initStep    :: Maybe Double\n    -- ^ initial step size - by default, CVode\n    -- estimates the initial step size to be the\n    -- solution \\(h\\) of the equation\n    -- \\(\\|\\frac{h^2\\ddot{y}}{2}\\| = 1\\), where\n    -- \\(\\ddot{y}\\) is an estimated value of the second\n    -- derivative of the solution at \\(t_0\\)\n  , jacobianRepr :: JacobianRepr\n    -- ^ use a sparse matrix to represent the Jacobian\n    -- and a sparse linear solver for Newton iterations\n  } deriving (Show)\n\n-- | Solve an ODE system using either ARKode or CVode (depending on what\n-- @method@ is instantiated with).\nsolve\n  :: forall m . Katip m\n  => ODEOpts -- ^ solver options\n  -> OdeProblem -- ^ the ODE system to solve\n  -> m (Either ErrorDiagnostics SundialsSolution)\nsolve opts =\n  let\n    solveC =\n      case odeMethod opts of\n        CVMethod{} -> CV.solveC\n        ARKMethod{} -> ARK.solveC\n  in\n    solveCommon solveC opts\n\n-- | The common solving logic between ARKode and CVode\nsolveCommon\n  :: (Katip m)\n  => (CConsts -> CVars (VS.MVector RealWorld) -> LogEnv -> IO CInt)\n      -- ^ the CVode/ARKode solving function; mostly inline-C code\n  -> ODEOpts\n  -> OdeProblem\n  -> m (Either ErrorDiagnostics SundialsSolution)\nsolveCommon solve_c opts problem@(OdeProblem{..})\n\n  | VS.null odeInitCond = -- 0-dimensional (empty) system\n\n    return . Right $ SundialsSolution\n      { actualTimeGrid = odeSolTimes\n      , solutionMatrix = (VS.length odeSolTimes >< 0) []\n      , diagnostics = mempty\n      }\n\n  | otherwise = do\n\n    log_env <- getLogEnv\n    liftIO $ do -- the rest is in the IO monad\n    vars <- allocateCVars problem\n    ret <- withCConsts opts problem $ \\consts ->\n      solve_c consts vars log_env\n    frozenVars <- freezeCVars vars\n    assembleSolverResult problem ret frozenVars\n\nwithCConsts\n  :: ODEOpts\n  -> OdeProblem\n  -> (CConsts -> IO r)\n  -> IO r\nwithCConsts ODEOpts{..} OdeProblem{..} = runContT $ do\n  let\n    dim = VS.length c_init_cond\n    c_init_cond = coerce odeInitCond\n    c_dim = fromIntegral dim\n    c_n_sol_times = fromIntegral . VS.length $ odeSolTimes\n    c_sol_time = coerce odeSolTimes\n    c_rtol = relTolerance odeTolerances\n    c_atol = either (VS.replicate dim) id $ absTolerances odeTolerances\n    c_minstep = coerce minStep\n    c_fixedstep = coerce fixedStep\n    c_max_n_steps = fromIntegral maxNumSteps\n    c_max_err_test_fails = fromIntegral maxFail\n    c_init_step_size_set = fromIntegral . fromEnum $ isJust initStep\n    c_init_step_size = coerce . fromMaybe 0 $ initStep\n    c_n_event_specs = fromIntegral $ V.length odeEventDirections\n    c_requested_event_direction = V.convert $ V.map directionToInt odeEventDirections\n    c_apply_event n_events event_indices_ptr t y_ptr y'_ptr stop_solver_ptr record_event_ptr = do\n      event_indices <- vecFromPtr event_indices_ptr (fromIntegral n_events)\n      y_vec <- peek y_ptr\n      EventHandlerResult{..} <-\n        odeEventHandler\n          (coerce t :: Double)\n          (coerce $ sunVecVals y_vec :: VS.Vector Double)\n          (VS.map fromIntegral event_indices :: VS.Vector Int)\n      poke y'_ptr $ SunVector\n        { sunVecN = sunVecN y_vec\n        , sunVecVals = coerce eventNewState\n        }\n      poke stop_solver_ptr . fromIntegral $ fromEnum eventStopSolver\n      poke record_event_ptr . fromIntegral $ fromEnum eventRecord\n      return 0\n    c_max_events = fromIntegral odeMaxEvents\n    c_next_time_event = coerce odeTimeBasedEvents\n    c_jac_set = fromIntegral . fromEnum $ isJust odeJacobian\n    c_sparse_jac = case jacobianRepr of\n      SparseJacobian (T.SparsePattern spat) ->\n        VS.sum (VS.map fromIntegral spat) +\n        -- additionally, add diagonal zeros, as they'll be allocated too\n        sum [ if spat VS.! (i + i * dim) == 0 then 1 else 0 | i <- [0 .. dim-1] ]\n      DenseJacobian -> 0\n    c_method = methodToInt odeMethod\n\n  (c_rhs, c_rhs_userdata) <-\n    case odeRhs of\n      OdeRhsC ptr u -> return (ptr, u)\n      OdeRhsHaskell fun -> do\n        let\n          funIO :: OdeRhsCType\n          funIO t y f _ptr = do\n            sv <- peek y\n            r <- fun t (sunVecVals sv)\n            poke f $ SunVector { sunVecN = sunVecN sv\n                               , sunVecVals = r\n                               }\n            return 0\n        funptr <- ContT $ bracket (mkOdeRhsC funIO) freeHaskellFunPtr\n        return (funptr, nullPtr)\n  c_jac <-\n    case odeJacobian of\n      Nothing   -> return nullFunPtr\n      Just (OdeJacobianC fptr) -> return fptr\n      Just (OdeJacobianHaskell jac_fn) -> do\n      let\n        funIO :: OdeJacobianCType\n        funIO t y_ptr _fy_ptr jac_ptr _userdata _tmp1 _tmp2 _tmp3 = do\n          y <- peek y_ptr\n          let jac = matrixToSunMatrix $\n                jac_fn\n                  (coerce t :: Double)\n                  (coerce $ sunVecVals y :: VS.Vector Double)\n          case jacobianRepr of\n            DenseJacobian -> poke jac_ptr jac\n            SparseJacobian spat -> poke (castPtr jac_ptr) (T.SparseMatrix spat jac)\n          return 0\n      funptr <- ContT $ bracket (mkOdeJacobianC funIO) freeHaskellFunPtr\n      return funptr\n  c_event_fn <-\n    case odeEventConditions of\n      EventConditionsC fptr -> return fptr\n      EventConditionsHaskell f -> do\n      let\n        funIO :: EventConditionCType\n        funIO t y_ptr out_ptr _ptr = do\n              y <- sunVecVals <$> peek y_ptr\n              -- FIXME: We should be able to use poke somehow\n              T.vectorToC (coerce f t y) (fromIntegral c_n_event_specs) out_ptr\n              return 0\n      funptr <- ContT $ bracket (mkEventConditionsC funIO) freeHaskellFunPtr\n      return funptr\n  return CConsts{..}\n", "meta": {"hexsha": "fda9ee35839bf411cf8f40e5efde1a747eb56ab0", "size": 8467, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Sundials.hs", "max_stars_repo_name": "novadiscovery/hmatrix-sundials", "max_stars_repo_head_hexsha": "76bfee5b5a8377dc3f7161514761946a60d4834a", "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/Sundials.hs", "max_issues_repo_name": "novadiscovery/hmatrix-sundials", "max_issues_repo_head_hexsha": "76bfee5b5a8377dc3f7161514761946a60d4834a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-27T15:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-27T15:32:53.000Z", "max_forks_repo_path": "src/Numeric/Sundials.hs", "max_forks_repo_name": "novadiscovery/hmatrix-sundials", "max_forks_repo_head_hexsha": "76bfee5b5a8377dc3f7161514761946a60d4834a", "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.1939163498, "max_line_length": 97, "alphanum_fraction": 0.6600921224, "num_tokens": 2378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.06278920684328233, "lm_q1q2_score": 0.030413841302434096}}
{"text": "-- (C) Copyright Chris Banks 2011-2012\n\n-- This file is part of The Continuous Pi-calculus Workbench (BondCalculusWB).\n\n--     BondCalculusWB is free software: you can redistribute it and/or modify\n--     it under the terms of the GNU General Public License as published by\n--     the Free Software Foundation, either version 3 of the License, or\n--     (at your option) any later version.\n\n--     BondCalculusWB is distributed in the hope that it will be useful,\n--     but WITHOUT ANY WARRANTY; without even the implied warranty of\n--     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n--     GNU General Public License for more details.\n\n--     You should have received a copy of the GNU General Public License\n--     along with BondCalculusWB.  If not, see <http://www.gnu.org/licenses/>.\n\n{-# OPTIONS_GHC -fno-warn-incomplete-patterns -w #-}\n\nmodule CPi.Tests where\n\nimport CPi.Lib\nimport CPi.Parser\nimport CPi.Semantics\nimport CPi.ODE\nimport CPi.Logic\nimport CPi.Plot\nimport CPi.Matlab\n\nimport Text.ParserCombinators.Parsec\nimport System.IO\nimport Data.List as L\nimport qualified Data.Map as Map\n\nimport qualified Numeric.GSL as GSL\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Graphics.Plot as Plot\n\n\n-----------------------------------\n-- Parser tests:\n-----------------------------------\n{-\n-- Parser Test harnesses:\ntParse :: (Pretty a) => Parser a -> String -> IO ()\ntParse p input = case (parse p \"\" input) of\n                      Left err -> do putStr \"parse error at\";\n                                     print err\n                      Right x -> print (pretty x)\n\ntParse' :: (Show a) => Parser a -> String -> IO ()\ntParse' p input = case (parse p \"\" input) of\n                      Left err -> do putStr \"parse error at\";\n                                     print err\n                      Right x -> print x\n\n-- -- Test file input:\n\ntFile x = do f <- readFile x\n             tParse' pDefinitionLines f\n-}\n-- Load an Env for testing:\ntEnv x = do f <- readFile x\n            case parseFile f of\n              Left err -> return []\n              Right x -> return x\n\ntProc env x = maybe tEmptyProc id (lookupProcName env x)\n\ntEmptyProc = Process [] (AffNet [])\n\n-- tSpec x = case (parse pSpecies \"\" x) of\n--             Left err -> error $ show err\n--             Right x -> return x\n\n-------------------------------\n-- Tests for transition system:\n-------------------------------\n\n-- Test transition system for enzyme example:\n{-tTrans = do file <- readFile \"testEnzyme.cpi\"\n            let defns = (\\(Right x) -> x)(parse pDefinitionLines \"\" file)\n            putStrLn $ concat $ map (\\x->(pretty x)++\"\\n\") defns\n            -- transitions of the species individually:\n            let mts = trans defns (MTS []) (Def \"S\" [\"s\"])\n            let mts' = trans defns mts (Def \"P\" [])\n            let mts'' = trans defns mts' (Def \"E\" [\"e\"])\n            -- let mts''' = trans defns mts'' (Def \"I\" [\"i\"])\n            putStrLn \"Initial species transtions:\\n\"\n            putStrLn $ pretty mts''\n            -- find resultant complexes (pseudoapps):\n            let compxs = appls mts''\n            putStrLn \"Complexes formed (pseudoapplications):\\n\"\n            putStrLn $ concat $ map (\\x->(pretty x)++\"\\n\") compxs\n            -- find transitions for the complexes and add to MTS\n            let finalmts = transs defns mts'' compxs\n            putStrLn \"Multi-transition system:\\n\"\n            putStrLn $ pretty finalmts\n            -- calculate the closure of the MTS\n            let fixedmts = fixMTS defns finalmts\n            putStrLn \"Closed MTS:\\n\"\n            putStrLn $ pretty fixedmts\n-}\n\n-- Some constants for playing with the Enzyme example:\ntEnzDefs = do file <- readFile \"testEnzyme.cpi\"\n              return ((\\(Right x) -> x) (parseFile file))\n\ntEnzPi = Process [(Def \"S\" [\"s\"],1.0),(Def \"E\" [\"e\"],0.1),(Def \"P\" [],0.0)] (AffNet [Aff ((\"e\",\"s\"),1.0)])\n\ntEnzPi' = Process [(Def \"S\" [\"s\"],1.0),(Def \"E\" [\"e\"],0.5),(Def \"P\" [],0.0),((New (AffNet [Aff ((\"a\",\"t\"),1.0),Aff ((\"a\",\"u\"),0.5)]) (Par [Sum [(Comm \"a\" [] [],Def \"E\" [\"e\"])],Sum [(Comm \"t\" [] [],Def \"P\" []),(Comm \"u\" [] [],Def \"S\" [\"s\"])]])),0.0)] (AffNet [Aff ((\"e\",\"s\"),1.0)])\n\n{-\n-- Test get full MTS of a process:\ntPTrans = do file <- readFile \"testEnzyme.cpi\"\n             let defns = (\\(Right x) -> x)(parse pDefinitionLines \"\" file)\n             let pi = Process [(Def \"S\" [\"s\"],\"1.0\"),(Def \"E\" [\"e\"],\"0.1\"),(Def \"P\" [],\"0.0\")] (AffNet [Aff ((\"e\",\"s\"),\"1.0\")])\n             let mts = processMTS defns pi\n             putStrLn $ (prettys defns)++\"\\nTransitions:\\n\"++(pretty mts)\n\n-- test recursive species\ntTransRec = do let defns = (\\(Right x)->x)(parse pDefinitionLines \"\" \"species P() = tau<1>.P();\")\n               let mts = trans defns (MTS []) (Def \"P\" [])\n               putStrLn $ pretty mts\n\n-- test infinite species\ntTransInf = do let defns = (\\(Right x)->x)(parse pDefinitionLines \"\" \"species P() = tau<1>.(P()|P());\")\n               let mts = trans defns (MTS []) (Def \"P\" [])\n               putStrLn $ pretty mts\n\n-- Test trans of Def/Nil\ntTrans' = trans [tcSpecP0] (MTS []) tcP\n\n-- Test trans of singleton Sum of Tau.P()\ntTrans'2 = trans [tcSpecP0] (MTS []) tcSum1TauP\n\n-- Test trans of Sum of Tau.P() + Tau.Q()\ntTrans'3 = trans [tcSpecP0,tcSpecQ0] (MTS []) tcSum2TauPQ\n\ntLookupDef = lookupDef [tcSpecP0] (tcP)\n\n-- Test tensor:\ntTensor = do env <- tEnzDefs\n             let net = AffNet [Aff ((\"e\",\"s\"),\"1.0\")]\n             let e = Process [(Def \"E\" [\"e\"],\"0.1\")] net\n             let s = Process [(Def \"S\" [\"s\"],\"1.0\")] net\n             print $ tensor env net (partial env e) (partial env s)\n-}\n-- Test tensor':\n{-tTensor' = do env <- tEnzDefs\n              let net = AffNet [Aff ((\"e\",\"s\"),\"1.0\")]\n              let e = Process [(Def \"E\" [\"e\"],\"0.1\")] net\n              let s = Process [(Def \"S\" [\"s\"],\"1.0\")] net\n              putStrLn $ prettyODE env $ tensor' env net (partial' env e) (partial' env s)\n-}\n\n-- Test symbolic dPdt:\n{-tdPdt = do env <- tEnzDefs\n           let pi = tEnzPi'\n           putStrLn $ prettyODE env $ dPdt' env pi\n-}\n\n------------------\n-- Test constants:\n------------------\n\n-- tau@<0.5>.P():\ntcSum1TauP = Sum [((Tau 0.5),tcP)]\n--  tau@<0.5>.P() + tau@<0.5>.Q()\ntcSum2TauPQ = Sum [((Tau 0.5),tcP),((Tau 0.6),tcQ)]\n-- P()\ntcP = Def \"P\" []\n-- Q()\ntcQ = Def \"Q\" []\n-- species P() = 0\ntcSpecP0 = SpeciesDef \"P\" [] Nil\n-- species Q() = 0\ntcSpecQ0 = SpeciesDef \"Q\" [] Nil\n\n-- tests for some struct.cong. rules\ntcSs = Def \"S\" [\"s\"]\ntcSsa = Def \"S\" [\"s\",\"a\"]\ntcXx = Def \"X\" [\"x\"]\ntcNet0 = AffNet []\ntcNet1 = AffNet [Aff ((\"s\",\"s'\"),1)]\ntcNet2 = AffNet [Aff ((\"a\",\"b\"),1)]\ntcNet3 = AffNet [Aff ((\"s\",\"s'\"),1),Aff ((\"x\",\"y\"),1)]\ntcNNS = New tcNet1 (New tcNet2 tcSs)\ntcNNSsa = New tcNet1 (New tcNet2 tcSsa)\ntcNSX = New tcNet1 (Par [tcXx,tcSs])\ntcN3SX = New tcNet3 (Par [tcXx,tcSs])\ntcN0SX = New tcNet0 (Par [tcXx,tcSs])\n\ntcC1 = ConcBase (Par [tcXx,tcSs]) [\"a\"] [\"s\"]\ntcC2 = ConcPar tcC1 [tcQ,tcP]\n\ntcNestPar = Par [tcQ, tcP,Par [tcXx,Par [tcSs,Nil]]]\n\n\n-----------------------------------\n-- Tests for new fixmts\n-----------------------------------\n{-\ntNPs = do env <- tEnv \"models/ddos.cpi\"\n          let pi = tProc env \"Pi\"\n              net' (Process _ net) = net\n              net = net' pi\n              ss' (Process ss _) = ss\n              ss = ss' pi\n              initmts = transs env (MTS []) (map fst ss)\n          return $ newPrimes env initmts\n\ntFixmts = do env <- tEnv \"models/ddos.cpi\"\n             let pi = tProc env \"Pi\"\n             return $ processMTS env pi\n-}\n-----------------------------------\n-- ODE solver tests\n-----------------------------------\n\n\n-- xdot t [x,v] = [v, -0.95*x - 0.1*v]\ntxdot t [e,s,p,c] = [(-1.0)*1.1*e*s + (-1.0)*0.9*c + 0.5*c,\n                    (-1.0)*1.1*e*s + 0.9*c,\n                    (-1.0)*0.5*p + 0.5*c,\n                    1.1*e*s + (-1.0)*0.9*c + (-1.0)*0.5*c]\ntxdot _ _ = undefined\nts = LA.linspace 250 (0,25)\n-- sol = GSL.odeSolve xdot [10,0] ts\nsol = GSL.odeSolve txdot [0.4,2.3,0,0] ts\ntODE = Plot.mplot (ts : LA.toColumns sol)\n\n{-tXdot = do env <- tEnzDefs\n           let pi = tEnzPi'\n           let x = xdot env (dPdt' env pi)\n           -- return $ x ts [1.0,0,0.5,0]\n           let sol' = GSL.odeSolve x [1.0,0,0.5,0] ts\n           Plot.mplot (ts : LA.toColumns sol')\n-}\n{-\ntSeries = do env <- tEnv \"testEnzyme.cpi\"\n             let pi = tProc env \"Pi\"\n             let mts = processMTS env pi\n             let pi' = wholeProc env pi mts\n             let dpdt = dPdt' env mts pi'\n             let odes = xdot env dpdt\n             let inits = initials env pi' dpdt\n             let ts = timePoints 250 (0,25)\n             let soln = solveODE env pi' dpdt (250,(0,25))\n             let ss = speciesIn env dpdt\n             return $ timeSeries ts soln ss\n-}\n\n-------------------------\n-- Model checker tests:\n-------------------------\n{-\ntModelCheck src p f trc = do env <- tEnv src\n                             let pi = tProc env p\n                             return $ modelCheck env solveODE trc pi mcts f\n\ntModelCheckDP src p f trc = do env <- tEnv src\n                               let pi = tProc env p\n                               return $ modelCheckDP env solveODE trc pi mcts f\n\ntModelCheckHy src p f trc = do env <- tEnv src\n                               let pi = tProc env p\n                               return $ modelCheckHy env solveODE trc pi mcts f\n\ntModelCheckHy2 src p f trc = do env <- tEnv src\n                                let pi = tProc env p\n                                return $ modelCheckHy2 env solveODE trc pi mcts f\n-}\nmcts = (1000,(0,100))\n--\n-- Some contrived formulae for benchmarking:\n-- (Use on the testGT.cpi model)\n\n-- F(S<0.1)\ntF1 = Pos (0,10) (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))\n\n-- F{5}(S<0.4 AND (F{5} (S<0.1)))\ntF1b = Pos (0,5)\n       (Conj\n        (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.4))\n        (Pos (0,5)\n         (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))))\n\ntF1c = Pos (0,10) (Nec (0,5)\n                  (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1)))\n\n-- test gaurantee (introduce an inhibitor)\ntF2 = Gtee \"In\" (Neg tF1)\n\n-- G(E>0.001) enzyme never runs out\ntF3 = Nec (0,25) (ValGT (Conc (Def \"E\" [\"e\"])) (R 0.001))\ntFn3 = Neg tF3\n\n-- still true with inhibitor:\ntF4 = Gtee \"In\" tF3\n\n-- test nested guarantee (re-solves for every time-point):\ntF5 = Nec (0,25) (Gtee \"In\" tF3)\n\n-- test nested TL\n-- G(F(S<0.1))\ntF6 = Nec (0,25) tF1\n-- G(F(G(E>0.001)))\ntF7 = Nec (0,25) $ Pos (0,25) tF3\n-- G(F(G(Inhib|>(E>0.001))))\ntF8 = Nec (0,25) $ Pos (0,25) tF4\n\n-- should be faster in Hy than in DP:\ntF9 = Pos (0,20) (ValGT (Conc (Def \"P\" [])) (R 0.5))\n\ntF10 = Nec (0,25) tF9\n\n-- for checking sim times:\nphi = (ValGT (Conc (Def \"A\" [])) (R 0.5))\npsi = (ValGT (Conc (Def \"B\" [])) (R 0.5))\ntF11 = Pos (0,10) (Nec (0,20) phi)\ntF12 = Nec (0,10) (Conj (Pos (0,10) phi) (Pos (0,20) psi))\ntF13 = Gtee \"I\" (Pos (0,10) phi)\n\n\ntFR1 = (Disj (Until (0.0,3.3935742971887564) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,3.4939759036144586) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,3.594377510040161) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,3.694779116465864) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,3.7951807228915664) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,3.8955823293172696) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,3.9959839357429727) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,4.096385542168675) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,4.196787148594378) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,4.2971887550200805) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,4.397590361445784) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Until (0.0,4.497991967871486) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Until (0.0,4.598393574297189) T (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1)))))))))))))))\n\ntFR2 = (Disj (Rels (0.0,2.3895582329317264) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Rels (0.0,2.4899598393574305) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Rels (0.0,2.5903614457831328) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Rels (0.0,2.690763052208835) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Rels (0.0,2.791164658634539) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Rels (0.0,2.8915662650602414) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Rels (0.0,2.9919678714859437) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Rels (0.0,3.092369477911646) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Rels (0.0,3.19277108433735) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Disj (Rels (0.0,3.2931726907630523) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1))) (Rels (0.0,3.3935742971887546) F (ValLT (Conc (Def \"S\" [\"s\"])) (R 0.1)))))))))))))\n\ntFR3 = (Conj (Disj (Rels (0.0,24.49799196787149) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.59839357429719) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.698795180722893) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.799196787148595) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.49799196787149) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))))))) (Conj (Disj (Rels (0.0,24.59839357429719) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.698795180722893) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.799196787148595) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.59839357429719) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3)))))))) (Conj (Disj (Rels (0.0,24.698795180722893) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.799196787148595) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.698795180722893) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))))) (Conj (Disj (Rels (0.0,24.799196787148595) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.799196787148595) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3)))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.899598393574298) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Rels (0.0,24.49799196787149) F (Until (0.0,25.0) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))))))))\n\ntFR4 = (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,23.895582329317275) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,23.995983935742977) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.09638554216868) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.19678714859438) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.297188755020084) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.397590361445786) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.49799196787149) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.59839357429719) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.698795180722893) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.799196787148595) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Conj (Disj (Rels (0.0,24.899598393574298) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))) (Until (0.0,24.899598393574298) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))) (Rels (0.0,23.895582329317275) F (Until (0.0,25.0) T (Rels (0.0,25.0) F (ValGT (Conc (Def \"E\" [\"e\"])) (R 1.0e-3))))))))))))))))\n\ntf z@(Disj (Until (0.0,t1) a b) (Disj (Until (0.0,t2) c d) e))\n    | a==c&&b==d\n        = (Disj (Until (0,(max t1 t2)) a b) e)\n    | otherwise\n        = z\n\n\n--------------------------\n-- Graph plotting tests:\n--------------------------\n\n{-\ntPlot = plot ts dims\n    where\n      ts = [0.0,0.05..60.0] -- ::[Double]\n      {-dims = [(\"Times 2\",map (*2) ts),\n              (\"Times 3\",map (*3) ts)\n             ]-}\n      dims = [(\"Sin x + \" ++ show x, map sin (map (+x) ts)) | x<-[0..5]]\n\ntPlotTimeSeries = do env <- tEnv \"models/testEnzyme\"\n                     let pi = tProc env \"Pi\"\n                     let mts = processMTS env pi\n                     let pi' = wholeProc env pi mts\n                     let dpdt = dPdt' env mts pi'\n                     let odes = xdot env dpdt\n                     let inits = initials env pi' dpdt\n                     let ts = timePoints 250 (0,25)\n                     let soln = solveODE env pi' dpdt (250,(0,25))\n                     let ss = speciesIn env dpdt\n                     plotTimeSeries ts soln ss\n-}\n\n---------------------------------\n-- Testing solver with Jacobain:\n---------------------------------\n\n{-tSolveMAPKwithJac = do env <- tEnv \"models/mapk.cpi\"\n                       let pi = tProc env \"MAPK\"\n                           mts = processMTS env pi\n                           pi' = wholeProc env pi mts\n                           dpdt = dPdt' env mts pi'\n                           odes = xdot env dpdt\n                           jacob = jac env dpdt\n                           inits = initials env pi' dpdt\n                           ts = timePoints 800 (0,80)\n                           soln = solveODE' odes jacob inits ts\n                       return soln\n\ntSolveMAPKwithoutJac = do env <- tEnv \"models/mapk.cpi\"\n                          let pi = tProc env \"MAPK\"\n                              mts = processMTS env pi\n                              pi' = wholeProc env pi mts\n                              dpdt = dPdt' env mts pi'\n                              odes = xdot env dpdt\n                              inits = initials env pi' dpdt\n                              ts = timePoints 800 (0,80)\n                              soln = solveODE odes inits ts\n                          return soln\n\ntPlotEnzwithJac = do env <- tEnv \"models/testEnzyme.cpi\"\n                     let pi = tProc env \"Pi\"\n                         mts = processMTS env pi\n                         pi' = wholeProc env pi mts\n                         dpdt = dPdt' env mts pi'\n                         odes = xdot env dpdt\n                         jacob = jac env dpdt\n                         inits = initials env pi' dpdt\n                         ts = timePoints 250 (0,25)\n                         soln = solveODE' odes jacob inits ts\n                         ss = speciesIn env dpdt\n                     plotTimeSeries ts soln ss\n\ntPlotEnzwithoutJac = do env <- tEnv \"models/testEnzyme.cpi\"\n                        let pi = tProc env \"Pi\"\n                            mts = processMTS env pi\n                            pi' = wholeProc env pi mts\n                            dpdt = dPdt' env mts pi'\n                            odes = xdot env dpdt\n                            inits = initials env pi' dpdt\n                            ts = timePoints 250 (0,25)\n                            soln = solveODE env pi' dpdt (250,(0,25)) ts\n                            ss = speciesIn env dpdt\n                        plotTimeSeries ts soln ss\n-}\n", "meta": {"hexsha": "0cd5a8e15e3e9e65b9ac5ffa0de0a7190abe5c86", "size": 20334, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "cpilib/CPi/Tests.hs", "max_stars_repo_name": "twright/bondwb", "max_stars_repo_head_hexsha": "5557788f8cdf780fa2899ca29eb926ed5c3ab205", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-04T20:00:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-16T11:54:15.000Z", "max_issues_repo_path": "cpilib/CPi/Tests.hs", "max_issues_repo_name": "twright/bondwb", "max_issues_repo_head_hexsha": "5557788f8cdf780fa2899ca29eb926ed5c3ab205", "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": "cpilib/CPi/Tests.hs", "max_forks_repo_name": "twright/bondwb", "max_forks_repo_head_hexsha": "5557788f8cdf780fa2899ca29eb926ed5c3ab205", "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": 48.5298329356, "max_line_length": 2176, "alphanum_fraction": 0.5120487853, "num_tokens": 7531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.06560483197834706, "lm_q1q2_score": 0.029228890287662252}}
{"text": "{-# LANGUAGE QuasiQuotes #-}\n\n{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}\n\n-- | C code generation of primitive Feldspar expressions\n\nmodule Feldspar.Primitive.Backend.C where\n\n\n\nimport Data.Complex\n\nimport Data.Constraint (Dict (..))\nimport Data.Proxy\n\nimport Language.C.Quote.C\nimport qualified Language.C.Syntax as C\n\nimport Language.C.Monad\nimport Language.Embedded.Backend.C\n\nimport Language.Syntactic\n\nimport Feldspar.Primitive.Representation\n\n\n\n-- Note: This module assumes a 32-bit target. For example the C function `abs`\n-- is used up to 32-bits, and `labs` is used above that.\n\nviewLitPrim :: ASTF (Primitive :&: PrimTypeRep) a -> Maybe a\nviewLitPrim (Sym (Lit a :&: _)) = Just a\nviewLitPrim (Sym (Pi :&: _))    = Just pi\nviewLitPrim _ = Nothing\n\ninstance CompTypeClass PrimType'\n  where\n    compType _ (_ :: proxy a) = case primTypeRep :: PrimTypeRep a of\n      BoolT   -> addInclude \"<stdbool.h>\" >> return [cty| typename bool     |]\n      Int8T   -> addInclude \"<stdint.h>\"  >> return [cty| typename int8_t   |]\n      Int16T  -> addInclude \"<stdint.h>\"  >> return [cty| typename int16_t  |]\n      Int32T  -> addInclude \"<stdint.h>\"  >> return [cty| typename int32_t  |]\n      Int64T  -> addInclude \"<stdint.h>\"  >> return [cty| typename int64_t  |]\n      Word8T  -> addInclude \"<stdint.h>\"  >> return [cty| typename uint8_t  |]\n      Word16T -> addInclude \"<stdint.h>\"  >> return [cty| typename uint16_t |]\n      Word32T -> addInclude \"<stdint.h>\"  >> return [cty| typename uint32_t |]\n      Word64T -> addInclude \"<stdint.h>\"  >> return [cty| typename uint64_t |]\n      FloatT  -> return [cty| float |]\n      DoubleT -> return [cty| double |]\n      ComplexFloatT  -> addInclude \"<tgmath.h>\" >> return [cty| float  _Complex |]\n      ComplexDoubleT -> addInclude \"<tgmath.h>\" >> return [cty| double _Complex |]\n\n    compLit _ a = case primTypeOf a of\n      BoolT   -> do addInclude \"<stdbool.h>\"\n                    return $ if a then [cexp| true |] else [cexp| false |]\n      Int8T   -> return [cexp| $a |]\n      Int16T  -> return [cexp| $a |]\n      Int32T  -> return [cexp| $a |]\n      Int64T  -> return [cexp| $a |]\n      Word8T  -> return [cexp| $a |]\n      Word16T -> return [cexp| $a |]\n      Word32T -> return [cexp| $a |]\n      Word64T -> return [cexp| $a |]\n      FloatT  -> return [cexp| $a |]\n      DoubleT -> return [cexp| $a |]\n      ComplexFloatT  -> return $ compComplexLit a\n      ComplexDoubleT -> return $ compComplexLit a\n\n-- | Compile a complex literal\ncompComplexLit :: (Eq a, Num a, ToExp a) => Complex a -> C.Exp\ncompComplexLit (r :+ 0) = [cexp| $r |]\ncompComplexLit (0 :+ i) = [cexp| $i * I |]\ncompComplexLit (r :+ i) = [cexp| $r + $i * I |]\n\naddTagMacro :: MonadC m => m ()\naddTagMacro = addGlobal [cedecl|$esc:(\"#define TAG(tag,exp) (exp)\")|]\n\n-- | Compile a unary operator\ncompUnOp :: MonadC m => C.UnOp -> ASTF PrimDomain a -> m C.Exp\ncompUnOp op a = do\n    a' <- compPrim $ Prim a\n    return $ C.UnOp op a' mempty\n\n-- | Compile a binary operator\ncompBinOp :: MonadC m =>\n    C.BinOp -> ASTF PrimDomain a -> ASTF PrimDomain b -> m C.Exp\ncompBinOp op a b = do\n    a' <- compPrim $ Prim a\n    b' <- compPrim $ Prim b\n    return $ C.BinOp op a' b' mempty\n\n-- | Compile a function call\ncompFun :: MonadC m => String -> Args (AST PrimDomain) sig -> m C.Exp\ncompFun fun args = do\n    as <- sequence $ listArgs (compPrim . Prim) args\n    return [cexp| $id:fun($args:as) |]\n\n-- | Compile a call to 'abs'\ncompAbs :: MonadC m => PrimTypeRep a -> ASTF PrimDomain a -> m C.Exp\ncompAbs t a = case viewPrimTypeRep t of\n    PrimTypeBool     -> error \"compAbs: type BoolT not supported\"\n    PrimTypeIntWord (IntType _)  -> addInclude \"<stdlib.h>\" >> compFun \"abs\" (a :* Nil)\n    PrimTypeIntWord (WordType _) -> compPrim $ Prim a\n    _ -> addInclude \"<tgmath.h>\" >> compFun \"fabs\" (a :* Nil)\n      -- Floating and complex types\n\ncomplexSign_def = [cedecl|\ndouble _Complex feld_complexSign(double _Complex c) {\n    double z = cabs(c);\n    if (z == 0) {\n        return 0;\n    } else {\n        return (creal(c)/z + I*(cimag(c)/z));\n    }\n}\n|]\n\ncomplexSignf_def = [cedecl|\nfloat _Complex feld_complexSignf(float _Complex c) {\n    float z = cabsf(c);\n    if (z == 0) {\n        return 0;\n    } else {\n        return (crealf(c)/z + I*(cimagf(c)/z));\n    }\n}\n|]\n\n-- | Compile a call to 'signum'\ncompSign :: MonadC m => PrimTypeRep a -> ASTF PrimDomain a -> m C.Exp\ncompSign t a = case viewPrimTypeRep t of\n    PrimTypeBool -> error \"compSign: type BoolT not supported\"\n    PrimTypeIntWord (WordType _) -> do\n        addTagMacro\n        a' <- compPrim $ Prim a\n        return [cexp| TAG(\"signum\", $a' > 0) |]\n    PrimTypeIntWord (IntType _) -> do\n        addTagMacro\n        a' <- compPrim $ Prim a\n        return [cexp| TAG(\"signum\", ($a' > 0) - ($a' < 0)) |]\n    PrimTypeFloating FloatType -> do\n        addTagMacro\n        a' <- compPrim $ Prim a\n        return [cexp| TAG(\"signum\", (float) (($a' > 0) - ($a' < 0))) |]\n    PrimTypeFloating DoubleType -> do\n        addTagMacro\n        a' <- compPrim $ Prim a\n        return [cexp| TAG(\"signum\", (double) (($a' > 0) - ($a' < 0))) |]\n    PrimTypeComplex ComplexDoubleType -> do\n        addInclude \"<tgmath.h>\"\n        addGlobal complexSign_def\n        a' <- compPrim $ Prim a\n        return [cexp| feld_complexSign($a') |]\n    PrimTypeComplex ComplexFloatType -> do\n        addInclude \"<complex.h>\"\n        addGlobal complexSignf_def\n        a' <- compPrim $ Prim a\n        return [cexp| feld_complexSignf($a') |]\n  -- TODO The floating point cases give `sign (-0.0) = 0.0`, which is (slightly)\n  -- wrong. They should return -0.0. I don't know whether it's correct for other\n  -- strange values.\n\n-- | Compile a type casted primitive expression\ncompCast :: MonadC m => PrimTypeRep a -> ASTF PrimDomain b -> m C.Exp\ncompCast t a = compPrim (Prim a) >>= compCastExp t\n\n-- | Applies type cast on a compiled expression\ncompCastExp :: MonadC m => PrimTypeRep a -> C.Exp -> m C.Exp\ncompCastExp t a\n    | Dict <- witPrimType t = do\n        t' <- compType (Proxy :: Proxy PrimType') t\n        return [cexp|($ty:t') $a|]\n\n-- | Compile a call to 'round'\n--   A cast is added to the resulting expression to allow compatibility\n--   between different integral and floating return types.\ncompRound :: (PrimType' a, Num a, RealFrac b, MonadC m) =>\n    PrimTypeRep a -> ASTF PrimDomain b -> m C.Exp\ncompRound t a = do\n    addInclude \"<tgmath.h>\"\n    rounded <- case viewPrimTypeRep t of\n        PrimTypeIntWord _  -> compFun \"lround\" (a :* Nil)\n        PrimTypeFloating _ -> compFun \"round\"  (a :* Nil)\n        PrimTypeComplex _  -> compFun \"round\"  (a :* Nil)\n        _ -> error $ \"compRound: type \" ++ show t ++ \" not supported\"\n    compCastExp t rounded\n\n-- Note: There's no problem with including both `tgmath.h` and `math.h`. As long\n-- as the former is included, including the latter (before or after) doesn't\n-- make a difference.\n--\n-- See: <https://gist.github.com/emilaxelsson/51310b3353f96914cd9bdb18b10b3103>\n\ndiv_def = [cedecl|\nint feld_div(int x, int y) {\n    int q = x/y;\n    int r = x%y;\n    if ((r!=0) && ((r<0) != (y<0))) --q;\n    return q;\n}\n|]\n\nldiv_def = [cedecl|\nlong int feld_ldiv(long int x, long int y) {\n    int q = x/y;\n    int r = x%y;\n    if ((r!=0) && ((r<0) != (y<0))) --q;\n    return q;\n}\n|]\n\nmod_def = [cedecl|\nint feld_mod(int x, int y) {\n    int r = x%y;\n    if ((r!=0) && ((r<0) != (y<0))) { r += y; }\n    return r;\n}\n|]\n\nlmod_def = [cedecl|\nlong int feld_lmod(long int x, long int y) {\n    int r = x%y;\n    if ((r!=0) && ((r<0) != (y<0))) { r += y; }\n    return r;\n}\n|]\n\n-- The above C implementations are taken from\n-- <http://www.microhowto.info/howto/round_towards_minus_infinity_when_dividing_integers_in_c_or_c++.html>\n\ncompDiv :: MonadC m =>\n    PrimTypeRep a -> ASTF PrimDomain a -> ASTF PrimDomain b -> m C.Exp\ncompDiv t a b = case viewPrimTypeRep t of\n    PrimTypeIntWord (WordType _) -> compBinOp C.Div a b\n    PrimTypeIntWord (IntType Int64Type) -> do\n        addGlobal ldiv_def\n        compFun \"feld_ldiv\" (a :* b :* Nil)\n    PrimTypeIntWord _ -> do\n        addGlobal div_def\n        compFun \"feld_div\" (a :* b :* Nil)\n    _ -> error $ \"compDiv: type \" ++ show t ++ \" not supported\"\n\ncompMod :: MonadC m =>\n    PrimTypeRep a -> ASTF PrimDomain a -> ASTF PrimDomain b -> m C.Exp\ncompMod t a b = case viewPrimTypeRep t of\n    PrimTypeIntWord (WordType _) -> compBinOp C.Mod a b\n    PrimTypeIntWord (IntType Int64Type) -> do\n        addGlobal lmod_def\n        compFun \"feld_lmod\" (a :* b :* Nil)\n    PrimTypeIntWord _ -> do\n        addGlobal mod_def\n        compFun \"feld_mod\" (a :* b :* Nil)\n    _ -> error $ \"compMod: type \" ++ show t ++ \" not supported\"\n\n-- | Compile an expression\ncompPrim :: MonadC m => Prim a -> m C.Exp\ncompPrim = simpleMatch (\\(s :&: t) -> go t s) . unPrim\n  where\n    go :: forall m sig . MonadC m\n        => PrimTypeRep (DenResult sig)\n        -> Primitive sig\n        -> Args (AST PrimDomain) sig\n        -> m C.Exp\n    go _ (FreeVar v) Nil = touchVar v >> return [cexp| $id:v |]\n    go t (Lit a) Nil\n        | Dict <- witPrimType t\n        = compLit (Proxy :: Proxy PrimType') a\n    go _ Add  (a :* b :* Nil) = compBinOp C.Add a b\n    go _ Sub  (a :* b :* Nil) = compBinOp C.Sub a b\n    go _ Mul  (a :* b :* Nil) = compBinOp C.Mul a b\n    go _ Neg  (a :* Nil)      = compUnOp C.Negate a\n    go t Abs  (a :* Nil)      = compAbs t a\n    go t Sign (a :* Nil)      = compSign t a\n\n    go _ Quot (a :* b :* Nil) = compBinOp C.Div a b\n    go _ Rem  (a :* b :* Nil) = compBinOp C.Mod a b\n    go t Div  (a :* b :* Nil) = compDiv t a b\n    go t Mod  (a :* b :* Nil) = compMod t a b\n    go _ FDiv (a :* b :* Nil) = compBinOp C.Div a b\n\n    go _ Pi Nil = addGlobal pi_def >> return [cexp| FELD_PI |]\n      where pi_def = [cedecl|$esc:(\"#define FELD_PI 3.141592653589793\")|]\n              -- This is the value of `pi :: Double`.\n              -- Apparently there is no standard C99 definition of pi.\n    go _ Exp   args = addInclude \"<tgmath.h>\" >> compFun \"exp\" args\n    go _ Log   args = addInclude \"<tgmath.h>\" >> compFun \"log\" args\n    go _ Sqrt  args = addInclude \"<tgmath.h>\" >> compFun \"sqrt\" args\n    go _ Pow   args = addInclude \"<tgmath.h>\" >> compFun \"pow\" args\n    go _ Sin   args = addInclude \"<tgmath.h>\" >> compFun \"sin\" args\n    go _ Cos   args = addInclude \"<tgmath.h>\" >> compFun \"cos\" args\n    go _ Tan   args = addInclude \"<tgmath.h>\" >> compFun \"tan\" args\n    go _ Asin  args = addInclude \"<tgmath.h>\" >> compFun \"asin\" args\n    go _ Acos  args = addInclude \"<tgmath.h>\" >> compFun \"acos\" args\n    go _ Atan  args = addInclude \"<tgmath.h>\" >> compFun \"atan\" args\n    go _ Sinh  args = addInclude \"<tgmath.h>\" >> compFun \"sinh\" args\n    go _ Cosh  args = addInclude \"<tgmath.h>\" >> compFun \"cosh\" args\n    go _ Tanh  args = addInclude \"<tgmath.h>\" >> compFun \"tanh\" args\n    go _ Asinh args = addInclude \"<tgmath.h>\" >> compFun \"asinh\" args\n    go _ Acosh args = addInclude \"<tgmath.h>\" >> compFun \"acosh\" args\n    go _ Atanh args = addInclude \"<tgmath.h>\" >> compFun \"atanh\" args\n\n    go _ Complex (a :* b :* Nil) = do\n        addInclude \"<tgmath.h>\"\n        a' <- compPrim $ Prim a\n        b' <- compPrim $ Prim b\n        return $ case (viewLitPrim a, viewLitPrim b) of\n            (Just 0, _) -> [cexp| I*$b'       |]\n            (_, Just 0) -> [cexp| $a'         |]\n            _           -> [cexp| $a' + I*$b' |]\n      -- We assume that constant folding has been performed, so that not both\n      -- `a` and `b` are constants\n    go _ Polar (m :* p :* Nil)\n        | Just 0 <- viewLitPrim m = return [cexp| 0 |]\n        | Just 0 <- viewLitPrim p = do\n            m' <- compPrim $ Prim m\n            return [cexp| $m' |]\n        | Just 1 <- viewLitPrim m = do\n            p' <- compPrim $ Prim p\n            return [cexp| exp(I*$p') |]\n        | otherwise = do\n            m' <- compPrim $ Prim m\n            p' <- compPrim $ Prim p\n            return [cexp| $m' * exp(I*$p') |]\n      -- We assume that constant folding has been performed, so that not both\n      -- `m` and `p` are constants\n    go _ Real      args = addInclude \"<tgmath.h>\" >> compFun \"creal\" args\n    go _ Imag      args = addInclude \"<tgmath.h>\" >> compFun \"cimag\" args\n    go _ Magnitude args = addInclude \"<tgmath.h>\" >> compFun \"cabs\"  args\n    go _ Phase     args = addInclude \"<tgmath.h>\" >> compFun \"carg\"  args\n    go _ Conjugate args = addInclude \"<tgmath.h>\" >> compFun \"conj\"  args\n\n    go t I2N   (a :* Nil) = compCast t a\n    go t I2B   (a :* Nil) = compCast t a\n    go t B2I   (a :* Nil) = compCast t a\n    go t Round (a :* Nil) = compRound t a\n\n    go _ Not  (a :* Nil)      = compUnOp C.Lnot a\n    go _ And  (a :* b :* Nil) = compBinOp C.Land a b\n    go _ Or   (a :* b :* Nil) = compBinOp C.Lor a b\n    go _ Eq   (a :* b :* Nil) = compBinOp C.Eq a b\n    go _ NEq  (a :* b :* Nil) = compBinOp C.Ne a b\n    go _ Lt   (a :* b :* Nil) = compBinOp C.Lt a b\n    go _ Gt   (a :* b :* Nil) = compBinOp C.Gt a b\n    go _ Le   (a :* b :* Nil) = compBinOp C.Le a b\n    go _ Ge   (a :* b :* Nil) = compBinOp C.Ge a b\n\n    go _ BitAnd   (a :* b :* Nil) = compBinOp C.And a b\n    go _ BitOr    (a :* b :* Nil) = compBinOp C.Or a b\n    go _ BitXor   (a :* b :* Nil) = compBinOp C.Xor a b\n    go _ BitCompl (a :* Nil)      = compUnOp C.Not a\n    go _ ShiftL   (a :* b :* Nil) = compBinOp C.Lsh a b\n    go _ ShiftR   (a :* b :* Nil) = compBinOp C.Rsh a b\n\n    go _ (ArrIx arr) (i :* Nil) = do\n        i' <- compPrim $ Prim i\n        touchVar arr\n        return [cexp| $id:arr[$i'] |]\n\n    go _ Cond (c :* t :* f :* Nil) = do\n        c' <- compPrim $ Prim c\n        t' <- compPrim $ Prim t\n        f' <- compPrim $ Prim f\n        return $ C.Cond c' t' f' mempty\n\n    go _ s _ = error $ \"compPrim: no handling of symbol \" ++ renderSym s\n      -- Should not occur, but the completeness checker doesn't know that\n\ninstance CompExp Prim where compExp = compPrim\n\n", "meta": {"hexsha": "8143c6382665a1196e28d52a58524ef998577e12", "size": 13868, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Feldspar/Primitive/Backend/C.hs", "max_stars_repo_name": "Abhiroop/mu-feldspar", "max_stars_repo_head_hexsha": "2a3afd53ea9d0139a4f33f0015321f84fddb5159", "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/Feldspar/Primitive/Backend/C.hs", "max_issues_repo_name": "Abhiroop/mu-feldspar", "max_issues_repo_head_hexsha": "2a3afd53ea9d0139a4f33f0015321f84fddb5159", "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/Feldspar/Primitive/Backend/C.hs", "max_forks_repo_name": "Abhiroop/mu-feldspar", "max_forks_repo_head_hexsha": "2a3afd53ea9d0139a4f33f0015321f84fddb5159", "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.4810810811, "max_line_length": 106, "alphanum_fraction": 0.5814825498, "num_tokens": 4598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.06278920289730222, "lm_q1q2_score": 0.027249350247240407}}
{"text": "--------------------------------------------------------------------------------\n--\n--  Copyright (c) 2010 - 2013 Tad Doxsee\n--  MIT License\n--\n--  Author: Tad Doxsee\n--\n--------------------------------------------------------------------------------\n\n{-# LANGUAGE CPP                      #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE EmptyDataDecls           #-}\n\nmodule Numeric.LinearAlgebra.CHOLMOD.CholmodXFace where\n\n-- base\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.C.Types\nimport Foreign.Marshal.Array (withArray)\n\n-- vector\nimport qualified Data.Vector.Storable.Mutable as V\n\n-- hcholmod\nimport Numeric.LinearAlgebra.CHOLMOD.CholmodXFaceLow\n\n--------------------------------------------------------------------------------\n\ndata Matrix a = Matrix {fPtr :: ForeignPtr a} \n-- a can be types Dense, Sparse, or Triplet\n\n\nclass MatrixC a where\n   getNRow  :: Matrix a -> IO CSize\n   getNCol  :: Matrix a -> IO CSize\n   getNZMax :: Matrix a -> IO CSize\n   getX     :: Matrix a -> IO (V.MVector s CDouble)\n   mtxFree  :: ForeignPtr Common -> Matrix a -> IO CInt\n--   finalizer :: FinalizerEnvPtr Common a\n\n\ninstance MatrixC Triplet where\n    getNRow  m = withForeignPtr (fPtr m) triplet_get_nrow\n    getNCol  m = withForeignPtr (fPtr m) triplet_get_ncol\n    getNZMax m = withForeignPtr (fPtr m) triplet_get_nzmax\n    getX     m = tripletGetX m\n    \n    mtxFree cfp  m = withForeignPtr (fPtr m) $ \\mp -> do \n                       withForeignPtr cfp $ \\cp -> do\n                         triplet_free mp cp\n                         \n--    finalizer  = triplet_free_ptr\n--    free c   m = to fix: complete free functions\n\ninstance MatrixC Dense where\n    getNRow  m = withForeignPtr (fPtr m) dense_get_nrow\n    getNCol  m = withForeignPtr (fPtr m) dense_get_ncol\n    getNZMax m = withForeignPtr (fPtr m) dense_get_nzmax\n    getX     m = denseGetX m\n    \n    mtxFree cfp  m = withForeignPtr (fPtr m) $ \\mp -> do \n                       withForeignPtr cfp $ \\cp -> do\n                         dense_free mp cp\n--    finalizer  = dense_free_ptr\n\ninstance MatrixC Sparse where\n    getNRow  m = withForeignPtr (fPtr m) sparse_get_nrow\n    getNCol  m = withForeignPtr (fPtr m) sparse_get_ncol\n    getNZMax m = withForeignPtr (fPtr m) sparse_get_nzmax\n    getX     m = sparseGetX m\n    \n    mtxFree cfp  m = withForeignPtr (fPtr m) $ \\mp -> do \n                       withForeignPtr cfp $ \\cp -> do\n                         sparse_free mp cp\n\n--------------------------------------------------------------------------------\n\nallocTriplet :: CSize -> CSize -> CSize ->\n                SType -> XType -> ForeignPtr Common ->\n                         IO (Matrix Triplet)\n\n\nallocTriplet nRow nCol nZMax sType xType cfp =\n    withForeignPtr cfp $ \\cp -> do\n      (triplet_allocate nRow nCol nZMax sType xType cp)\n      >>= newForeignPtr_\n      >>= (return . Matrix)\n\nallocCommon :: IO (ForeignPtr Common)\nallocCommon = newForeignPtr common_finish_and_free_ptr =<< common_allocate\n\nstartC :: ForeignPtr Common -> IO ()\nstartC cfp = withForeignPtr cfp start\n\ntripletGetRowIndices :: Matrix Triplet -> IO (V.IOVector CInt)\ntripletGetRowIndices m = do\n  ip <- withForeignPtr (fPtr m) (triplet_get_row_indices)     :: IO (Ptr CInt)\n  ipp <- newForeignPtr_ ip                              :: IO (ForeignPtr CInt)\n  nZMax <- getNZMax m                                         :: IO CSize\n  return $ V.unsafeFromForeignPtr ipp 0 (fromIntegral nZMax)\n\n\ntripletGetColIndices :: Matrix Triplet -> IO (V.IOVector CInt)\ntripletGetColIndices m = do\n  jp <- withForeignPtr (fPtr m) (triplet_get_col_indices) :: IO (Ptr CInt)\n  jpp <- newForeignPtr_ jp                               :: IO (ForeignPtr CInt)\n  nZMax <- getNZMax m                                    :: IO CSize\n  return $ V.unsafeFromForeignPtr jpp 0 (fromIntegral nZMax)\n\ntripletGetX :: Matrix Triplet -> IO (V.MVector s CDouble)\ntripletGetX m = do\n  xp <- withForeignPtr (fPtr m) triplet_get_x  :: IO (Ptr CDouble)\n  xpp <- newForeignPtr_ xp                     :: IO (ForeignPtr CDouble)\n  nZMax <- getNZMax m                          :: IO CSize\n  return $ V.unsafeFromForeignPtr xpp 0 (fromIntegral nZMax)\n\n\ntripletSetNNZ :: Matrix Triplet -> CSize -> IO ()\ntripletSetNNZ m nnz = withForeignPtr (fPtr m) $ \\mp -> (triplet_set_nnz mp nnz)\n\ntripletGetNNZ :: Matrix Triplet -> IO CSize\ntripletGetNNZ m = withForeignPtr (fPtr m) triplet_get_nnz\n\n\ntripletToSparse :: Matrix Triplet -> ForeignPtr Common -> IO (Matrix Sparse)\ntripletToSparse t cfp = do\n    nnz <- tripletGetNNZ t\n    withForeignPtr cfp $ \\cp -> do\n      withForeignPtr (fPtr t) $ \\tp -> do\n         sp <- triplet_to_sparse tp nnz cp :: IO (Ptr Sparse)\n         sfp <- newForeignPtr_ sp :: IO (ForeignPtr Sparse)\n         return (Matrix sfp)\n\n\nzeros :: CSize -> CSize -> XType -> ForeignPtr Common -> IO (Matrix Dense)\nzeros nRow nCol xt cfp =\n  withForeignPtr cfp $ \\cp -> do\n    op <- zerosL nRow nCol xt cp :: IO (Ptr Dense)\n    ofp<- newForeignPtr_ op :: IO (ForeignPtr Dense)\n    return (Matrix ofp)\n\nones :: CSize -> CSize -> XType -> ForeignPtr Common -> IO (Matrix Dense)\nones nRow nCol xt cfp =\n  withForeignPtr cfp $ \\cp -> do\n    op <- onesL nRow nCol xt cp :: IO (Ptr Dense)\n    ofp<- newForeignPtr_ op :: IO (ForeignPtr Dense)\n    return (Matrix ofp)\n\neye :: CSize -> CSize -> XType -> ForeignPtr Common -> IO (Matrix Dense)\neye nRow nCol xt cfp =\n  withForeignPtr cfp $ \\cp -> do\n    op <- eyeL nRow nCol xt cp :: IO (Ptr Dense)\n    ofp<- newForeignPtr_ op :: IO (ForeignPtr Dense)\n    return (Matrix ofp)\n\n\nanalyze :: Matrix Sparse -> ForeignPtr Common -> IO (ForeignPtr Factor)\nanalyze m cfp = withForeignPtr (fPtr m) $ \\mp -> do\n                   withForeignPtr cfp $ \\cp -> do\n                     lp <- analyzeL mp cp :: IO (Ptr Factor)\n                     newForeignPtrEnv factor_free_ptr cp lp\n\nfactorize :: Matrix Sparse -> ForeignPtr Factor -> ForeignPtr Common -> IO ()\nfactorize m ffp cfp =\n    withForeignPtr (fPtr m) $ \\mp -> do\n      withForeignPtr ffp $ \\fp -> do\n        withForeignPtr cfp $ \\cp ->  (factorizeL mp fp cp)\n        \nsolve ::  SystemType\n      -> ForeignPtr Factor\n      -> Matrix Dense\n      -> ForeignPtr Common\n      -> IO (Matrix Dense)\n\nsolve st ffp m cfp =\n    withForeignPtr ffp $ \\fp -> do\n      withForeignPtr (fPtr m) $ \\mp -> do\n        withForeignPtr cfp $ \\cp -> do\n          xp <- solveL st fp mp cp\n          xfp <- newForeignPtr_ xp\n          return (Matrix xfp)\n\ndenseGetX :: Matrix Dense -> IO (V.MVector s CDouble)\ndenseGetX m = do\n\n  nZMax <- getNZMax m                       :: IO CSize\n  xp <- withForeignPtr (fPtr m) dense_get_x :: IO (Ptr CDouble)\n  xpp <- newForeignPtr_ xp                  :: IO (ForeignPtr CDouble)\n  return $ V.unsafeFromForeignPtr xpp 0 (fromIntegral nZMax)\n\n\n\ndenseCopy :: Matrix Dense -> ForeignPtr Common -> IO (Matrix Dense)\ndenseCopy m cfp =\n    withForeignPtr (fPtr m) $ \\mp -> do\n      withForeignPtr cfp $ \\cp -> do\n        m2p <- dense_copy mp cp\n        m2fp <- newForeignPtr_ m2p\n        return (Matrix m2fp)\n\nsdMult :: Matrix Sparse  -- ^ A, sparse matrix to multiply\n       -> DoTranspose    -- ^ \n       -> [CDouble]      -- ^ alpha[2], scale factor for A\n       -> [CDouble]      -- ^ beta[2],  scale factor for Y\n       -> Matrix Dense   -- ^ X, dense matrix to multiply\n       -> Matrix Dense   -- ^ Y, resulting dense matrix\n       -> ForeignPtr Common\n       -> IO CInt\n\nsdMult s doT alphaL betaL x y cfp =\n    withForeignPtr (fPtr s) $ \\sp -> do\n      withArray alphaL $ \\alpha -> do\n        withArray betaL $ \\beta -> do\n          withForeignPtr (fPtr x) $ \\xp -> do\n            withForeignPtr (fPtr y) $ \\yp -> do\n              withForeignPtr cfp $ \\cp -> do\n                sdmult sp doT alpha beta xp yp cp\n\n\ndenseNorm :: Matrix Dense -> NormType -> ForeignPtr Common -> IO CDouble\n\ndenseNorm m nt cfp = \n    withForeignPtr (fPtr m) $ \\mp -> do\n      withForeignPtr cfp $ \\cp -> do\n        dense_norm mp nt cp\n\n\nsparseToDense :: Matrix Sparse -> ForeignPtr Common -> IO (Matrix Dense)\nsparseToDense m cfp =\n    withForeignPtr (fPtr m) $ \\mp -> do\n      withForeignPtr cfp $ \\cp -> do\n        m2p <- sparse_to_dense mp cp\n        m2fp <- newForeignPtr_ m2p\n        return (Matrix m2fp)\n\n\n\nsparseGetX :: Matrix Sparse -> IO (V.MVector s CDouble)\nsparseGetX m = do\n  xp <- withForeignPtr (fPtr m) sparse_get_x   :: IO (Ptr CDouble)\n  xpp <- newForeignPtr_ xp                     :: IO (ForeignPtr CDouble)\n  nZMax <- getNZMax m                          :: IO CSize\n  return $ V.unsafeFromForeignPtr xpp 0 (fromIntegral nZMax)\n\n", "meta": {"hexsha": "610dc70ceb3492041231f26fb3854be1743333f2", "size": 8572, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/CHOLMOD/CholmodXFace.hs", "max_stars_repo_name": "tdox/hcholmod", "max_stars_repo_head_hexsha": "2fd545dd8c14a5b4a65b5b2975bef8ae961b06de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-25T02:46:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T10:10:16.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/CHOLMOD/CholmodXFace.hs", "max_issues_repo_name": "tdox/hcholmod", "max_issues_repo_head_hexsha": "2fd545dd8c14a5b4a65b5b2975bef8ae961b06de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-07-24T15:32:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-24T15:32:06.000Z", "max_forks_repo_path": "lib/Numeric/LinearAlgebra/CHOLMOD/CholmodXFace.hs", "max_forks_repo_name": "tdox/hcholmod", "max_forks_repo_head_hexsha": "2fd545dd8c14a5b4a65b5b2975bef8ae961b06de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-23T12:52:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-23T12:52:46.000Z", "avg_line_length": 34.8455284553, "max_line_length": 80, "alphanum_fraction": 0.5926271582, "num_tokens": 2372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.05419872982318558, "lm_q1q2_score": 0.02477622940759149}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes, FlexibleContexts, MagicHash #-}\r\n\r\n-- | Utility functions for type-safe PPCA\r\n-- This module contains mostly redefined functions for DimMatrix wrapper\r\n-- around the REPA matrix\r\nmodule GPLVM.TypeSafe.Util\r\n  ( cholM\r\n  , deleteColumnsM\r\n  , deleteRowsM\r\n  , detSM\r\n  , diagM\r\n  , eigSHM\r\n  , emptyM\r\n  , extendX\r\n  , extendY\r\n  , foldAllSM\r\n  , getColumn\r\n  , getFirstColumns\r\n  , getRow\r\n  , invSM\r\n  , makeLessThenNat\r\n  , mapDiagonalM\r\n  , mapMM\r\n  , meanColumnM\r\n  , meanColumnWithNanM\r\n  , meanCovSM\r\n  , mulM\r\n  , pinvSM\r\n  , solveM\r\n  , substractMeanM\r\n  , sumAllSM\r\n  , sumListMatricesM\r\n  , toListM\r\n  , trace2SM\r\n  , transposeM\r\n  , withMat\r\n  , withVec\r\n  , vecToMat\r\n  , (+^^)\r\n  , (^++^)\r\n  , (-^^)\r\n  , (*^^)\r\n  , (^!^)\r\n  , Decisions\r\n  ) where\r\n\r\nimport Universum hiding (All, Any, Nat, One, Vector,\r\n                         map, toList, transpose,\r\n                         (%~), (++))\r\n\r\nimport GPLVM.Types\r\nimport GPLVM.TypeSafe.Types\r\nimport GPLVM.Util\r\n\r\nimport Data.Array.Repa\r\nimport Numeric.LinearAlgebra.Repa hiding (Matrix, Vector, diag)\r\n\r\nimport Data.Singletons.Decide (Decision(..))\r\nimport Data.Type.Natural hiding (Z)\r\n\r\n-- | Creates new Matrix with dimensions in its type and passes it to continuation.\r\n-- Also creates SinI instances for dimensions\r\nwithMat\r\n  :: Matrix D Double\r\n  -> (forall (x :: Nat) (y :: Nat). (SingI y, SingI x) => DimMatrix D x y Double -> k)\r\n  -> k\r\nwithMat m f =\r\n    let (Z  :.  y  :.  x) = extent m\r\n    in\r\n    case toSing (intToNat y) of\r\n      SomeSing (sy :: Sing m) -> withSingI sy $\r\n        case toSing (intToNat x) of\r\n          SomeSing (sx :: Sing n) -> withSingI sx $ f (DimMatrix @D @m @n m)\r\n\r\n-- | Vector cousin of withMat\r\nwithVec\r\n  :: Vector D a\r\n  -> (forall (n :: Nat). SingI n => DimVector D n a -> k)\r\n  -> k\r\nwithVec vec f =\r\n  case toSing (intToNat n) of\r\n    SomeSing (sy :: Sing m) -> withSingI sy $ f (DimVector @D @m vec)\r\n  where\r\n    (Z :. n) = extent vec\r\n\r\nvecToMat\r\n  :: forall (n :: Nat) a.\r\n  SingI n\r\n  => DimVector D n a\r\n  -> DimMatrix D n One a\r\nvecToMat (DimVector vec) =\r\n  DimMatrix $\r\n  fromFunction (Z :. dim :. 1) (\\(Z :. a :. b) -> index vec (Z :. a))\r\n  where\r\n    dim = natToInt $ demote @n :: Int\r\n\r\n-- | Creates type-level number which is less then given Nat type\r\nmakeLessThenNat :: forall (max :: Nat). (SingI max) => Int -> LessThen max\r\nmakeLessThenNat i =\r\n  case toSing (intToNat i) of\r\n    (SomeSing (tt:: Sing (uu :: Nat))) ->\r\n          case (tt %< (Sing :: Sing max)) of\r\n            (Proved LS) -> withSingI tt $ Less (Proxy @uu)\r\n            (Disproved _) -> error \"the first number is not less then given type-level number\"\r\n\r\n-- | Creates empty column with desired number of rows\r\nemptyM\r\n  :: forall y x. (SingI y, SingI x) => (x ~ Zero)\r\n  => DimMatrix D y x Double\r\nemptyM =\r\n  let x = fromIntegral $ toNatural (sing :: Sing x)\r\n      y = fromIntegral $ toNatural (sing :: Sing y)\r\n  in DimMatrix (delay  $ fromListUnboxed (Z  :.  y  :.  x) []) :: DimMatrix D y x Double\r\n\r\n-- | Returns the column with given index\r\n\r\ngetColumn\r\n  :: forall n x y. (((n <= x) ~ 'True), SingI n)\r\n  => DimMatrix D y x Double\r\n  -> DimMatrix D y One Double\r\ngetColumn (DimMatrix m) =\r\n  let i = (fromIntegral $ toNatural (Sing :: Sing n)) :: Int\r\n  in DimMatrix $ extend (Any   :.  (1 :: Int)) $ slice m (Any :.  i)\r\n\r\n-- | Replicates the given column\r\nextendX :: forall n y. (SingI n)\r\n        => DimMatrix D y One Double\r\n        -> DimMatrix D y n Double\r\nextendX (DimMatrix m) =\r\n  let n = natToInt $ fromSing (Sing :: Sing n) :: Int\r\n  in DimMatrix $ (extend (Any :. n) $ slice m (Any   :.  (0 :: Int)))\r\n\r\n-- | Replicates the given row\r\nextendY :: forall n x. (SingI n)\r\n        => DimMatrix D One x Double\r\n        -> DimMatrix D n x Double\r\nextendY (DimMatrix m) =\r\n  let n = natToInt $ fromSing (Sing :: Sing n) :: Int\r\n  in DimMatrix $ (extend (Any :. n :. All) $ slice m (Any   :.  (0 :: Int) :. All))\r\n\r\n-- | Returns the row with given index\r\ngetRow\r\n  :: forall n x y. (((n <= y) ~ 'True), SingI n)\r\n  => DimMatrix D y x Double\r\n  -> DimMatrix D One x Double\r\ngetRow (DimMatrix m) =\r\n  let j = (fromIntegral $ toNatural (Sing :: Sing n)) :: Int\r\n  in DimMatrix $ extend (Any   :.  (1 :: Int)  :.  All ) $ slice m (Any   :.  (j :: Int)  :.  All )\r\n\r\n-- | Column of the mean values along every dimension\r\nmeanColumnM\r\n  :: forall y x. DimMatrix D y x Double\r\n  -> DimMatrix D x One Double\r\nmeanColumnM (DimMatrix m) = DimMatrix $ extend (Any   :.  (1 :: Int)) $ meanColumn m\r\n\r\n-- | Similar to \"meanColumnM\" but it does not take into account NaN values\r\nmeanColumnWithNanM\r\n  :: forall y x. DimMatrix D y x Double\r\n  -> DimMatrix D y One Double\r\nmeanColumnWithNanM (DimMatrix m) = DimMatrix $ extend (Any   :.  (1 :: Int)) $ meanColumnWithNan m\r\n\r\n\r\n-- todo: make sure that length of deleting indexes is equal to toDel\r\n-- of change the list to list with length in its type\r\ndeleteRowsM\r\n  :: forall toDel y1 x1. DimMatrix D y1 x1 Double\r\n  -> [Int]\r\n  -> DimMatrix D (y1 - toDel) x1 Double\r\ndeleteRowsM (DimMatrix m) indexes = DimMatrix $\r\n  deleteRows indexes m\r\n\r\ndeleteColumnsM\r\n  :: forall toDel y1 x1. DimMatrix D y1 x1 Double\r\n  -> [Int]\r\n  -> DimMatrix D y1 (x1 - toDel) Double\r\ndeleteColumnsM (DimMatrix m) indexes = DimMatrix $\r\n  deleteColumns indexes m\r\n\r\ngetFirstColumns\r\n  :: forall toSave y1 x1. (SingI toSave, (toSave <= x1) ~ 'True)\r\n  => DimMatrix D y1 x1 Double\r\n  -> DimMatrix D y1 toSave Double\r\ngetFirstColumns (DimMatrix m@(ADelayed (Z :. y :. x) f)) =\r\n  let desiredColumns = natToInt $ fromSing (Sing :: Sing toSave)\r\n  in DimMatrix $ ADelayed (Z :. y :. desiredColumns) f\r\n\r\nsumListMatricesM\r\n  :: [DimMatrix D y x Double]\r\n  -> DimMatrix D y x Double\r\nsumListMatricesM [] = error \"Empty matrices list\"\r\nsumListMatricesM mss = foldl1 (\\ms m -> ms +^^ m) mss\r\n\r\n-- == Numeric functions from REPA of Numeric.LinearAlgebra for DimMatrix ==\r\n\r\nmulM\r\n  :: forall y1 x1 y2 x2.\r\n  (x1 ~ y2)\r\n  => DimMatrix D y1 x1 Double\r\n  -> DimMatrix D y2 x2 Double\r\n  -> DimMatrix D y1 x2 Double\r\nmulM (DimMatrix m1) (DimMatrix m2) = DimMatrix $ delay  $ m1 `mulS` m2\r\n\r\ntransposeM\r\n  :: DimMatrix D y x Double\r\n  -> DimMatrix D x y Double\r\ntransposeM (DimMatrix m) = DimMatrix $ transpose m\r\n\r\nmapMM :: (Double -> Double)\r\n  -> DimMatrix D y x Double\r\n  -> DimMatrix D y x Double\r\nmapMM f (DimMatrix m) =  DimMatrix $ map f m\r\n\r\nmapDiagonalM :: (Double -> Double)\r\n  -> DimMatrix D y x Double\r\n  -> DimMatrix D y x Double\r\nmapDiagonalM f (DimMatrix m) = DimMatrix $ mapDiagonal f m\r\n\r\ninvSM\r\n  :: (y ~ x)\r\n  => DimMatrix D y x Double\r\n  -> DimMatrix D y x Double\r\ninvSM (DimMatrix m) = DimMatrix $ delay  $ invS m\r\n\r\npinvSM\r\n  :: DimMatrix D y x Double\r\n  -> DimMatrix D x y Double\r\npinvSM (DimMatrix m) = DimMatrix $ delay $ pinvS m\r\n\r\nsubstractMeanM\r\n  :: DimMatrix D y x Double\r\n  -> DimMatrix D y x Double\r\nsubstractMeanM (DimMatrix m) = DimMatrix $ substractMean m\r\n\r\n(+^^) :: forall y1 x1 y2 x2.\r\n  ( x1 ~ x2\r\n  , y1 ~ y2\r\n  )\r\n  => DimMatrix D y1 x1 Double\r\n  -> DimMatrix D y2 x2 Double\r\n  -> DimMatrix D y2 x2 Double\r\n(+^^) (DimMatrix m1) (DimMatrix m2) = DimMatrix $ m1 +^ m2\r\n\r\n(^++^) :: forall y1 x1 y2 x2.\r\n  ( y1 ~ y2\r\n  )\r\n  => DimMatrix D y1 x1 Double\r\n  -> DimMatrix D y2 x2 Double\r\n  -> DimMatrix D y2 (x1 :+: x2) Double\r\n(^++^) (DimMatrix m1) (DimMatrix m2) = DimMatrix $ m1 ++ m2\r\n\r\n(-^^) :: forall y1 x1 y2 x2.\r\n  ( x1 ~ x2\r\n  , y1 ~ y2\r\n  )\r\n  => DimMatrix D y1 x1 Double\r\n  -> DimMatrix D y2 x2 Double\r\n  -> DimMatrix D y2 x2 Double\r\n(-^^) (DimMatrix m1) (DimMatrix m2) = DimMatrix $ m1 -^ m2\r\n\r\n(*^^) :: forall y1 x1 y2 x2.\r\n  ( x1 ~ x2\r\n  , y1 ~ y2\r\n  )\r\n  => DimMatrix D y1 x1 Double\r\n  -> DimMatrix D y2 x2 Double\r\n  -> DimMatrix D y2 x2 Double\r\n(*^^) (DimMatrix m1) (DimMatrix m2) = DimMatrix $ m1 *^ m2\r\n\r\n(^!^) :: forall y x. DimMatrix D y x Double\r\n      -> (LessThen y, LessThen x)\r\n      -> Double\r\n(^!^) (DimMatrix m) ((Less (Proxy :: Proxy y1)), (Less (Proxy :: Proxy x1))) =\r\n  let y1 = natToInt $ fromSing (Sing :: Sing y1)\r\n      x1 = natToInt $ fromSing (Sing :: Sing x1)\r\n  in m ! (Z :. y1 :. x1)\r\n\r\ncholM\r\n  :: DimMatrix D y x Double\r\n  -> DimMatrix D y x Double\r\ncholM (DimMatrix m) = DimMatrix $ delay  $ chol $ trustSym $ computeS m\r\n\r\nmeanCovSM\r\n  :: DimMatrix D y x Double\r\n  -> (DimMatrix D One x Double, DimMatrix D x x Double)\r\nmeanCovSM (DimMatrix m) =\r\n  let (meanVec, covMatrix) = meanCovS m\r\n  in ((DimMatrix $ extend (Any  :. (1 :: Int) :. All) meanVec), DimMatrix $ delay $ unSym covMatrix)\r\n\r\nsolveM\r\n  :: forall x1 y1 x2 y2.\r\n  ( y1 ~ y2\r\n  , x1 ~ y2\r\n  )\r\n  => DimMatrix D y1 x1 Double\r\n  -> DimMatrix D y2 x2 Double\r\n  -> DimMatrix D y1 x2 Double\r\nsolveM (DimMatrix m1) (DimMatrix m2) = DimMatrix $ delay $ m1 `solveS` m2\r\n\r\nsumAllSM\r\n  :: DimMatrix D y x Double\r\n  -> Double\r\nsumAllSM (DimMatrix m) = sumAllS m\r\n\r\nfoldAllSM\r\n  :: (Double -> Double -> Double)\r\n  -> Double\r\n  -> DimMatrix D y x Double\r\n  -> Double\r\nfoldAllSM f initValue (DimMatrix m) = foldAllS f initValue m\r\n\r\ndetSM\r\n  :: DimMatrix D y x Double\r\n  -> Double\r\ndetSM (DimMatrix m) = detS m\r\n\r\neigSHM\r\n  :: (x ~ y, y1 ~ x) => DimMatrix D y x Double\r\n  -> (DimMatrix D y1 One Double, DimMatrix D y x Double)\r\neigSHM (DimMatrix m) =\r\n  let hermM = trustSymS m\r\n      (eigenVals, eigenVecs) = eigSH hermM\r\n  in ((DimMatrix $ extend (Any   :.  (1 :: Int)) eigenVals), DimMatrix $ delay eigenVecs)\r\n\r\ndiagM\r\n  :: forall x y. (y ~ x)\r\n  => DimMatrix D y x Double\r\n  -> DimMatrix D y One Double\r\ndiagM (DimMatrix m) = DimMatrix $ diag m\r\n\r\ntrace2SM\r\n  :: DimMatrix D y x Double\r\n  -> Double\r\ntrace2SM (DimMatrix m) = trace2S $ computeS m\r\n\r\ntoListM\r\n  :: DimMatrix D x1 y1 Double\r\n  -> [Double]\r\ntoListM (DimMatrix m) = toList m\r\n\r\n-- | this type family is introduced as a syntax-sugar for multiple decisions\r\ntype family Decisions k :: Type\r\n\r\ntype instance Decisions (a, b, c) = (Decision a, Decision b, Decision c)\r\n", "meta": {"hexsha": "bf9ca9a1d8b65aa083cd6c2db0486f882395b204", "size": 9903, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GPLVM/TypeSafe/Util.hs", "max_stars_repo_name": "serokell/GPLVMHaskell", "max_stars_repo_head_hexsha": "bf6c01b3a9e1812be0da59e39c479f2b5ed47e9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-08-08T23:15:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-27T16:47:52.000Z", "max_issues_repo_path": "src/GPLVM/TypeSafe/Util.hs", "max_issues_repo_name": "serokell/GPLVMHaskell", "max_issues_repo_head_hexsha": "bf6c01b3a9e1812be0da59e39c479f2b5ed47e9b", "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/GPLVM/TypeSafe/Util.hs", "max_forks_repo_name": "serokell/GPLVMHaskell", "max_forks_repo_head_hexsha": "bf6c01b3a9e1812be0da59e39c479f2b5ed47e9b", "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.7877906977, "max_line_length": 101, "alphanum_fraction": 0.608704433, "num_tokens": 3274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153862, "lm_q2_score": 0.05340332829327472, "lm_q1q2_score": 0.02420569127238206}}
{"text": "{- |\n\nModule      :  Numeric.GSL\nCopyright   :  (c) Alberto Ruiz 2006-7\nLicense     :  GPL-style\n\nMaintainer  :  Alberto Ruiz (aruiz at um dot es)\nStability   :  provisional\nPortability :  uses -fffi and -fglasgow-exts\n\nThis module reexports all available GSL functions.\n\nThe GSL special functions are in the separate package hmatrix-special.\n\n-}\n\nmodule Numeric.GSL (\n  module Numeric.GSL.Integration\n, module Numeric.GSL.Differentiation\n, module Numeric.GSL.Fourier\n, module Numeric.GSL.Polynomials\n, module Numeric.GSL.Minimization\n, module Numeric.GSL.Root\n, module Numeric.GSL.ODE\n, module Numeric.GSL.Fitting\n, module Data.Complex\n, setErrorHandlerOff\n) where\n\nimport Numeric.GSL.Integration\nimport Numeric.GSL.Differentiation\nimport Numeric.GSL.Fourier\nimport Numeric.GSL.Polynomials\nimport Numeric.GSL.Minimization\nimport Numeric.GSL.Root\nimport Numeric.GSL.ODE\nimport Numeric.GSL.Fitting\nimport Data.Complex\n\n\n-- | This action removes the GSL default error handler (which aborts the program), so that\n-- GSL errors can be handled by Haskell (using Control.Exception) and ghci doesn't abort.\nforeign import ccall unsafe \"GSL/gsl-aux.h no_abort_on_error\" setErrorHandlerOff :: IO ()\n", "meta": {"hexsha": "5f39a3ecdb5a618bef8b597baef08484742e9e85", "size": 1190, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL.hs", "max_stars_repo_name": "curiousleo/liquidhaskell", "max_stars_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 941, "max_stars_repo_stars_event_min_datetime": "2015-01-13T10:51:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:32:32.000Z", "max_issues_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL.hs", "max_issues_repo_name": "curiousleo/liquidhaskell", "max_issues_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 1300, "max_issues_repo_issues_event_min_datetime": "2015-01-01T05:41:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:11:03.000Z", "max_forks_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL.hs", "max_forks_repo_name": "curiousleo/liquidhaskell", "max_forks_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 145, "max_forks_repo_forks_event_min_datetime": "2015-01-12T08:34:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:29:30.000Z", "avg_line_length": 27.0454545455, "max_line_length": 90, "alphanum_fraction": 0.7781512605, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.05184546738228388, "lm_q1q2_score": 0.02151062457670361}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE NamedFieldPuns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ConstraintKinds #-}\n\nmodule Language.Grappa.Interp.ProbFun where\n\nimport Data.Vector (Vector)\nimport qualified Data.Vector as V\nimport qualified Numeric.Log as Log\nimport qualified Numeric.LinearAlgebra as M\nimport Data.Functor.Compose\nimport Data.Aeson\n\nimport Language.Grappa.Distribution\nimport Language.Grappa.Interp\nimport Language.Grappa.GrappaInternals\nimport Language.Grappa.Interp.PVIE\nimport GHC.Exts (IsList(..))\n\nimport Debug.Trace\n\n-- | Type tag for the representation that views @'Dist' a@ as a function from\n-- @a@ to 'Prob'\ndata ProbFunRepr\n\ntype family ProbFunReprF a where\n  ProbFunReprF (a -> b) = (ProbFunReprF a -> ProbFunReprF b)\n  ProbFunReprF (Dist a) = ProbFunReprF a -> Prob\n  ProbFunReprF (ADT adt) = adt (GExpr ProbFunRepr) (ADT adt)\n  ProbFunReprF (Vector a) = Vector (ProbFunReprF a)\n  ProbFunReprF RVector = RVector\n  ProbFunReprF RMatrix = RMatrix\n  ProbFunReprF ProbVector = ProbVector\n  ProbFunReprF ProbMatrix = ProbMatrix\n  ProbFunReprF (VIDist a) = (VIDistFamExpr (ProbFunReprF a))\n  ProbFunReprF VISize = VIDim\n  ProbFunReprF a = a\n\ninstance ValidExprRepr ProbFunRepr where\n  type GExprRepr ProbFunRepr a = ProbFunReprF a\n  interp__'bottom = error \"ProbFunRepr: unexpected bottom!\"\n  interp__'injTuple tup = GExpr tup\n  interp__'projTuple (GExpr tup) k = k tup\n  interp__'app (GExpr f) (GExpr x) = GExpr (f x)\n  interp__'lam f = GExpr (unGExpr . f . GExpr)\n  interp__'fix f = f (interp__'fix f)\n\ninstance ValidRepr ProbFunRepr where\n  type GVExprRepr ProbFunRepr a = ProbFunReprF a\n  type GStmtRepr ProbFunRepr a = Prob\n\n  interp__'projTupleStmt (GExpr tup) k = k tup\n\n  interp__'vInjTuple tup = GVExpr $ mapADT (GExpr . unGVExpr) tup\n  interp__'vProjTuple (GVExpr ve) k = k $ mapADT (GVExpr . unGExpr) ve\n\n  interp__'vwild _ = error \"ProbFunRepr: wildcard variables not allowed!\"\n  interp__'vlift (GExpr e) k = k (GVExpr e)\n\n  interp__'return (GExpr _) = GStmt 1\n  interp__'let rhs body = body rhs\n  interp__'sample (GExpr d) (GVExpr v) k =\n    -- FIXME: evaluate these two sides in parallel!\n    GStmt $ d v * unGStmt (k $ GExpr v)\n\n  interp__'mkDist f = GExpr (\\ dv -> unGStmt $ f $ GVExpr dv)\n\ninstance TraversableADT adt =>\n         Interp__ADT__Expr ProbFunRepr adt where\n  interp__'injADT adt = GExpr adt\n  interp__'projADT (GExpr adt) k = k adt\n  interp__'projMatchADT (GExpr adt) _ matcher k_succ k_fail =\n    if applyCtorMatcher matcher adt then k_succ adt else k_fail\n\ninstance TraversableADT adt => Interp__ADT ProbFunRepr adt where\n  interp__'vInjADT adt = GVExpr (mapADT (GExpr . unGVExpr) adt)\n  interp__'vProjMatchADT (GVExpr adt) _ matcher k_succ k_fail =\n    if applyCtorMatcher matcher adt then\n      k_succ (mapADT (GVExpr . unGExpr) adt)\n    else k_fail\n\ninstance EmbedRepr ProbFunRepr Bool where\n  embedRepr = GExpr\ninstance EmbedRepr ProbFunRepr Int where\n  embedRepr = GExpr\ninstance EmbedRepr ProbFunRepr R where\n  embedRepr = GExpr\ninstance EmbedRepr ProbFunRepr Prob where\n  embedRepr = GExpr\n\ninstance IsList (ListF a (GExpr ProbFunRepr) (ADT (ListF a))) where\n  type Item (ListF a (GExpr ProbFunRepr) (ADT (ListF a))) = ProbFunReprF a\n  fromList [] = Nil\n  fromList (x:xs) = (Cons (GExpr x) (GExpr (fromList xs)))\n  toList Nil = []\n  toList (Cons (GExpr x) (GExpr xs)) = x : toList xs\n\n\n----------------------------------------------------------------------\n-- Boolean and comparison operations\n----------------------------------------------------------------------\n\ninstance Interp__'ifThenElse ProbFunRepr where\n  interp__'ifThenElse (GExpr c) t e = if c then t else e\n\ninstance Interp__'vmatchSwitch ProbFunRepr where\n  interp__'vmatchSwitch (GExpr i) stmts = stmts !! i\n\ninstance Interp__not ProbFunRepr where\n  interp__not = GExpr not\n\ninstance Interp__'amp'amp ProbFunRepr where\n  interp__'amp'amp = GExpr (&&)\n\ninstance Interp__'bar'bar ProbFunRepr where\n  interp__'bar'bar = GExpr (||)\n\ninstance (Eq a, Eq (ProbFunReprF a)) =>\n         Interp__'eq'eq ProbFunRepr a where\n  interp__'eq'eq = GExpr (==)\n\ninstance (Ord a, Ord (ProbFunReprF a)) =>\n         Interp__'lt ProbFunRepr a where\n  interp__'lt = GExpr (<)\n\ninstance (Ord a, Ord (ProbFunReprF a)) =>\n         Interp__'gt ProbFunRepr a where\n  interp__'gt = GExpr (>)\n\ninstance (Ord a, Ord (ProbFunReprF a)) =>\n         Interp__'lt'eq ProbFunRepr a where\n  interp__'lt'eq = GExpr (<=)\n\ninstance (Ord a, Ord (ProbFunReprF a)) =>\n         Interp__'gt'eq ProbFunRepr a where\n  interp__'gt'eq = GExpr (>=)\n\ninstance (Ord a, Ord (ProbFunReprF a)) =>\n         Interp__min ProbFunRepr a where\n  interp__min = GExpr min\n\ninstance (Ord a, Ord (ProbFunReprF a)) =>\n         Interp__max ProbFunRepr a where\n  interp__max = GExpr max\n\n\n----------------------------------------------------------------------\n-- Numeric Operations\n----------------------------------------------------------------------\n\ninstance (Num a, Num (ProbFunReprF a)) =>\n         Interp__'plus ProbFunRepr a where\n  interp__'plus = GExpr (+)\n\ninstance (Num a, Num (ProbFunReprF a)) =>\n         Interp__'minus ProbFunRepr a where\n  interp__'minus = GExpr (-)\n\ninstance (Num a, Num (ProbFunReprF a)) =>\n         Interp__'times ProbFunRepr a where\n  interp__'times = GExpr (*)\n\ninstance (Num a, Num (ProbFunReprF a)) =>\n         Interp__negate ProbFunRepr a where\n  interp__negate = GExpr negate\n\ninstance (Num a, Num (ProbFunReprF a)) =>\n         Interp__abs ProbFunRepr a where\n  interp__abs = GExpr abs\n\ninstance (Num a, Num (ProbFunReprF a)) =>\n         Interp__signum ProbFunRepr a where\n  interp__signum = GExpr signum\n\ninstance (Num a, Num (ProbFunReprF a)) =>\n         Interp__fromInteger ProbFunRepr a where\n  interp__fromInteger = GExpr fromInteger\n\ninstance (Num a, Num (ProbFunReprF a)) =>\n         Interp__'integer ProbFunRepr a where\n  interp__'integer n = GExpr (fromInteger n)\n\ninstance (Interp__'integer ProbFunRepr a,\n          Eq (ProbFunReprF a))\n         => Interp__'eqInteger ProbFunRepr a where\n  interp__'eqInteger (GExpr x) (GExpr y) = GExpr (x == y)\n\n\ninstance (Integral a, Integral (ProbFunReprF a)) =>\n         Interp__quot ProbFunRepr a where\n  interp__quot = GExpr quot\n\ninstance (Integral a, Integral (ProbFunReprF a)) =>\n         Interp__rem ProbFunRepr a where\n  interp__rem = GExpr rem\n\ninstance (Integral a, Integral (ProbFunReprF a)) =>\n         Interp__div ProbFunRepr a where\n  interp__div = GExpr div\n\ninstance (Integral a, Integral (ProbFunReprF a)) =>\n         Interp__mod ProbFunRepr a where\n  interp__mod = GExpr mod\n\ninstance (Integral a, Integral (ProbFunReprF a)) =>\n         Interp__toInteger ProbFunRepr a where\n  interp__toInteger = GExpr toInteger\n\ninstance (Fractional a, Fractional (ProbFunReprF a)) =>\n         Interp__'div ProbFunRepr a where\n  interp__'div = GExpr (/)\n\ninstance (Fractional a, Fractional (ProbFunReprF a)) =>\n         Interp__recip ProbFunRepr a where\n  interp__recip = GExpr recip\n\ninstance (Fractional a, Fractional (ProbFunReprF a)) =>\n         Interp__fromRational ProbFunRepr a where\n  interp__fromRational = GExpr fromRational\n\ninstance (Fractional a, Fractional (ProbFunReprF a)) =>\n         Interp__'rational ProbFunRepr a where\n  interp__'rational n = GExpr (fromRational n)\n\ninstance (Interp__'rational ProbFunRepr a,\n          Eq (ProbFunReprF a))\n         => Interp__'eqRational ProbFunRepr a where\n  interp__'eqRational (GExpr x) (GExpr y) = GExpr (x == y)\n\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__pi ProbFunRepr a where\n  interp__pi = GExpr pi\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__exp ProbFunRepr a where\n  interp__exp = GExpr exp\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__log ProbFunRepr a where\n  interp__log = GExpr log\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__sqrt ProbFunRepr a where\n  interp__sqrt = GExpr sqrt\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__'times'times ProbFunRepr a where\n  interp__'times'times = GExpr (**)\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__logBase ProbFunRepr a where\n  interp__logBase = GExpr logBase\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__sin ProbFunRepr a where\n  interp__sin = GExpr sin\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__cos ProbFunRepr a where\n  interp__cos = GExpr cos\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__tan ProbFunRepr a where\n  interp__tan = GExpr tan\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__asin ProbFunRepr a where\n  interp__asin = GExpr asin\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__acos ProbFunRepr a where\n  interp__acos = GExpr acos\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__atan ProbFunRepr a where\n  interp__atan = GExpr atan\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__sinh ProbFunRepr a where\n  interp__sinh = GExpr sinh\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__cosh ProbFunRepr a where\n  interp__cosh = GExpr cosh\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__tanh ProbFunRepr a where\n  interp__tanh = GExpr tanh\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__asinh ProbFunRepr a where\n  interp__asinh = GExpr asinh\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__acosh ProbFunRepr a where\n  interp__acosh = GExpr acosh\n\ninstance (Floating a, Floating (ProbFunReprF a)) =>\n         Interp__atanh ProbFunRepr a where\n  interp__atanh = GExpr atanh\n\n\n----------------------------------------------------------------------\n-- Probability expression operations\n----------------------------------------------------------------------\n\ninstance Interp__realToProb ProbFunRepr where\n  interp__realToProb = GExpr $ \\x ->\n    if x < 0 then 0 else rToProb x\n\ninstance Interp__logRealToProb ProbFunRepr where\n  interp__logRealToProb = GExpr logRToProb\n\ninstance Interp__probToReal ProbFunRepr where\n  interp__probToReal = GExpr probToR\n\ninstance Interp__probToLogReal ProbFunRepr where\n  interp__probToLogReal = GExpr probToLogR\n\ninstance Interp__gammaProb ProbFunRepr where\n  interp__gammaProb = GExpr (Prob . Log.Exp . logGamma)\n\ninstance Interp__digamma ProbFunRepr where\n  interp__digamma = GExpr digamma\n\n\n----------------------------------------------------------------------\n-- Misc operations\n----------------------------------------------------------------------\n\ninstance (Show a, Show (ProbFunReprF a)) =>\n         Interp__gtrace ProbFunRepr a b where\n  interp__gtrace = GExpr gtrace\n\ninstance Interp__gerror ProbFunRepr a where\n  interp__gerror = GExpr gerror\n\n\n----------------------------------------------------------------------\n-- Interpreting Distributions\n----------------------------------------------------------------------\n\ninstance Interp__delta ProbFunRepr Int where\n  interp__delta = GExpr $ \\i x -> if x == i then 1 else 0\n\ninstance Interp__normal ProbFunRepr where\n  interp__normal = GExpr normalDensity\n\ninstance Interp__uniform ProbFunRepr where\n  interp__uniform = GExpr uniformDensity\n\ninstance Interp__exponential ProbFunRepr where\n  interp__exponential = GExpr $ \\rate x -> Prob $ exponentialDensity rate x\n\ninstance Interp__gamma ProbFunRepr where\n  interp__gamma = GExpr $ \\k theta x -> Prob $ gammaDensity k theta x\n\ninstance Interp__beta ProbFunRepr where\n  interp__beta = GExpr $ \\alpha beta x -> Prob $ betaDensity alpha beta x\n\ninstance Interp__betaProb ProbFunRepr where\n  interp__betaProb = GExpr $ \\alpha beta p ->\n    Prob $ betaDensityLog alpha beta (fromProb p)\n\ninstance Interp__dirichlet ProbFunRepr where\n  interp__dirichlet = GExpr $ \\alphas xs ->\n    Prob $ dirichletDensity (toList alphas) (toList xs)\n\ninstance Interp__dirichletProb ProbFunRepr where\n  interp__dirichletProb = GExpr $ \\alphas xs ->\n    Prob $ dirichletDensityLog (toList alphas) (map fromProb $ toList xs)\n\ninstance Interp__dirichletV ProbFunRepr where\n  interp__dirichletV = GExpr $ \\alphas xs ->\n    dirichletDensityV alphas xs\n\ninstance Interp__dirichletPV ProbFunRepr where\n  interp__dirichletPV = GExpr $ \\alphas xs ->\n    dirichletDensityPV alphas xs\n\ninstance Interp__categorical ProbFunRepr where\n  interp__categorical = GExpr $ \\probs x ->\n    if x >= length (toList probs) then\n      trace (\"Categorical: unexpected value x = \" ++ show x) 0\n    else\n      (toList probs) !! x\n\ninstance Interp__poisson ProbFunRepr where\n  interp__poisson = GExpr $ \\rate k ->\n    if rate < 0 then error \"Poisson: rate < 0!\" else\n      if rate == 0 then\n        if k == 0 then 1 else 0\n      else\n        if k < 0 then 0 else\n          Prob $ Log.Exp $\n          fromIntegral k * log rate - rate - logGamma (fromIntegral $ k + 1)\n\ninstance Interp__binary_mixture ProbFunRepr a where\n  interp__binary_mixture = GExpr $ \\p d1 d2 x ->\n    p * d1 x + (1 - p) * d2 x\n\ninstance Interp__scaleDist ProbFunRepr a where\n  interp__scaleDist = GExpr $ \\p d x -> p * d x\n\ninstance Interp__ctorDist__ListF ProbFunRepr where\n  interp__ctorDist__Nil = GExpr $ \\d xs ->\n    case xs of\n      Nil -> d Tuple0\n      _ -> error \"Unexpected Cons!\"\n  interp__ctorDist__Cons = GExpr $ \\d xs ->\n    case xs of\n      Cons x xs' -> d (Tuple2 x xs')\n      _ -> error \"Unexpected Nil!\"\n\ninstance Interp__adtDist__ListF ProbFunRepr where\n  interp__adtDist__ListF = GExpr $ \\probNil dNil probCons dCons xs ->\n    case xs of\n      Nil -> probNil * dNil Tuple0\n      Cons x xs' -> probCons * dCons (Tuple2 x xs')\n\ninstance Interp__arbitrary ProbFunRepr a where\n  interp__arbitrary = GExpr $ \\_ -> 1\n\n\n----------------------------------------------------------------------\n-- Interpreting Vectors\n----------------------------------------------------------------------\n\ninstance Interp__vec_head ProbFunRepr a where\n  interp__vec_head = GExpr V.head\n\ninstance Interp__vec_tail ProbFunRepr a where\n  interp__vec_tail = GExpr V.tail\n\ninstance Interp__vec_nth ProbFunRepr a where\n  interp__vec_nth = GExpr (V.!)\n\ninstance Interp__vec_length ProbFunRepr a where\n  interp__vec_length = GExpr V.length\n\ninstance Interp__vec_map ProbFunRepr a b where\n  interp__vec_map = GExpr V.map\n\ninstance Interp__vec_foldr ProbFunRepr a b where\n  interp__vec_foldr = GExpr V.foldr'\n\ninstance Interp__vec_iid ProbFunRepr a where\n  interp__vec_iid = GExpr $ \\n d xs ->\n    if V.length xs == n then\n      product $ V.map d xs\n    else 0\n\n{-\ninstance Interp__vec_dist ProbFunRepr where\n  interp__vec_dist = GExpr $ \\d xs -> d (V.toList xs)\n-}\n\ninstance Interp__vec_nil_dist ProbFunRepr a where\n  interp__vec_nil_dist = GExpr $ \\xs ->\n    if V.null xs then 1 else 0\n\ninstance Interp__vec_cons_dist ProbFunRepr a where\n  interp__vec_cons_dist = GExpr $ \\d xs ->\n    if V.null xs then 0 else\n      d (Tuple2 (GExpr $ V.head xs) (GExpr $ V.tail xs))\n\n\n----------------------------------------------------------------------\n-- Interpreting unboxed vectors and matrices\n----------------------------------------------------------------------\n\ninstance Interp__lengthV ProbFunRepr where\n  interp__lengthV = GExpr lengthV\n\ninstance Interp__atV ProbFunRepr where\n  interp__atV = GExpr atV\n\ninstance Interp__generateV ProbFunRepr where\n  interp__generateV = GExpr generateV\n\ninstance Interp__sumV ProbFunRepr where\n  interp__sumV = GExpr sumV\n\ninstance Interp__rowsM ProbFunRepr where\n  interp__rowsM = GExpr rowsM\n\ninstance Interp__colsM ProbFunRepr where\n  interp__colsM = GExpr colsM\n\ninstance Interp__atM ProbFunRepr where\n  interp__atM = GExpr atM\n\ninstance Interp__fromRowsM ProbFunRepr where\n  interp__fromRowsM =\n    GExpr (fromRowsM . map unGExpr . toHaskellListF unGExpr)\n\ninstance Interp__fromColsM ProbFunRepr where\n  interp__fromColsM =\n    GExpr (fromColsM . map unGExpr . toHaskellListF unGExpr)\n\ninstance Interp__toRowsM ProbFunRepr where\n  interp__toRowsM =\n    GExpr (fromHaskellListF GExpr . map GExpr . toRowsM)\n\ninstance Interp__toColsM ProbFunRepr where\n  interp__toColsM =\n    GExpr (fromHaskellListF GExpr . map GExpr . toColsM)\n\ninstance Interp__mulM ProbFunRepr where\n  interp__mulM = GExpr mulM\n\ninstance Interp__mulMV ProbFunRepr where\n  interp__mulMV = GExpr mulMV\n\ninstance Interp__mulVM ProbFunRepr where\n  interp__mulVM = GExpr mulVM\n\n\n----------------------------------------------------------------------\n-- Interpreting unboxed vectors and matrices of probabilities\n----------------------------------------------------------------------\n\ninstance Interp__lengthPV ProbFunRepr where\n  interp__lengthPV = GExpr lengthPV\n\ninstance Interp__atPV ProbFunRepr where\n  interp__atPV = GExpr atPV\n\ninstance Interp__generatePV ProbFunRepr where\n  interp__generatePV = GExpr generatePV\n\ninstance Interp__sumPV ProbFunRepr where\n  interp__sumPV = GExpr sumPV\n\ninstance Interp__rowsPM ProbFunRepr where\n  interp__rowsPM = GExpr rowsPM\n\ninstance Interp__colsPM ProbFunRepr where\n  interp__colsPM = GExpr colsPM\n\ninstance Interp__atPM ProbFunRepr where\n  interp__atPM = GExpr atPM\n\ninstance Interp__fromRowsPM ProbFunRepr where\n  interp__fromRowsPM =\n    GExpr (fromRowsPM . map unGExpr . toHaskellListF unGExpr)\n\ninstance Interp__fromColsPM ProbFunRepr where\n  interp__fromColsPM =\n    GExpr (fromColsPM . map unGExpr . toHaskellListF unGExpr)\n\ninstance Interp__toRowsPM ProbFunRepr where\n  interp__toRowsPM =\n    GExpr (fromHaskellListF GExpr . map GExpr . toRowsPM)\n\ninstance Interp__toColsPM ProbFunRepr where\n  interp__toColsPM =\n    GExpr (fromHaskellListF GExpr . map GExpr . toColsPM)\n\ninstance Interp__mulPM ProbFunRepr where\n  interp__mulPM = GExpr mulPM\n\ninstance Interp__mulPMV ProbFunRepr where\n  interp__mulPMV = GExpr mulPMV\n\ninstance Interp__mulPVM ProbFunRepr where\n  interp__mulPVM = GExpr mulPVM\n\n\n----------------------------------------------------------------------\n-- Distributions involving unboxed vectors and matrices of probabilities\n----------------------------------------------------------------------\n\ninstance Interp__categoricalPV ProbFunRepr where\n  interp__categoricalPV = GExpr $ \\probs x ->\n    if x >= lengthPV probs then\n      trace (\"Categorical: unexpected value x = \" ++ show x) 0\n    else\n      atPV probs x\n\ninstance Interp__categoricalV ProbFunRepr where\n  interp__categoricalV = GExpr $ \\probs x ->\n    if x >= lengthV probs then\n      trace (\"Categorical: unexpected value x = \" ++ show x) 0\n    else\n      realToProb (atV probs x)\n\n{-\ninstance Interp__mv_normal ProbFunRepr where\n  interp__mvNormal =\n-}\n\n----------------------------------------------------------------------\n-- Interpreting VI Distribution Families\n----------------------------------------------------------------------\n\ninstance Interp__withVISize ProbFunRepr where\n  interp__withVISize = GExpr $ \\f -> bindVIDimFamExpr f\n\ninstance Interp__viNormal ProbFunRepr where\n  interp__viNormal = GExpr normalVIFamExpr\n\ninstance Interp__viUniform ProbFunRepr where\n  interp__viUniform = GExpr uniformVIFamExpr\n\ninstance Interp__viGamma ProbFunRepr where\n  interp__viGamma = GExpr gammaVIFamExpr\n\ninstance Interp__viGammaProb ProbFunRepr where\n  interp__viGammaProb = GExpr gammaProbVIFamExpr\n\ninstance Interp__viBeta ProbFunRepr where\n  interp__viBeta = GExpr betaVIFamExpr\n\ninstance Interp__viBetaProb ProbFunRepr where\n  interp__viBetaProb = GExpr betaProbVIFamExpr\n\ninstance Interp__viCategorical ProbFunRepr where\n  interp__viCategorical = GExpr categoricalVIFamExpr\n\ninstance Interp__viDirichlet ProbFunRepr where\n  interp__viDirichlet =\n    GExpr $ \\sz ->\n    xformVIDistFamExpr fromList toList (dirichletVIFamExpr sz)\n\ninstance Interp__viDirichletProb ProbFunRepr where\n  interp__viDirichletProb =\n    GExpr $ \\sz ->\n    xformVIDistFamExpr fromList toList (dirichletProbVIFamExpr sz)\n\ninstance Interp__viDirichletV ProbFunRepr where\n  interp__viDirichletV =\n    GExpr $ \\sz ->\n    xformVIDistFamExpr (fromListV . fromList) (toList . toListV)\n    (dirichletVIFamExpr sz)\n\ninstance Interp__viDirichletPV ProbFunRepr where\n  interp__viDirichletPV =\n    GExpr $ \\sz ->\n    xformVIDistFamExpr (fromListPV . fromList) (toList . toListPV)\n    (dirichletProbVIFamExpr sz)\n\ninstance (Eq (ProbFunReprF a), GrappaShow (ProbFunReprF a)) =>\n         Interp__viDelta ProbFunRepr a where\n  interp__viDelta = GExpr deltaVIFamExpr\n\ninstance (Eq (ProbFunReprF a), GrappaShow (ProbFunReprF a),\n          FromJSON (ProbFunReprF a)) =>\n         Interp__viJSONInput ProbFunRepr a where\n  interp__viJSONInput = GExpr readJSONVIDistFamExpr\n\ninstance FromJSON (ProbFunReprF a) =>\n         Interp__viMappedJSONInput ProbFunRepr a b where\n  interp__viMappedJSONInput = GExpr mapJSONVIDistFamExpr\n\ninstance Interp__viTuple0 ProbFunRepr where\n  interp__viTuple0 = GExpr $ tupleVIFamExpr Tuple0\n\ninstance Interp__viTuple1 ProbFunRepr a where\n  interp__viTuple1 = GExpr $ \\da ->\n    tupleVIFamExpr (Tuple1 $ Compose $ xformVIDistFamExpr GExpr unGExpr da)\n\ninstance Interp__viTuple2 ProbFunRepr a b where\n  interp__viTuple2 = GExpr $ \\da db ->\n    tupleVIFamExpr (Tuple2\n                    (Compose $ xformVIDistFamExpr GExpr unGExpr da)\n                    (Compose $ xformVIDistFamExpr GExpr unGExpr db))\n\ninstance Interp__viTuple3 ProbFunRepr a b c where\n  interp__viTuple3 = GExpr $ \\da db dc ->\n    tupleVIFamExpr (Tuple3\n                    (Compose $ xformVIDistFamExpr GExpr unGExpr da)\n                    (Compose $ xformVIDistFamExpr GExpr unGExpr db)\n                    (Compose $ xformVIDistFamExpr GExpr unGExpr dc))\n\ninstance Interp__viTuple4 ProbFunRepr a b c d where\n  interp__viTuple4 = GExpr $ \\da db dc dd ->\n    tupleVIFamExpr (Tuple4\n                    (Compose $ xformVIDistFamExpr GExpr unGExpr da)\n                    (Compose $ xformVIDistFamExpr GExpr unGExpr db)\n                    (Compose $ xformVIDistFamExpr GExpr unGExpr dc)\n                    (Compose $ xformVIDistFamExpr GExpr unGExpr dd))\n\ninstance Interp__viIID ProbFunRepr a where\n  interp__viIID =\n    GExpr $ \\sz d ->\n    xformVIDistFamExpr fromList toList (iidVIFamExpr sz d)\n\ninstance Interp__viVecDist ProbFunRepr a where\n  interp__viVecDist = GExpr vecDistVIFamExpr\n\ninstance Interp__viVecIID ProbFunRepr a where\n  interp__viVecIID = GExpr vecIIDVIFamExpr\n\ninstance Interp__viIIDPV ProbFunRepr where\n  interp__viIIDPV = GExpr iidPVVIFamExpr\n", "meta": {"hexsha": "db5b90db590ddcaf28267e9108b3d08a3c8df5a2", "size": 22586, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Language/Grappa/Interp/ProbFun.hs", "max_stars_repo_name": "kquick/grappa", "max_stars_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "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/Language/Grappa/Interp/ProbFun.hs", "max_issues_repo_name": "kquick/grappa", "max_issues_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "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/Language/Grappa/Interp/ProbFun.hs", "max_forks_repo_name": "kquick/grappa", "max_forks_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "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.946251768, "max_line_length": 77, "alphanum_fraction": 0.6942796423, "num_tokens": 6657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.03789242921002377, "lm_q1q2_score": 0.01879820031475642}}
{"text": "-- {-# OPTIONS_GHC -fplugin-opt=ConCat.Plugin:trace #-}\n-- {-# OPTIONS_GHC -fplugin-opt=ConCat.Plugin:showResiduals #-}\n-- {-# OPTIONS_GHC -fplugin-opt=ConCat.Plugin:showCcc #-}\n\n-- To run:\n--\n--   stack build :misc-examples\n--\n--   stack build :misc-trace >& ~/Haskell/concat/out/o1\n--\n-- You might also want to use stack's --file-watch flag for automatic recompilation.\n\n{-# LANGUAGE CPP                     #-}\n{-# LANGUAGE FlexibleContexts        #-}\n{-# LANGUAGE TypeApplications        #-}\n{-# LANGUAGE TypeOperators           #-}\n{-# LANGUAGE ScopedTypeVariables     #-}\n{-# LANGUAGE ConstraintKinds         #-}\n{-# LANGUAGE LambdaCase              #-}\n{-# LANGUAGE TypeFamilies            #-}\n{-# LANGUAGE ViewPatterns            #-}\n{-# LANGUAGE PatternSynonyms         #-}\n{-# LANGUAGE DataKinds               #-}\n\n-- For OkLC as a class\n{-# LANGUAGE UndecidableInstances    #-}\n{-# LANGUAGE FlexibleInstances       #-}\n{-# LANGUAGE MultiParamTypeClasses   #-}\n\n{-# OPTIONS_GHC -Wall #-}\n\n{-# OPTIONS -Wno-type-defaults #-}\n\n{-# OPTIONS_GHC -Wno-missing-signatures #-}\n{-# OPTIONS_GHC -Wno-unused-imports #-}\n\n-- Now in concat-examples.cabal\n-- {-# OPTIONS_GHC -fplugin=ConCat.Plugin #-}\n\n-- {-# OPTIONS_GHC -fplugin-opt=ConCat.Plugin:maxSteps=100 #-}\n\n-- {-# OPTIONS_GHC -fno-specialise #-}\n\n-- {-# OPTIONS_GHC -ddump-simpl #-}\n-- {-# OPTIONS_GHC -dverbose-core2core #-}\n\n-- {-# OPTIONS_GHC -ddump-rule-rewrites #-}\n-- {-# OPTIONS_GHC -ddump-rules #-}\n\n-- Does this flag make any difference?\n-- {-# OPTIONS_GHC -fexpose-all-unfoldings #-}\n\n-- Tweak simpl-tick-factor from default of 100\n-- {-# OPTIONS_GHC -fsimpl-tick-factor=2500 #-}\n{-# OPTIONS_GHC -fsimpl-tick-factor=500 #-}\n-- {-# OPTIONS_GHC -fsimpl-tick-factor=250 #-}\n-- {-# OPTIONS_GHC -fsimpl-tick-factor=25  #-}\n-- {-# OPTIONS_GHC -fsimpl-tick-factor=5  #-}\n\n-- {-# OPTIONS_GHC -dsuppress-uniques #-}\n{-# OPTIONS_GHC -dsuppress-idinfo #-}\n-- {-# OPTIONS_GHC -dsuppress-module-prefixes #-}\n\n-- {-# OPTIONS_GHC -ddump-tc-trace #-}\n\n-- {-# OPTIONS_GHC -dsuppress-all #-}\n\n-- {-# OPTIONS_GHC -fno-float-in #-}\n-- {-# OPTIONS_GHC -ffloat-in #-}\n-- {-# OPTIONS_GHC -fdicts-cheap #-}\n{-# OPTIONS_GHC -fdicts-strict #-}\n\n-- For experiments\n{-# OPTIONS_GHC -Wno-orphans #-}\n\n----------------------------------------------------------------------\n-- |\n-- Module      :  Examples\n-- Copyright   :  (c) 2017 Conal Elliott\n-- License     :  BSD3\n--\n-- Maintainer  :  conal@conal.net\n-- Stability   :  experimental\n--\n-- Suite of automated tests\n----------------------------------------------------------------------\n\nmodule Main where\n\nimport Prelude hiding (unzip,zip,zipWith) -- (id,(.),curry,uncurry)\nimport qualified Prelude as P\n\nimport Data.Monoid (Sum(..))\nimport Data.Foldable (fold)\nimport Control.Applicative (liftA2)\nimport Control.Arrow (second)\nimport Control.Monad ((<=<))\nimport Data.List (unfoldr)  -- TEMP\nimport Data.Complex (Complex)\nimport GHC.Exts (inline)\nimport GHC.Float (int2Double)\nimport GHC.TypeLits ()\n\n-- packFiniteM experiment\nimport GHC.TypeLits\nimport Data.Maybe (fromJust)\nimport GHC.Integer\n\nimport Data.Constraint (Dict(..),(:-)(..))\nimport Data.Pointed\nimport Data.Key\nimport Data.Distributive\nimport Data.Functor.Rep\nimport qualified Data.Functor.Rep as FR\nimport Data.Vector.Sized (Vector)\n\nimport ConCat.Misc\nimport ConCat.Rep (HasRep(..))\nimport qualified ConCat.Category as C\nimport ConCat.Incremental (andInc,inc)\nimport ConCat.Dual\nimport ConCat.GAD\nimport ConCat.Additive\nimport ConCat.AdditiveFun\nimport ConCat.AD\nimport ConCat.ADFun hiding (D)\n-- import qualified ConCat.ADFun as ADFun\nimport ConCat.RAD\nimport ConCat.Free.VectorSpace (HasV(..),distSqr,(<.>),normalizeV)\n-- import ConCat.GradientDescent\nimport ConCat.Interval\nimport ConCat.Syntactic (Syn,render)\nimport ConCat.Circuit (GenBuses,(:>))\nimport qualified ConCat.RunCircuit as RC\nimport qualified ConCat.AltCat as A\n-- import ConCat.AltCat\nimport ConCat.AltCat\n  (toCcc,toCcc',unCcc,unCcc',conceal,(:**:)(..),Ok,Ok2,U2,equal)\nimport qualified ConCat.Rep\nimport ConCat.Rebox () -- necessary for reboxing rules to fire\nimport ConCat.Orphans ()\nimport ConCat.Nat\nimport ConCat.Shaped\n-- import ConCat.Scan\n-- import ConCat.FFT\nimport ConCat.Free.LinearRow -- (L,OkLM,linearL)\nimport ConCat.LC\nimport ConCat.Deep\nimport qualified ConCat.Deep as D\n-- import ConCat.Finite\nimport ConCat.Isomorphism\nimport ConCat.TArr\nimport qualified ConCat.TArr as TA\n\n-- Experimental\nimport qualified ConCat.Inline.SampleMethods as I\n\nimport qualified ConCat.Regress as R\nimport ConCat.Free.Affine\nimport ConCat.Choice\n-- import ConCat.RegressChoice\n\n-- import ConCat.Vector -- (liftArr2,FFun,arrFFun)  -- and (orphan) instances\n#ifdef CONCAT_SMT\nimport ConCat.SMT\n#endif\n\n-- These imports bring newtype constructors into scope, allowing CoerceCat (->)\n-- dictionaries to be constructed. We could remove the LinearRow import if we\n-- changed L from a newtype to data, but we still run afoul of coercions for\n-- GHC.Generics newtypes.\n--\n-- TODO: Find a better solution!\nimport qualified GHC.Generics as G\nimport qualified ConCat.Free.LinearRow\nimport qualified Data.Monoid\n\n-- For FFT\nimport GHC.Generics hiding (C,R,D)\n\nimport Control.Newtype.Generics (Newtype(..))\n\n-- Experiments\nimport GHC.Exts (Coercible,coerce)\n\nimport Miscellany\n\nmain :: IO ()\nmain = sequence_ [\n    putChar '\\n' -- return ()\n\n    -- , runSyn S.t14'\n\n  -- , runSyn $ toCcc $ A.addC . A.dup\n  -- , runSyn $ toCcc $ A.addC . (A.id A.&&& A.id)\n\n  -- -- first add . first dup\n\n  -- , runSynStack $ toCcc $ id @ Int\n\n  -- , runSynStack $ toCcc $ negate . negate @ Int\n\n  -- , runSynStack $ toCcc $ \\ (x :: Int) -> x  -- fine\n  -- , runSyn $ toCcc $ \\ (x :: Int) -> (x,x) -- fine\n  -- , runSyn $ toCcc $ A.id A.&&& A.id -- fine\n  -- , runSyn $ toCcc $ A.addC . (A.id A.&&& A.id) -- okay\n\n  -- , runSynStack $ toCcc $ A.addC . A.dup\n\n\n  -- -- first add . ((first swapP . (lassocP . id . rassocP) . first swapP) . lassocP . id . rassocP) . first dup\n  -- , runSynStack $ toCcc $ A.addC . (A.id A.&&& A.id)\n\n  -- -- [first dup,first addC]\n  -- , runChainStack $ toCcc $ A.addC . A.dup\n\n  -- -- [first dup,rassocP,lassocP,first swapP,rassocP,lassocP,first swapP,first addC]\n  -- -- [first dup,first addC]  -- with AltCat rule (id &&& id) = dup\n  -- , runChainStack $ toCcc $ A.addC . (A.id A.&&& A.id)\n\n  -- -- twice x = x + x\n  -- , runSyn        $ toCcc twice  -- addC . dup\n  -- , runSynStack   $ toCcc twice  -- first addC . first dup\n\n  -- , runSynStack $ toCcc $ \\ x     -> x + x  -- addC . dup, [Dup,Add]\n  -- , runSynStack $ toCcc $ \\ (x,y) -> x * y  -- mulC, [Mul]\n\n  -- -- addC . (exl *** mulC . (const 3 *** exr) . dup) . dup\n  -- -- [Dup,Push,Exl,Pop,Swap,Push,Dup,Push,Const 3,Pop,Swap,Push,Exr,Pop,Swap,Mul,Pop,Swap,Add]\n  -- -- TODO: better categorical optimization\n  -- , runSynStack $ toCcc $ \\ (x,y) -> x + 3 * y\n\n  -- -- addC . (mulC . (const 2 *** exl) . dup *** mulC . (const 3 *** exr) . dup) . dup\n  -- -- [Dup,Push,Dup,Push,Const 2,Pop,Swap,Push,Exl,Pop,Swap,Mul,Pop,Swap,Push,Dup,Push,Const 3,Pop,Swap,Push,Exr,Pop,Swap,Mul,Pop,Swap,Add]\n  -- , runSynStack $ toCcc $ \\ (x,y) -> 2 * x + 3 * y\n\n  -- , runSynStack $ toCcc $ \\ y -> 3 * y\n\n  -- , runSyn $ toCcc' $ A.lassocP A.. A.rassocP                  -- id\n  -- , runSyn $ toCcc' $ A.lassocP A.. A.id A.. A.rassocP         -- id\n  -- , runSyn $ toCcc' $ A.first A.id                             -- id\n  -- , runSyn $ toCcc' $ A.lassocP A.. A.first A.id A.. A.rassocP -- id\n\n  -- , runSynCirc \"sum-fun-B\" $ toCcc $ sum @((->) Bool) @Int\n  -- , runSynCirc \"sum-fun-BxB\" $ toCcc $ sum @((->) (Bool :* Bool)) @Int\n\n  -- , runSynCirc \"foo\" $ toCcc $ \\ (arr :: Arr Bool Int) -> arr `FR.index` False -- okay\n\n  -- , runSynCirc \"sum-arr-B\"   $ toCcc $ sum @(Arr Bool) @Int -- okay\n\n  -- , runSynCirc \"arrSplitProd-B-B\" $ toCcc $ arrSplitProd @Bool @Bool @Int -- okay\n\n  -- , runSynCirc \"foo\" $ toCcc $ arrSplitProd @Bool @Bool @(Sum Int) -- okay\n\n  -- , runSynCirc \"foo\" $ toCcc $ fmap fold . arrSplitProd @Bool @Bool @(Sum Int) -- fail\n\n  -- , runSynCirc \"foo\" $ toCcc $ fmap @(Vector 2) not -- okay\n\n  -- , runSynCirc \"foo\" $ toCcc $ fmap @(Arr Bool) not -- okay\n\n  -- , runSynCirc \"foo\" $ toCcc $ fmap @(Arr Bool) @(Arr Bool (Sum Int)) fold \n\n  -- , runSynCirc \"foo\" $ toCcc $ fold @(Arr Bool) @(Sum Int) --\n\n  -- , runSynCirc \"foo\" $ toCcc $ (TA.!) @Bool @(Sum Int)\n\n  -- , runSynCirc \"sum-arr-BxB\" $ toCcc $ sum @(Arr (Bool :* Bool)) @Int -- okay\n\n  -- , runSynCirc \"sum-arr-BxBxB-r\" $ toCcc $ sum @(Arr (Bool :* (Bool :* Bool))) @Int -- okay\n  -- , runSynCirc \"sum-arr-BxBxB-l\" $ toCcc $ sum @(Arr ((Bool :* Bool) :* Bool)) @Int -- okay\n\n  -- , runSynCirc \"foo\" $ toCcc $ sum @((->) (Bool :* (Bool :* ()))) @Int -- okay\n  -- , runSynCirc \"foo\" $ toCcc $ sum @(Arr (Bool :* ())) @Int -- okay\n  -- , runSynCirc \"foo\" $ toCcc $ sum @(Arr (Bool :* (Bool :* ()))) @Int -- okay\n\n  -- , runSynCirc \"sum-flat-rbin-3\" $ toCcc $ sum @(Flat (RBin N3)) @Int -- okay\n  -- , runSynCirc \"sum-flat-lbin-3\" $ toCcc $ sum @(Flat (LBin N3)) @Int -- okay\n\n  -- , runSynCirc \"fmap-rbin-4\" $ toCcc $ fmap @(Flat (LBin N4)) not -- \n\n  -- , runSynCirc \"add-int\" $ toCcc $ (+) @Int -- fine\n\n  -- , runSynCirc \"add-int\" $ toCcc $ (+) @Integer -- \n\n  -- , runSynCirc \"foo\" $ toCcc $ toFin @Bool -- works\n\n  -- , runSyn $ toCcc $ unFin @Bool -- breaks\n\n  -- , runSyn $ toCcc $ finVal @2 -- \n\n  -- , runSyn $ toCcc $ unFin @() -- works\n\n  -- , runSyn{-Circ \"foo\"-} $ toCcc $ sum @((->) (Finite 5)) @Int -- breaks\n\n  -- , runSynCirc \"foo\" $ toCcc $ sum @((->) (Bool :* (Bool :* ()))) @Int -- works\n\n  -- , runCirc \"foo\" $ toCcc $ fmap @(Arr (Bool :* (Bool :* ()))) not -- works\n\n  -- , runCirc \"foo\" $ toCcc $ fmap @(Flat (RBin N6)) not -- works\n\n  -- , runCirc \"foo\" $ toCcc $ sum @(Arr (Bool :* (Bool :* ()))) @Int -- nope\n\n  -- , runCirc \"foo\" $ toCcc $ fmap @(Arr (Bool :* (Bool :* ()))) not -- works with Syn but not Circ\n\n  -- , runSynCirc \"sum-rbin-3\" $ toCcc $ sum @(RBin N3) @Int\n\n  -- , runSyn{-Circ \"sum-flat-rbin-1\"-} $ toCcc $ sum @(Flat (RBin N1)) @Int -- ?\n\n  -- , runSynCirc \"packFinite\" $ toCcc $ packFinite @5 -- fail (missing INLINE)\n\n  -- , runSynCirc \"packFiniteM\" $ toCcc $ packFiniteM @5 @Maybe -- okay \n\n  -- , runSynCirc \"vecIndexDef\" $ toCcc $ vecIndexDef @5 @R -- okay\n\n  -- , runSynCirc \"finite\" $ toCcc $ Finite @5 -- okay\n\n  -- , runSynCirc \"add-integer\" $ toCcc $ uncurry ((+) @Integer) -- fine\n\n  -- , runSynCirc \"sum1\" $ toCcc $ sum @Par1 @R -- ??\n\n  -- , runSynCirc \"sum2\" $ toCcc $ sum @Pair @R -- ??\n\n  -- , runSynCirc \"sumV\" $ toCcc $ sum @(Vector 5) @R -- ??\n\n  -- , runSynCirc \"sumAV\" $ toCcc $ sumA @(Vector 5) @R -- ??\n\n  -- , runSynCirc \"foo\" $ toCcc $ andDerR $ \\ () -> zero @((Vector 3 :.: Bump (Vector 2)) R) -- works\n\n  -- , runSynCirc \"foo\" $ toCcc $ andDerR $ \\ () -> zero @((Vector 3 :.: Vector 2) R) -- o2 works\n\n  -- , runSynCirc \"foo\" $ toCcc $ \\ () -> zero @((Vector 3 :.: Vector 2) R) -- o3 fail\n\n  -- , runSynCirc \"foo\" $ toCcc $ \\ () -> zero @((Vector 3 :.: Par1) R) -- o4 fail; o7, o1 (without vector-sized mod)\n\n\n  -- , runSynCirc \"foo\" $ toCcc $ point @(Vector 3 :.: Par1) @R -- o6 fail\n\n\n  -- , runSynCirc \"foo\" $ toCcc $ \\ () -> zero @((Par1 :.: Par1) R) -- okay\n  -- , runSynCirc \"foo\" $ toCcc $ \\ () -> zero @(Vector 3 R) -- okay\n  -- , runSynCirc \"foo\" $ toCcc $ \\ () -> zero @((Par1 :.: Par1) R) -- okay\n  -- , runSynCirc \"foo\" $ toCcc $ point @(Vector 3 :.: Vector 2) @R -- fail (unsized Vector?)\n  -- , runSynCirc \"foo\" $ toCcc $ andDerR $ \\ () -> zero @(Vector 3 R) -- okay\n  -- , runSynCirc \"foo\" $ toCcc $ (^+^) @(Vector 3 R) -- okay\n  -- , runSynCirc \"foo\" $ toCcc $ andDerR $ id @(Vector 2 R) -- okay\n  -- , runSynCirc \"foo\" $ toCcc $ andDerR $ id @((Vector 3 :.: Bump (Vector 2)) R) -- okay\n\n  -- , runSynCirc \"step-lr1\" $ toCcc $ D.step (lr1 @(Vector 2) @(Vector 3)) 0.01\n\n  -- , runSynCirc \"errGrad-lr1\" $ toCcc $ D.errGrad (lr1 @(Vector 2) @(Vector 3)) -- fails with cast confusion\n\n  -- , runSynCirc \"step-lr2\" $ toCcc $ D.step (lr2 @(Vector 2) @(Vector 3) @(Vector 5)) 0.01\n\n    -- , runSynCirc \"fmap\" $ toCcc $ fmap @(Vector 7) not\n\n    -- , runSynCirc \"constV\" $ toCcc $ \\ () -> pure 1 :: Vector 7 Int\n\n    -- , runSynCirc \"pointV\" $ toCcc $ point @(Vector 7) @Bool -- fail\n\n    -- , runSynCirc \"addV\" $ toCcc $ (^+^) @(Vector 7 R)\n\n    -- , runSynCirc \"zeroV\" $ toCcc $ \\ () -> zero @(Vector 7 R)\n\n    -- , runSynCirc \"addR\" $ toCcc $ (^+^) @R\n\n    -- , runSyn $ toCcc $ \\ () -> finite @2 (nat @1) -- okay\n\n    -- , runSyn $ toCcc $ \\ (i :: Finite 2) -> finite @2 (nat @2 - 1) -- okay\n\n    -- , runSyn $ toCcc $ \\ (i :: Finite 2) -> finite (nat @2 - 1) - i -- okay\n\n    -- , runSyn $ toCcc $ reverseFinite @5  -- Fine\n\n    -- , runSynCirc \"reverseFinite\" $ toCcc $ reverseFinite @5\n\n    -- , runSynCirc \"reverseF-pair\" $ toCcc $ reverseF @Pair @Int\n\n    -- , runSynCirc \"reverseF-vec\" $ toCcc $ reverseF @(Vector 5) @Int\n\n    -- , runSynCirc \"reverseFin-Bool-802\" $ toCcc $ isoFwd (reverseFinIso @Bool)\n\n    -- , runSynCirc \"reverseFin-vec\" $ toCcc $ isoFwd (reverseFinIso @(A.Finite 5))\n\n    -- , runSynCirc \"reverseFin-Bool-cheat\" $ toCcc $ unFin @Bool . (1 -) . toFin @Bool\n\n    -- -- https://github.com/conal/concat/issues/49\n    -- -- , putStrLn $ render (toCcc (\\f g x -> f (g (x))))\n    -- , putStrLn $ render (toCcc (\\ (f :: Int -> Bool) (g :: Bool -> Int) x -> f (g (x))))\n\n  -- Circuit graphs\n  , runSynCirc \"add\"         $ toCcc $ (+) @R\n  , runSynCirc \"add-uncurry\" $ toCcc $ uncurry ((+) @R)\n  , runSynCirc \"dup\"         $ toCcc $ A.dup @(->) @R\n  , runSynCirc \"fst\"         $ toCcc $ fst @R @R\n  , runSynCirc \"twice\"       $ toCcc $ twice @R\n  , runSynCirc \"sqr\"         $ toCcc $ sqr @R\n  , runSynCirc \"complex-mul\" $ toCcc $ uncurry ((*) @C)\n  , runSynCirc \"magSqr\"      $ toCcc $ magSqr @R\n  , runSynCirc \"cosSinProd\"  $ toCcc $ cosSinProd @R\n  , runSynCirc \"xp3y\"        $ toCcc $ \\ (x,y) -> x + 3 * y :: R\n  , runSynCirc \"horner\"      $ toCcc $ horner @R [1,3,5]\n  , runSynCirc \"cos-2xx\"     $ toCcc $ \\ x -> cos (2 * x * x) :: R\n  , runSynCirc \"log-2xx\"     $ toCcc $ \\ x -> log (2 * x * x) :: R\n\n  -- -- Automatic differentiation\n  -- , runSynCircDers \"add\"     $ uncurry ((+) @R)\n  -- , runSynCircDers \"fst\"     $ fst @R @R\n  -- , runSynCircDers \"twice\"   $ twice @R\n  -- , runSynCircDers \"sqr\"     $ sqr @R\n  -- , runSynCircDers \"sin\"     $ sin @R\n  -- , runSynCircDers \"cos\"     $ cos @R\n  -- , runSynCircDers \"magSqr\"  $ magSqr  @R\n  -- , runSynCircDers \"cos-2x\"  $ \\ x -> cos (2 * x) :: R\n  -- , runSynCircDers \"cos-2xx\" $ \\ x -> cos (2 * x * x) :: R\n  -- , runSynCircDers \"cos-xpy\" $ \\ (x,y) -> cos (x + y) :: R\n  -- , runSynCircDers \"cos-xpytz\" $ \\ (x,y,z) -> cos (x + y * z) :: R\n\n  -- , runSynCirc \"cos-xpy-adr-802\" $ toCcc $ andGradR $ \\ (x,y) -> cos (x + y) :: R\n\n  -- , runSynCirc \"sqr-adr-802\" $ toCcc $ andGradR $ sqr @R\n\n  -- , runSynCirc \"magSqr-adr\"  $ toCcc $ andDerR $ magSqr  @R\n  -- , runSynCirc \"cosSinProd-adr\"  $ toCcc $ andDerR $ cosSinProd @R\n  -- , runSynCirc \"cosSinProd-gradr\"  $ toCcc $ andGrad2R $ cosSinProd @R\n\n  -- , runSynCirc \"cosSinProd-adf\" $ toCcc $ andDerF $ cosSinProd @R\n  -- , runSynCirc \"cosSinProd-adr\" $ toCcc $ andDerR $ cosSinProd @R\n\n  -- , runCirc \"affRelu\"         $ toCcc $                affRelu @(Vector 2) @(Vector 3) @R\n  -- , runCirc \"affRelu-err\"     $ toCcc $ errSqrSampled (affRelu @(Vector 2) @(Vector 3) @R)\n  -- , runCirc \"affRelu-errGrad\" $ toCcc $ errGrad (affRelu @(Vector 2) @(Vector 3) @R) -- fail\n\n  -- , runCirc \"affRelu2\"         $ toCcc $                lr2 @(Vector 5) @(Vector 3) @(Vector 2)\n  -- , runCirc \"affRelu2-err\"     $ toCcc $ errSqrSampled (lr2 @(Vector 5) @(Vector 3) @(Vector 2))\n  -- , runCirc \"affRelu2-errGrad\" $ toCcc $ errGrad       (lr2 @(Vector 5) @(Vector 3) @(Vector 2))\n\n  -- , runCirc \"affRelu3\"         $ toCcc $                lr3 @(Vector 7) @(Vector 5) @(Vector 3) @(Vector 2)\n  -- , runCirc \"affRelu3-err\"     $ toCcc $ errSqrSampled (lr3 @(Vector 7) @(Vector 5) @(Vector 3) @(Vector 2))\n  -- , runCirc \"affRelu3-errGrad\" $ toCcc $ errGrad       (lr3 @(Vector 7) @(Vector 5) @(Vector 3) @(Vector 2))\n\n  ]\n\ndata P = P R R\n\ninstance HasRep P where\n  type Rep P = R :* R\n  repr (P x y) = (x,y)\n  abst (x,y) = P x y\n\ninstance Additive P where\n  zero = P zero zero\n  P a b ^+^ P c d = P (a+c) (b+d)\n\n#if 0\n\n-- | Convert an 'Integer' into a 'Finite', returning 'Nothing' if the input is out of bounds.\n-- This version has an INLINE pragma.\npackFiniteM :: forall n m. (KnownNat n, Monad m) => Integer -> m (Finite n)\npackFiniteM x | 0 <= x && x < natValAt @n = return (Finite x)\n              | otherwise                 = fail \"packFiniteM: bad index\"\n{-# INLINE packFiniteM #-}\n\n-- Index a sized vector with an integer, given a default\nvecIndexDef :: KnownNat n => a -> Vector n a -> Integer -> a\nvecIndexDef def v i = maybe def (FR.index v) (packFiniteM i)\n{-# INLINE vecIndexDef #-}\n\n#endif\n\n-- foo :: Stack Syn Int Int\n-- foo = toCcc $ A.addC . (A.id A.&&& A.id) --\n\n-- foo = toCcc $ A.addC . (A.id A.&&& A.id) --\n-- foo = reveal $ toCcc $ A.addC . (A.id A.&&& A.id) -- \n-- foo = toCcc $ \\ x -> x + x\n-- foo = toCcc $ A.reveal (A.addC . (A.id A.&&& A.id))\n\n-- z2 :: Syn ((Int :* Bool) :* z) ((Int :* Bool) :* z)\n-- z2 = S.z2\n\n-- z1 :: Int -> Int\n-- z1 = A.addC A.. (A.id A.&&& A.id)\n\n-- z2 :: Stack Syn Int Int\n-- z2 = A.addC A.. (A.id A.&&& A.id)\n\n-- z2' :: Stack Syn Int Int\n-- z2' = A.reveal (A.addC A.. (A.id A.&&& A.id))\n\n-- z3 :: Stack Syn Int Int\n-- z3 = toCcc (\\ x -> x + x)\n\n-- z4 :: Stack Syn Int Int\n-- z4 = toCcc' (\\ x -> x + x)\n\n-- z5 :: Syn (Int :* ()) (Int :* ())\n-- z5 = S.unStack (toCcc' (\\ x -> x + x))\n\n-- z5 :: Syn (Int :* ()) (Int :* ())\n-- z5 = S.unStack (toCcc (\\ x -> x + x))\n\n-- z2' :: Syn (Int :* ()) (Int :* ())\n-- z2' = unStack z2\n\n-- z3 :: Syn (Int :* ()) (Int :* ())\n-- z3 = toCcc $ \\ x -> x + x\n\n-- z3' :: Syn (Int :* ()) (Int :* ())\n-- z3' = unStack z3\n\n\n-- z5 :: Stack Syn Int Int\n-- z5 = A.negateC A.. A.negateC\n\n-- z5' :: Stack Syn Int Int\n-- z5' = A.reveal (A.negateC A.. A.negateC)\n\n-- z6 :: Stack Syn (Int :* Int) (Int :* Int)\n-- z6 = A.negateC A.*** A.negateC\n\n-- z6' :: Stack Syn (Int :* Int) (Int :* Int)\n-- z6' = A.reveal (A.negateC A.*** A.negateC)\n\n-- z6'' :: Stack Syn (Int :* Int) (Int :* Int)\n-- z6'' = C.negateC C.*** C.negateC\n\n-- z7 :: Stack Syn (Int :* Int) (Int :* Int)\n-- z7 = C.negateC `C.crossSecondFirst` C.negateC\n\n-- z7' :: Stack Syn (Int :* Int) (Int :* Int)\n-- z7' = C.negateC `A.crossSecondFirst` C.negateC\n\n-- z8 :: Stack Syn (Int :* Int) (Int :* Int)\n-- z8 = C.negateC C.*** C.negateC\n\n-- z8' :: Stack Syn (Int :* Int) (Int :* Int)\n-- z8' = C.negateC `S.cross` C.negateC\n\n-- z8'' :: Stack Syn (Int :* Int) (Int :* Int)\n-- z8'' = C.negateC `C.crossSecondFirst` C.negateC\n\n-- z8' :: Stack Syn (Int :* Int) (Int :* Int)\n-- z8' = C.negateC A.*** C.negateC\n\n-- z9 :: Stack Syn (Int :* Int) (Int :* Int)\n-- z9 = C.negateC `S.cross` C.negateC\n", "meta": {"hexsha": "37c7d4bfb13dee7a94350de9ae6aa7061946304f", "size": 18859, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/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": "examples/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": "examples/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": 34.4771480804, "max_line_length": 141, "alphanum_fraction": 0.5734662495, "num_tokens": 6903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.03461883535315925, "lm_q1q2_score": 0.016903802467428078}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}\nmodule Parse (readExpr, readExprList) where\nimport LispVals\n\nimport Control.Monad (liftM, join)\nimport Text.ParserCombinators.Parsec (\n    unexpected,\n    char\n    , try\n    , (<|>)\n    , many\n    , many1\n    , string\n    , sepEndBy\n    , endBy\n    , Parser\n    , oneOf\n    , noneOf\n    , skipMany1\n    , space\n    , anyChar\n    , letter\n    , digit\n    , octDigit\n    , hexDigit\n    , parse)\nimport Numeric (readOct, readHex, readFloat)\nimport Data.Char (digitToInt)\nimport Data.Ratio ((%))\nimport Data.Complex (Complex((:+)))\nimport Control.Monad.Error (MonadError, throwError)\nimport qualified Data.Vector as V (fromList)\n\n-- $setup\n-- >>> import Text.ParserCombinators.Parsec (parse)\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=?>@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany1 space\n\n-- |\n-- >>> parse parseString \"lisp\" \"\\\"he\\\\nllo\\\"\"\n-- Right \"he\\nllo\"\nparseString :: Parser LispVal\nparseString = do\n    char '\\\"'\n    x <- many (many1 (noneOf \"\\\\\\\"\") <|> do\n        char '\\\\'\n        s <- oneOf \"nrt\\\"\\\\\"\n        case s of\n            '\\\"' -> return \"\\\"\"\n            '\\\\' -> return \"\\\\\"\n            't' -> return \"\\t\"\n            'n' -> return \"\\n\"\n            'r' -> return \"\\r\"\n            c -> unexpected [c])\n    char '\\\"'\n    return $ String $ join x\n\n-- |\n-- >>> parse parseAtom \"lisp\" \"hello\"\n-- Right hello\nparseAtom :: Parser LispVal\nparseAtom = do\n    first <- letter <|> symbol\n    rest <- many (letter <|> digit <|> symbol)\n    return $ Atom $ first : rest\n\n-- |\n-- >>> parse parseBool \"lisp\" \"#t\"\n-- Right #t\n--\n-- >>> parse parseBool \"lisp\" \"#f\"\n-- Right #f\nparseBool :: Parser LispVal\nparseBool = try $ do\n    char '#'\n    x <- oneOf \"tf\"\n    case x of\n        't' -> return $ Bool True\n        'f' -> return $ Bool False\n        c -> unexpected [c]\n\n-- |\n-- >>> parse parseSignedNumber \"lisp\" \"+#x123\"\n-- Right 291\n--\n-- >>> parse parseSignedNumber \"lisp\" \"+#o123\"\n-- Right 83\n--\n-- >>> parse parseSignedNumber \"lisp\" \"+#d123\"\n-- Right 123\n--\n-- >>> parse parseSignedNumber \"lisp\" \"-#b101\"\n-- Right -5\n--\n-- >>> parse parseSignedNumber \"lisp\" \"-123\"\n-- Right -123\n--\n-- >>> parse parseSignedNumber \"lisp\" \"-3+2i\"\n-- Right -3.0+2.0i\n--\n-- >>> parse parseSignedNumber \"lisp\" \"-3/2\"\n-- Right -3/2\nparseSignedNumber :: Parser LispVal\nparseSignedNumber = try $ do\n    signChar <- oneOf \"+-\"\n    let sign = case signChar of\n                '-' -> -1 :: Integer\n                _ -> 1\n    ureal <- parseComplex <|> parseRatio <|> parseFloat <|> parsePrefixNumber <|> parseDecimal\n    case ureal of\n                Ratio r -> return $ Ratio (r * fromIntegral sign)\n                Complex (r :+ i) -> return $ Complex $ (fromIntegral sign * r) :+ i\n                Float f -> return $ Float $ fromIntegral sign * f\n                Number n -> return $ Number $ sign * n\n                _ -> unexpected (show ureal)\n\n-- |\n-- >>> parse parseUnsignedNumber \"lisp\" \"#x123\"\n-- Right 291\n--\n-- >>> parse parseUnsignedNumber \"lisp\" \"#o123\"\n-- Right 83\n--\n-- >>> parse parseUnsignedNumber \"lisp\" \"#d123\"\n-- Right 123\n--\n-- >>> parse parseUnsignedNumber \"lisp\" \"#b101\"\n-- Right 5\n--\n-- >>> parse parseUnsignedNumber \"lisp\" \"123\"\n-- Right 123\nparseUnsignedNumber :: Parser LispVal\nparseUnsignedNumber = parsePrefixNumber <|> parseDecimal\n\nparsePrefixNumber :: Parser LispVal\nparsePrefixNumber = parseOctal\n    <|> parseHexadecimal\n    <|> parseBinary\n    <|> (do\n        try $ string \"#d\"\n        parseDecimal)\n\nparseOctal :: Parser LispVal\nparseOctal = do\n    try $ string \"#o\"\n    os <- many1 octDigit\n    return $ (Number . fst . head . readOct) os\n\nparseHexadecimal :: Parser LispVal\nparseHexadecimal = do\n    try $ string \"#x\"\n    os <- many1 hexDigit\n    return $ (Number . fst . head . readHex) os\n\nparseBinary :: Parser LispVal\nparseBinary = do\n    try $ string \"#b\"\n    bs <- many1 (oneOf \"01\")\n    return $ (Number . readBinary) bs\n\nreadBinary :: Num a => String -> a\nreadBinary = foldl (\\x y -> x * 2 + (fromIntegral . digitToInt) y) 0\n\nparseDecimal :: Parser LispVal\nparseDecimal = do\n    ds <- many1 digit\n    return $ (Number . read) ds\n\n-- |\n-- >>> parse parseChar \"list\" \"#\\\\c\"\n-- Right #\\c\n--\n-- >>> parse parseChar \"lisp\" \"#\\\\space\"\n-- Right #\\space\nparseChar :: Parser LispVal\nparseChar = do\n    try $ string \"#\\\\\"\n    cs <- parseCharLiteral <|> anyChar\n    return $ Char cs\n\nparseCharLiteral :: Parser Char\nparseCharLiteral = try $ do\n    cs <- string \"space\" <|> string \"newline\"\n    case cs of\n        \"space\" -> return ' '\n        \"newline\" -> return '\\n'\n        s -> unexpected s\n\nparseFloat :: Parser LispVal\nparseFloat = try $ do\n    integer <- many1 digit\n    char '.'\n    fractional <- many1 digit\n    return $ (Float . fst . head . readFloat) (integer ++ \".\" ++ fractional)\n\nparseRatio :: Parser LispVal\nparseRatio = try $ do\n    numerator <- many1 digit\n    char '/'\n    denominator <- many1 digit\n    return $ Ratio $ read numerator % read denominator\n\n-- |\n-- >>> parse parseComplex \"lisp\" \"3.2+2i\"\n-- Right 3.2+2.0i\n--\n-- >>> parse parseComplex \"lisp\" \"+2i\"\n-- Right 0.0+2.0i\n--\n-- >>> parse parseComplex \"lisp\" \"-2i\"\n-- Right 0.0-2.0i\nparseComplex :: Parser LispVal\nparseComplex = parseImaginary <|> try (do\n    real <- many1 digit\n    realFrac <- (char '.' >> many1 digit) <|> return \"0\"\n    sign <- oneOf \"+-\"\n    complex <- many digit\n    let okComplex = case complex of\n                        [] -> \"1\"\n                        _ -> complex\n    complexFrac <- (char '.' >> many1 digit) <|> return \"0\"\n    char 'i'\n    return $ Complex  ((fst . head . readFloat) (real ++ \".\" ++ realFrac) :+\n                        (fst . head . readFloat) (okComplex ++ \".\" ++ complexFrac) * case sign of\n                            '-' -> -1\n                            _ -> 1))\n\nparseImaginary :: Parser LispVal\nparseImaginary = try $ do\n    sign <- (oneOf \"+-\" >>= \\s -> return [s]) <|> return \"\"\n    complex <- many1 digit\n    complexFrac <- (char '.' >> many1 digit) <|> return \"0\"\n    char 'i'\n    let okComplex = case complex of\n                        [] -> \"1\"\n                        _ -> complex\n    return $ Complex (0.0 :+ (fst . head . readFloat) (okComplex ++ \".\" ++ complexFrac) * case sign of\n                            ('-':_) -> -1\n                            _ -> 1)\n\n-- |\n-- >>> parse parseList \"lisp\" \"1 2 3\"\n-- Right (1 2 3)\nparseList :: Parser LispVal\nparseList = liftM List $ sepEndBy parseExpr spaces\n\n-- |\n-- >>> parse parseDottedList \"lisp\" \"1 . 2\"\n-- Right (1 . 2)\nparseDottedList :: Parser LispVal\nparseDottedList = do\n    h <- endBy parseExpr spaces\n    t <- char '.' >> spaces >> parseExpr\n    return $ DottedList h t\n\nparseQuoted :: Parser LispVal\nparseQuoted = do\n    char '\\''\n    x <- parseExpr\n    return $ List [Atom \"quote\", x]\n\nparseUnquoted :: Parser LispVal\nparseUnquoted = do\n    char ','\n    x <- parseExpr\n    return $ List [Atom \"unquote\", x]\n\nparseQuasiQuoted :: Parser LispVal\nparseQuasiQuoted = do\n    char '`'\n    x <- parseExpr\n    return $ List [Atom \"quasiquote\", x]\n\n-- |\n-- >>> parse parseVector \"lisp\" \"#(1 2 3)\"\n-- Right #(1 2 3)\nparseVector :: Parser LispVal\nparseVector = try $ do\n    string \"#(\"\n    many space\n    x <- sepEndBy parseExpr spaces\n    string \")\"\n    return $ Vector $ V.fromList x\n\nparseBracketedParser :: Parser LispVal -> Parser LispVal\nparseBracketedParser p = try $ do\n    char '('\n    many space\n    x <- p\n    char ')'\n    return x\n\n-- |\n-- >>> parse parseExpr \"lisp\" \"hello\"\n-- Right hello\n--\n-- >>> parse parseExpr \"lisp\" \"#(1 2 3)\"\n-- Right #(1 2 3)\n--\n-- >>> parse parseExpr \"lisp\" \"3+2i\"\n-- Right 3.0+2.0i\n--\n-- >>> parse parseExpr \"lisp\" \"3.2+2i\"\n-- Right 3.2+2.0i\n--\n-- >>> parse parseExpr \"lisp\" \"3/2\"\n-- Right 3/2\n--\n-- >>> parse parseExpr \"lisp\" \"3.2\"\n-- Right 3.2\n--\n-- >>> parse parseExpr \"lisp\" \"-3.2\"\n-- Right -3.2\n--\n-- >>> parse parseExpr \"lisp\" \"+#x123\"\n-- Right 291\n--\n-- >>> parse parseExpr \"lisp\" \"#x123\"\n-- Right 291\n--\n-- >>> parse parseExpr \"lisp\" \"+#o123\"\n-- Right 83\n--\n-- >>> parse parseExpr \"lisp\" \"+#d123\"\n-- Right 123\n--\n-- >>> parse parseExpr \"lisp\" \"123\"\n-- Right 123\n--\n-- >>> parse parseExpr \"lisp\" \"-#b101\"\n-- Right -5\n--\n-- >>> parse parseExpr \"lisp\" \"#t\"\n-- Right #t\n--\n-- >>> parse parseExpr \"lisp\" \"#f\"\n-- Right #f\n--\n-- >>> parse parseExpr \"list\" \"#\\\\c\"\n-- Right #\\c\n--\n-- >>> parse parseExpr \"lisp\" \"#\\\\space\"\n-- Right #\\space\n--\n-- >>> parse parseExpr \"lisp\" \"atom\"\n-- Right atom\n--\n-- >>> parse parseExpr \"lisp\" \"'(a list)\"\n-- Right (quote (a list))\n--\n-- >>> parse parseExpr \"lisp\" \"`(a list)\"\n-- Right (quasiquote (a list))\n--\n-- >>> parse parseExpr \"lisp\" \"`(a ,( + 1 2))\"\n-- Right (quasiquote (a (unquote (+ 1 2))))\n--\n-- >>> parse parseExpr \"lisp\" \"#(1 2 3 )\"\n-- Right #(1 2 3)\n--\n-- >>> parse parseExpr \"lisp\" \"(1 2 3)\"\n-- Right (1 2 3)\n--\n-- >>> parse parseExpr \"lisp\" \"( 1 2 . 3)\"\n-- Right (1 2 . 3)\n--\n-- >>> parse parseExpr \"lisp\" \"\\\"he\\\\nllo\\\"\"\n-- Right \"he\\nllo\"\nparseExpr :: Parser LispVal\nparseExpr = parseString\n    <|> parseComplex\n    <|> parseRatio\n    <|> parseFloat\n    <|> parseSignedNumber\n    <|> parseUnsignedNumber\n    <|> parseBool\n    <|> parseChar\n    <|> parseAtom\n    <|> parseQuoted\n    <|> parseQuasiQuoted\n    <|> parseUnquoted\n    <|> parseVector\n    <|> parseBracketedParser parseList\n    <|> parseBracketedParser parseDottedList\n\nreadExpr :: (MonadError LispError m) => String -> m LispVal\nreadExpr = readOrThrow parseExpr\n\nreadExprList :: (MonadError LispError m) => String -> m [LispVal]\nreadExprList = readOrThrow (endBy parseExpr spaces)\n\nreadOrThrow :: (MonadError LispError m) => Parser a -> String -> m a\nreadOrThrow parser input = case parse parser \"lisp\" input of\n    Left err -> throwError $ Parser err\n    Right val -> return val\n", "meta": {"hexsha": "f9937fcd96b2d7bb63624fade291078369b60073", "size": 9713, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Parse.hs", "max_stars_repo_name": "tismith/tlisp", "max_stars_repo_head_hexsha": "c73b541867c01fa79439c6c85870e01fa9142561", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-01-25T04:35:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-04T11:41:12.000Z", "max_issues_repo_path": "src/Parse.hs", "max_issues_repo_name": "tismith/tlisp", "max_issues_repo_head_hexsha": "c73b541867c01fa79439c6c85870e01fa9142561", "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/Parse.hs", "max_forks_repo_name": "tismith/tlisp", "max_forks_repo_head_hexsha": "c73b541867c01fa79439c6c85870e01fa9142561", "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": 24.2825, "max_line_length": 102, "alphanum_fraction": 0.5682075569, "num_tokens": 2962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.031143831996063104, "lm_q1q2_score": 0.013277288508595338}}
{"text": "-----------------\n-- GHC Options --\n-----------------\n\n{-# OPTIONS_GHC -O2                       #-}\n{-# OPTIONS_GHC -Wno-unused-imports       #-}\n{-# OPTIONS_GHC -Wno-missing-import-lists #-}\n\n-------------------------\n-- Language Extensions --\n-------------------------\n\n{-# LANGUAGE BlockArguments       #-}\n{-# LANGUAGE DataKinds            #-}\n{-# LANGUAGE LambdaCase           #-}\n{-# LANGUAGE MultiWayIf           #-}\n{-# LANGUAGE NegativeLiterals     #-}\n{-# LANGUAGE OverloadedLists      #-}\n{-# LANGUAGE OverloadedStrings    #-}\n{-# LANGUAGE RankNTypes           #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE StrictData           #-}\n{-# LANGUAGE TupleSections        #-}\n{-# LANGUAGE TypeApplications     #-}\n{-# LANGUAGE TypeFamilies         #-}\n{-# LANGUAGE ExtendedDefaultRules #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE ViewPatterns         #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NamedFieldPuns #-}\n\nmodule Main where\n\n------------------\n-- Import Lists --\n------------------\n\nimport           Control.Arrow                  ( (>>>) )\nimport qualified Control.Monad                 as M\nimport qualified Control.Monad.Primitive       as Prim\nimport qualified Control.Monad.RWS             as RWS\nimport qualified Control.Monad.Reader          as Reader\nimport qualified Control.Monad.ST              as ST\nimport qualified Control.Monad.State           as State\nimport qualified Control.Monad.Writer          as Writer\nimport qualified Data.Array.IArray             as A\nimport qualified Data.Array.IO                 as AIO\nimport qualified Data.Array.ST                 as AST\nimport           Data.Bifunctor\nimport qualified Data.Bits                     as Bits\nimport qualified Data.ByteString.Char8         as BS\nimport qualified Data.Char                     as Char\nimport qualified Data.Complex                  as Comp\nimport           Data.Foldable\nimport qualified Data.Function                 as Func\nimport qualified Data.Functor                  as Functor\nimport qualified Data.IORef                    as IORef\nimport qualified Data.IntPSQ                   as PSQueue\nimport qualified Data.Ix                       as Ix\nimport qualified Data.List                     as L\nimport qualified Data.Map.Strict               as Map\nimport qualified Data.Maybe                    as Maybe\nimport qualified Data.Primitive.MutVar         as MutVar\nimport qualified Data.Proxy                    as Proxy\nimport qualified Data.Ratio                    as Ratio\nimport qualified Data.STRef                    as STRef\nimport qualified Data.Sequence                 as Seq\nimport           Data.Sequence                  ( (<|)\n                                                , (><)\n                                                , ViewL((:<), EmptyL)\n                                                , ViewR((:>), EmptyR)\n                                                , viewl\n                                                , viewr\n                                                , (|>)\n                                                )\nimport qualified Data.Set                      as Set\nimport qualified Data.Text                     as T\nimport qualified Data.Text.IO                  as TIO\nimport qualified Data.Tree                     as Tree\nimport qualified Data.Vector                   as V\nimport qualified Data.Vector.Algorithms.Merge  as VAM\nimport qualified Data.Vector.Algorithms.Radix  as VAR\nimport qualified Data.Vector.Algorithms.Search as VAS\nimport           Data.Vector.Generic            ( (!)\n                                                , (!?)\n                                                )\nimport qualified Data.Vector.Generic           as VG\nimport qualified Data.Vector.Generic.Mutable   as VGM\nimport qualified Data.Vector.Mutable           as VM\nimport qualified Data.Vector.Unboxed\nimport qualified Data.Vector.Unboxing          as VU\nimport qualified Data.Vector.Unboxing.Mutable  as VUM\nimport qualified Debug.Trace                   as Trace\nimport qualified GHC.Generics\nimport qualified GHC.TypeNats                  as TypeNats\nimport           Prelude                 hiding ( (!)\n                                                , head\n                                                , map\n                                                , print\n                                                , tail\n                                                , uncons\n                                                )\nimport qualified Prelude\n\n----------\n-- Main --\n----------\n\nyes, no :: BS.ByteString\nyes = \"Yes\"\nno = \"No\"\n\nmain :: IO ()\nmain = do\n  [a, b] <- get @[I]\n  print $ a + b\n\n-------------\n-- Library --\n-------------\n\ntype V = V.Vector\ntype VU = VU.Vector\ntype VM = VM.MVector\ntype VUM = VUM.MVector\ntype BS = BS.ByteString\ntype I = Int\ntype IG = Int\ntype D = Double\ntype B = Bool\ntype S = String\n\ndefault (V.Vector, [], BS.ByteString, String, Int, Double)\n\ninfixl 1 #\n(#) :: a -> (a -> b) -> b\n(#) a f = f a\n\nmap :: Monad m => (a -> b) -> m a -> m b\nmap = fmap\n\n---------\n-- I/O --\n---------\n\n-- | ex) get @I, get @(V I) ..\nget :: ReadText a => IO a\nget = readText <$> BS.getLine\n\n-- | ex) getLn @(V I) n, getLn @[I] n\ngetLines :: Int -> forall a . ReadTextLines a => IO a\ngetLines n = readTextLines <$> M.replicateM n BS.getLine\n\n-- |\noutput :: ShowText a => a -> IO ()\noutput = BS.putStr . showText\n\n-- |\noutputLines :: ShowTextLines a => a -> IO ()\noutputLines = BS.putStr . BS.unlines . showTextLines\n\n-- |\nprint :: ShowText a => a -> IO ()\nprint = BS.putStrLn . showText\n\n-- |\nprintLines :: ShowTextLines a => a -> IO ()\nprintLines = BS.putStrLn . BS.unlines . showTextLines\n\n---------------\n-- Read/Show --\n---------------\n\n-- | TextRead\nclass ReadText a where\n  readText :: BS.ByteString -> a\n\nclass ShowText a where\n  showText :: a -> BS.ByteString\n\ninstance ReadText Int where\n  readText s = case BS.readInt s of\n    Just (i, _) -> i\n    Nothing     -> error \"readText Int\"\n\ninstance ReadText Integer where\n  readText s = case BS.readInteger s of\n    Just (i, _) -> i\n    Nothing     -> error \"readText Integer\"\n\ninstance ReadText Double where\n  readText = read . BS.unpack\n\ninstance ReadText BS.ByteString where\n  readText = id\n\ninstance ReadText a => ReadText (V.Vector a) where\n  readText = readVec\n\ninstance (ReadText a, VUM.Unboxable a) => ReadText (VU.Vector a) where\n  readText = readVec\n\ninstance ReadText a => ReadText [a] where\n  readText = map readText . BS.words\n\ninstance (ReadText a, ReadText b) => ReadText (a, b) where\n  readText (BS.words -> [a, b]) = (readText a, readText b)\n  readText _ = error \"Invalid Format :: readText :: BS -> (a, b)\"\n\ninstance (ReadText a, ReadText b, ReadText c) => ReadText (a, b, c) where\n  readText (BS.words -> [a, b, c]) = (readText a, readText b, readText c)\n  readText _ = error \"Invalid Format :: readText :: BS -> (a, b, c)\"\n\ninstance (ReadText a, ReadText b, ReadText c, ReadText d) => ReadText (a, b, c, d) where\n  readText (BS.words -> [a, b, c, d]) =\n    (readText a, readText b, readText c, readText d)\n  readText _ = error \"Invalid Format :: readText :: BS -> (a, b, c, d)\"\n\ninstance ShowText Integer where\n  showText = BS.pack . show\n\ninstance ShowText Int where\n  showText = BS.pack . show\n\ninstance ShowText Double where\n  showText = BS.pack . show\n\ninstance ShowText Bool where\n  showText True  = yes\n  showText False = no\n\ninstance ShowText BS.ByteString where\n  showText = id\n\ninstance (ShowText a) => ShowText (V.Vector a) where\n  showText = showVec\n\ninstance (ShowText a, VU.Unboxable a) => ShowText (VU.Vector a) where\n  showText = showVec\n\ninstance ShowText a => ShowText [a] where\n  showText = BS.unwords . map showText\n\ninstance (ShowText a, ShowText b) => ShowText (a, b) where\n  showText (a, b) = showText a `BS.append` \" \" `BS.append` showText b\n\ninstance (ShowText a, ShowText b, ShowText c) => ShowText (a, b, c) where\n  showText (a, b, c) =\n    showText a\n      `BS.append` \" \"\n      `BS.append` showText b\n      `BS.append` \" \"\n      `BS.append` showText c\n\ninstance (ShowText a, ShowText b, ShowText c, ShowText d) => ShowText (a, b, c, d) where\n  showText (a, b, c, d) =\n    showText a\n      `BS.append` \" \"\n      `BS.append` showText b\n      `BS.append` \" \"\n      `BS.append` showText c\n      `BS.append` \" \"\n      `BS.append` showText d\n\nreadVec :: (VG.Vector v a, ReadText a) => BS.ByteString -> v a\nreadVec = VG.fromList . readText\n\nshowVec :: (VG.Vector v a, ShowText a) => v a -> BS.ByteString\nshowVec = showText . VG.toList\n\nclass ReadTextLines a where\n  readTextLines :: [BS.ByteString] -> a\n\nclass ShowTextLines a where\n  showTextLines :: a -> [BS.ByteString]\n\ninstance ReadText a => ReadTextLines [a] where\n  readTextLines = map readText\n\ninstance ReadText a => ReadTextLines (V.Vector a) where\n  readTextLines = readVecLines\n\ninstance (ReadText a, VU.Unboxable a) => ReadTextLines (VU.Vector a) where\n  readTextLines = readVecLines\n\ninstance ReadTextLines BS.ByteString where\n  readTextLines = BS.unlines\n\ninstance (ReadText a, ReadText b) => ReadTextLines (a, b) where\n  readTextLines (a : b : _) = (readText a, readText b)\n  readTextLines _ = error \"Invalid Format :: readTextLines :: [BS] -> (a, b)\"\n\ninstance (ReadText a, ReadText b, ReadText c) => ReadTextLines (a, b, c) where\n  readTextLines (a : b : c : _) = (readText a, readText b, readText c)\n  readTextLines _ =\n    error \"Invalid Format :: readTextLines :: [BS] -> (a, b, c)\"\n\ninstance ShowText a => ShowTextLines [a] where\n  showTextLines = map showText\n\ninstance ShowText a => ShowTextLines (V.Vector a) where\n  showTextLines = showVecLines\n\ninstance (ShowText a, VU.Unboxable a) => ShowTextLines (VU.Vector a) where\n  showTextLines = showVecLines\n\ninstance ShowTextLines BS.ByteString where\n  showTextLines s = [s]\n\ninstance (ShowText a, ShowText b) => ShowTextLines (a, b) where\n  showTextLines (a, b) = [showText a, showText b]\n\ninstance (ShowText a, ShowText b, ShowText c) => ShowTextLines (a, b, c) where\n  showTextLines (a, b, c) = [showText a, showText b, showText c]\n\nreadVecLines :: (VG.Vector v a, ReadText a) => [BS.ByteString] -> v a\nreadVecLines = VG.fromList . map readText\n\nshowVecLines :: (VG.Vector v a, ShowText a) => v a -> [BS.ByteString]\nshowVecLines = map showText . VG.toList\n\n------------\n-- ModInt --\n------------\n\nnewtype Mod a (p :: TypeNats.Nat) = ModInt a deriving (Eq, Show, VU.Unboxable)\n\ninstance ShowText a => ShowText (Mod a p) where\n  showText (ModInt x) = showText x\n\ninstance ReadText a => ReadText (Mod a p) where\n  readText = ModInt . readText\n\ninstance (TypeNats.KnownNat p, Integral a) => Num (Mod a p) where\n  (ModInt x) + (ModInt y) = ModInt $ (x + y) `mod` p\n    where p = fromIntegral $ TypeNats.natVal (Proxy.Proxy :: Proxy.Proxy p)\n  (ModInt x) * (ModInt y) = ModInt $ (x * y) `mod` p\n    where p = fromIntegral $ TypeNats.natVal (Proxy.Proxy :: Proxy.Proxy p)\n  negate (ModInt x) = ModInt $ -x `mod` p\n    where p = fromIntegral $ TypeNats.natVal (Proxy.Proxy :: Proxy.Proxy p)\n  abs = id\n  signum _ = 1\n  fromInteger n = ModInt $ fromInteger n `mod` p\n    where p = fromIntegral $ TypeNats.natVal (Proxy.Proxy :: Proxy.Proxy p)\n\ninstance (TypeNats.KnownNat p, Integral a) => Fractional (Mod a p) where\n  recip (ModInt n)\n    | gcd n p /= 1 = error\n      \"recip :: Mod a p -> Mod a p : The inverse element does not exisBS.\"\n    | otherwise = ModInt . fst $ extendedEuc n (-p)\n    where p = fromIntegral $ TypeNats.natVal (Proxy.Proxy :: Proxy.Proxy p)\n  fromRational r = ModInt n / ModInt d   where\n    n = fromInteger $ Ratio.numerator r\n    d = fromInteger $ Ratio.denominator r\n\n------------\n-- InfInt --\n------------\n\ndata Sign = Positive | Negative | NA deriving (Eq, Show)\n\nnegateSign :: Sign -> Sign\nnegateSign Positive = Negative\nnegateSign Negative = Positive\nnegateSign NA       = NA\n\naddSign :: Sign -> Sign -> Sign\naddSign Positive Positive = Positive\naddSign Positive Negative = NA\naddSign Negative Positive = NA\naddSign Negative Negative = Negative\naddSign _        _        = NA\n\nmulSign :: Sign -> Sign -> Sign\nmulSign Positive Positive = Positive\nmulSign Positive Negative = Negative\nmulSign Negative Positive = Negative\nmulSign Negative Negative = Positive\nmulSign _        _        = NA\n\ncompareSign :: Sign -> Sign -> Ordering\ncompareSign Positive Positive = EQ\ncompareSign Positive Negative = GT\ncompareSign Negative Positive = LT\ncompareSign Negative Negative = EQ\ncompareSign _        _        = EQ\n\ndata Inf a = Infinity Sign | Finity a deriving (Eq, Show)\n\ninstance ReadText a => ReadText (Inf a) where\n  readText = \\case\n    \"Infinity\"  -> Infinity Positive\n    \"-Infinity\" -> Infinity Negative\n    \"NA\"        -> Infinity NA\n    x           -> Finity $ readText x\n\ninstance ShowText a => ShowText (Inf a) where\n  showText = \\case\n    Infinity Positive -> \"Infinity\"\n    Infinity Negative -> \"-Infinity\"\n    Infinity NA       -> \"NA\"\n    Finity   x        -> showText x\n\ninstance (Num a, Ord a) => Num (Inf a) where\n  x + y = case x of\n    Infinity sign -> case y of\n      Infinity sign' -> Infinity $ addSign sign sign'\n      Finity   y'    -> Infinity sign\n    Finity x' -> case y of\n      Infinity sign' -> Infinity sign'\n      Finity   y'    -> Finity $ x' + y'\n\n  x * y = case x of\n    Infinity sign -> case y of\n      Infinity sign' -> Infinity $ mulSign sign sign'\n      Finity y' | y' < 0    -> Infinity $ negateSign sign\n                | y' == 0   -> Infinity NA\n                | otherwise -> Infinity sign\n    Finity x' -> case y of\n      Infinity sign | x' < 0    -> Infinity $ negateSign sign\n                    | x' == 0   -> Infinity NA\n                    | otherwise -> Infinity sign\n      Finity y' -> Finity $ x' * y'\n  negate = \\case\n    Infinity sign -> Infinity $ negateSign sign\n    Finity   x    -> Finity $ negate x\n  abs = \\case\n    Infinity sign -> Infinity Positive\n    Finity   x    -> Finity $ abs x\n  signum = \\case\n    Infinity Positive -> Finity 1\n    Infinity Negative -> Finity -1\n    Infinity NA       -> Infinity NA\n    Finity   x        -> Finity $ signum x\n  fromInteger n = Finity $ fromInteger n\n\ninstance (Num a, Ord a) => Ord (Inf a) where\n  compare = \\case\n    Infinity sign -> \\case\n      Infinity sign' -> compareSign sign sign'\n      Finity   _     -> if sign == Positive then GT else LT\n    Finity x -> \\case\n      Infinity sign -> if sign == Positive then LT else GT\n      Finity   y    -> compare x y\n\ninfinity :: Num a => Inf a\ninfinity = Infinity Positive\n\nna :: Inf a\nna = Infinity NA\n\ndropWhileRev :: VG.Vector v a => (a -> Bool) -> v a -> v a\ndropWhileRev f xs | VG.null xs = VG.empty\n                  | f x        = dropWhileRev f xs'\n                  | otherwise  = xs\n where\n  x   = VG.last xs\n  xs' = VG.init xs\n\n------------------\n-- Disjoint Set --\n------------------\n\ntype DisjointSet = VU.Vector Int\ndata DisjointSetM m = DSet\n  { dsParents :: VUM.MVector m Int\n  , dsDepths  :: VUM.MVector m Int\n  }\n\nnewDSet :: Prim.PrimMonad m => Int -> m (DisjointSetM (Prim.PrimState m))\nnewDSet n = DSet <$> VU.thaw (VU.generate n id) <*> VUM.replicate n 1\n\nroot :: DisjointSet -> Int -> Int\nroot xs i | xs ! i == i = i\n          | otherwise   = root xs $ xs ! i\n\nfind :: DisjointSet -> Int -> Int -> Bool\nfind xs i j = root xs i == root xs j\n\n-- |\nrootM :: Prim.PrimMonad m => DisjointSetM (Prim.PrimState m) -> Int -> m Int\nrootM ds i = VUM.read (dsParents ds) i >>= \\p -> if p == i\n  then pure i\n  else rootM ds p >>= \\r -> VUM.write (dsParents ds) i r >> pure r\n\nfindM\n  :: Prim.PrimMonad m => DisjointSetM (Prim.PrimState m) -> Int -> Int -> m Bool\nfindM ds i j = (==) <$> rootM ds i <*> rootM ds j\n\nunion\n  :: Prim.PrimMonad m => DisjointSetM (Prim.PrimState m) -> Int -> Int -> m ()\nunion ds i j = do\n  rooti <- rootM ds i\n  rootj <- rootM ds j\n  depi  <- VUM.read (dsDepths ds) rooti\n  depj  <- VUM.read (dsDepths ds) rootj\n  if\n    | depi == depj\n    -> VUM.modify (dsDepths ds) (+ 1) rooti\n      >> VUM.write (dsParents ds) rootj rooti\n    | depi > depj\n    -> VUM.write (dsParents ds) rootj rooti\n    | otherwise\n    -> VUM.write (dsParents ds) rooti rootj\n\n----------------------------\n-- Monadic Priority Queue --\n----------------------------\n\ntype MPSQueue m p v = MutVar.MutVar m (PSQueue.IntPSQ p v)\n\nmpsqNull :: Prim.PrimMonad m => MPSQueue (Prim.PrimState m) p v -> m Bool\nmpsqNull q = PSQueue.null <$> MutVar.readMutVar q\n\nmpsqEmpty :: Prim.PrimMonad m => m (MPSQueue (Prim.PrimState m) p v)\nmpsqEmpty = MutVar.newMutVar PSQueue.empty\n\nmpsqSingleton\n  :: Prim.PrimMonad m\n  => Ord p => Int -> p -> v -> m (MPSQueue (Prim.PrimState m) p v)\nmpsqSingleton k p v = MutVar.newMutVar $ PSQueue.singleton k p v\n\nmpsqInsert\n  :: Prim.PrimMonad m\n  => Ord p => MPSQueue (Prim.PrimState m) p v -> Int -> p -> v -> m ()\nmpsqInsert m k p v = MutVar.modifyMutVar' m (PSQueue.insert k p v)\n\n-- |\nmpsqFindMin\n  :: Prim.PrimMonad m\n  => Ord p => MPSQueue (Prim.PrimState m) p v -> m (Maybe (Int, p, v))\nmpsqFindMin q = PSQueue.findMin <$> MutVar.readMutVar q\n\n-- |\nmpsqMinView\n  :: Prim.PrimMonad m\n  => Ord p => MPSQueue (Prim.PrimState m) p v -> m (Maybe (Int, p, v))\nmpsqMinView q = do\n  res <- PSQueue.minView <$> MutVar.readMutVar q\n  case res of\n    Nothing            -> pure Nothing\n    Just (k, p, v, q') -> do\n      MutVar.writeMutVar q q'\n      pure $ Just (k, p, v)\n\n\n----------------------\n-- Monadic Sequence --\n----------------------\n\ntype MSequence m a = MutVar.MutVar m (Seq.Seq a)\n\nmsqEmpty :: Prim.PrimMonad m => m (MSequence (Prim.PrimState m) a)\nmsqEmpty = MutVar.newMutVar Seq.empty\n\nmsqSingleton :: Prim.PrimMonad m => a -> m (MSequence (Prim.PrimState m) a)\nmsqSingleton x = MutVar.newMutVar $ Seq.singleton x\n\ninfixr 5 <<|\ninfixl 5 |>>\n\n-- | Cons\n(<<|) :: Prim.PrimMonad m => a -> MSequence (Prim.PrimState m) a -> m ()\nx <<| xs = MutVar.modifyMutVar' xs (x Seq.<|)\n\n-- | Snoc\n(|>>) :: Prim.PrimMonad m => MSequence (Prim.PrimState m) a -> a -> m ()\nxs |>> x = MutVar.modifyMutVar' xs (Seq.|> x)\n\nmsqViewL :: Prim.PrimMonad m => MSequence (Prim.PrimState m) a -> m (Maybe a)\nmsqViewL xs = do\n  xs' <- MutVar.readMutVar xs\n  case viewl xs' of\n    EmptyL -> pure Nothing\n    x :< _ -> pure (Just x)\n\nmsqViewR :: Prim.PrimMonad m => MSequence (Prim.PrimState m) a -> m (Maybe a)\nmsqViewR xs = do\n  xs' <- MutVar.readMutVar xs\n  case viewr xs' of\n    EmptyR    -> pure Nothing\n    xs'' :> x -> pure (Just x)\n\nmsqPopL :: Prim.PrimMonad m => MSequence (Prim.PrimState m) a -> m (Maybe a)\nmsqPopL xs = do\n  xs' <- MutVar.readMutVar xs\n  case viewl xs' of\n    EmptyL    -> pure Nothing\n    x :< xs'' -> do\n      MutVar.writeMutVar xs xs''\n      pure (Just x)\n\nmsqPopR :: Prim.PrimMonad m => MSequence (Prim.PrimState m) a -> m (Maybe a)\nmsqPopR xs = do\n  xs' <- MutVar.readMutVar xs\n  case viewr xs' of\n    EmptyR    -> pure Nothing\n    xs'' :> x -> do\n      MutVar.writeMutVar xs xs''\n      pure (Just x)\n\nmsqNull :: Prim.PrimMonad m => MSequence (Prim.PrimState m) a -> m Bool\nmsqNull xs = do\n  xs' <- MutVar.readMutVar xs\n  pure $ Seq.null xs'\n\n-----------\n-- Graph --\n-----------\n\ntype Graph a = V.Vector [(Int, a)] --a\ntype UGraph = Graph ()\n\ngEmpty :: Graph a\ngEmpty = V.singleton []\n\ngFromEdges :: VG.Vector v (Int, Int, a) => Int -> v (Int, Int, a) -> Graph a\ngFromEdges n edges = ST.runST do\n  v <- VM.replicate n []\n  VG.forM_ edges \\(i, j, a) -> VM.modify v ((j, a) :) i\n  V.freeze v\n\n-- |\ngReverse :: Graph a -> Graph a\ngReverse g = ST.runST do\n  let n = V.length g\n  v <- VM.replicate n []\n  V.forM_ [0 .. n - 1] \\i -> M.forM_ (g ! i) \\(j, a) -> VM.modify v ((i, a) :) j\n  V.freeze v\n\n-- |\n-- |\n-- | (Listcons)\ndijkstra :: Graph Int -> Int -> V.Vector (Inf Int, [Int])\ndijkstra g i = V.create do\n  let n = V.length g\n\n  --\n  -- dists ! j == (i, )\n  dists <- VM.replicate n (infinity, [])\n  VM.write dists i (0, [i])\n\n  --\n  -- key: , : , value: ()\n  queue <- mpsqSingleton i 0 ()\n\n  let --\n      -- prev: , v: , alt: ()\n      -- prev\n      update prev v alt = do\n        (_, xs) <- VM.read dists prev\n        VM.write dists v (alt, v : xs)\n        --\n        -- ( C++  continue )\n        mpsqInsert queue v alt ()\n\n      --\n      -- u:\n      processing u = do\n        --\n        (dist_u, _) <- VM.read dists u\n        M.forM_\n          (g ! u)\n          (\\(v, cost) -> do\n            (dist_v, _) <- VM.read dists v\n            let alt = dist_u + fromIntegral cost\n            M.when (dist_v > alt) $ update u v alt\n          )\n\n  --\n  while do\n    res <- mpsqMinView queue\n    case res of\n      Nothing        -> pure False\n      Just (u, _, _) -> do\n        processing u\n        pure True\n  pure dists\n\ndfs :: Graph a -> Int -> Tree.Tree Int\ndfs g i = ST.runST do\n  reached <- VM.replicate (V.length g) False\n  let loop now = do\n        VM.write reached now True\n        next     <- M.filterM (fmap not . VM.read reached) . map fst $ g ! now\n        children <- M.mapM loop next\n        pure $ Tree.Node now children\n  loop i\n\n----------\n-- Maze --\n----------\n\ntype Maze = V.Vector (VU.Vector Char)\n-- ^ Char\n\nmzHeight :: Maze -> Int\nmzHeight = V.length\n\nmzWidth :: Maze -> Int\nmzWidth v = maybe 0 VU.length (v !? 0)\n\ntype Rules a = Char -> Char -> Maybe a\n\nreadMaze :: BS.ByteString -> Maze\nreadMaze str = V.fromList $ map (VU.fromList . BS.unpack) $ BS.lines str\n\ngetMaze :: Int -> IO Maze\ngetMaze h = readMaze <$> getLines h\n\nmazePos :: Maze -> (Int, Int) -> Int\nmazePos mz (i, j) = i * mzWidth mz + j\n\nmazeToGraph :: Rules a -> Maze -> Graph a\nmazeToGraph rules maze =\n  let h = mzHeight maze\n      w = mzWidth maze\n  in  gFromEdges (h * w)\n        $ V.fromList\n        $ Maybe.catMaybes\n        $ [ edge\n          | i        <- [0 .. h - 1]\n          , j        <- [0 .. w - 1]\n          , (i', j') <- [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]\n          , i' >= 0\n          , i' < h\n          , j' >= 0\n          , j' < w\n          , let c    = maze ! i ! j\n          , let c' = maze ! i' ! j'\n          , let edge = (w * i + j, w * i' + j', ) <$> rules c c'\n          ]\n\n\n----------\n-- Tree --\n----------\n\ndepth :: Eq a => Tree.Tree a -> a -> Maybe Int\ndepth (Tree.Node a []) b | a == b = Just 0\ndepth (Tree.Node _ []) _          = Nothing\ndepth (Tree.Node a xs) b          = case Maybe.mapMaybe (`depth` b) xs of\n  [] -> Nothing\n  xs -> Just $ 1 + minimum xs\n\n--------------\n-- MultiSet --\n--------------\n\ntype MultiSet a = Map.Map a Int\n\nmsEmpty :: MultiSet a\nmsEmpty = Map.empty\n\nmsSingleton :: a -> MultiSet a\nmsSingleton a = Map.singleton a 1\n\nmsFromList :: Ord a => [a] -> MultiSet a\nmsFromList xs = Map.fromListWith (+) $ map (, 1) xs\n\nmsInsert :: Ord a => a -> MultiSet a -> MultiSet a\nmsInsert a = Map.insertWith (+) a 1\n\nmsInserts :: Ord a => a -> Int -> MultiSet a -> MultiSet a\nmsInserts = Map.insertWith (+)\n\nmsDelete :: Ord a => a -> MultiSet a -> MultiSet a\nmsDelete = Map.update (\\n -> if n > 1 then Just (n - 1) else Nothing)\n\nmsDeletes :: Ord a => a -> Int -> MultiSet a -> MultiSet a\nmsDeletes a n = Map.update (\\n' -> if n' > n then Just (n' - n) else Nothing) a\n\nmsDeleteAll :: Ord a => a -> MultiSet a -> MultiSet a\nmsDeleteAll = Map.delete\n\nmsMember :: Ord a => a -> MultiSet a -> Bool\nmsMember = Map.member\n\nmsLookupLT :: Ord a => a -> MultiSet a -> Maybe a\nmsLookupLT a = fmap fst . Map.lookupLT a\n\nmsLookupGT :: Ord a => a -> MultiSet a -> Maybe a\nmsLookupGT a = fmap fst . Map.lookupGT a\n\nmsLookupLE :: Ord a => a -> MultiSet a -> Maybe a\nmsLookupLE a = fmap fst . Map.lookupLE a\n\nmsLookupGE :: Ord a => a -> MultiSet a -> Maybe a\nmsLookupGE a = fmap fst . Map.lookupGE a\n\nmsNull :: MultiSet a -> Bool\nmsNull = Map.null\n\nmsUnion :: Ord a => MultiSet a -> MultiSet a -> MultiSet a\nmsUnion = Map.unionWith (+)\n\n-- | split MultiSet into two MultiSet\n-- | (LT, GE)\nmsSplitLTGE :: Ord a => a -> MultiSet a -> (MultiSet a, MultiSet a)\nmsSplitLTGE a ms =\n  let (lt, x, gt) = Map.splitLookup a ms\n      ge          = case x of\n        Nothing -> gt\n        Just v  -> msInserts a v gt\n  in  (lt, ge)\n\nmsSplitLEGT :: Ord a => a -> MultiSet a -> (MultiSet a, MultiSet a)\nmsSplitLEGT a ms =\n  let (lt, x, gt) = Map.splitLookup a ms\n      le          = case x of\n        Nothing -> lt\n        Just v  -> msInserts a v lt\n  in  (le, gt)\n\nmsElemAtL :: Ord a => Int -> MultiSet a -> Maybe a\nmsElemAtL i ms = case Map.minViewWithKey ms of\n  Nothing -> Nothing\n  Just ((k, v), rest) | i < v     -> Just k\n                      | otherwise -> msElemAtL (i - v) rest\n\nmsElemAtG :: Ord a => Int -> MultiSet a -> Maybe a\nmsElemAtG i ms = case Map.maxViewWithKey ms of\n  Nothing -> Nothing\n  Just ((k, v), rest) | i < v     -> Just k\n                      | otherwise -> msElemAtG (i - v) rest\n\n---------------------\n-- MutableMultiSet --\n---------------------\n\ntype MutableMultiSet m a = MutVar.MutVar m (MultiSet a)\n\nmmsEmpty :: Prim.PrimMonad m => m (MutableMultiSet (Prim.PrimState m) a)\nmmsEmpty = MutVar.newMutVar msEmpty\n\nmmsSingleton\n  :: Prim.PrimMonad m => a -> m (MutableMultiSet (Prim.PrimState m) a)\nmmsSingleton a = MutVar.newMutVar $ msSingleton a\n\nmmsFromList\n  :: Prim.PrimMonad m\n  => Ord a => [a] -> m (MutableMultiSet (Prim.PrimState m) a)\nmmsFromList = MutVar.newMutVar . msFromList\n\nmmsInsert\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> m ()\nmmsInsert mms a = MutVar.modifyMutVar' mms $ msInsert a\n\nmmsInserts\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> Int -> m ()\nmmsInserts mms a n = MutVar.modifyMutVar' mms $ msInserts a n\n\nmmsDelete\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> m ()\nmmsDelete mms a = MutVar.modifyMutVar' mms $ msDelete a\n\nmmsDeletes\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> Int -> m ()\nmmsDeletes mms a n = MutVar.modifyMutVar' mms $ msDeletes a n\n\nmmsDeleteAll\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> m ()\nmmsDeleteAll mms a = MutVar.modifyMutVar' mms $ msDeleteAll a\n\nmmsMember\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> m Bool\nmmsMember mms a = MutVar.readMutVar mms Functor.<&> msMember a\n\nmmsLookupLT\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> m (Maybe a)\nmmsLookupLT mms a = MutVar.readMutVar mms Functor.<&> msLookupLT a\n\nmmsLookupGT\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> m (Maybe a)\nmmsLookupGT mms a = MutVar.readMutVar mms Functor.<&> msLookupGT a\n\nmmsLookupLE\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> m (Maybe a)\nmmsLookupLE mms a = MutVar.readMutVar mms Functor.<&> msLookupLE a\n\nmmsLookupGE\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> a -> m (Maybe a)\nmmsLookupGE mms a = MutVar.readMutVar mms Functor.<&> msLookupGE a\n\nmmsNull :: Prim.PrimMonad m => MutableMultiSet (Prim.PrimState m) a -> m Bool\nmmsNull mms = MutVar.readMutVar mms Functor.<&> msNull\n\nmmsUnion\n  :: Prim.PrimMonad m\n  => Ord a\n  => MutableMultiSet (Prim.PrimState m) a\n  -> MutableMultiSet (Prim.PrimState m) a\n  -> m ()\nmmsUnion mms1 mms2 = do\n  ms1 <- MutVar.readMutVar mms1\n  ms2 <- MutVar.readMutVar mms2\n  MutVar.modifyMutVar' mms1 $ msUnion ms2\n\nmmsSplitLTGE\n  :: Prim.PrimMonad m\n  => Ord a\n  => MutableMultiSet (Prim.PrimState m) a\n  -> a\n  -> m (MultiSet a, MultiSet a)\nmmsSplitLTGE mms a = MutVar.readMutVar mms Functor.<&> msSplitLTGE a\n\nmmsSplitLEGT\n  :: Prim.PrimMonad m\n  => Ord a\n  => MutableMultiSet (Prim.PrimState m) a\n  -> a\n  -> m (MultiSet a, MultiSet a)\nmmsSplitLEGT mms a = MutVar.readMutVar mms Functor.<&> msSplitLEGT a\n\nmmsElemAtL\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> Int -> m (Maybe a)\nmmsElemAtL mms i = MutVar.readMutVar mms Functor.<&> msElemAtL i\n\nmmsElemAtG\n  :: Prim.PrimMonad m\n  => Ord a => MutableMultiSet (Prim.PrimState m) a -> Int -> m (Maybe a)\nmmsElemAtG mms i = MutVar.readMutVar mms Functor.<&> msElemAtG i\n\n------------\n-- Others --\n------------\n\nhead :: VG.Vector v a => v a -> Maybe a\nhead v = if VG.null v then Nothing else Just (v ! 0)\n\ntail :: VG.Vector v a => v a -> Maybe (v a)\ntail v = if VG.null v then Nothing else Just (VG.tail v)\n\nuncons :: VG.Vector v a => v a -> Maybe (a, v a)\nuncons v = if VG.null v then Nothing else Just (v ! 0, VG.tail v)\n\nwhile :: Monad m => m Bool -> m ()\nwhile f = f >>= \\frag -> M.when frag $ while f\n\ndivisor :: Integral a => a -> [a]\ndivisor n\n  | n <= 0 = error\n    \"divisor : Definition range does not include negative numbers or zero\"\n  | otherwise = half ++ rev where\n  mid  = floor . sqrt @Double . fromIntegral $ n\n  half = filter ((== 0) . mod n) [1 .. mid]\n  rev =\n    reverse\n      . map (n `div`)\n      . (if mid ^ (2 :: Int) == n then init else id)\n      $ half\n\nprimeFact :: forall a b . (Integral a, Integral b) => a -> [(a, b)]\nprimeFact 1 = []\nprimeFact n\n  | n == 1 = []\n  | n <= 0 = error\n    \"primefact : Definition range does not include negative numbers or zero\"\n  | otherwise = case L.find ((== 0) . mod n) ([2 .. mid] :: [a]) of\n    Nothing -> [(n, 1)]\n    Just p  -> (p, m) : primeFact next     where\n      m    = loop n p\n      next = n `div` (p ^ m)\n where\n  loop m q | m `mod` q == 0 = 1 + loop (m `div` q) q\n           | otherwise      = 0\n  mid = floor . sqrt @Double . fromIntegral $ n\n\n-- |\nprimes :: forall a . Integral a => a -> [a]\nprimes n | n <= 1    = []\n         | otherwise = filter ((frags !) . fromIntegral) [2 .. n] where\n  frags = VU.create do\n    v <- VUM.replicate (fromIntegral (n + 1)) True\n    VUM.write v 0 False\n    VUM.write v 1 False\n    VU.forM_\n      [2 .. floor . sqrt @Double . fromIntegral $ n]\n      \\i -> do\n        frag <- VUM.read v i\n        M.when frag $ VU.forM_ [2 * i, 3 * i .. fromIntegral n]\n                               \\j -> VUM.write v j False\n    pure v\n\n-- |\n-- | ax + by = gcd a b\nextendedEuc :: (Integral b) => b -> b -> (b, b)\nextendedEuc a b | a >= 0 && b == 0 = (1, 0)\n                | a < 0 && b == 0  = (-1, 0)\n                | otherwise        = (t, s - q * t) where\n  (q, r) = divMod a b\n  (s, t) = extendedEuc b r\n", "meta": {"hexsha": "6fb636e1122374b1a614132a0a610b58ed65476d", "size": 29999, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/AddTest.hs", "max_stars_repo_name": "yukikurage/comp-programming-stack", "max_stars_repo_head_hexsha": "e6464683b2476ce2585d8f7294d77eac9e70de93", "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/AddTest.hs", "max_issues_repo_name": "yukikurage/comp-programming-stack", "max_issues_repo_head_hexsha": "e6464683b2476ce2585d8f7294d77eac9e70de93", "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/AddTest.hs", "max_forks_repo_name": "yukikurage/comp-programming-stack", "max_forks_repo_head_hexsha": "e6464683b2476ce2585d8f7294d77eac9e70de93", "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.8794820717, "max_line_length": 88, "alphanum_fraction": 0.5811860395, "num_tokens": 8890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.032100708105956687, "lm_q1q2_score": 0.012714068137954395}}
{"text": "--------------------------------------------------------------------------------\n\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\n--------------------------------------------------------------------------------\n\n{-# LANGUAGE AllowAmbiguousTypes       #-}\n{-# LANGUAGE BangPatterns              #-}\n{-# LANGUAGE CPP                       #-} \n{-# LANGUAGE EmptyDataDecls            #-}\n{-# LANGUAGE FlexibleContexts          #-}\n{-# LANGUAGE FlexibleInstances         #-}\n{-# LANGUAGE ForeignFunctionInterface  #-}\n{-# LANGUAGE FunctionalDependencies    #-}\n{-# LANGUAGE GADTs                     #-}\n{-# LANGUAGE KindSignatures            #-}\n{-# LANGUAGE LambdaCase                #-}\n{-# LANGUAGE MagicHash                 #-}\n{-# LANGUAGE MultiParamTypeClasses     #-}\n{-# LANGUAGE Rank2Types                #-}\n{-# LANGUAGE ScopedTypeVariables       #-}\n{-# LANGUAGE StandaloneDeriving        #-}\n{-# LANGUAGE TypeApplications          #-}\n{-# LANGUAGE TypeFamilyDependencies    #-}\n{-# LANGUAGE TypeInType                #-}\n{-# LANGUAGE UnboxedTuples             #-}\n{-# LANGUAGE UndecidableInstances      #-}\n\n--------------------------------------------------------------------------------\n\n-- | Internal module to Eigen.\n--   Here we define all foreign function calls,\n--   and some typeclasses integral to the public and private interfaces\n--   of the library.\nmodule Eigen.Internal where --   FIXME: Explicit export list\n\n--------------------------------------------------------------------------------\n\nimport           Control.Monad            (when)\nimport           Data.Binary              (Binary(put,get))\nimport           Data.Binary.Get          (getByteString, getWord32be)\nimport           Data.Binary.Put          (putByteString, putWord32be)\nimport           Data.Bits                (xor)\nimport           Data.Complex             (Complex((:+)))\nimport           Data.Kind                (Type)\nimport           Data.Proxy               (Proxy(Proxy))\nimport           Foreign.C.String         (CString, peekCString)\nimport           Foreign.C.Types          (CInt(CInt), CFloat(CFloat), CDouble(CDouble), CChar)\nimport           Foreign.ForeignPtr       (ForeignPtr, castForeignPtr, withForeignPtr)\nimport           Foreign.Ptr              (Ptr, castPtr, nullPtr, plusPtr)\nimport           Foreign.Storable         (Storable(sizeOf, alignment, poke, peek, peekByteOff, peekElemOff, pokeByteOff, pokeElemOff))\nimport           GHC.TypeLits             (natVal, KnownNat, Nat)\nimport           System.IO.Unsafe         (unsafeDupablePerformIO)\nimport qualified Data.Vector.Storable     as VS\nimport qualified Data.ByteString          as BS\nimport qualified Data.ByteString.Internal as BSI\n\n--------------------------------------------------------------------------------\n\n-- | Like 'Proxy', but specialised to 'Nat'.\ndata Row (r :: Nat) = Row\n-- | Like 'Proxy', but specialised to 'Nat'.\ndata Col (c :: Nat) = Col\n\n-- | Used internally. Given a 'KnownNat' constraint, turn the type-level 'Nat' into an 'Int'.\nnatToInt :: forall n. KnownNat n => Int\n{-# INLINE natToInt #-}\nnatToInt = fromIntegral (natVal @n Proxy)\n\n--------------------------------------------------------------------------------\n\n-- | Cast to and from a C-FFI type\n--   'Cast' is a closed typeclass with an associated injective type family.\n--   It is closed in the sense that we provide only four types\n--   with instances for it; and intend for eigen to only be used\n--   with those four types. The injectivity of the type family is\n--   then useful for avoiding MPTCs. 'Cast' has two functions; 'toC'\n--   and 'fromC', where 'toC' goes from a Haskell type to its associated\n--   C type for internal use, with the C FFI, and 'fromC' goes from the\n--   associated C type to the Haskell type.\nclass Cast (a :: Type) where\n  type family C a = (result :: Type) | result -> a\n  toC   :: a -> C a\n  fromC :: C a -> a\n\ninstance Cast Int where\n  type C Int = CInt\n  toC = CInt . fromIntegral\n  {-# INLINE toC #-}\n  fromC (CInt x) = fromIntegral x\n  {-# INLINE fromC #-}\n\ninstance Cast Float where\n  type C Float = CFloat\n  toC = CFloat\n  {-# INLINE toC #-}\n  fromC (CFloat x) = x\n  {-# INLINE fromC #-}\n\ninstance Cast Double where\n  type C Double = CDouble\n  toC = CDouble\n  {-# INLINE toC #-}\n  fromC (CDouble x) = x\n  {-# INLINE fromC #-}\n\ninstance Cast a => Cast (Complex a) where\n  type C (Complex a) = CComplex (C a)\n  toC (a :+ b) = CComplex (toC a) (toC b)\n  {-# INLINE toC #-}\n  fromC (CComplex a b) = (fromC a) :+ (fromC b)\n  {-# INLINE fromC #-}\n\n-- | WARNING! 'toC' is lossy for any Int greater than (maxBound :: Int32)!\ninstance Cast a => Cast (Int, Int, a) where\n  type C (Int, Int, a) = CTriplet a\n  {-# INLINE toC #-}\n  toC (x, y, z) = CTriplet (toC x) (toC y) (toC z)\n  {-# INLINE fromC #-}\n  fromC (CTriplet x y z) = (fromC x, fromC y, fromC z)\n\n--------------------------------------------------------------------------------\n\n-- | Complex number for FFI with the same memory layout as std::complex\\<T\\>\ndata CComplex a = CComplex !a !a deriving (Show)\n\ninstance Storable a => Storable (CComplex a) where\n    sizeOf _ = sizeOf (undefined :: a) * 2\n    alignment _ = alignment (undefined :: a)\n    poke p (CComplex x y) = do\n        pokeElemOff (castPtr p) 0 x\n        pokeElemOff (castPtr p) 1 y\n    peek p = CComplex\n        <$> peekElemOff (castPtr p) 0\n        <*> peekElemOff (castPtr p) 1\n\n--------------------------------------------------------------------------------\n\n-- | FIXME: Doc\ndata CTriplet a where\n  CTriplet :: Cast a => !CInt -> !CInt -> !(C a) -> CTriplet a\n\nderiving instance (Show a, Show (C a)) => Show (CTriplet a)\n\ninstance (Storable a, Elem a) => Storable (CTriplet a) where\n    sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: CInt) * 2\n    alignment _ = alignment (undefined :: CInt)\n    poke p (CTriplet row col val) = do\n        pokeElemOff (castPtr p) 0 row\n        pokeElemOff (castPtr p) 1 col\n        pokeByteOff p (sizeOf (undefined :: CInt) * 2) val\n    peek p = CTriplet\n        <$> peekElemOff (castPtr p) 0\n        <*> peekElemOff (castPtr p) 1\n        <*> peekByteOff p (sizeOf (undefined :: CInt) * 2)\n\n--------------------------------------------------------------------------------\n\n-- | `Elem` is a closed typeclass that encompasses the properties\n--   eigen expects its values to possess, and simplifies the external\n--   API quite a bit.\nclass (Num a, Cast a, Storable a, Storable (C a), Code (C a)) => Elem a\n\ninstance Elem Float\ninstance Elem Double\ninstance Elem (Complex Float)\ninstance Elem (Complex Double)\n\n--------------------------------------------------------------------------------\n\n-- | Encode a C Type as a CInt\n--\n--   Hack used in FFI wrapper functions when constructing FFI calls\nclass Code a where; code :: a -> CInt\ninstance Code CFloat             where; code _ = 0\ninstance Code CDouble            where; code _ = 1\ninstance Code (CComplex CFloat)  where; code _ = 2\ninstance Code (CComplex CDouble) where; code _ = 3\n\n-- | Hack used in constructing FFI calls.\nnewtype MagicCode = MagicCode CInt deriving Eq\n\ninstance Binary MagicCode where\n    put (MagicCode _code) = putWord32be $ fromIntegral _code\n    get = MagicCode . fromIntegral <$> getWord32be\n\n-- | Hack used in constructing FFI calls.\nmagicCode :: Code a => a -> MagicCode\nmagicCode x = MagicCode (code x `xor` 0x45696730)\n\n--------------------------------------------------------------------------------\n\n-- | Machine size of a 'CInt'.\nintSize :: Int\nintSize = sizeOf (undefined :: CInt)\n\n-- | FIXME: Doc\nencodeInt :: CInt -> BS.ByteString\nencodeInt x = BSI.unsafeCreate (sizeOf x) $ (`poke` x) . castPtr\n\n-- | FIXME: Doc\ndecodeInt :: BS.ByteString -> CInt\ndecodeInt (BSI.PS fp fo fs)\n    | fs == sizeOf x = x\n    | otherwise = error \"decodeInt: wrong buffer size\"\n    where x = performIO $ withForeignPtr fp $ peek . (`plusPtr` fo)\n\n--------------------------------------------------------------------------------\n\n-- | 'Binary' instance for 'Data.Vector.Storable.Mutable.Vector'\ninstance Storable a => Binary (VS.Vector a) where\n    put vs = put (BS.length bs) >> putByteString bs where\n        (fp,fs) = VS.unsafeToForeignPtr0 vs\n        es = sizeOf (VS.head vs)\n        bs = BSI.fromForeignPtr (castForeignPtr fp) 0 (fs * es)\n        \n    get = get >>= getByteString >>= \\bs -> let\n        (fp,fo,fs) = BSI.toForeignPtr bs\n        es = sizeOf (VS.head vs)\n        -- `plusForeignPtr` is used qualified here to just remind a reader\n        -- that it is defined internally within eigen\n        vs = VS.unsafeFromForeignPtr0 (Eigen.Internal.plusForeignPtr fp fo) (fs `div` es)\n        in return vs\n\n--------------------------------------------------------------------------------\n\n-- | FIXME: Doc\ndata CSparseMatrix a\n-- | FIXME: Doc\ntype CSparseMatrixPtr a = Ptr (CSparseMatrix a)\n\n-- | FIXME: Doc\ndata CSolver a\n-- | FIXME: Doc\ntype CSolverPtr a = Ptr (CSolver a)\n\n-- {-# INLINE unholyPerformIO #-}\n-- unholyPerformIO :: IO a -> a\n-- unholyPerformIO (IO m) = case m realWorld# of (# _, r #) -> r\n\n-- | FIXME: replace with unholyPerformIO (?)\nperformIO :: IO a -> a\nperformIO = unsafeDupablePerformIO\n\n-- | FIXME: Doc\nplusForeignPtr :: ForeignPtr a -> Int -> ForeignPtr b\nplusForeignPtr fp fo = castForeignPtr fp1 where\n    vs :: VS.Vector CChar\n    vs = VS.unsafeFromForeignPtr (castForeignPtr fp) fo 0\n    (fp1, _) = VS.unsafeToForeignPtr0 vs\n\nforeign import ccall \"eigen-proxy.h free\" c_freeString :: CString -> IO ()\n\ncall :: IO CString -> IO ()\ncall func = func >>= \\c_str -> when (c_str /= nullPtr) $\n    peekCString c_str >>= \\str -> c_freeString c_str >> fail str\n\nforeign import ccall \"eigen-proxy.h free\" free :: Ptr a -> IO ()\n\nforeign import ccall \"eigen-proxy.h eigen_setNbThreads\" c_setNbThreads :: CInt -> IO ()\nforeign import ccall \"eigen-proxy.h eigen_getNbThreads\" c_getNbThreads :: IO CInt\n\n--------------------------------------------------------------------------------\n\n#let api1 name, args = \"foreign import ccall \\\"eigen_%s\\\" c_%s :: CInt -> %s\\n%s :: forall a . Code (C a) => %s\\n%s = c_%s (code (undefined :: (C a)))\", #name, #name, args, #name, args, #name, #name\n\n#api1 random,        \"Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 identity,      \"Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 add,           \"Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 sub,           \"Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 mul,           \"Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 diagonal,      \"Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 transpose,     \"Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 inverse,       \"Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 adjoint,       \"Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 conjugate,     \"Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 normalize,     \"Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 sum,           \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 prod,          \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 mean,          \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 norm,          \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 trace,         \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 squaredNorm,   \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 blueNorm,      \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 hypotNorm,     \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 determinant,   \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 rank,          \"CInt -> Ptr CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 image,         \"CInt -> Ptr (Ptr (C a)) -> Ptr CInt -> Ptr CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 kernel,        \"CInt -> Ptr (Ptr (C a)) -> Ptr CInt -> Ptr CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 solve,         \"CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api1 relativeError, \"Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n\n--------------------------------------------------------------------------------\n\n#let api2 name, args = \"foreign import ccall \\\"eigen_%s\\\" c_%s :: CInt -> %s\\n%s :: forall a . Code (C a) => %s\\n%s = c_%s (code (undefined :: (C a)))\", #name, #name, args, #name, args, #name, #name\n\n#api2 sparse_new,           \"CInt -> CInt -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_clone,         \"CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_fromList,      \"CInt -> CInt -> Ptr (CTriplet a) -> CInt -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_toList,        \"CSparseMatrixPtr a -> Ptr (CTriplet a) -> CInt -> IO CString\"\n#api2 sparse_free,          \"CSparseMatrixPtr a -> IO CString\"\n#api2 sparse_makeCompressed,\"CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_uncompress,    \"CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_isCompressed,  \"CSparseMatrixPtr a -> Ptr CInt -> IO CString\"\n#api2 sparse_transpose,     \"CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_adjoint,       \"CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_pruned,        \"CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_prunedRef,     \"CSparseMatrixPtr a -> Ptr (C a) -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_scale,         \"CSparseMatrixPtr a -> Ptr (C a) -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_nonZeros,      \"CSparseMatrixPtr a -> Ptr CInt -> IO CString\"\n#api2 sparse_innerSize,     \"CSparseMatrixPtr a -> Ptr CInt -> IO CString\"\n#api2 sparse_outerSize,     \"CSparseMatrixPtr a -> Ptr CInt -> IO CString\"\n#api2 sparse_coeff,         \"CSparseMatrixPtr a -> CInt -> CInt -> Ptr (C a) -> IO CString\"\n#api2 sparse_coeffRef,      \"CSparseMatrixPtr a -> CInt -> CInt -> Ptr (Ptr (C a)) -> IO CString\"\n#api2 sparse_cols,          \"CSparseMatrixPtr a -> Ptr CInt -> IO CString\"\n#api2 sparse_rows,          \"CSparseMatrixPtr a -> Ptr CInt -> IO CString\"\n#api2 sparse_norm,          \"CSparseMatrixPtr a -> Ptr (C a) -> IO CString\"\n#api2 sparse_squaredNorm,   \"CSparseMatrixPtr a -> Ptr (C a) -> IO CString\"\n#api2 sparse_blueNorm,      \"CSparseMatrixPtr a -> Ptr (C a) -> IO CString\"\n#api2 sparse_add,           \"CSparseMatrixPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_sub,           \"CSparseMatrixPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_mul,           \"CSparseMatrixPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_block,         \"CSparseMatrixPtr a -> CInt -> CInt -> CInt -> CInt -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_fromMatrix,    \"Ptr (C a) -> CInt -> CInt -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api2 sparse_toMatrix,      \"CSparseMatrixPtr a -> Ptr (C a) -> CInt -> CInt -> IO CString\"\n#api2 sparse_values,        \"CSparseMatrixPtr a -> Ptr CInt -> Ptr (Ptr (C a)) -> IO CString\"\n#api2 sparse_outerStarts,   \"CSparseMatrixPtr a -> Ptr CInt -> Ptr (Ptr CInt) -> IO CString\"\n#api2 sparse_innerIndices,  \"CSparseMatrixPtr a -> Ptr CInt -> Ptr (Ptr CInt) -> IO CString\"\n#api2 sparse_innerNNZs,     \"CSparseMatrixPtr a -> Ptr CInt -> Ptr (Ptr CInt) -> IO CString\"\n#api2 sparse_setZero,       \"CSparseMatrixPtr a -> IO CString\"\n#api2 sparse_setIdentity,   \"CSparseMatrixPtr a -> IO CString\"\n#api2 sparse_reserve,       \"CSparseMatrixPtr a -> CInt -> IO CString\"\n#api2 sparse_resize,        \"CSparseMatrixPtr a -> CInt -> CInt -> IO CString\"\n\n#api2 sparse_conservativeResize,    \"CSparseMatrixPtr a -> CInt -> CInt -> IO CString\"\n#api2 sparse_compressInplace,       \"CSparseMatrixPtr a -> IO CString\"\n#api2 sparse_uncompressInplace,     \"CSparseMatrixPtr a -> IO CString\"\n\n--------------------------------------------------------------------------------\n\n#let api3 name, args = \"foreign import ccall \\\"eigen_%s\\\" c_%s :: CInt -> CInt -> %s\\n%s :: forall s a . (Code s, Code (C a)) => s -> %s\\n%s s = c_%s (code (undefined :: (C a))) (code s)\", #name, #name, args, #name, args, #name, #name\n\n#api3 sparse_la_newSolver,          \"Ptr (CSolverPtr a) -> IO CString\"\n#api3 sparse_la_freeSolver,         \"CSolverPtr a -> IO CString\"\n#api3 sparse_la_factorize,          \"CSolverPtr a -> CSparseMatrixPtr a -> IO CString\"\n#api3 sparse_la_analyzePattern,     \"CSolverPtr a -> CSparseMatrixPtr a -> IO CString\"\n#api3 sparse_la_compute,            \"CSolverPtr a -> CSparseMatrixPtr a -> IO CString\"\n#api3 sparse_la_tolerance,          \"CSolverPtr a -> Ptr CDouble -> IO CString\"\n#api3 sparse_la_setTolerance,       \"CSolverPtr a -> CDouble -> IO CString\"\n#api3 sparse_la_maxIterations,      \"CSolverPtr a -> Ptr CInt -> IO CString\"\n#api3 sparse_la_setMaxIterations,   \"CSolverPtr a -> CInt -> IO CString\"\n#api3 sparse_la_info,               \"CSolverPtr a -> Ptr CInt -> IO CString\"\n#api3 sparse_la_error,              \"CSolverPtr a -> Ptr CDouble -> IO CString\"\n#api3 sparse_la_iterations,         \"CSolverPtr a -> Ptr CInt -> IO CString\"\n#api3 sparse_la_solve,              \"CSolverPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n-- #api3 sparse_la_solveWithGuess,     \"CSolverPtr a -> CSparseMatrixPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api3 sparse_la_matrixQ,            \"CSolverPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api3 sparse_la_matrixR,            \"CSolverPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api3 sparse_la_setPivotThreshold,  \"CSolverPtr a -> CDouble -> IO CString\"\n#api3 sparse_la_rank,               \"CSolverPtr a -> Ptr CInt -> IO CString\"\n#api3 sparse_la_matrixL,            \"CSolverPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api3 sparse_la_matrixU,            \"CSolverPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString\"\n#api3 sparse_la_setSymmetric,       \"CSolverPtr a -> CInt -> IO CString\"\n#api3 sparse_la_determinant,        \"CSolverPtr a -> Ptr (C a) -> IO CString\"\n#api3 sparse_la_logAbsDeterminant,  \"CSolverPtr a -> Ptr (C a) -> IO CString\"\n#api3 sparse_la_absDeterminant,     \"CSolverPtr a -> Ptr (C a) -> IO CString\"\n#api3 sparse_la_signDeterminant,    \"CSolverPtr a -> Ptr (C a) -> IO CString\"\n\n--------------------------------------------------------------------------------\n", "meta": {"hexsha": "30b2055a879afb9406b8f994819666b3d6d8afe6", "size": 18692, "ext": "hsc", "lang": "Haskell", "max_stars_repo_path": "src/Eigen/Internal.hsc", "max_stars_repo_name": "nilsalex/eigen", "max_stars_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-07-17T08:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T10:27:07.000Z", "max_issues_repo_path": "src/Eigen/Internal.hsc", "max_issues_repo_name": "nilsalex/eigen", "max_issues_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2018-07-17T14:12:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T11:37:18.000Z", "max_forks_repo_path": "src/Eigen/Internal.hsc", "max_forks_repo_name": "nilsalex/eigen", "max_forks_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-11-22T08:11:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T07:40:02.000Z", "avg_line_length": 50.5189189189, "max_line_length": 234, "alphanum_fraction": 0.5786432698, "num_tokens": 5212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.030675799716800664, "lm_q1q2_score": 0.010051486766716394}}
{"text": "module Sondages where\n\nimport qualified Data.Text as T\nimport Data.Time (UTCTime)\nimport qualified Data.Map as M\nimport Data.Time.Segment\nimport Statistics.LinearRegression (linearRegression)\nimport qualified Data.Vector.Unboxed as U\n\ndata Candidat = Macron | LePen | Clinton | Trump\n    deriving (Show, Read, Eq, Ord, Enum, Bounded)\n\n\ndata VoteIntention = VoteIntention { unCandidat :: Candidat\n                                   , unIntention :: Double\n             } deriving (Show, Read, Eq)\n\ndata Sondage = Sondage { unSondeur   :: T.Text\n                       , unDateBegin :: UTCTime\n                       , unDateEnd   :: Maybe UTCTime\n                       , echantillon :: Maybe Int\n                       , margeErreur :: Maybe Double\n                       , abstention  :: Maybe Double\n                       , indecis     :: Maybe Double\n                       , intentions  :: [(Candidat, Double)]\n                       } deriving (Show, Read, Eq)\n\n\nsondages :: [Sondage]\nsondages = [ Sondage \"Harris\"     (jour 2017 04 23) Nothing                  (Just 2684)   Nothing   Nothing     Nothing            [(Macron, 0.64)]\n           , Sondage \"Ipsos\"      (jour 2017 04 23) Nothing                  (Just 1379)   Nothing   Nothing     Nothing            [(Macron, 0.62)]\n           , Sondage \"OpinionWay\" (jour 2017 04 23) (Just $ jour 2017 04 24) (Just 1461)   Nothing   Nothing     Nothing     [(Macron, 0.61)]\n           , Sondage \"Ifop\"       (jour 2017 04 23) (Just $ jour 2017 04 24) (Just 846)    Nothing  (Just 0.26) (Just 0.12)  [(Macron, 0.60)]\n           , Sondage \"Harris\"     (jour 2017 04 25) (Just $ jour 2017 04 27) (Just 1016)   Nothing   Nothing     Nothing     [(Macron, 0.61)]\n           , Sondage \"OpinionWay\" (jour 2017 04 25) (Just $ jour 2017 04 27) (Just 1500)   Nothing  (Just 0.25)  Nothing     [(Macron, 0.60)]\n           , Sondage \"Odoxa\"      (jour 2017 04 26) (Just $ jour 2017 04 27) (Just 1003)   Nothing  (Just 0.20)   Nothing     [(Macron, 0.59)]\n           , Sondage \"BVA\"        (jour 2017 04 26) (Just $ jour 2017 04 28) (Just 1506)   Nothing  (Just 0.245) (Just 0.15) [(Macron, 0.59)]\n           , Sondage \"Ipsos\"      (jour 2017 04 28) (Just $ jour 2017 04 29) (Just 1504)   Nothing  (Just 0.25)   Nothing     [(Macron, 0.60)]\n           , Sondage \"Kantar\"     (jour 2017 04 28) (Just $ jour 2017 04 30) (Just 1539)   Nothing   Nothing      Nothing     [(Macron, 0.59)]\n           , Sondage \"Elabe\"      (jour 2017 04 28) (Just $ jour 2017 05 02) (Just 3956)   Nothing   Nothing     (Just 0.11)  [(Macron, 0.59)]\n           , Sondage \"Ifop\"       (jour 2017 04 28) (Just $ jour 2017 05 02) (Just 1388)   Nothing  (Just 0.27)   Nothing     [(Macron, 0.595)]\n           , Sondage \"Cevifop\"    (jour 2017 04 30) (Just $ jour 2017 05 01) (Just 13742)  Nothing  (Just 0.24)  (Just 0.15)  [(Macron, 0.59)]\n           , Sondage \"BVA\"        (jour 2017 05 01) (Just $ jour 2017 05 02) (Just 1435)   Nothing  (Just 0.22)   Nothing     [(Macron, 0.60)]\n           , Sondage \"OpinionWay\" (jour 2017 05 02) (Just $ jour 2017 05 04) (Just 1500)   Nothing  (Just 0.25)  (Just 0.15)  [(Macron, 0.62)]\n           , Sondage \"Elabe\"      (jour 2017 05 04)  Nothing                 (Just 1009)   Nothing   Nothing      Nothing     [(Macron, 0.62)]\n           , Sondage \"Ipsos\"      (jour 2017 05 04)  Nothing                 (Just 2632)   Nothing  (Just 0.24)   Nothing     [(Macron, 0.615)]\n           , Sondage \"Odoxa\"      (jour 2017 05 04)  Nothing                 (Just 998)    Nothing  (Just 0.25)  (Just 0.21)  [(Macron, 0.62)]\n           , Sondage \"Harris\"     (jour 2017 05 02) (Just $ jour 2017 05 05) (Just 4991)   Nothing  (Just 0.25)   Nothing     [(Macron, 0.62)]\n           , Sondage \"Ifop\"       (jour 2017 05 02) (Just $ jour 2017 05 05) (Just 1861)   Nothing  (Just 0.245)  Nothing     [(Macron, 0.63)]\n           , Sondage \"Ipsos\"      (jour 2017 05 05)  Nothing                 (Just 5331)   Nothing  (Just 0.24)  Nothing      [(Macron, 0.63)]\n           ]\n\npolls :: [Sondage]\npolls = [ Sondage \"YouGov\" (jour 2016 10 22) (Just $ jour 2016 10 26) (Just 1376) (Just 0.031) Nothing Nothing [(Clinton, 0.49), (Trump, 0.46)]\n        , Sondage \"ABC\"    (jour 2016 10 23) (Just $ jour 2016 10 26) (Just 1150) (Just 0.03)  Nothing Nothing [(Clinton, 0.50), (Trump, 0.45)]\n        , Sondage \"USC\"    (jour 2016 10 21) (Just $ jour 2016 10 27) (Just 3248) (Just 0.045) Nothing Nothing [(Clinton, 0.44), (Trump, 0.46)]\n        , Sondage \"Ipsos\"  (jour 2016 10 21) (Just $ jour 2016 10 27) (Just 1627) (Just 0.03)  Nothing Nothing [(Clinton, 0.42), (Trump, 0.36)]\n        , Sondage \"IBD\"    (jour 2016 10 22) (Just $ jour 2016 10 27) (Just 973)  (Just 0.033) Nothing Nothing [(Clinton, 0.45), (Trump, 0.42)]\n        , Sondage \"ABC\"    (jour 2016 10 24) (Just $ jour 2016 10 27) (Just 1148) (Just 0.03)  Nothing Nothing [(Clinton, 0.49), (Trump, 0.46)]\n        , Sondage \"IBD\"    (jour 2016 10 23) (Just $ jour 2016 10 28) (Just 1013) (Just 0.033) Nothing Nothing [(Clinton, 0.46), (Trump, 0.41)]\n        , Sondage \"ABC\"    (jour 2016 10 25) (Just $ jour 2016 10 28) (Just 1160) (Just 0.03)  Nothing Nothing [(Clinton, 0.46), (Trump, 0.45)]\n        ]\n\npollsResult :: [Sondage]\npollsResult = [Sondage \"REAL\" (jour 2016 11 08) Nothing Nothing Nothing Nothing Nothing [(Clinton, 0.481), (Trump, 0.46)]]\n\nnormalizePolls :: [Sondage] -> [Sondage]\nnormalizePolls xs = Prelude.map normalizePolls' xs\n    where\n        normalizePolls' (Sondage a b c d e f g is) = Sondage a b c d e f g is'\n            where\n                is' = Prelude.map (\\(m, n) -> (m, n/total)) is\n                total = sum $ Prelude.map snd is\n\nsondage2date :: [Sondage] -> [(UTCTime, [(Candidat, Double)])]\nsondage2date xs = concat ( map (dureeSondage) xs )\n    where\n        dureeSondage (Sondage _ begin end _ _ _ _ is) = case end of\n                    Nothing   -> zip (timesBetween begin begin D) (repeat is)\n                    Just end' -> zip (timesBetween begin end'  D) (repeat is)\n\ntoMap :: forall k a. Ord k => [(k, [a])] -> M.Map k [a]\ntoMap = Prelude.foldr (\\s -> M.insertWith (++) (fst s) (snd s)) M.empty \n\ntoMap' :: forall k a. Ord k => [(k, a)] -> M.Map k [a]\ntoMap' = Prelude.foldr (\\s -> M.insertWith (++) (fst s) ([snd s])) M.empty \n\nmapSondages :: [Sondage] -> M.Map UTCTime (M.Map Candidat Double)\nmapSondages sondage = M.map (M.map mean) $ M.map toMap' $ toMap (sondage2date sondage)\n    where\n        mean :: [Double] -> Double\n        mean xs = (sum xs) / (fromIntegral $ length xs)\n\npredict :: (Double -> Double) -> Int -> [(UTCTime, Double)]\npredict f days = predict' sondages f days\n\npredict' :: [Sondage] -> (Double -> Double) -> Int -> [(UTCTime, Double)]\npredict' sondes f days = zip dates $ Prelude.map (\\x -> f $ a' + b' * x) [1.. (fromIntegral n)]\n    where\n        sondes' = M.toAscList (mapSondages sondes)\n        firstDate = fst $ head sondes'\n        n = length sondes' + days\n        dates = timesAfter n D firstDate\n        (a', b') = linearRegression (U.fromList a) (U.fromList b)\n        (a, b) = unzip $ zip ([1..] :: [Double]) $  Prelude.map snd $ concat $ Prelude.map M.toList $ Prelude.map snd sondes'\n", "meta": {"hexsha": "9aa0730a767b25737a49ca8fa9d99b532335d48c", "size": 7166, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Sondages.hs", "max_stars_repo_name": "delanoe/vote-abstention", "max_stars_repo_head_hexsha": "822f729707e1393eb0da28dbe2a5d2decbc17d16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-29T02:06:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-29T02:06:53.000Z", "max_issues_repo_path": "src/Sondages.hs", "max_issues_repo_name": "delanoe/vote-abstention", "max_issues_repo_head_hexsha": "822f729707e1393eb0da28dbe2a5d2decbc17d16", "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/Sondages.hs", "max_forks_repo_name": "delanoe/vote-abstention", "max_forks_repo_head_hexsha": "822f729707e1393eb0da28dbe2a5d2decbc17d16", "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": 67.6037735849, "max_line_length": 148, "alphanum_fraction": 0.5616801563, "num_tokens": 2575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.01854656668203518, "lm_q1q2_score": 0.005824559612361665}}